@xenra/dsh-draworld 0.1.40 → 0.1.46
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.md +86 -12
- package/client.js +437 -97
- package/index.js +1026 -71
- package/package.json +1 -1
- package/pixelops.js +1288 -0
- package/pixels.js +182 -19
package/index.js
CHANGED
|
@@ -43,18 +43,147 @@ const BRUSH_IDS = [
|
|
|
43
43
|
];
|
|
44
44
|
|
|
45
45
|
const DEFAULT_DOC = {
|
|
46
|
-
version:
|
|
46
|
+
version: 3,
|
|
47
47
|
width: 1024,
|
|
48
48
|
height: 1024,
|
|
49
49
|
background: "#ffffff",
|
|
50
50
|
activeLayer: "l1",
|
|
51
51
|
seq: 0,
|
|
52
|
+
groups: [],
|
|
52
53
|
layers: [
|
|
53
|
-
{ id: "l1", name: DEFAULT_LAYER_NAME, visible: true, opacity: 1, blend: "normal", strokes: [] },
|
|
54
|
+
{ id: "l1", name: DEFAULT_LAYER_NAME, visible: true, opacity: 1, blend: "normal", role: "base", groupId: "g_color", strokes: [] },
|
|
54
55
|
],
|
|
55
56
|
redo: [],
|
|
56
57
|
};
|
|
57
58
|
|
|
59
|
+
// ---- 图层栈(v3):组 → role → 层;顺序常量是渲染与插入位置的唯一依据 ----
|
|
60
|
+
const GROUP_ORDER = ["ref", "sketch", "lineart", "color", "final"];
|
|
61
|
+
const ROLE_ORDER = {
|
|
62
|
+
sketch: ["sketch", "perspective"],
|
|
63
|
+
lineart: ["line", "lineColor", "occlusion"],
|
|
64
|
+
color: ["base", "shadow1", "shadow2", "lightblock"],
|
|
65
|
+
final: ["texture", "highlight", "iridescent", "atmosphere", "grade"],
|
|
66
|
+
};
|
|
67
|
+
const ROLES = ["ref", ...Object.values(ROLE_ORDER).flat()];
|
|
68
|
+
const ROLE_GROUP = {
|
|
69
|
+
ref: "ref",
|
|
70
|
+
sketch: "sketch", perspective: "sketch",
|
|
71
|
+
line: "lineart", lineColor: "lineart", occlusion: "lineart",
|
|
72
|
+
base: "color", shadow1: "color", shadow2: "color", lightblock: "color",
|
|
73
|
+
texture: "final", highlight: "final", iridescent: "final", atmosphere: "final", grade: "final",
|
|
74
|
+
};
|
|
75
|
+
const ROLE_BLEND = {
|
|
76
|
+
line: "multiply", lineColor: "normal", occlusion: "multiply",
|
|
77
|
+
shadow1: "multiply", shadow2: "multiply", lightblock: "overlay",
|
|
78
|
+
highlight: "screen", iridescent: "linear-dodge", atmosphere: "overlay",
|
|
79
|
+
};
|
|
80
|
+
const BLEND_MODES = ["normal", "multiply", "screen", "overlay", "soft-light", "linear-dodge"];
|
|
81
|
+
const ROLE_LABELS = {
|
|
82
|
+
sketch: "构图草稿", perspective: "透视辅助", line: "精线稿", lineColor: "线稿上色", occlusion: "闭塞线",
|
|
83
|
+
base: "固有色平铺", shadow1: "一级暗部", shadow2: "二级暗部", lightblock: "铺光大关系",
|
|
84
|
+
texture: "材质纹理", highlight: "高光", iridescent: "镭射反光", atmosphere: "氛围光效", grade: "调色调整",
|
|
85
|
+
};
|
|
86
|
+
const GROUP_LABELS = { ref: "参考", sketch: "草图", lineart: "线稿", color: "色稿", final: "成稿" };
|
|
87
|
+
const LEGACY_ROLE = {
|
|
88
|
+
"铺底": "base", "固有色": "base", "色块": "base", "底稿": "base",
|
|
89
|
+
"塑形": "shadow1", "暗部": "shadow1",
|
|
90
|
+
"过渡": "shadow2", "闭塞": "shadow2",
|
|
91
|
+
"收边": "line", "线稿": "line", "粗线": "line",
|
|
92
|
+
"点睛": "highlight", "高光": "highlight",
|
|
93
|
+
"笔触": "base", "绘画": "base",
|
|
94
|
+
};
|
|
95
|
+
const GROUP_TINT = "#8aa0b8";
|
|
96
|
+
|
|
97
|
+
/** 5 个语义组是图层栈的骨架:永远存在、id 固定、顺序即 GROUP_ORDER。 */
|
|
98
|
+
function defaultGroups() {
|
|
99
|
+
return GROUP_ORDER.map((kind) => ({
|
|
100
|
+
id: `g_${kind}`,
|
|
101
|
+
name: GROUP_LABELS[kind],
|
|
102
|
+
kind,
|
|
103
|
+
visible: true,
|
|
104
|
+
locked: false,
|
|
105
|
+
opacity: 1,
|
|
106
|
+
collapsed: false,
|
|
107
|
+
color: GROUP_TINT,
|
|
108
|
+
}));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* 组唯一化 + 补齐 5 个骨架组;自定义组(kind=custom)保留在原位置。
|
|
113
|
+
* 同一 kind 出现多次时,第一个当骨架,其余降级成自定义组——不丢用户数据。
|
|
114
|
+
*/
|
|
115
|
+
function normalizeGroups(raw) {
|
|
116
|
+
const list = [];
|
|
117
|
+
const seen = new Set();
|
|
118
|
+
const take = (input, forceKind) => {
|
|
119
|
+
if (!input || typeof input !== "object") return;
|
|
120
|
+
const kind = forceKind || (GROUP_ORDER.includes(input.kind) ? input.kind : "custom");
|
|
121
|
+
let id = String(input.id || "").trim();
|
|
122
|
+
if (!id || seen.has(id)) id = `g_${kind === "custom" ? "c" : kind}${list.length}${Math.random().toString(36).slice(2, 4)}`;
|
|
123
|
+
seen.add(id);
|
|
124
|
+
const label = kind === "custom" ? "图层组" : GROUP_LABELS[kind];
|
|
125
|
+
list.push({
|
|
126
|
+
id,
|
|
127
|
+
name: String(input.name || label).trim().slice(0, 30) || label,
|
|
128
|
+
kind,
|
|
129
|
+
visible: input.visible !== false,
|
|
130
|
+
locked: input.locked === true,
|
|
131
|
+
opacity: clamp01(input.opacity),
|
|
132
|
+
collapsed: input.collapsed === true,
|
|
133
|
+
color: typeof input.color === "string" ? input.color : GROUP_TINT,
|
|
134
|
+
});
|
|
135
|
+
};
|
|
136
|
+
(Array.isArray(raw) ? raw : []).forEach((g) => {
|
|
137
|
+
if (g && GROUP_ORDER.includes(g.kind) && list.some((x) => x.kind === g.kind)) take(g, "custom");
|
|
138
|
+
else take(g);
|
|
139
|
+
});
|
|
140
|
+
for (const kind of GROUP_ORDER) {
|
|
141
|
+
if (list.some((g) => g.kind === kind)) continue;
|
|
142
|
+
const prev = GROUP_ORDER[GROUP_ORDER.indexOf(kind) - 1];
|
|
143
|
+
const at = prev ? list.findIndex((g) => g.kind === prev) : -1;
|
|
144
|
+
const def = defaultGroups().find((g) => g.kind === kind);
|
|
145
|
+
let id = def.id;
|
|
146
|
+
let n = 2;
|
|
147
|
+
while (seen.has(id)) {
|
|
148
|
+
id = `${def.id}_${n}`;
|
|
149
|
+
n += 1;
|
|
150
|
+
}
|
|
151
|
+
seen.add(id);
|
|
152
|
+
list.splice(at + 1, 0, { ...def, id });
|
|
153
|
+
}
|
|
154
|
+
return list;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** layers[] 是唯一 z 顺序,且同组必须连续;按组顺序稳定重排,组内相对顺序不动。 */
|
|
158
|
+
function orderLayers(layers, groups) {
|
|
159
|
+
const order = new Map((groups || []).map((g, i) => [g.id, i]));
|
|
160
|
+
return layers
|
|
161
|
+
.map((layer, i) => ({ layer, i, g: order.has(layer.groupId) ? order.get(layer.groupId) : -1 }))
|
|
162
|
+
.sort((a, b) => (a.g - b.g) || (a.i - b.i))
|
|
163
|
+
.map((x) => x.layer);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const roleOfName = (name) => LEGACY_ROLE[String(name || "").trim()] || null;
|
|
167
|
+
const groupOfRole = (role) => ROLE_GROUP[role] || "color";
|
|
168
|
+
const roleIndex = (role) => {
|
|
169
|
+
const group = groupOfRole(role);
|
|
170
|
+
const g = GROUP_ORDER.indexOf(group);
|
|
171
|
+
const r = (ROLE_ORDER[group] || []).indexOf(role);
|
|
172
|
+
return (g < 0 ? 99 : g) * 100 + (r < 0 ? 99 : r);
|
|
173
|
+
};
|
|
174
|
+
const blendOfRole = (role) => ROLE_BLEND[role] || "normal";
|
|
175
|
+
// paint 五步 → v3 图层栈
|
|
176
|
+
const PAINT_STAGE_ROLE = {
|
|
177
|
+
base: "base", block: "shadow1", blend: "shadow2", edge: "line", accent: "highlight",
|
|
178
|
+
sketch: "sketch", lineColor: "lineColor", occlusion: "occlusion", lightblock: "lightblock",
|
|
179
|
+
texture: "texture", iridescent: "iridescent", atmosphere: "atmosphere", grade: "grade",
|
|
180
|
+
};
|
|
181
|
+
const PAINT_STAGE_NAME = {
|
|
182
|
+
base: "固有色平铺", block: "一级暗部", blend: "二级暗部", edge: "精线稿", accent: "高光",
|
|
183
|
+
sketch: "构图草稿", lineColor: "线稿上色", occlusion: "闭塞线", lightblock: "铺光大关系",
|
|
184
|
+
texture: "材质纹理", iridescent: "镭射反光", atmosphere: "氛围光效", grade: "调色调整",
|
|
185
|
+
};
|
|
186
|
+
|
|
58
187
|
/** 压回 0~1,非数字按 1 处理。 */
|
|
59
188
|
function clamp01(value) {
|
|
60
189
|
const n = Number(value);
|
|
@@ -148,6 +277,8 @@ function migrateDoc(parsed = {}) {
|
|
|
148
277
|
: DEFAULT_DOC.background;
|
|
149
278
|
|
|
150
279
|
let counter = 0;
|
|
280
|
+
const groups = normalizeGroups(parsed.groups);
|
|
281
|
+
const groupIds = new Set(groups.map((g) => g.id));
|
|
151
282
|
const normalizeLayer = (layer, index) => {
|
|
152
283
|
const strokes = Array.isArray(layer.strokes) ? layer.strokes : [];
|
|
153
284
|
for (const s of strokes) {
|
|
@@ -159,15 +290,43 @@ function migrateDoc(parsed = {}) {
|
|
|
159
290
|
}
|
|
160
291
|
if (!s.id) s.id = `s${s.seq}`;
|
|
161
292
|
}
|
|
293
|
+
const hasImage = layer.image && typeof layer.image.file === "string";
|
|
294
|
+
const namedRole = roleOfName(layer.name);
|
|
295
|
+
const role = ROLES.includes(layer.role)
|
|
296
|
+
? layer.role
|
|
297
|
+
: (hasImage ? "ref" : (namedRole || "base"));
|
|
298
|
+
const wantGroup = String(layer.groupId || "").trim();
|
|
299
|
+
const groupId = groupIds.has(wantGroup)
|
|
300
|
+
? wantGroup
|
|
301
|
+
: (groups.find((g) => g.kind === wantGroup || g.name === wantGroup) || {}).id || `g_${groupOfRole(role)}`;
|
|
302
|
+
// 旧文档的 paint 层按名字映射 role 时,normal 换成该 role 的默认混合模式
|
|
303
|
+
const blend = BLEND_MODES.includes(layer.blend) && !(namedRole && layer.blend === "normal" && !ROLES.includes(layer.role))
|
|
304
|
+
? layer.blend
|
|
305
|
+
: blendOfRole(role);
|
|
306
|
+
const hueNum = Number(layer.hue);
|
|
162
307
|
return {
|
|
163
308
|
id: String(layer.id || `l${index + 1}`),
|
|
164
309
|
name: String(layer.name || `图层 ${index + 1}`),
|
|
310
|
+
role,
|
|
311
|
+
groupId,
|
|
165
312
|
visible: layer.visible !== false,
|
|
166
313
|
opacity: clamp01(layer.opacity),
|
|
167
|
-
blend
|
|
314
|
+
blend,
|
|
315
|
+
clipTo: typeof layer.clipTo === "string" && layer.clipTo ? layer.clipTo : null,
|
|
316
|
+
lockAlpha: layer.lockAlpha === true,
|
|
317
|
+
hue: Number.isFinite(hueNum) ? Math.max(-180, Math.min(180, Math.round(hueNum))) : 0,
|
|
318
|
+
grade: layer.grade && typeof layer.grade === "object"
|
|
319
|
+
? {
|
|
320
|
+
brightness: Math.max(-1, Math.min(1, Number(layer.grade.brightness) || 0)),
|
|
321
|
+
contrast: Math.max(0, Math.min(3, Number(layer.grade.contrast) === undefined ? 1 : Number(layer.grade.contrast))),
|
|
322
|
+
saturation: Math.max(0, Math.min(3, Number(layer.grade.saturation) === undefined ? 1 : Number(layer.grade.saturation))),
|
|
323
|
+
hue: Math.max(-180, Math.min(180, Number(layer.grade.hue) || 0)),
|
|
324
|
+
}
|
|
325
|
+
: undefined,
|
|
326
|
+
locked: layer.locked === true,
|
|
168
327
|
strokes,
|
|
169
328
|
// 图片层:file 相对缓存目录(images/xxx.png),x/y/w/h 是它在画布上的落位
|
|
170
|
-
image:
|
|
329
|
+
image: hasImage
|
|
171
330
|
? {
|
|
172
331
|
file: String(layer.image.file).slice(0, 200),
|
|
173
332
|
x: Number(layer.image.x) || 0,
|
|
@@ -182,7 +341,12 @@ function migrateDoc(parsed = {}) {
|
|
|
182
341
|
const rawLayers = Array.isArray(parsed.layers) && parsed.layers.length > 0
|
|
183
342
|
? parsed.layers
|
|
184
343
|
: [{ id: "l1", name: DEFAULT_LAYER_NAME, strokes: Array.isArray(parsed.strokes) ? parsed.strokes : [] }];
|
|
185
|
-
|
|
344
|
+
// v3 已存组内顺序:尊重它,只按组切块;老文档:先按 role 归位一次再切块
|
|
345
|
+
const normalized = rawLayers.map(normalizeLayer);
|
|
346
|
+
const layers = parsed.version >= 3 && Array.isArray(parsed.groups) && parsed.groups.length
|
|
347
|
+
? orderLayers(normalized, groups)
|
|
348
|
+
: orderLayers(normalized.sort((a, b) => roleIndex(a.role) - roleIndex(b.role)), groups);
|
|
349
|
+
if (layers.length === 0) layers.push(normalizeLayer({ id: "l1", name: DEFAULT_LAYER_NAME }, 0));
|
|
186
350
|
|
|
187
351
|
const redo = Array.isArray(parsed.redo)
|
|
188
352
|
? parsed.redo.filter((entry) => entry && entry.stroke).slice(-200)
|
|
@@ -210,12 +374,13 @@ function migrateDoc(parsed = {}) {
|
|
|
210
374
|
}
|
|
211
375
|
|
|
212
376
|
return {
|
|
213
|
-
version:
|
|
377
|
+
version: 3,
|
|
214
378
|
width,
|
|
215
379
|
height,
|
|
216
380
|
background,
|
|
217
381
|
activeLayer: layers.some((l) => l.id === parsed.activeLayer) ? parsed.activeLayer : layers[layers.length - 1].id,
|
|
218
382
|
seq: counter,
|
|
383
|
+
groups,
|
|
219
384
|
layers,
|
|
220
385
|
redo,
|
|
221
386
|
selection,
|
|
@@ -243,15 +408,18 @@ const PROTOCOL = `你可以用 \`paint_canvas\` 在界面里的一块真画布
|
|
|
243
408
|
4. 每画几笔用 \`action=view\` 看一眼渲染结果(返回 PNG 路径、每层的包围盒与覆盖率),不要假设画对了。
|
|
244
409
|
要贴脸看细节就带 \`rect=[x,y,w,h]\` 与 \`zoom=2~4\`;只看某一层就带 \`layer="线稿"\`。
|
|
245
410
|
5. 画错用 \`action=undo\` 撤掉最近一笔,撤多了用 \`action=redo\` 回来;要整幅重来才用 \`action=clear\`。
|
|
246
|
-
6. 图层不只是画布边界:\`action=layer layerOp=add name="上色"\` 建层,\`layerOp=set\` 改名字/显隐/\`layerOpacity\`/\`blend\`/\`locked\`,
|
|
247
|
-
\`layerOp=select\` 切成当前层,\`layerOp=list\`
|
|
411
|
+
6. 图层不只是画布边界:\`action=layer layerOp=add name="上色"\` 建层,\`layerOp=set\` 改名字/显隐/\`layerOpacity\`/\`blend\`/\`locked\`/\`role\`/\`clipTo\`/\`lockAlpha\`/\`hue\`,
|
|
412
|
+
\`layerOp=select\` 切成当前层,\`layerOp=list\` 看全部(含每层的 role、blend、图片信息和笔迹数)。
|
|
413
|
+
**一次只画一层**;v3 图层栈由 role 决定 z 高度与默认混合模式:line/shadow1/shadow2=multiply,highlight=screen,lightblock/atmosphere=overlay,iridescent=linear-dodge,其余 normal。
|
|
414
|
+
不要再自己算"先画哪层"——建层时给 \`role\`,位置会自动插对。\`clipTo\` 指向显式层 id(跨组也成立),\`lockAlpha=true\` 锁透明像素,\`hue\` 只转本层色相。
|
|
248
415
|
想让某层淡一点就 \`layerOpacity=0.4\`,想做叠加效果就 \`blend=multiply\`;把参考图那一层 \`locked=true\` 就盖不上去也擦不掉。
|
|
249
416
|
7. 图片当底稿:\`action=import path="D:\\\\ref\\\\pose.png"\` 会把图存进缓存目录的 images/ 并压成**最底层**(图层 1),
|
|
250
417
|
默认 contain(整张居中放进画布);之后正常 draw 就是描图。导入后图层里带 \`image\` 字段。
|
|
251
418
|
8. 画布本身也能改:\`action=canvas width=… height=… background=#rrggbb\`;\`action=export\` 把当前渲染另存成 PNG。
|
|
252
419
|
|
|
253
420
|
**最省事的复刻就两条命令**(不需要自己估坐标、算配色、找缺口):
|
|
254
|
-
- \`action=copy style=anime\`(或 lineart / flat):自动抽轮廓、按区域配主色、建「色块 / 线稿」两层,描线默认走三次贝塞尔拟合(长弧一条曲线走完,比磨圆更像手画),每根线按量出来的原线宽落笔,并顺带跑一次 compare,直接给出覆盖率;要粗细分层加 \`splitLines=true\`;
|
|
421
|
+
- \`action=copy style=anime\`(或 lineart / flat / paint):自动抽轮廓、按区域配主色、建「色块 / 线稿」两层,描线默认走三次贝塞尔拟合(长弧一条曲线走完,比磨圆更像手画),每根线按量出来的原线宽落笔,并顺带跑一次 compare,直接给出覆盖率;要粗细分层加 \`splitLines=true\`;
|
|
422
|
+
\`style=paint\` 是另一条路(0.1.44 起是**完整 14 层栈**,不是网格点彩):01 构图草稿(粗轮廓、锁定、低透明度)→ 03 精线稿(色阶边界、multiply)→ 04 线稿上色(clip 到 03、锁定透明像素)→ 05 闭塞线(比固有色暗很多的窄缝)→ 06 固有色平铺(按颜色+位置拆 06a 皮肤 / 06b 头发 / 06c 上装 / 06d 下装 / 06e 道具,大色块 fill)→ 07 一级暗部 / 08 二级暗部(tone map 暗区、multiply)→ 09 铺光大关系(亮区宽笔、overlay)→ 10 材质纹理(程序纸纹、clip 到 06)→ 11 高光(screen、clip 到 06)→ 12 镭射反光(沿高光、linear-dodge)→ 13 氛围光效(边缘宽笔、overlay)→ 14 调色调整(参数化,不落笔)。**一次只画一层**;\`paintStages="base,edge"\` 只跑其中几步(重跑自动 snapshot)。总笔数默认 4000,按 weight 分给各层。\`paintColors\` / \`paintBlocks\` 调固有色,\`paintStep\` 调笔距(默认 10)。paint 固定走宿主侧引擎,回报 \`computedBy=host\`、\`paintStats\`(覆盖率/场强/丢弃块)和 \`paintLayers\`(每层 role/blend/clipTo)。fix 的墨迹补漏不适用于彩稿;用 \`action=check\` 做关层自检和 06 覆盖率检查。
|
|
255
423
|
- \`action=fix target=90 maxRounds=3\`:只看最漏的几块自动补描,到达标或没得补就停,返回每轮数字;落在色块洞里(高光)的缺口会跳过,不会把高光涂掉。
|
|
256
424
|
- \`action=fill x=… y=…\`:点一片区域就按 palette 填色(边界来自已有笔迹,也能手动给 color),不用一笔笔涂;区域里的洞(高光、瞳孔)会按轮廓嵌套挖掉不涂;
|
|
257
425
|
- \`action=select rect=[x,y,w,h]\` 或 \`points=[[x,y]…]\`(套索)把落笔限制在选区里,\`clearSelection=true\` 取消;
|
|
@@ -269,6 +437,8 @@ const PROTOCOL = `你可以用 \`paint_canvas\` 在界面里的一块真画布
|
|
|
269
437
|
- 一笔要多处对称就用 \`mirror="x"\` 或 \`"y"\`;一次补很多笔用 \`batches=[…]\`。
|
|
270
438
|
- 大面积改写前先 \`action=snapshot label="上色前"\`,画崩了 \`action=restore\` 整幅回退(比逐笔 undo 干净)。
|
|
271
439
|
|
|
440
|
+
**像素任务走哪条路**:裁切/取色/差分/主色/描线这些会在「浏览器面板」和「宿主 pixelops.js」之间自动选;\`copy style=paint\` 与 \`posterize\` 固定走宿主(两边只保留一份实现,避免结果不一致)。回报里的 \`computedBy\` 写 \`host\` 或 \`panel\`;想强制宿主排查就给 \`forceHeadless=true\`。宿主侧需要画布上有**图片层**当参考图,别把参考层删了。
|
|
441
|
+
|
|
272
442
|
用户也可能同时在画布上画,所以落笔前先 doc 看一眼版本,必要时以最新内容为准。`;
|
|
273
443
|
|
|
274
444
|
/** 每个缓存目录只留一份内存文档(见 Document.forDir)。挂在 globalThis 上,插件被重新加载也能复用。 */
|
|
@@ -463,32 +633,63 @@ class Document {
|
|
|
463
633
|
this.save();
|
|
464
634
|
}
|
|
465
635
|
|
|
466
|
-
/** 按 id
|
|
636
|
+
/** 按 id、名字、或「组/层」路径找一层(组可用 id、kind 或名字)。 */
|
|
467
637
|
layer(idOrName) {
|
|
468
638
|
const key = String(idOrName || "").trim();
|
|
469
639
|
if (!key) return null;
|
|
470
|
-
|
|
640
|
+
const exact = this.doc.layers.find((l) => l.id === key) || this.doc.layers.find((l) => l.name === key);
|
|
641
|
+
if (exact) return exact;
|
|
642
|
+
for (const sep of ["/", ":"]) {
|
|
643
|
+
const at = key.lastIndexOf(sep);
|
|
644
|
+
if (at <= 0) continue;
|
|
645
|
+
const group = this.group(key.slice(0, at).trim());
|
|
646
|
+
if (!group) continue;
|
|
647
|
+
const name = key.slice(at + 1).trim();
|
|
648
|
+
const hit = this.doc.layers.find((l) => l.groupId === group.id && l.name === name);
|
|
649
|
+
if (hit) return hit;
|
|
650
|
+
}
|
|
651
|
+
return null;
|
|
471
652
|
}
|
|
472
653
|
|
|
473
654
|
active() {
|
|
474
655
|
return this.layer(this.doc.activeLayer) || this.doc.layers[this.doc.layers.length - 1];
|
|
475
656
|
}
|
|
476
657
|
|
|
477
|
-
/**
|
|
658
|
+
/** 取一层;不给或没有就建同名层(模型按名字落笔时用)。支持「组/层」直接建进该组。 */
|
|
478
659
|
ensureLayer(idOrName) {
|
|
479
660
|
const key = String(idOrName || "").trim();
|
|
480
661
|
if (!key) return this.active();
|
|
481
662
|
const found = this.layer(key);
|
|
482
663
|
if (found) return found;
|
|
664
|
+
let group = null;
|
|
665
|
+
let layerName = key;
|
|
666
|
+
for (const sep of ["/", ":"]) {
|
|
667
|
+
const at = key.lastIndexOf(sep);
|
|
668
|
+
if (at <= 0) continue;
|
|
669
|
+
const g = this.group(key.slice(0, at).trim());
|
|
670
|
+
if (g) {
|
|
671
|
+
group = g;
|
|
672
|
+
layerName = key.slice(at + 1).trim() || "图层";
|
|
673
|
+
break;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
const role = roleOfName(layerName) || "base";
|
|
677
|
+
const groupId = group ? group.id : `g_${groupOfRole(role)}`;
|
|
483
678
|
const layer = {
|
|
484
679
|
id: `l${Date.now().toString(36)}${Math.random().toString(36).slice(2, 5)}`,
|
|
485
|
-
name:
|
|
680
|
+
name: layerName.slice(0, 40),
|
|
681
|
+
role,
|
|
682
|
+
groupId,
|
|
486
683
|
visible: true,
|
|
487
684
|
opacity: 1,
|
|
488
|
-
blend:
|
|
685
|
+
blend: blendOfRole(role),
|
|
686
|
+
clipTo: null,
|
|
687
|
+
lockAlpha: false,
|
|
688
|
+
hue: 0,
|
|
689
|
+
locked: false,
|
|
489
690
|
strokes: [],
|
|
490
691
|
};
|
|
491
|
-
this.
|
|
692
|
+
this.insertOrdered(layer);
|
|
492
693
|
this.doc.activeLayer = layer.id;
|
|
493
694
|
return layer;
|
|
494
695
|
}
|
|
@@ -566,9 +767,15 @@ class Document {
|
|
|
566
767
|
const layer = {
|
|
567
768
|
id: `l${stamp}${rand}`,
|
|
568
769
|
name: String(input.name || "").trim().slice(0, 40) || "图片 1",
|
|
770
|
+
role: "ref",
|
|
771
|
+
groupId: "g_ref",
|
|
569
772
|
visible: true,
|
|
570
773
|
opacity: clamp01(input.opacity),
|
|
571
774
|
blend: "normal",
|
|
775
|
+
clipTo: null,
|
|
776
|
+
lockAlpha: false,
|
|
777
|
+
hue: 0,
|
|
778
|
+
locked: false,
|
|
572
779
|
strokes: [],
|
|
573
780
|
image: { file: path.posix.join("images", fileName), x, y, w, h },
|
|
574
781
|
};
|
|
@@ -581,16 +788,198 @@ class Document {
|
|
|
581
788
|
};
|
|
582
789
|
}
|
|
583
790
|
|
|
584
|
-
|
|
791
|
+
/** 插到目标组的连续块里:组内按 role 高度找位置,组块本身不能被打散。 */
|
|
792
|
+
insertOrdered(layer) {
|
|
793
|
+
const layers = this.doc.layers;
|
|
794
|
+
const groups = this.doc.groups || [];
|
|
795
|
+
const want = layer.groupId;
|
|
796
|
+
const gAt = groups.findIndex((g) => g.id === want);
|
|
797
|
+
let start = layers.findIndex((l) => l.groupId === want);
|
|
798
|
+
if (start < 0) {
|
|
799
|
+
// 这一组还没有层:插在该组顺序对应的块起点(保持组块连续)
|
|
800
|
+
if (gAt < 0) {
|
|
801
|
+
layers.push(layer);
|
|
802
|
+
return;
|
|
803
|
+
}
|
|
804
|
+
const next = layers.findIndex((l) => {
|
|
805
|
+
const gi = groups.findIndex((g) => g.id === l.groupId);
|
|
806
|
+
return gi > gAt;
|
|
807
|
+
});
|
|
808
|
+
if (next < 0) layers.push(layer);
|
|
809
|
+
else layers.splice(next, 0, layer);
|
|
810
|
+
return;
|
|
811
|
+
}
|
|
812
|
+
let end = start;
|
|
813
|
+
while (end < layers.length && layers[end].groupId === want) end += 1;
|
|
814
|
+
for (let i = start; i < end; i += 1) {
|
|
815
|
+
if (roleIndex(layers[i].role) > roleIndex(layer.role)) {
|
|
816
|
+
layers.splice(i, 0, layer);
|
|
817
|
+
return;
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
layers.splice(end, 0, layer);
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
/** 组既能用 id、kind、名字找。 */
|
|
824
|
+
group(ref) {
|
|
825
|
+
const key = String(ref || "").trim();
|
|
826
|
+
if (!key) return null;
|
|
827
|
+
const list = this.doc.groups || [];
|
|
828
|
+
return list.find((g) => g.id === key) || list.find((g) => g.kind === key) || list.find((g) => g.name === key) || null;
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
addGroup(input = {}) {
|
|
832
|
+
const groups = this.doc.groups || (this.doc.groups = []);
|
|
833
|
+
const list = groups;
|
|
834
|
+
const layerList = this.doc.layers || [];
|
|
835
|
+
const kind = GROUP_ORDER.includes(input.kind) ? input.kind : "custom";
|
|
836
|
+
if (kind !== "custom" && list.some((g) => g.kind === kind)) throw new Error(`已经有 ${GROUP_LABELS[kind]} 组了`);
|
|
837
|
+
let id = String(input.id || "").trim();
|
|
838
|
+
if (!id || list.some((g) => g.id === id)) id = `g_c${Date.now().toString(36)}${Math.random().toString(36).slice(2, 4)}`;
|
|
839
|
+
const group = {
|
|
840
|
+
id,
|
|
841
|
+
name: String(input.name || (kind === "custom" ? "图层组" : GROUP_LABELS[kind])).trim().slice(0, 30) || "图层组",
|
|
842
|
+
kind,
|
|
843
|
+
visible: input.visible !== false,
|
|
844
|
+
locked: input.locked === true,
|
|
845
|
+
opacity: input.opacity === undefined ? 1 : clamp01(input.opacity),
|
|
846
|
+
collapsed: input.collapsed === true,
|
|
847
|
+
color: typeof input.color === "string" ? input.color : GROUP_TINT,
|
|
848
|
+
};
|
|
849
|
+
// 位置:after 指定的组之后;默认压最顶(即 layers 的最上面)
|
|
850
|
+
const afterRef = input.after !== undefined ? input.after : input.afterId;
|
|
851
|
+
const after = afterRef !== undefined ? this.group(afterRef) : null;
|
|
852
|
+
if (after) list.splice(list.indexOf(after) + 1, 0, group);
|
|
853
|
+
else list.push(group);
|
|
854
|
+
// layers 里也要留出这个组的空块:按组顺序重排即可(该组暂无层,天然为空)
|
|
855
|
+
this.doc.layers = orderLayers(layerList, list);
|
|
856
|
+
this.bump();
|
|
857
|
+
return group;
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
updateGroup(ref, patch = {}) {
|
|
861
|
+
const group = this.group(ref);
|
|
862
|
+
if (!group) throw new Error(`没有这个组:${ref}`);
|
|
863
|
+
if (typeof patch.name === "string" && patch.name.trim()) group.name = patch.name.trim().slice(0, 30);
|
|
864
|
+
if (patch.visible !== undefined) group.visible = patch.visible !== false;
|
|
865
|
+
if (patch.locked !== undefined) group.locked = patch.locked === true;
|
|
866
|
+
if (patch.opacity !== undefined) group.opacity = clamp01(patch.opacity);
|
|
867
|
+
if (patch.collapsed !== undefined) group.collapsed = patch.collapsed === true;
|
|
868
|
+
if (typeof patch.color === "string") group.color = patch.color;
|
|
869
|
+
this.bump();
|
|
870
|
+
return group;
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
/** 组上移/下移一格(layers 同步重排,保证组块顺序跟 groups[] 一致)。 */
|
|
874
|
+
moveGroup(ref, offset) {
|
|
875
|
+
const groups = this.doc.groups || [];
|
|
876
|
+
const group = this.group(ref);
|
|
877
|
+
if (!group) throw new Error(`没有这个组:${ref}`);
|
|
878
|
+
const from = groups.indexOf(group);
|
|
879
|
+
const to = Math.max(0, Math.min(groups.length - 1, from + (Number(offset) || 0)));
|
|
880
|
+
if (to !== from) {
|
|
881
|
+
groups.splice(from, 1);
|
|
882
|
+
groups.splice(to, 0, group);
|
|
883
|
+
this.doc.layers = orderLayers(this.doc.layers, groups);
|
|
884
|
+
this.bump();
|
|
885
|
+
}
|
|
886
|
+
return { group, index: to };
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
/** 删组:默认只删空组;force=true 时组内层挪到相邻组,再删。 */
|
|
890
|
+
removeGroup(ref, opts = {}) {
|
|
891
|
+
const groups = this.doc.groups || [];
|
|
892
|
+
const group = this.group(ref);
|
|
893
|
+
if (!group) throw new Error(`没有这个组:${ref}`);
|
|
894
|
+
if (group.kind !== "custom" && !opts.force) throw new Error(`「${group.name}」是图层栈骨架组,不能删`);
|
|
895
|
+
if (groups.length <= 1) throw new Error("至少留一组");
|
|
896
|
+
const inside = this.doc.layers.filter((l) => l.groupId === group.id);
|
|
897
|
+
if (inside.length && !opts.force) throw new Error(`「${group.name}」里还有 ${inside.length} 层:先用 force 把层并到相邻组`);
|
|
898
|
+
if (inside.length) {
|
|
899
|
+
const at = groups.indexOf(group);
|
|
900
|
+
const fallback = groups[at - 1] || groups[at + 1];
|
|
901
|
+
if (!fallback) throw new Error("没有相邻组可以接收这些层");
|
|
902
|
+
for (const layer of inside) layer.groupId = fallback.id;
|
|
903
|
+
}
|
|
904
|
+
groups.splice(groups.indexOf(group), 1);
|
|
905
|
+
this.doc.layers = orderLayers(this.doc.layers, groups);
|
|
906
|
+
this.bump();
|
|
907
|
+
return { id: group.id, moved: inside.length };
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
/** 层跨组移动:落到目标组块内(index 指定组内位置,缺省按 role 找位置)。 */
|
|
911
|
+
moveLayerToGroup(layerRef, groupRef, index) {
|
|
912
|
+
const layer = this.layer(layerRef);
|
|
913
|
+
if (!layer) throw new Error(`没有这一层:${layerRef}`);
|
|
914
|
+
const group = this.group(groupRef);
|
|
915
|
+
if (!group) throw new Error(`没有这个组:${groupRef}`);
|
|
916
|
+
this.doc.layers = this.doc.layers.filter((l) => l !== layer);
|
|
917
|
+
layer.groupId = group.id;
|
|
918
|
+
const start = this.doc.layers.findIndex((l) => l.groupId === group.id);
|
|
919
|
+
if (start < 0) {
|
|
920
|
+
// 这一组还是空的:按组序落位,别甩到数组末尾
|
|
921
|
+
this.insertOrdered(layer);
|
|
922
|
+
} else {
|
|
923
|
+
let end = start;
|
|
924
|
+
while (end < this.doc.layers.length && this.doc.layers[end].groupId === group.id) end += 1;
|
|
925
|
+
const want = Number(index);
|
|
926
|
+
const at = Number.isFinite(want) ? Math.max(start, Math.min(end, start + Math.round(want))) : end;
|
|
927
|
+
this.doc.layers.splice(at, 0, layer);
|
|
928
|
+
}
|
|
929
|
+
this.bump();
|
|
930
|
+
return layer;
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
/** 层在当前组内上移/下移(不跨组)。 */
|
|
934
|
+
moveLayer(ref, offset) {
|
|
935
|
+
const layer = this.layer(ref);
|
|
936
|
+
if (!layer) throw new Error(`没有这一层:${ref}`);
|
|
937
|
+
const layers = this.doc.layers;
|
|
938
|
+
const start = layers.findIndex((l) => l.groupId === layer.groupId);
|
|
939
|
+
let end = start;
|
|
940
|
+
while (end < layers.length && layers[end].groupId === layer.groupId) end += 1;
|
|
941
|
+
const from = layers.indexOf(layer);
|
|
942
|
+
const to = Math.max(start, Math.min(end - 1, from + (Number(offset) || 0)));
|
|
943
|
+
if (to !== from) {
|
|
944
|
+
layers.splice(from, 1);
|
|
945
|
+
layers.splice(to, 0, layer);
|
|
946
|
+
this.bump();
|
|
947
|
+
}
|
|
948
|
+
return { layer, index: to - start };
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
addLayer(name, opts = {}) {
|
|
952
|
+
const role = ROLES.includes(opts.role) ? opts.role : (roleOfName(name) || "base");
|
|
953
|
+
const named = this.group(opts.groupId);
|
|
954
|
+
const groupId = named ? named.id : `g_${groupOfRole(role)}`;
|
|
955
|
+
const blend = BLEND_MODES.includes(opts.blend) ? opts.blend : blendOfRole(role);
|
|
956
|
+
const hueNum = Number(opts.hue);
|
|
585
957
|
const layer = {
|
|
586
958
|
id: `l${Date.now().toString(36)}${Math.random().toString(36).slice(2, 5)}`,
|
|
587
|
-
name: String(name || `图层 ${this.doc.layers.length + 1}`).trim().slice(0, 40) || `图层 ${this.doc.layers.length + 1}`,
|
|
959
|
+
name: String(name || ROLE_LABELS[role] || `图层 ${this.doc.layers.length + 1}`).trim().slice(0, 40) || `图层 ${this.doc.layers.length + 1}`,
|
|
960
|
+
role,
|
|
961
|
+
groupId,
|
|
588
962
|
visible: true,
|
|
589
|
-
opacity: 1,
|
|
590
|
-
blend
|
|
963
|
+
opacity: opts.opacity === undefined ? 1 : clamp01(opts.opacity),
|
|
964
|
+
blend,
|
|
965
|
+
clipTo: typeof opts.clipTo === "string" && opts.clipTo ? opts.clipTo : null,
|
|
966
|
+
lockAlpha: opts.lockAlpha === true,
|
|
967
|
+
hue: Number.isFinite(hueNum) ? Math.max(-180, Math.min(180, Math.round(hueNum))) : 0,
|
|
968
|
+
grade: opts.grade && typeof opts.grade === "object" ? opts.grade : undefined,
|
|
969
|
+
locked: opts.locked === true,
|
|
591
970
|
strokes: [],
|
|
592
971
|
};
|
|
593
|
-
this.
|
|
972
|
+
this.insertOrdered(layer);
|
|
973
|
+
// index 给的是组内第几位(0=组内最底),把默认的 role 落位覆盖掉
|
|
974
|
+
if (opts.index !== undefined && opts.index !== null && Number.isFinite(Number(opts.index))) {
|
|
975
|
+
const layers = this.doc.layers;
|
|
976
|
+
const start = layers.findIndex((l) => l.groupId === layer.groupId);
|
|
977
|
+
let end = start;
|
|
978
|
+
while (end < layers.length && layers[end].groupId === layer.groupId) end += 1;
|
|
979
|
+
layers.splice(layers.indexOf(layer), 1);
|
|
980
|
+
const at = Math.max(start, Math.min(end - 1, start + Math.max(0, Math.round(Number(opts.index)))));
|
|
981
|
+
layers.splice(at, 0, layer);
|
|
982
|
+
}
|
|
594
983
|
this.doc.activeLayer = layer.id;
|
|
595
984
|
this.bump();
|
|
596
985
|
return layer;
|
|
@@ -602,8 +991,31 @@ class Document {
|
|
|
602
991
|
if (typeof patch.name === "string" && patch.name.trim()) layer.name = patch.name.trim().slice(0, 40);
|
|
603
992
|
if (patch.visible !== undefined) layer.visible = patch.visible !== false;
|
|
604
993
|
if (patch.opacity !== undefined) layer.opacity = clamp01(patch.opacity);
|
|
605
|
-
if (patch.blend !== undefined) layer.blend = patch.blend
|
|
994
|
+
if (patch.blend !== undefined) layer.blend = BLEND_MODES.includes(patch.blend) ? patch.blend : "normal";
|
|
606
995
|
if (patch.locked !== undefined) layer.locked = patch.locked === true;
|
|
996
|
+
if (patch.role !== undefined && ROLES.includes(patch.role)) {
|
|
997
|
+
layer.role = patch.role;
|
|
998
|
+
// 骨架组跟着 role 走;自定义组是用户自己归的类,不被 role 顶掉
|
|
999
|
+
const current = this.group(layer.groupId);
|
|
1000
|
+
if (!current || current.kind !== "custom") layer.groupId = `g_${groupOfRole(patch.role)}`;
|
|
1001
|
+
this.doc.layers = this.doc.layers.filter((l) => l !== layer);
|
|
1002
|
+
this.insertOrdered(layer);
|
|
1003
|
+
}
|
|
1004
|
+
if (patch.groupId !== undefined) {
|
|
1005
|
+
const target = this.group(patch.groupId);
|
|
1006
|
+
if (target && target.id !== layer.groupId) {
|
|
1007
|
+
this.doc.layers = this.doc.layers.filter((l) => l !== layer);
|
|
1008
|
+
layer.groupId = target.id;
|
|
1009
|
+
this.insertOrdered(layer);
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
if (patch.clipTo !== undefined) layer.clipTo = typeof patch.clipTo === "string" && patch.clipTo ? patch.clipTo : null;
|
|
1013
|
+
if (patch.lockAlpha !== undefined) layer.lockAlpha = patch.lockAlpha === true;
|
|
1014
|
+
if (patch.grade !== undefined && patch.grade && typeof patch.grade === "object") layer.grade = patch.grade;
|
|
1015
|
+
if (patch.hue !== undefined) {
|
|
1016
|
+
const hueNum = Number(patch.hue);
|
|
1017
|
+
layer.hue = Number.isFinite(hueNum) ? Math.max(-180, Math.min(180, Math.round(hueNum))) : 0;
|
|
1018
|
+
}
|
|
607
1019
|
if (patch.active === true) this.doc.activeLayer = layer.id;
|
|
608
1020
|
this.bump();
|
|
609
1021
|
return layer;
|
|
@@ -622,11 +1034,24 @@ class Document {
|
|
|
622
1034
|
append(strokes, layerRef) {
|
|
623
1035
|
const layer = layerRef ? this.ensureLayer(layerRef) : this.active();
|
|
624
1036
|
if (layer.locked === true) throw new Error(`图层「${layer.name}」被锁定,画不上去;要动它先 action=layer layerOp=set locked=false`);
|
|
1037
|
+
// 锁定透明像素:裁剪基线 = 落笔前的层内容(不能用落笔后的 alpha,会自举扩张)
|
|
1038
|
+
const baseline = layer.lockAlpha === true ? layer.strokes.slice() : null;
|
|
1039
|
+
if (baseline && baseline.length === 0 && strokes.length > 0) {
|
|
1040
|
+
throw new Error(`图层「${layer.name}」锁定了透明像素但本来就没有内容:先关掉 lockAlpha,铺一层底色再锁`);
|
|
1041
|
+
}
|
|
625
1042
|
const sel = this.doc.selection || null;
|
|
626
1043
|
let added = 0;
|
|
627
1044
|
for (const s of strokes) {
|
|
628
1045
|
// 有选区就只保留框内的点,一笔越界会被切成几段
|
|
629
|
-
|
|
1046
|
+
let parts = sel && s.mode !== "fill" ? clipPoints(s.points || [], sel) : [s.points];
|
|
1047
|
+
if (baseline) {
|
|
1048
|
+
if (s.mode === "fill") {
|
|
1049
|
+
const solid = (s.points || []).every((p) => pointInBaseline(baseline, Number(p[0]), Number(p[1])));
|
|
1050
|
+
parts = solid ? parts : [];
|
|
1051
|
+
} else {
|
|
1052
|
+
parts = parts.flatMap((points) => clipToBaseline(points || [], baseline));
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
630
1055
|
for (const points of parts) {
|
|
631
1056
|
if (!points || points.length < 2) continue;
|
|
632
1057
|
this.doc.seq += 1;
|
|
@@ -779,22 +1204,40 @@ class Document {
|
|
|
779
1204
|
const colors = new Set();
|
|
780
1205
|
let strokes = 0;
|
|
781
1206
|
let points = 0;
|
|
1207
|
+
const groups = (this.doc.groups || []).map((g) => ({
|
|
1208
|
+
id: g.id,
|
|
1209
|
+
name: g.name,
|
|
1210
|
+
kind: g.kind,
|
|
1211
|
+
visible: g.visible !== false,
|
|
1212
|
+
locked: g.locked === true,
|
|
1213
|
+
opacity: g.opacity === undefined ? 1 : g.opacity,
|
|
1214
|
+
collapsed: g.collapsed === true,
|
|
1215
|
+
}));
|
|
782
1216
|
const layers = this.doc.layers.map((l) => {
|
|
783
1217
|
strokes += l.strokes.length;
|
|
784
1218
|
points += l.strokes.reduce((n, s) => n + (s.points ? s.points.length : 0), 0);
|
|
785
1219
|
for (const s of l.strokes) colors.add(s.color);
|
|
1220
|
+
const ready = l.strokes.length > 0 || Boolean(l.image);
|
|
786
1221
|
return {
|
|
787
1222
|
id: l.id,
|
|
788
1223
|
name: l.name,
|
|
789
|
-
|
|
1224
|
+
role: l.role || "base",
|
|
1225
|
+
groupId: l.groupId || null,
|
|
1226
|
+
visible: l.visible !== false,
|
|
790
1227
|
opacity: l.opacity,
|
|
791
|
-
blend: l.blend,
|
|
1228
|
+
blend: l.blend || "normal",
|
|
1229
|
+
clipTo: l.clipTo || null,
|
|
1230
|
+
lockAlpha: l.lockAlpha === true,
|
|
1231
|
+
hue: l.hue || 0,
|
|
1232
|
+
grade: l.grade || null,
|
|
792
1233
|
locked: l.locked === true,
|
|
1234
|
+
ready,
|
|
793
1235
|
strokes: l.strokes.length,
|
|
794
1236
|
image: l.image ? { file: l.image.file, x: l.image.x, y: l.image.y, w: l.image.w, h: l.image.h } : null,
|
|
795
1237
|
};
|
|
796
1238
|
});
|
|
797
1239
|
return {
|
|
1240
|
+
version: this.doc.version || 3,
|
|
798
1241
|
width: this.doc.width,
|
|
799
1242
|
height: this.doc.height,
|
|
800
1243
|
background: this.doc.background,
|
|
@@ -804,6 +1247,7 @@ class Document {
|
|
|
804
1247
|
points,
|
|
805
1248
|
colors: [...colors].slice(0, 12),
|
|
806
1249
|
bounds: this.bounds(),
|
|
1250
|
+
groups,
|
|
807
1251
|
layers,
|
|
808
1252
|
selection: this.doc.selection || null,
|
|
809
1253
|
redo: (this.doc.redo || []).length,
|
|
@@ -1016,6 +1460,53 @@ function pointInPoly(x, y, pts) {
|
|
|
1016
1460
|
return inside;
|
|
1017
1461
|
}
|
|
1018
1462
|
|
|
1463
|
+
/** 点在一条笔迹的几何范围内(锁定透明像素时的近似裁剪)。 */
|
|
1464
|
+
function pointInStrokeGeometry(stroke, x, y) {
|
|
1465
|
+
if (!Array.isArray(stroke.points) || stroke.points.length === 0) return false;
|
|
1466
|
+
if (stroke.mode === "fill") {
|
|
1467
|
+
if (!pointInPoly(x, y, stroke.points)) return false;
|
|
1468
|
+
for (const hole of stroke.holes || []) if (pointInPoly(x, y, hole)) return false;
|
|
1469
|
+
return true;
|
|
1470
|
+
}
|
|
1471
|
+
const r = Math.max(1, (Number(stroke.size) || 8) / 2) + 1;
|
|
1472
|
+
const pts = stroke.points;
|
|
1473
|
+
if (pts.length === 1) return Math.hypot(x - pts[0][0], y - pts[0][1]) <= r;
|
|
1474
|
+
for (let i = 1; i < pts.length; i += 1) {
|
|
1475
|
+
const ax = Number(pts[i - 1][0]);
|
|
1476
|
+
const ay = Number(pts[i - 1][1]);
|
|
1477
|
+
const bx = Number(pts[i][0]);
|
|
1478
|
+
const by = Number(pts[i][1]);
|
|
1479
|
+
const dx = bx - ax;
|
|
1480
|
+
const dy = by - ay;
|
|
1481
|
+
const len2 = dx * dx + dy * dy;
|
|
1482
|
+
const t = len2 > 0 ? Math.max(0, Math.min(1, ((x - ax) * dx + (y - ay) * dy) / len2)) : 0;
|
|
1483
|
+
if (Math.hypot(x - (ax + dx * t), y - (ay + dy * t)) <= r) return true;
|
|
1484
|
+
}
|
|
1485
|
+
return false;
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
function pointInBaseline(baseline, x, y) {
|
|
1489
|
+
for (const stroke of baseline) if (pointInStrokeGeometry(stroke, x, y)) return true;
|
|
1490
|
+
return false;
|
|
1491
|
+
}
|
|
1492
|
+
|
|
1493
|
+
/** 把点序列裁成「落在基线笔迹里」的连续段。 */
|
|
1494
|
+
function clipToBaseline(points, baseline) {
|
|
1495
|
+
const runs = [];
|
|
1496
|
+
let cur = [];
|
|
1497
|
+
for (const p of points) {
|
|
1498
|
+
const x = Number(p[0]);
|
|
1499
|
+
const y = Number(p[1]);
|
|
1500
|
+
if (pointInBaseline(baseline, x, y)) cur.push(p);
|
|
1501
|
+
else {
|
|
1502
|
+
if (cur.length >= 2) runs.push(cur);
|
|
1503
|
+
cur = [];
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
if (cur.length >= 2) runs.push(cur);
|
|
1507
|
+
return runs;
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1019
1510
|
/** 这点是不是落在某块色块挖的洞里(洞是参考图的高光,不该往上涂)。 */
|
|
1020
1511
|
function inFillHole(doc, x, y) {
|
|
1021
1512
|
for (const layer of doc.layers || []) {
|
|
@@ -1086,10 +1577,16 @@ function layerDetails(docx) {
|
|
|
1086
1577
|
layers.push({
|
|
1087
1578
|
id: layer.id,
|
|
1088
1579
|
name: layer.name,
|
|
1580
|
+
role: layer.role || "base",
|
|
1581
|
+
groupId: layer.groupId || null,
|
|
1089
1582
|
kind: layer.image ? "image" : "draw",
|
|
1090
1583
|
visible: layer.visible !== false,
|
|
1091
1584
|
opacity: layer.opacity === undefined ? 1 : layer.opacity,
|
|
1092
1585
|
blend: layer.blend || "normal",
|
|
1586
|
+
clipTo: layer.clipTo || null,
|
|
1587
|
+
lockAlpha: layer.lockAlpha === true,
|
|
1588
|
+
hue: layer.hue || 0,
|
|
1589
|
+
grade: layer.grade || null,
|
|
1093
1590
|
locked: layer.locked === true,
|
|
1094
1591
|
strokes: (layer.strokes || []).length,
|
|
1095
1592
|
bbox: has ? { x: Math.round(minX), y: Math.round(minY), w: Math.round(maxX - minX), h: Math.round(maxY - minY) } : null,
|
|
@@ -1109,6 +1606,45 @@ function mirrorPoints(points, axis, width, height) {
|
|
|
1109
1606
|
});
|
|
1110
1607
|
}
|
|
1111
1608
|
|
|
1609
|
+
/**
|
|
1610
|
+
* 工具返回值必须是「无损 JSON」:DSH 会拒绝 undefined、NaN/Infinity、-0、类实例。
|
|
1611
|
+
* 画布坐标用 Math.round 时,-0.4 会变成 -0(JSON.stringify 又写成 0),
|
|
1612
|
+
* 于是 action=doc/view 这种纯读动作也会报「value is not lossless JSON」。
|
|
1613
|
+
* 这里在工具出口统一洗一遍,别让模型以为操作没发生。
|
|
1614
|
+
*/
|
|
1615
|
+
function jsonSafe(value, seen = new Set()) {
|
|
1616
|
+
if (value === null) return null;
|
|
1617
|
+
const type = typeof value;
|
|
1618
|
+
if (type === "number") {
|
|
1619
|
+
if (Object.is(value, -0)) return 0;
|
|
1620
|
+
return Number.isFinite(value) ? value : null;
|
|
1621
|
+
}
|
|
1622
|
+
if (type === "string" || type === "boolean") return value;
|
|
1623
|
+
if (type === "undefined" || type === "function" || type === "symbol") return undefined;
|
|
1624
|
+
if (type === "bigint") return value.toString();
|
|
1625
|
+
if (type !== "object") return null;
|
|
1626
|
+
if (seen.has(value)) return null;
|
|
1627
|
+
if (Array.isArray(value)) {
|
|
1628
|
+
seen.add(value);
|
|
1629
|
+
const out = value.map((item) => {
|
|
1630
|
+
const safe = jsonSafe(item, seen);
|
|
1631
|
+
return safe === undefined ? null : safe;
|
|
1632
|
+
});
|
|
1633
|
+
seen.delete(value);
|
|
1634
|
+
return out;
|
|
1635
|
+
}
|
|
1636
|
+
if (value instanceof Date) return value.toISOString();
|
|
1637
|
+
if (ArrayBuffer.isView(value)) return Array.from(value);
|
|
1638
|
+
seen.add(value);
|
|
1639
|
+
const out = {};
|
|
1640
|
+
for (const key of Object.keys(value)) {
|
|
1641
|
+
const safe = jsonSafe(value[key], seen);
|
|
1642
|
+
if (safe !== undefined) out[key] = safe;
|
|
1643
|
+
}
|
|
1644
|
+
seen.delete(value);
|
|
1645
|
+
return out;
|
|
1646
|
+
}
|
|
1647
|
+
|
|
1112
1648
|
function json(res, status, body) {
|
|
1113
1649
|
const text = JSON.stringify(body);
|
|
1114
1650
|
res.writeHead(status, {
|
|
@@ -1213,6 +1749,8 @@ export function apply(ctx, config = {}) {
|
|
|
1213
1749
|
bindError: null,
|
|
1214
1750
|
// 端点信息:GUI 端口每次重启都可能变,写进 endpoint.json 给脚本用
|
|
1215
1751
|
endpoint: null,
|
|
1752
|
+
// 正在大批落笔时的进度(/doc 里带出去,侧边面板据此画进度条,不用等全部写完才看见)
|
|
1753
|
+
painting: null,
|
|
1216
1754
|
// 版本自检:插件自己去 GitHub 看有没有新 Release,界面上给个提示
|
|
1217
1755
|
update: { checkedAt: null, latest: null, hasUpdate: false, url: null, error: null, enabled: config.updateCheck !== false },
|
|
1218
1756
|
};
|
|
@@ -1242,14 +1780,56 @@ export function apply(ctx, config = {}) {
|
|
|
1242
1780
|
jobStats.done += 1;
|
|
1243
1781
|
jobStats.headless += 1;
|
|
1244
1782
|
jobStats.last = { kind, at: Date.now(), mode: "host" };
|
|
1245
|
-
return out;
|
|
1783
|
+
return { ...out, computedBy: "host" };
|
|
1246
1784
|
} catch (err) {
|
|
1247
1785
|
jobStats.failed += 1;
|
|
1248
1786
|
return { ok: false, error: `宿主侧算 ${kind} 失败:${(err && err.message) || err}`, headless: true };
|
|
1249
1787
|
}
|
|
1250
1788
|
};
|
|
1251
1789
|
|
|
1252
|
-
|
|
1790
|
+
/** 让出一次事件循环:大批笔迹分块落盘时,前端 700ms 轮询才看得到中间状态。 */
|
|
1791
|
+
const yieldTick = () => new Promise((resolve) => setImmediate(resolve));
|
|
1792
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
1793
|
+
|
|
1794
|
+
/**
|
|
1795
|
+
* 分块追加:一次 append 2000 笔会在最后一次性 bump,界面上就是「卡住 → 突然全出来」。
|
|
1796
|
+
* 这里按 120 笔一段写,每段都 bump 一次,并把自己的进度记进 state.painting(/doc 里带出去)。
|
|
1797
|
+
*
|
|
1798
|
+
* 有人开着面板时还要慢放:只 yieldTick 的话 1 万笔在几十毫秒内就全落完,
|
|
1799
|
+
* 700ms 的轮询只能看到最终态,等于没过程。所以按「整批放完约 2 秒」反算每块之间的停顿,
|
|
1800
|
+
* 单块 15~180ms;没人看就全速,不白等。
|
|
1801
|
+
*/
|
|
1802
|
+
const appendInChunks = async (strokes, layerRef, chunkSize = 120) => {
|
|
1803
|
+
const total = strokes.length;
|
|
1804
|
+
const chunks = Math.ceil(total / chunkSize);
|
|
1805
|
+
const showProgress = total > chunkSize;
|
|
1806
|
+
const pause = showProgress && panelLive()
|
|
1807
|
+
? Math.max(15, Math.min(180, Math.round(2000 / chunks)))
|
|
1808
|
+
: 0;
|
|
1809
|
+
let layer = null;
|
|
1810
|
+
let done = 0;
|
|
1811
|
+
for (let i = 0; i < total; i += chunkSize) {
|
|
1812
|
+
const part = strokes.slice(i, i + chunkSize);
|
|
1813
|
+
layer = docs.append(part, layer ? layer.id : layerRef);
|
|
1814
|
+
done += part.length;
|
|
1815
|
+
state.painting = showProgress
|
|
1816
|
+
? { action: "append", done, total, layer: layer.name, at: Date.now() }
|
|
1817
|
+
: null;
|
|
1818
|
+
if (showProgress) {
|
|
1819
|
+
if (pause > 0) await sleep(pause);
|
|
1820
|
+
else await yieldTick();
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
state.painting = null;
|
|
1824
|
+
return layer;
|
|
1825
|
+
};
|
|
1826
|
+
|
|
1827
|
+
const runPixelJob = (kind, params = {}, timeoutMs, forceHeadless = false) => new Promise((resolve) => {
|
|
1828
|
+
if (forceHeadless) {
|
|
1829
|
+
// paint / posterize 这类新管线只在宿主侧有一份实现:不交给浏览器,避免两套算法不一致
|
|
1830
|
+
runHeadlessPixel(kind, params).then(resolve);
|
|
1831
|
+
return;
|
|
1832
|
+
}
|
|
1253
1833
|
if (config.headless !== false && HEADLESS_KINDS.has(kind) && !panelLive()) {
|
|
1254
1834
|
// 没有面板 → 直接宿主侧算,不再干等 5 秒超时
|
|
1255
1835
|
runHeadlessPixel(kind, params).then((out) => {
|
|
@@ -1297,11 +1877,61 @@ export function apply(ctx, config = {}) {
|
|
|
1297
1877
|
if (payload && payload.ok) jobStats.done += 1;
|
|
1298
1878
|
else if (payload && payload.error === "timeout") jobStats.timeout += 1;
|
|
1299
1879
|
else jobStats.failed += 1;
|
|
1300
|
-
jobStats.last = { id: job.id, kind: job.kind, at: Date.now() };
|
|
1301
|
-
|
|
1880
|
+
jobStats.last = { id: job.id, kind: job.kind, at: Date.now(), mode: "panel" };
|
|
1881
|
+
const result = payload || { ok: false, error: "前端没有回结果" };
|
|
1882
|
+
if (result.ok && !result.computedBy) result.computedBy = "panel";
|
|
1883
|
+
job.settle(result);
|
|
1302
1884
|
return true;
|
|
1303
1885
|
};
|
|
1304
1886
|
|
|
1887
|
+
/**
|
|
1888
|
+
* 关层自检:逐层隐藏后和全图比,变化最大的层可能是「承载太多」;
|
|
1889
|
+
* 同时看 06 固有色覆盖率——没铺到 85% 就提示先别进成稿。
|
|
1890
|
+
*/
|
|
1891
|
+
const checkLayers = async () => {
|
|
1892
|
+
const { rasterDoc } = await import("./pixels.js");
|
|
1893
|
+
const resolve = (file) => path.resolve(dir, file);
|
|
1894
|
+
const doc = docs.doc;
|
|
1895
|
+
const artDoc = { ...doc, layers: (doc.layers || []).filter((l) => !l.image) };
|
|
1896
|
+
const total = (doc.width || 1024) * (doc.height || 1024);
|
|
1897
|
+
const full = await rasterDoc(artDoc, { resolve });
|
|
1898
|
+
const rows = [];
|
|
1899
|
+
for (const layer of artDoc.layers || []) {
|
|
1900
|
+
if (layer.visible === false) continue;
|
|
1901
|
+
if (!(layer.strokes || []).length) continue;
|
|
1902
|
+
const alone = await rasterDoc({ ...artDoc, layers: [{ ...layer }] }, { resolve });
|
|
1903
|
+
let alphaPx = 0;
|
|
1904
|
+
for (let i = 3; i < alone.data.length; i += 4) if (alone.data[i] > 16) alphaPx += 1;
|
|
1905
|
+
const areaPct = Number(((alphaPx / total) * 100).toFixed(1));
|
|
1906
|
+
let impactPct = areaPct;
|
|
1907
|
+
if (areaPct >= 2) {
|
|
1908
|
+
const hidden = await rasterDoc({ ...artDoc, layers: artDoc.layers.map((l) => (l.id === layer.id ? { ...l, visible: false } : l)) }, { resolve });
|
|
1909
|
+
let diff = 0;
|
|
1910
|
+
for (let i = 0; i < full.data.length; i += 4) {
|
|
1911
|
+
if (Math.abs(full.data[i] - hidden.data[i]) + Math.abs(full.data[i + 1] - hidden.data[i + 1]) + Math.abs(full.data[i + 2] - hidden.data[i + 2]) + Math.abs(full.data[i + 3] - hidden.data[i + 3]) > 12) diff += 1;
|
|
1912
|
+
}
|
|
1913
|
+
impactPct = Number(((diff / total) * 100).toFixed(1));
|
|
1914
|
+
}
|
|
1915
|
+
rows.push({ id: layer.id, name: layer.name, role: layer.role || "base", areaPct, impactPct });
|
|
1916
|
+
}
|
|
1917
|
+
rows.sort((a, b) => b.impactPct - a.impactPct);
|
|
1918
|
+
const baseLayers = (artDoc.layers || []).filter((l) => l.role === "base" && l.visible !== false);
|
|
1919
|
+
let basePct = 0;
|
|
1920
|
+
if (baseLayers.length) {
|
|
1921
|
+
const baseSurf = await rasterDoc({ ...artDoc, layers: baseLayers }, { resolve });
|
|
1922
|
+
let basePx = 0;
|
|
1923
|
+
for (let i = 3; i < full.data.length; i += 4) if (full.data[i] > 16) basePx += 1;
|
|
1924
|
+
let covered = 0;
|
|
1925
|
+
for (let i = 3; i < baseSurf.data.length; i += 4) if (baseSurf.data[i] > 16) covered += 1;
|
|
1926
|
+
basePct = basePx ? Number(((covered / basePx) * 100).toFixed(1)) : 0;
|
|
1927
|
+
}
|
|
1928
|
+
const warnings = [];
|
|
1929
|
+
for (const row of rows) if (row.impactPct > 35) warnings.push(`「${row.name}」关掉后画面变化 ${row.impactPct}%:这层承载太多,建议拆`);
|
|
1930
|
+
if (basePct > 0 && basePct < 85) warnings.push(`固有色只盖住 ${basePct}% 的画面:先补 06,再进高光/纹理`);
|
|
1931
|
+
if (rows.length > 0 && rows[0].impactPct > 60) warnings.push(`「${rows[0].name}」是画面主体,删/关前先 snapshot`);
|
|
1932
|
+
return { ok: true, baseCoveragePct: basePct, layers: rows, warnings };
|
|
1933
|
+
};
|
|
1934
|
+
|
|
1305
1935
|
/** 前端回传的 PNG dataURL 落盘,返回可给 read_image 的绝对路径。 */
|
|
1306
1936
|
const writePng = (dataUrl, prefix) => {
|
|
1307
1937
|
const m = /^data:image\/png;base64,(.+)$/.exec(String(dataUrl || ""));
|
|
@@ -1555,7 +2185,16 @@ export function apply(ctx, config = {}) {
|
|
|
1555
2185
|
if (typeof tick.unref === "function") tick.unref();
|
|
1556
2186
|
}
|
|
1557
2187
|
}
|
|
1558
|
-
return {
|
|
2188
|
+
return {
|
|
2189
|
+
ok: true,
|
|
2190
|
+
sessionId: id,
|
|
2191
|
+
bound: didBind,
|
|
2192
|
+
pending: !didBind,
|
|
2193
|
+
variant: meta.variant || null,
|
|
2194
|
+
note: didBind
|
|
2195
|
+
? "已绑定:paint_canvas 会出现在**下一轮**工具表里(运行中的 agent 不会动态拿到新工具)。这一轮如果还看不见,继续用 /canvas-api/*,或让用户再发一条消息。"
|
|
2196
|
+
: "还没绑定:先看 /diagnostics 的 scope.bound 与 tools.bindError,期间用 /canvas-api/* 顶一下。",
|
|
2197
|
+
};
|
|
1559
2198
|
};
|
|
1560
2199
|
|
|
1561
2200
|
/** 前端关掉画界时调用:留 15 秒宽限,切标签时不会来回解绑/重绑。 */
|
|
@@ -1714,6 +2353,33 @@ export function apply(ctx, config = {}) {
|
|
|
1714
2353
|
}
|
|
1715
2354
|
return;
|
|
1716
2355
|
}
|
|
2356
|
+
// 关层自检:逐层隐藏 diff + 06 覆盖率,结果给面板/工具
|
|
2357
|
+
if (route === "/check" && req.method === "GET") {
|
|
2358
|
+
try {
|
|
2359
|
+
const result = await checkLayers();
|
|
2360
|
+
json(res, 200, result);
|
|
2361
|
+
} catch (err) {
|
|
2362
|
+
json(res, 500, { ok: false, error: String((err && err.message) || err) });
|
|
2363
|
+
}
|
|
2364
|
+
return;
|
|
2365
|
+
}
|
|
2366
|
+
// 绕过工具层直接跑宿主像素引擎(工具这一轮还没挂上时用;返回结果,不落画布)。
|
|
2367
|
+
// POST {kind:"copy", params:{style:"paint", ...}} / {kind:"posterize", ...}
|
|
2368
|
+
if (route === "/pixel" && req.method === "POST") {
|
|
2369
|
+
try {
|
|
2370
|
+
const body = JSON.parse((await readBody(req)) || "{}");
|
|
2371
|
+
const kind = String(body.kind || "").trim();
|
|
2372
|
+
if (!HEADLESS_KINDS.has(kind)) {
|
|
2373
|
+
json(res, 400, { ok: false, error: `不支持的像素任务:${kind || "(空)"}(可用:${[...HEADLESS_KINDS].join(" / ")})` });
|
|
2374
|
+
return;
|
|
2375
|
+
}
|
|
2376
|
+
const out = await runHeadlessPixel(kind, body.params || body.args || {});
|
|
2377
|
+
json(res, 200, { ok: Boolean(out && out.ok), ...(out || {}) });
|
|
2378
|
+
} catch (err) {
|
|
2379
|
+
json(res, 500, { ok: false, error: String((err && err.message) || err) });
|
|
2380
|
+
}
|
|
2381
|
+
return;
|
|
2382
|
+
}
|
|
1717
2383
|
if (route === "/doc" && req.method === "GET") {
|
|
1718
2384
|
json(res, 200, {
|
|
1719
2385
|
ok: true,
|
|
@@ -1722,6 +2388,7 @@ export function apply(ctx, config = {}) {
|
|
|
1722
2388
|
revision: docs.revision,
|
|
1723
2389
|
doc: { ...docs.doc, revision: docs.revision },
|
|
1724
2390
|
update: state.update,
|
|
2391
|
+
painting: state.painting,
|
|
1725
2392
|
version: localVersion,
|
|
1726
2393
|
pixelJobs: jobs.size,
|
|
1727
2394
|
});
|
|
@@ -1824,11 +2491,14 @@ export function apply(ctx, config = {}) {
|
|
|
1824
2491
|
color: typeof s.color === "string" ? s.color : "#111111",
|
|
1825
2492
|
size: Math.max(1, Math.min(400, Number(s.size) || 8)),
|
|
1826
2493
|
opacity: s.opacity === undefined ? 1 : Math.max(0.02, Math.min(1, Number(s.opacity))),
|
|
1827
|
-
mode: s.mode === "eraser" ? "eraser" : "brush",
|
|
2494
|
+
mode: s.mode === "eraser" ? "eraser" : (s.mode === "fill" ? "fill" : "brush"),
|
|
1828
2495
|
brush: s.brush,
|
|
1829
2496
|
taper: s.taper === true,
|
|
1830
2497
|
minSize: s.minSize,
|
|
1831
2498
|
points: normalizePoints(s.points, docs.doc.width, docs.doc.height),
|
|
2499
|
+
holes: Array.isArray(s.holes) && s.holes.length
|
|
2500
|
+
? s.holes.map((hole) => normalizePoints(hole, docs.doc.width, docs.doc.height))
|
|
2501
|
+
: undefined,
|
|
1832
2502
|
}));
|
|
1833
2503
|
const layer = docs.append(normalized, body.layer);
|
|
1834
2504
|
json(res, 200, {
|
|
@@ -1853,9 +2523,28 @@ export function apply(ctx, config = {}) {
|
|
|
1853
2523
|
} else if (body.op === "redo") {
|
|
1854
2524
|
result = docs.redo(Math.max(1, Math.round(Number(body.count) || 1)));
|
|
1855
2525
|
} else if (body.op === "layer.add") {
|
|
1856
|
-
result = docs.addLayer(body.name);
|
|
2526
|
+
result = docs.addLayer(body.name, body);
|
|
1857
2527
|
} else if (body.op === "layer.set") {
|
|
1858
2528
|
result = docs.updateLayer(body.id, body.patch || body);
|
|
2529
|
+
} else if (body.op === "layer.group") {
|
|
2530
|
+
result = docs.updateGroup(body.groupId || body.id, {
|
|
2531
|
+
visible: body.visible,
|
|
2532
|
+
opacity: body.opacity,
|
|
2533
|
+
name: body.name,
|
|
2534
|
+
collapsed: body.collapsed,
|
|
2535
|
+
locked: body.locked,
|
|
2536
|
+
color: body.color,
|
|
2537
|
+
});
|
|
2538
|
+
} else if (body.op === "group.add") {
|
|
2539
|
+
result = docs.addGroup(body);
|
|
2540
|
+
} else if (body.op === "group.remove") {
|
|
2541
|
+
result = docs.removeGroup(body.groupId || body.id, { force: body.force === true });
|
|
2542
|
+
} else if (body.op === "group.move") {
|
|
2543
|
+
result = docs.moveGroup(body.groupId || body.id, body.offset === undefined ? 1 : body.offset);
|
|
2544
|
+
} else if (body.op === "group.moveLayer") {
|
|
2545
|
+
result = docs.moveLayerToGroup(body.layer || body.layerId, body.groupId, body.index);
|
|
2546
|
+
} else if (body.op === "layer.move") {
|
|
2547
|
+
result = docs.moveLayer(body.layer || body.id, body.offset);
|
|
1859
2548
|
} else if (body.op === "layer.remove") {
|
|
1860
2549
|
result = docs.removeLayer(body.id);
|
|
1861
2550
|
} else {
|
|
@@ -2045,8 +2734,8 @@ export function apply(ctx, config = {}) {
|
|
|
2045
2734
|
properties: {
|
|
2046
2735
|
action: {
|
|
2047
2736
|
type: "string",
|
|
2048
|
-
enum: ["doc", "copy", "posterize", "fix", "fill", "draw", "view", "ref", "trace", "pick", "compare", "palette", "select", "snapshot", "restore", "undo", "redo", "clear", "layer", "import", "canvas", "export", "new"],
|
|
2049
|
-
description: "要执行的动作。new
|
|
2737
|
+
enum: ["doc", "check", "copy", "posterize", "fix", "fill", "draw", "view", "ref", "trace", "pick", "compare", "palette", "select", "snapshot", "restore", "undo", "redo", "clear", "layer", "group", "import", "canvas", "export", "new"],
|
|
2738
|
+
description: "要执行的动作。new 是另起一幅(可先保存当前、也可用图片建画布);group 管图层组(建组/删组/改组/移层)。",
|
|
2050
2739
|
},
|
|
2051
2740
|
points: {
|
|
2052
2741
|
type: "array",
|
|
@@ -2092,8 +2781,8 @@ export function apply(ctx, config = {}) {
|
|
|
2092
2781
|
},
|
|
2093
2782
|
layerOp: {
|
|
2094
2783
|
type: "string",
|
|
2095
|
-
enum: ["list", "add", "select", "set", "remove"],
|
|
2096
|
-
description: "layer: list 列图层(默认);add 新建;select 设为当前;set 改属性;remove
|
|
2784
|
+
enum: ["list", "add", "select", "set", "remove", "group"],
|
|
2785
|
+
description: "layer: list 列图层(默认);add 新建;select 设为当前;set 改属性;remove 删掉;group 改组(配合 groupId/visible/layerOpacity/name)。",
|
|
2097
2786
|
},
|
|
2098
2787
|
name: {
|
|
2099
2788
|
type: "string",
|
|
@@ -2106,8 +2795,44 @@ export function apply(ctx, config = {}) {
|
|
|
2106
2795
|
},
|
|
2107
2796
|
blend: {
|
|
2108
2797
|
type: "string",
|
|
2109
|
-
enum:
|
|
2110
|
-
description: "layer.set
|
|
2798
|
+
enum: BLEND_MODES,
|
|
2799
|
+
description: "layer.set / layer.add:混合模式 normal / multiply / screen / overlay / soft-light / linear-dodge。按 role 有默认值(shadow1/2、line=multiply、highlight=screen)。",
|
|
2800
|
+
},
|
|
2801
|
+
role: {
|
|
2802
|
+
type: "string",
|
|
2803
|
+
enum: ROLES,
|
|
2804
|
+
description: "layer.add / set:图层语义(v3 图层栈)。决定插入高度与默认混合模式;不填按层名猜。",
|
|
2805
|
+
},
|
|
2806
|
+
groupId: { type: "string", description: "layer.add / set:归到哪个组(g_ref/g_sketch/g_lineart/g_color/g_final),不填按 role。" },
|
|
2807
|
+
clipTo: { type: "string", description: "layer.set:剪贴到哪个层 id(显式 id,跨组也成立);渲染时用目标层 alpha 做掩码。" },
|
|
2808
|
+
lockAlpha: { type: "boolean", description: "layer.set:锁定透明像素(落笔不超出本层已有 alpha;追加笔迹时按基线裁剪)。" },
|
|
2809
|
+
hue: { type: "number", description: "layer.set:该层色相偏移 -180~180 度,只影响这一层。" },
|
|
2810
|
+
grade: { type: "object", additionalProperties: true, description: "layer.set(role=grade):调色参数 {brightness -1..1, contrast 0..3, saturation 0..3, hue -180..180}。" },
|
|
2811
|
+
collapsed: { type: "boolean", description: "layer group:组是否折叠显示。" },
|
|
2812
|
+
groupOp: {
|
|
2813
|
+
type: "string",
|
|
2814
|
+
enum: ["list", "add", "set", "remove", "move", "moveLayer"],
|
|
2815
|
+
description: "group: list 列组(默认);add 新建组;set 改组属性;remove 删组;move 组上移/下移;moveLayer 把层移进组(配 layer + groupId + index)。",
|
|
2816
|
+
},
|
|
2817
|
+
kind: {
|
|
2818
|
+
type: "string",
|
|
2819
|
+
description: "group.add:组类型 ref/sketch/lineart/color/final 之一,留空就是自定义组。",
|
|
2820
|
+
},
|
|
2821
|
+
index: {
|
|
2822
|
+
type: "number",
|
|
2823
|
+
description: "group.moveLayer / layer.add:组内第几位,0 是组内最底。",
|
|
2824
|
+
},
|
|
2825
|
+
offset: {
|
|
2826
|
+
type: "number",
|
|
2827
|
+
description: "group.move:+1 上移(更靠面)、-1 下移(更靠底)。",
|
|
2828
|
+
},
|
|
2829
|
+
force: {
|
|
2830
|
+
type: "boolean",
|
|
2831
|
+
description: "group.remove:组里还有层时,先把层并到相邻组再删。",
|
|
2832
|
+
},
|
|
2833
|
+
after: {
|
|
2834
|
+
type: "string",
|
|
2835
|
+
description: "group.add:插到这个组之后;不填就压最顶。",
|
|
2111
2836
|
},
|
|
2112
2837
|
path: {
|
|
2113
2838
|
type: "string",
|
|
@@ -2184,14 +2909,26 @@ export function apply(ctx, config = {}) {
|
|
|
2184
2909
|
fitStep: { type: "number", description: "trace / copy: 拟合后采样间距(像素),默认 3。小一点更贴原线,点也更多。" },
|
|
2185
2910
|
style: {
|
|
2186
2911
|
type: "string",
|
|
2187
|
-
enum: ["lineart", "flat", "anime"],
|
|
2188
|
-
description: "copy: 复刻风格。lineart 只出线稿;flat 只出区域色块;anime
|
|
2912
|
+
enum: ["lineart", "flat", "anime", "paint"],
|
|
2913
|
+
description: "copy: 复刻风格。lineart 只出线稿;flat 只出区域色块;anime 出线稿+色块(默认);paint 完整 14 层栈——构图草稿/精线稿/线稿上色/闭塞线/固有色(拆 5 部件)/一级暗部/二级暗部/铺光/纹理/高光/镭射/氛围/调色,role 自动排 z 序与 blend;只在宿主侧算,有面板也一样。",
|
|
2189
2914
|
},
|
|
2915
|
+
paintStep: { type: "number", description: "copy style=paint: 取样与笔距的基准(像素),默认 10。越小笔触越密,但塑形/过渡层会多。" },
|
|
2916
|
+
maxStrokes: { type: "number", description: "copy style=paint: 总笔数上限,默认 4000。按一级暗部/二级暗部/线稿/高光/闭塞/铺光/纹理/镭射/氛围等权重分,改大就是真变多。" },
|
|
2917
|
+
paintStages: { type: "string", description: "copy style=paint: 只跑其中几步,逗号分隔 base,block,blend,edge,accent,sketch,lineColor,occlusion,lightblock,texture,iridescent,atmosphere,grade(默认全跑)。例如只补轮廓 \"base,edge\";重跑某层前先清掉旧层。" },
|
|
2918
|
+
paintColors: { type: "number", description: "copy style=paint: 铺底层并成几档大色,默认 8(3~12)。中间调多给几档,脸/手/腰带才不会被并掉。" },
|
|
2919
|
+
paintBlocks: { type: "number", description: "copy style=paint: 铺底初始块数,默认 120。不足 95% 覆盖率会按面积自动补,最多 400 块;白背景按四边连通域整块剔除。" },
|
|
2920
|
+
paintBaseMinArea: { type: "number", description: "copy style=paint: 铺底最小色块像素,默认画布面积/6000(1080×1440 约 259);脸、手、腰带这些中小色块要留下来。" },
|
|
2921
|
+
paintEdgeMinLength: { type: "number", description: "copy style=paint: 收边用色阶边界折线的最短长度,默认 24。" },
|
|
2922
|
+
paintEdgeMaxLines: { type: "number", description: "copy style=paint: 收边最多取几条色阶边界折线,默认 1800。" },
|
|
2923
|
+
paintPasses: { type: "number", description: "旧参数,已被 paintStages 取代:1 等价于 paintStages=\"base,block\";保留兼容。" },
|
|
2924
|
+
paintMinLum: { type: "number", description: "copy style=paint: 亮度达到这个值就当白底,默认 246。浅色衣袍调低一点(236)。" },
|
|
2925
|
+
lineart: { type: "boolean", description: "旧参数,paint 的「收边」已经是独立一层,不再额外叠线稿;保留兼容。" },
|
|
2190
2926
|
colors: { type: "number", description: "copy / posterize / palette: 主色档数 2~12(copy 默认 6,posterize 默认 8)。彩稿要火、金、肤这些颜色都出来,给 10~12。" },
|
|
2191
2927
|
minFill: { type: "number", description: "copy: 小于多少像素的闭合区域不填色,默认 320。" },
|
|
2192
2928
|
target: { type: "number", description: "fix: 目标覆盖率百分比,默认 90。到了就停。" },
|
|
2193
2929
|
maxRounds: { type: "number", description: "fix: 最多迭代几轮,默认 3(上限 5)。" },
|
|
2194
2930
|
refLayer: { type: "string", description: "copy / fix: 用哪一个图片层当参考图,默认第一张可见图片层。" },
|
|
2931
|
+
forceHeadless: { type: "boolean", description: "像素任务强制走宿主侧引擎(copy style=paint / posterize 本来就固定走宿主)。回报里的 computedBy 写 host 或 panel,两条路径行为不一致时用这个对比排查。" },
|
|
2195
2932
|
mode: {
|
|
2196
2933
|
type: "string",
|
|
2197
2934
|
enum: ["edge", "center"],
|
|
@@ -2218,9 +2955,10 @@ export function apply(ctx, config = {}) {
|
|
|
2218
2955
|
render: (_args, value) => [{ type: "text", text: JSON.stringify(value, null, 2) }],
|
|
2219
2956
|
},
|
|
2220
2957
|
async execute(args) {
|
|
2221
|
-
const action = args && args.action;
|
|
2222
2958
|
docs.syncFromDisk();
|
|
2223
2959
|
try {
|
|
2960
|
+
return jsonSafe(await (async () => {
|
|
2961
|
+
const action = args && args.action;
|
|
2224
2962
|
switch (action) {
|
|
2225
2963
|
case "new": {
|
|
2226
2964
|
let savedPath = null;
|
|
@@ -2274,6 +3012,8 @@ export function apply(ctx, config = {}) {
|
|
|
2274
3012
|
}
|
|
2275
3013
|
case "doc":
|
|
2276
3014
|
return { ok: true, ...docs.summary(), dir };
|
|
3015
|
+
case "check":
|
|
3016
|
+
return { ...(await checkLayers()), revision: docs.revision };
|
|
2277
3017
|
case "draw": {
|
|
2278
3018
|
const W = docs.doc.width;
|
|
2279
3019
|
const H = docs.doc.height;
|
|
@@ -2313,7 +3053,7 @@ export function apply(ctx, config = {}) {
|
|
|
2313
3053
|
// 镜像:一笔画两边(对称复刻人像/建筑)
|
|
2314
3054
|
const axis = args.mirror === "x" || args.mirror === "y" ? args.mirror : null;
|
|
2315
3055
|
const strokes = axis ? list.concat(list.map((s) => ({ ...s, points: mirrorPoints(s.points, axis, W, H) }))) : list;
|
|
2316
|
-
const layer =
|
|
3056
|
+
const layer = await appendInChunks(strokes, args.layer);
|
|
2317
3057
|
return {
|
|
2318
3058
|
ok: true,
|
|
2319
3059
|
revision: docs.revision,
|
|
@@ -2330,8 +3070,18 @@ export function apply(ctx, config = {}) {
|
|
|
2330
3070
|
return { ok: true, revision: docs.revision, active: docs.doc.activeLayer, layers: docs.summary().layers };
|
|
2331
3071
|
}
|
|
2332
3072
|
if (op === "add") {
|
|
2333
|
-
const layer = docs.addLayer(args.name
|
|
2334
|
-
|
|
3073
|
+
const layer = docs.addLayer(args.name, {
|
|
3074
|
+
role: args.role,
|
|
3075
|
+
groupId: args.groupId,
|
|
3076
|
+
blend: args.blend,
|
|
3077
|
+
clipTo: args.clipTo,
|
|
3078
|
+
lockAlpha: args.lockAlpha,
|
|
3079
|
+
hue: args.hue,
|
|
3080
|
+
opacity: args.layerOpacity,
|
|
3081
|
+
locked: args.locked,
|
|
3082
|
+
index: args.index,
|
|
3083
|
+
});
|
|
3084
|
+
return { ok: true, revision: docs.revision, layer: { id: layer.id, name: layer.name, role: layer.role, groupId: layer.groupId, blend: layer.blend }, layers: docs.summary().layers };
|
|
2335
3085
|
}
|
|
2336
3086
|
if (op === "select") {
|
|
2337
3087
|
const layer = docs.layer(target);
|
|
@@ -2347,6 +3097,11 @@ export function apply(ctx, config = {}) {
|
|
|
2347
3097
|
if (args.layerOpacity !== undefined) patch.opacity = args.layerOpacity;
|
|
2348
3098
|
if (args.blend !== undefined) patch.blend = args.blend;
|
|
2349
3099
|
if (args.locked !== undefined) patch.locked = args.locked === true;
|
|
3100
|
+
if (args.role !== undefined) patch.role = args.role;
|
|
3101
|
+
if (args.groupId !== undefined) patch.groupId = args.groupId;
|
|
3102
|
+
if (args.clipTo !== undefined) patch.clipTo = args.clipTo;
|
|
3103
|
+
if (args.lockAlpha !== undefined) patch.lockAlpha = args.lockAlpha === true;
|
|
3104
|
+
if (args.hue !== undefined) patch.hue = args.hue;
|
|
2350
3105
|
const layer = docs.updateLayer(target, patch);
|
|
2351
3106
|
return {
|
|
2352
3107
|
ok: true,
|
|
@@ -2354,20 +3109,96 @@ export function apply(ctx, config = {}) {
|
|
|
2354
3109
|
layer: {
|
|
2355
3110
|
id: layer.id,
|
|
2356
3111
|
name: layer.name,
|
|
3112
|
+
role: layer.role,
|
|
3113
|
+
groupId: layer.groupId,
|
|
2357
3114
|
visible: layer.visible,
|
|
2358
3115
|
opacity: layer.opacity,
|
|
2359
3116
|
blend: layer.blend,
|
|
3117
|
+
clipTo: layer.clipTo,
|
|
3118
|
+
lockAlpha: layer.lockAlpha,
|
|
3119
|
+
hue: layer.hue,
|
|
2360
3120
|
locked: layer.locked === true,
|
|
2361
3121
|
},
|
|
2362
3122
|
layers: docs.summary().layers,
|
|
2363
3123
|
};
|
|
2364
3124
|
}
|
|
3125
|
+
if (op === "group") {
|
|
3126
|
+
const want = args.groupId || args.id || args.layer;
|
|
3127
|
+
const group = docs.updateGroup(want, {
|
|
3128
|
+
visible: args.visible,
|
|
3129
|
+
opacity: args.layerOpacity,
|
|
3130
|
+
name: args.name,
|
|
3131
|
+
collapsed: args.collapsed,
|
|
3132
|
+
locked: args.locked,
|
|
3133
|
+
});
|
|
3134
|
+
return { ok: true, revision: docs.revision, group, groups: docs.summary().groups, layers: docs.summary().layers };
|
|
3135
|
+
}
|
|
2365
3136
|
if (op === "remove") {
|
|
2366
3137
|
const removed = docs.removeLayer(target);
|
|
2367
3138
|
return { ok: true, revision: docs.revision, removed, layers: docs.summary().layers };
|
|
2368
3139
|
}
|
|
2369
3140
|
throw new Error(`未知 layerOp: ${op}`);
|
|
2370
3141
|
}
|
|
3142
|
+
case "group": {
|
|
3143
|
+
const op = args.groupOp || "list";
|
|
3144
|
+
if (op === "list") {
|
|
3145
|
+
return {
|
|
3146
|
+
ok: true,
|
|
3147
|
+
revision: docs.revision,
|
|
3148
|
+
groups: docs.summary().groups.map((g) => ({
|
|
3149
|
+
...g,
|
|
3150
|
+
layers: docs.doc.layers.filter((l) => l.groupId === g.id).map((l) => ({ id: l.id, name: l.name, role: l.role })),
|
|
3151
|
+
})),
|
|
3152
|
+
layers: docs.summary().layers,
|
|
3153
|
+
};
|
|
3154
|
+
}
|
|
3155
|
+
if (op === "add") {
|
|
3156
|
+
const group = docs.addGroup({
|
|
3157
|
+
name: args.name,
|
|
3158
|
+
kind: args.kind,
|
|
3159
|
+
color: args.color,
|
|
3160
|
+
after: args.after !== undefined ? args.after : args.groupId,
|
|
3161
|
+
opacity: args.opacity !== undefined ? args.opacity : args.layerOpacity,
|
|
3162
|
+
visible: args.visible,
|
|
3163
|
+
locked: args.locked,
|
|
3164
|
+
});
|
|
3165
|
+
return { ok: true, revision: docs.revision, group, groups: docs.summary().groups };
|
|
3166
|
+
}
|
|
3167
|
+
if (op === "set") {
|
|
3168
|
+
const group = docs.updateGroup(args.groupId || args.id || args.name, {
|
|
3169
|
+
name: args.name,
|
|
3170
|
+
visible: args.visible,
|
|
3171
|
+
opacity: args.opacity !== undefined ? args.opacity : args.layerOpacity,
|
|
3172
|
+
locked: args.locked,
|
|
3173
|
+
collapsed: args.collapsed,
|
|
3174
|
+
color: args.color,
|
|
3175
|
+
});
|
|
3176
|
+
return { ok: true, revision: docs.revision, group, groups: docs.summary().groups };
|
|
3177
|
+
}
|
|
3178
|
+
if (op === "remove") {
|
|
3179
|
+
const removed = docs.removeGroup(args.groupId || args.id || args.name, { force: args.force === true });
|
|
3180
|
+
return { ok: true, revision: docs.revision, ...removed, groups: docs.summary().groups, layers: docs.summary().layers };
|
|
3181
|
+
}
|
|
3182
|
+
if (op === "move") {
|
|
3183
|
+
const moved = docs.moveGroup(args.groupId || args.id || args.name, args.offset === undefined ? 1 : args.offset);
|
|
3184
|
+
return { ok: true, revision: docs.revision, ...moved, groups: docs.summary().groups, layers: docs.summary().layers };
|
|
3185
|
+
}
|
|
3186
|
+
if (op === "moveLayer") {
|
|
3187
|
+
const moved = docs.moveLayerToGroup(
|
|
3188
|
+
args.layer !== undefined ? args.layer : args.id,
|
|
3189
|
+
args.groupId || args.name,
|
|
3190
|
+
args.index,
|
|
3191
|
+
);
|
|
3192
|
+
return {
|
|
3193
|
+
ok: true,
|
|
3194
|
+
revision: docs.revision,
|
|
3195
|
+
layer: { id: moved.id, name: moved.name, groupId: moved.groupId },
|
|
3196
|
+
groups: docs.summary().groups,
|
|
3197
|
+
layers: docs.summary().layers,
|
|
3198
|
+
};
|
|
3199
|
+
}
|
|
3200
|
+
throw new Error(`未知 groupOp: ${op}`);
|
|
3201
|
+
}
|
|
2371
3202
|
case "import": {
|
|
2372
3203
|
let buffer = null;
|
|
2373
3204
|
if (typeof args.path === "string" && args.path.trim()) {
|
|
@@ -2489,7 +3320,7 @@ export function apply(ctx, config = {}) {
|
|
|
2489
3320
|
rect,
|
|
2490
3321
|
zoom: args.zoom === undefined ? 1 : Number(args.zoom),
|
|
2491
3322
|
layer: args.layer === undefined ? null : args.layer,
|
|
2492
|
-
});
|
|
3323
|
+
}, undefined, args.forceHeadless === true);
|
|
2493
3324
|
if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
|
|
2494
3325
|
const file = writePng(job.dataUrl, "view");
|
|
2495
3326
|
return {
|
|
@@ -2549,7 +3380,7 @@ export function apply(ctx, config = {}) {
|
|
|
2549
3380
|
: "这就是参考图原文件,用 read_image 直接看;要看某一块就带 rect=[x,y,w,h]。",
|
|
2550
3381
|
};
|
|
2551
3382
|
}
|
|
2552
|
-
const job = await runPixelJob("ref", { rect, zoom: args.zoom === undefined ? 1 : Number(args.zoom), layer: target.id });
|
|
3383
|
+
const job = await runPixelJob("ref", { rect, zoom: args.zoom === undefined ? 1 : Number(args.zoom), layer: target.id }, undefined, args.forceHeadless === true);
|
|
2553
3384
|
if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
|
|
2554
3385
|
const file = writePng(job.dataUrl, "ref");
|
|
2555
3386
|
return {
|
|
@@ -2572,7 +3403,7 @@ export function apply(ctx, config = {}) {
|
|
|
2572
3403
|
y: Math.round(Number(args.y)),
|
|
2573
3404
|
rect,
|
|
2574
3405
|
color: args.color || null,
|
|
2575
|
-
}, PIXEL_TIMEOUT_MS * 3);
|
|
3406
|
+
}, PIXEL_TIMEOUT_MS * 3, args.forceHeadless === true);
|
|
2576
3407
|
if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
|
|
2577
3408
|
if (!job.polygons || job.polygons.length === 0) throw new Error("这个种子点没围出可填的区域:先有线稿边界,或者换一个点");
|
|
2578
3409
|
const want = String(args.fillLayer || args.layer || "色块").trim();
|
|
@@ -2614,8 +3445,15 @@ export function apply(ctx, config = {}) {
|
|
|
2614
3445
|
throw new Error("select 需要 rect=[x,y,w,h]、points=[[x,y]…](套索),或 clearSelection=true 清掉");
|
|
2615
3446
|
}
|
|
2616
3447
|
case "copy": {
|
|
2617
|
-
const style = args.style === "lineart" || args.style === "flat" ? args.style : "anime";
|
|
3448
|
+
const style = args.style === "lineart" || args.style === "flat" || args.style === "paint" ? args.style : "anime";
|
|
2618
3449
|
const rect = parseRect(args.rect, docs.doc.width, docs.doc.height);
|
|
3450
|
+
const isPaint = style === "paint";
|
|
3451
|
+
// paint 是五步管线,只在宿主侧算:有面板也走宿主,保证「有面板/没面板」同一套层数和笔法。
|
|
3452
|
+
const paintStages = isPaint
|
|
3453
|
+
? (typeof args.paintStages === "string" && args.paintStages.trim()
|
|
3454
|
+
? args.paintStages
|
|
3455
|
+
: (args.paintPasses === 1 ? "base,block" : undefined))
|
|
3456
|
+
: undefined;
|
|
2619
3457
|
const job = await runPixelJob("copy", {
|
|
2620
3458
|
rect,
|
|
2621
3459
|
style,
|
|
@@ -2630,7 +3468,17 @@ export function apply(ctx, config = {}) {
|
|
|
2630
3468
|
fit: args.fit === undefined ? true : args.fit === true,
|
|
2631
3469
|
fitStep: args.fitStep,
|
|
2632
3470
|
mode: args.mode,
|
|
2633
|
-
|
|
3471
|
+
paintStep: args.paintStep,
|
|
3472
|
+
maxStrokes: args.maxStrokes,
|
|
3473
|
+
paintPasses: args.paintPasses,
|
|
3474
|
+
paintMinLum: args.paintMinLum,
|
|
3475
|
+
paintStages,
|
|
3476
|
+
paintColors: args.paintColors,
|
|
3477
|
+
paintBlocks: args.paintBlocks,
|
|
3478
|
+
paintBaseMinArea: args.paintBaseMinArea,
|
|
3479
|
+
paintEdgeMinLength: args.paintEdgeMinLength,
|
|
3480
|
+
paintEdgeMaxLines: args.paintEdgeMaxLines,
|
|
3481
|
+
}, PIXEL_TIMEOUT_MS * 3, isPaint);
|
|
2634
3482
|
if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
|
|
2635
3483
|
const created = [];
|
|
2636
3484
|
// 同名空层直接复用,避免反复 copy 堆出一串「线稿 2」「色块 3」
|
|
@@ -2640,16 +3488,102 @@ export function apply(ctx, config = {}) {
|
|
|
2640
3488
|
if (found && !found.locked && !found.image && (found.strokes || []).length === 0) return found;
|
|
2641
3489
|
return docs.addLayer(want || undefined);
|
|
2642
3490
|
};
|
|
2643
|
-
//
|
|
2644
|
-
|
|
3491
|
+
// paint 五步 → v3 图层栈:按 role 找/建层,blend 由 role 决定;重跑先 snapshot 再清空
|
|
3492
|
+
const hasLine = Array.isArray(job.paintStages) && job.paintStages.some((s) => s.key === "edge");
|
|
3493
|
+
const pickStageLayer = (stage, nameOverride) => {
|
|
3494
|
+
const role = PAINT_STAGE_ROLE[stage.key] || "base";
|
|
3495
|
+
const want = nameOverride || PAINT_STAGE_NAME[stage.key] || stage.name || "图层";
|
|
3496
|
+
const legacy = [stage.name, "铺底", "塑形", "过渡", "收边", "点睛"].filter(Boolean);
|
|
3497
|
+
const found = docs.doc.layers.find((l) => !l.image && l.role === role && (l.name === want || legacy.includes(l.name)));
|
|
3498
|
+
if (found) {
|
|
3499
|
+
if ((found.strokes || []).length > 0) {
|
|
3500
|
+
docs.snapshot(`重跑 ${want}`);
|
|
3501
|
+
docs.clear(found.id);
|
|
3502
|
+
}
|
|
3503
|
+
// 草稿/线色这类层可能是锁的,重跑前临时解锁
|
|
3504
|
+
docs.updateLayer(found.id, { role, name: want, blend: blendOfRole(role), locked: false, clipTo: stage.clipTo || null, opacity: stage.opacity === undefined ? 1 : stage.opacity, lockAlpha: false });
|
|
3505
|
+
return found;
|
|
3506
|
+
}
|
|
3507
|
+
return docs.addLayer(want, { role, blend: blendOfRole(role), clipTo: stage.clipTo || null, opacity: stage.opacity });
|
|
3508
|
+
};
|
|
3509
|
+
// 13 步管线:role 决定 z 高度与 blend
|
|
3510
|
+
if (isPaint && Array.isArray(job.paintStages)) {
|
|
3511
|
+
for (const stage of job.paintStages) {
|
|
3512
|
+
const role = PAINT_STAGE_ROLE[stage.key] || "base";
|
|
3513
|
+
if (stage.kind === "grade") {
|
|
3514
|
+
const layer = pickStageLayer(stage);
|
|
3515
|
+
docs.updateLayer(layer.id, { grade: stage.grade || { brightness: 0, contrast: 1, saturation: 1, hue: 0 } });
|
|
3516
|
+
created.push({ name: layer.name, role, kind: "grade", items: 0, stage: stage.key });
|
|
3517
|
+
continue;
|
|
3518
|
+
}
|
|
3519
|
+
if (stage.kind === "fill") {
|
|
3520
|
+
const parts = Array.isArray(stage.parts) && stage.parts.length
|
|
3521
|
+
? stage.parts
|
|
3522
|
+
: [{ key: "all", name: "", fills: stage.fills || [], outlines: stage.outlines || [] }];
|
|
3523
|
+
for (const part of parts) {
|
|
3524
|
+
if (!Array.isArray(part.fills) || part.fills.length === 0) continue;
|
|
3525
|
+
const layerName = part.key === "all" ? "固有色平铺" : `固有色-${part.name}`;
|
|
3526
|
+
const layer = pickStageLayer(stage, layerName);
|
|
3527
|
+
await appendInChunks(
|
|
3528
|
+
part.fills.map((f) => ({ mode: "fill", color: f.color, size: 1, opacity: 1, points: f.points, holes: f.holes || [] })),
|
|
3529
|
+
layer.id,
|
|
3530
|
+
);
|
|
3531
|
+
if (!hasLine && Array.isArray(part.outlines) && part.outlines.length > 0) {
|
|
3532
|
+
await appendInChunks(
|
|
3533
|
+
part.outlines.map((o) => ({ mode: "brush", color: o.color, size: o.size, opacity: o.opacity, brush: "hard", points: o.points })),
|
|
3534
|
+
layer.id,
|
|
3535
|
+
);
|
|
3536
|
+
}
|
|
3537
|
+
created.push({ name: layer.name, role, part: part.key, kind: "fill", items: part.fills.length, outlines: hasLine ? 0 : (part.outlines ? part.outlines.length : 0), stage: stage.key });
|
|
3538
|
+
}
|
|
3539
|
+
} else {
|
|
3540
|
+
if (!Array.isArray(stage.strokes) || stage.strokes.length === 0) continue;
|
|
3541
|
+
const layer = pickStageLayer(stage);
|
|
3542
|
+
const brush = BRUSH_IDS.includes(stage.brush) ? stage.brush : "round";
|
|
3543
|
+
await appendInChunks(
|
|
3544
|
+
stage.strokes.map((s) => ({
|
|
3545
|
+
mode: "brush",
|
|
3546
|
+
color: s.color,
|
|
3547
|
+
size: s.size,
|
|
3548
|
+
opacity: s.opacity,
|
|
3549
|
+
brush,
|
|
3550
|
+
taper: s.taper === true || stage.taper === true,
|
|
3551
|
+
minSize: s.minSize === undefined ? stage.minSize : s.minSize,
|
|
3552
|
+
points: s.points,
|
|
3553
|
+
})),
|
|
3554
|
+
layer.id,
|
|
3555
|
+
);
|
|
3556
|
+
if (stage.lockAlpha === true) docs.updateLayer(layer.id, { lockAlpha: true });
|
|
3557
|
+
if (stage.locked === true) docs.updateLayer(layer.id, { locked: true });
|
|
3558
|
+
created.push({ name: layer.name, role, blend: blendOfRole(role), clipTo: stage.clipTo || null, kind: "paint", items: stage.strokes.length, stage: stage.key });
|
|
3559
|
+
}
|
|
3560
|
+
}
|
|
3561
|
+
} else if (isPaint && Array.isArray(job.paint) && job.paint.length > 0) {
|
|
3562
|
+
// 兼容旧宿主:只回 job.paint 的单层笔触
|
|
3563
|
+
const layer = pickLayer(args.fillLayer || "笔触");
|
|
3564
|
+
await appendInChunks(
|
|
3565
|
+
job.paint.map((p) => ({
|
|
3566
|
+
mode: "brush",
|
|
3567
|
+
color: p.color,
|
|
3568
|
+
size: p.size,
|
|
3569
|
+
opacity: p.opacity,
|
|
3570
|
+
brush: "hard",
|
|
3571
|
+
points: p.points,
|
|
3572
|
+
})),
|
|
3573
|
+
layer.id,
|
|
3574
|
+
);
|
|
3575
|
+
created.push({ name: layer.name, kind: "paint", items: job.paint.length });
|
|
3576
|
+
}
|
|
3577
|
+
if (!isPaint && style !== "lineart" && Array.isArray(job.fills) && job.fills.length > 0) {
|
|
2645
3578
|
const layer = pickLayer(args.fillLayer || "色块");
|
|
2646
|
-
|
|
3579
|
+
await appendInChunks(
|
|
2647
3580
|
job.fills.map((f) => ({ mode: "fill", color: f.color, size: 1, opacity: 1, points: f.points, holes: f.holes })),
|
|
2648
3581
|
layer.id,
|
|
2649
3582
|
);
|
|
2650
3583
|
created.push({ name: layer.name, kind: "fill", items: job.fills.length });
|
|
2651
3584
|
}
|
|
2652
|
-
|
|
3585
|
+
// 非 paint:厚涂图没有清晰墨线,默认不描线;要就显式 lineart=true
|
|
3586
|
+
if (!isPaint && style !== "flat" && Array.isArray(job.paths) && job.paths.length > 0) {
|
|
2653
3587
|
const palette = job.palette || [];
|
|
2654
3588
|
const darkest = palette.length
|
|
2655
3589
|
? palette.reduce((a, b) => (lumOf(a) <= lumOf(b) ? a : b))
|
|
@@ -2672,24 +3606,25 @@ export function apply(ctx, config = {}) {
|
|
|
2672
3606
|
const thick = pairs.filter((p) => p.size >= avg * 0.8);
|
|
2673
3607
|
if (thin.length === 0 || thick.length === 0) {
|
|
2674
3608
|
const layer = pickLayer(args.layer || "线稿");
|
|
2675
|
-
|
|
3609
|
+
await appendInChunks(pairs.map(strokeOf), layer.id);
|
|
2676
3610
|
created.push({ name: layer.name, kind: "line", items: pairs.length });
|
|
2677
3611
|
} else {
|
|
2678
3612
|
const lineLayer = pickLayer(args.layer || "线稿");
|
|
2679
|
-
|
|
3613
|
+
await appendInChunks(thin.map(strokeOf), lineLayer.id);
|
|
2680
3614
|
created.push({ name: lineLayer.name, kind: "line", items: thin.length });
|
|
2681
3615
|
const heavyLayer = pickLayer("粗线");
|
|
2682
|
-
|
|
3616
|
+
await appendInChunks(thick.map(strokeOf), heavyLayer.id);
|
|
2683
3617
|
created.push({ name: heavyLayer.name, kind: "line", items: thick.length });
|
|
2684
3618
|
}
|
|
2685
3619
|
} else {
|
|
2686
3620
|
const layer = pickLayer(args.layer || "线稿");
|
|
2687
|
-
|
|
3621
|
+
await appendInChunks(pairs.map(strokeOf), layer.id);
|
|
2688
3622
|
created.push({ name: layer.name, kind: "line", items: pairs.length });
|
|
2689
3623
|
}
|
|
2690
3624
|
}
|
|
2691
3625
|
// 自动验收,让模型不用再问一次
|
|
2692
|
-
const cmp = await runPixelJob("compare", { rect: job.rect }, PIXEL_TIMEOUT_MS * 2);
|
|
3626
|
+
const cmp = await runPixelJob("compare", { rect: job.rect, paint: isPaint }, PIXEL_TIMEOUT_MS * 2, isPaint);
|
|
3627
|
+
const summary = created.map((c) => `${c.name}(${c.items})`).join(" + ") || "没有可画的内容";
|
|
2693
3628
|
return {
|
|
2694
3629
|
ok: true,
|
|
2695
3630
|
revision: docs.revision,
|
|
@@ -2704,12 +3639,20 @@ export function apply(ctx, config = {}) {
|
|
|
2704
3639
|
created,
|
|
2705
3640
|
palette: job.palette,
|
|
2706
3641
|
lines: job.lines,
|
|
2707
|
-
fills: job.fills.length,
|
|
3642
|
+
fills: Array.isArray(job.fills) ? job.fills.length : 0,
|
|
3643
|
+
paint: isPaint ? (job.paint || 0) : 0,
|
|
3644
|
+
paintLayers: isPaint ? created.map((c) => ({ name: c.name, role: c.role || null, kind: c.kind, items: c.items, blend: c.blend || null, clipTo: c.clipTo || null })) : null,
|
|
3645
|
+
paintStats: job.paintStats || null,
|
|
2708
3646
|
points: job.points,
|
|
3647
|
+
computedBy: job.computedBy || null,
|
|
2709
3648
|
metrics: cmp.ok ? cmp.metrics : null,
|
|
2710
|
-
hint:
|
|
2711
|
-
|
|
2712
|
-
|
|
3649
|
+
hint: (isPaint
|
|
3650
|
+
? `14 层复刻完成:${summary};估算覆盖率 ${job.paintStats ? job.paintStats.coveragePct : "?"}%。每层可单独显隐、改 blend/clipTo/hue;只重跑某几步给 paintStages(如 "base,block"),重跑前会自动 snapshot;action=check 可做关层自检。`
|
|
3651
|
+
: `已按 ${style} 复刻:${summary}。`)
|
|
3652
|
+
+ (cmp.ok
|
|
3653
|
+
? `验收覆盖率 ${cmp.metrics.coveragePct}%,多画 ${cmp.metrics.extraPct}%${cmp.metrics.meanColorDiff === null || cmp.metrics.meanColorDiff === undefined ? "" : `,平均色差 ${cmp.metrics.meanColorDiff}`}${cmp.metrics.meanDeltaE === undefined ? "" : `(ΔE≈${cmp.metrics.meanDeltaE})`}。`
|
|
3654
|
+
: "(验收没跑成,稍后 action=compare 再看)")
|
|
3655
|
+
+ (isPaint ? "想更细就给更小的 paintStep 或更大的 maxStrokes;fix 的墨迹补漏不适用于彩稿。" : "想补差距就 action=fix。"),
|
|
2713
3656
|
};
|
|
2714
3657
|
}
|
|
2715
3658
|
case "posterize": {
|
|
@@ -2726,7 +3669,7 @@ export function apply(ctx, config = {}) {
|
|
|
2726
3669
|
lines: args.lines === true,
|
|
2727
3670
|
minLength: args.minLength,
|
|
2728
3671
|
maxLines: args.maxLines,
|
|
2729
|
-
}, PIXEL_TIMEOUT_MS * 3);
|
|
3672
|
+
}, PIXEL_TIMEOUT_MS * 3, true);
|
|
2730
3673
|
if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
|
|
2731
3674
|
const created = [];
|
|
2732
3675
|
const pickLayer = (name) => {
|
|
@@ -2754,7 +3697,7 @@ export function apply(ctx, config = {}) {
|
|
|
2754
3697
|
);
|
|
2755
3698
|
created.push({ name: layer.name, kind: "line", items: job.paths.length });
|
|
2756
3699
|
}
|
|
2757
|
-
const cmp = await runPixelJob("compare", { rect }, PIXEL_TIMEOUT_MS * 2);
|
|
3700
|
+
const cmp = await runPixelJob("compare", { rect }, PIXEL_TIMEOUT_MS * 2, true);
|
|
2758
3701
|
return {
|
|
2759
3702
|
ok: true,
|
|
2760
3703
|
revision: docs.revision,
|
|
@@ -2762,6 +3705,7 @@ export function apply(ctx, config = {}) {
|
|
|
2762
3705
|
created,
|
|
2763
3706
|
palette: job.stats && job.stats.palette,
|
|
2764
3707
|
stats: job.stats,
|
|
3708
|
+
computedBy: job.computedBy || null,
|
|
2765
3709
|
metrics: cmp.ok ? cmp.metrics : null,
|
|
2766
3710
|
hint: `已按 ${job.stats ? job.stats.colorCount : "?"} 色阶分区复刻:${created.map((c) => `${c.name}(${c.items})`).join(" + ") || "没有可画的内容"}。`
|
|
2767
3711
|
+ (cmp.ok ? `覆盖率 ${cmp.metrics.coveragePct}%,多画 ${cmp.metrics.extraPct}%,色差 ${cmp.metrics.meanColorDiff}。` : "")
|
|
@@ -2769,13 +3713,22 @@ export function apply(ctx, config = {}) {
|
|
|
2769
3713
|
};
|
|
2770
3714
|
}
|
|
2771
3715
|
case "fix": {
|
|
3716
|
+
// paint 五步画布的「缺口」是彩稿覆盖/色差,不是墨迹漏描;
|
|
3717
|
+
// 用 trace 往 5 层里补黑线只会画脏,直接让调用方去重跑对应层。
|
|
3718
|
+
if (args.layer === undefined && docs.doc.layers.some((l) => ["固有色平铺", "一级暗部", "二级暗部", "精线稿", "高光"].includes(l.name))) {
|
|
3719
|
+
return {
|
|
3720
|
+
ok: false,
|
|
3721
|
+
revision: docs.revision,
|
|
3722
|
+
error: "这是 paint 五步画布:fix 的墨迹补漏不适合彩稿。用 copy style=paint paintStages=... rect=... 局部重跑,或 action=compare 看覆盖率/色差。",
|
|
3723
|
+
};
|
|
3724
|
+
}
|
|
2772
3725
|
const rect = parseRect(args.rect, docs.doc.width, docs.doc.height);
|
|
2773
3726
|
const maxRounds = Math.max(1, Math.min(5, Math.round(Number(args.maxRounds) || 3)));
|
|
2774
3727
|
const target = Math.max(30, Math.min(99, Number(args.target) || 90));
|
|
2775
3728
|
const rounds = [];
|
|
2776
3729
|
let last = null;
|
|
2777
3730
|
for (let i = 0; i < maxRounds; i += 1) {
|
|
2778
|
-
const cmp = await runPixelJob("compare", { rect }, PIXEL_TIMEOUT_MS * 2);
|
|
3731
|
+
const cmp = await runPixelJob("compare", { rect }, PIXEL_TIMEOUT_MS * 2, args.forceHeadless === true);
|
|
2779
3732
|
if (!cmp.ok) return { ok: false, error: cmp.error, rounds, revision: docs.revision };
|
|
2780
3733
|
last = cmp.metrics;
|
|
2781
3734
|
const entry = {
|
|
@@ -2807,7 +3760,7 @@ export function apply(ctx, config = {}) {
|
|
|
2807
3760
|
tolerance: Math.min(2, Number(args.tolerance) || 2),
|
|
2808
3761
|
minLength: 6,
|
|
2809
3762
|
maxLines: 30,
|
|
2810
|
-
}, PIXEL_TIMEOUT_MS * 2);
|
|
3763
|
+
}, PIXEL_TIMEOUT_MS * 2, args.forceHeadless === true);
|
|
2811
3764
|
if (!tr.ok || !tr.paths.length) continue;
|
|
2812
3765
|
const brush = BRUSH_IDS.includes(args.brush) ? args.brush : "liner";
|
|
2813
3766
|
const strokes = tr.paths
|
|
@@ -2821,7 +3774,7 @@ export function apply(ctx, config = {}) {
|
|
|
2821
3774
|
if (added === 0) break;
|
|
2822
3775
|
}
|
|
2823
3776
|
// 收尾再验收一次,数字才是补完后的
|
|
2824
|
-
const final = await runPixelJob("compare", { rect }, PIXEL_TIMEOUT_MS * 2);
|
|
3777
|
+
const final = await runPixelJob("compare", { rect }, PIXEL_TIMEOUT_MS * 2, args.forceHeadless === true);
|
|
2825
3778
|
return {
|
|
2826
3779
|
ok: true,
|
|
2827
3780
|
revision: docs.revision,
|
|
@@ -2846,7 +3799,7 @@ export function apply(ctx, config = {}) {
|
|
|
2846
3799
|
fitStep: args.fitStep,
|
|
2847
3800
|
widths: args.widths === true,
|
|
2848
3801
|
mode: args.mode === "center" ? "center" : "edge",
|
|
2849
|
-
});
|
|
3802
|
+
}, undefined, args.forceHeadless === true);
|
|
2850
3803
|
if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
|
|
2851
3804
|
return {
|
|
2852
3805
|
ok: true,
|
|
@@ -2876,7 +3829,7 @@ export function apply(ctx, config = {}) {
|
|
|
2876
3829
|
y: Math.round(Number(args.y)),
|
|
2877
3830
|
layer: args.layer === undefined ? null : args.layer,
|
|
2878
3831
|
on: args.on === "canvas" ? "canvas" : "ref",
|
|
2879
|
-
});
|
|
3832
|
+
}, undefined, args.forceHeadless === true);
|
|
2880
3833
|
if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
|
|
2881
3834
|
return { ok: true, revision: docs.revision, ...job };
|
|
2882
3835
|
}
|
|
@@ -2884,7 +3837,7 @@ export function apply(ctx, config = {}) {
|
|
|
2884
3837
|
const job = await runPixelJob("compare", {
|
|
2885
3838
|
rect: parseRect(args.rect, docs.doc.width, docs.doc.height),
|
|
2886
3839
|
layer: args.layer === undefined ? null : args.layer,
|
|
2887
|
-
});
|
|
3840
|
+
}, undefined, args.forceHeadless === true);
|
|
2888
3841
|
if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
|
|
2889
3842
|
const file = writePng(job.dataUrl, "compare");
|
|
2890
3843
|
return {
|
|
@@ -2898,7 +3851,7 @@ export function apply(ctx, config = {}) {
|
|
|
2898
3851
|
}
|
|
2899
3852
|
case "palette": {
|
|
2900
3853
|
const k = Math.max(2, Math.min(8, Math.round(Number(args.k) || 6)));
|
|
2901
|
-
const job = await runPixelJob("palette", { k, rect: parseRect(args.rect, docs.doc.width, docs.doc.height), layer: args.layer === undefined ? null : args.layer });
|
|
3854
|
+
const job = await runPixelJob("palette", { k, rect: parseRect(args.rect, docs.doc.width, docs.doc.height), layer: args.layer === undefined ? null : args.layer }, undefined, args.forceHeadless === true);
|
|
2902
3855
|
if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
|
|
2903
3856
|
return { ok: true, revision: docs.revision, ...job };
|
|
2904
3857
|
}
|
|
@@ -2925,8 +3878,9 @@ export function apply(ctx, config = {}) {
|
|
|
2925
3878
|
default:
|
|
2926
3879
|
return { ok: false, error: `未知 action: ${action}` };
|
|
2927
3880
|
}
|
|
3881
|
+
})());
|
|
2928
3882
|
} catch (err) {
|
|
2929
|
-
return { ok: false, error: String((err && err.message) || err) };
|
|
3883
|
+
return jsonSafe({ ok: false, error: String((err && err.message) || err) });
|
|
2930
3884
|
}
|
|
2931
3885
|
},
|
|
2932
3886
|
isConcurrencySafe: () => false,
|
|
@@ -3008,3 +3962,4 @@ export function apply(ctx, config = {}) {
|
|
|
3008
3962
|
}
|
|
3009
3963
|
};
|
|
3010
3964
|
}
|
|
3965
|
+
|