@xenra/dsh-draworld 0.1.40 → 0.1.41

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 CHANGED
@@ -165,7 +165,7 @@ https://github.com/RUO-MO/dsh-draworld
165
165
  | 动作 | 说明 |
166
166
  |---|---|
167
167
  | `doc` | 看尺寸、图层、笔迹数、颜色、内容范围、版本;图层带 `image` 就是图片层 |
168
- | `copy` | **一键复刻**:`style=lineart/flat/anime`,自动抽轮廓 + 区域配色,建「色块 / 线稿」两层,并顺带跑 compare 返回覆盖率;`colors`、`minFill` 可调;`mode` 不传则自动判断参考图是线稿还是照片(回报 `mode`、`inkRatio`);描线默认做**三次贝塞尔拟合**(`fit=false` 退回磨圆 `smooth=0~3`);每根线按量出来的**原线宽**落笔,`splitLines=true` 再把粗细分到「线稿 / 粗线」两层 |
168
+ | `copy` | **一键复刻**:`style=lineart/flat/anime/paint`。lineart/flat/anime 走「抽轮廓 + 区域配色」,建「色块 / 线稿」两层,并顺带跑 compare 返回覆盖率;`colors`、`minFill` 可调;`mode` 不传则自动判断参考图是线稿还是照片(回报 `mode`、`inkRatio`);描线默认做**三次贝塞尔拟合**(`fit=false` 退回磨圆 `smooth=0~3`);每根线按量出来的**原线宽**落笔,`splitLines=true` 再把粗细分到「线稿 / 粗线」两层。<br>**`style=paint`(0.1.40 起,厚涂/渐变/火焰这种没有闭合边界的图用它)**:不描轮廓,改成笔触铺色——先按大网格把整幅铺一遍(保证不留白),再只在局部对比强的地方(脸、手、褶皱、火焰边缘)补细笔;颜色取该格均色、笔触方向沿等色线、笔宽盖住格子对角线、不透明度随对比度走。默认 8000 笔出结构,`maxStrokes=12000` 接近成图质感(上限 20000);`paintStep` 控细节网格、`paintPasses=1` 只粗铺先看大关系;默认**不叠线稿**(厚涂图硬描会拖出大黑斜线),要叠给 `lineart=true`;`paintBrush` 可选笔刷。返回 `paint`(笔数)、`paintStats`(step/coarse/cells/skippedBg/capped) |
169
169
  | `posterize` | **彩图复刻成图(0.1.40 起)**:先 k-means 量化成 `colors` 档(2~12,默认 8),再把每一色的连通区按 marching squares 轮廓各自落成一块可编辑填色(大块先垫、小块压上;细长条不过滤,避免交界白缝),建「色块」层;`lines=true` 顺手把色块边界描成「线稿」层。**彩稿用这个,别用 `copy`**——`copy` 的墨迹阈值会把黑袍当一整块墨,只出 160 根长线。`minArea`(默认面积/4000)、`maxFills`(默认 1600)、`tolerance`、`colors` 可调 |
170
170
  | `fix` | **自动补漏**:只看 compare 的 `topGaps` 重描最漏的几块,`target=90`、`maxRounds=3`,达标或没得补就停,返回每轮数字;落在色块洞里(高光)的缺口会跳过(`skippedHoles`) |
171
171
  | `fill` | **点一下填色**:`x`、`y` 是区域内的种子点,边界取现有笔迹,颜色默认取参考图该点并映射到主色;`color`、`rect`、`fillLayer` 可调;区域里的洞按轮廓嵌套自动挖掉(`evenodd` 填充) |
@@ -186,7 +186,13 @@ https://github.com/RUO-MO/dsh-draworld
186
186
  | `undo` / `redo` | 按全局顺序撤/恢复最近 N 笔 |
187
187
  | `clear` | 清空整幅;带 `layer` 只清那层(`all`/`*` 等同整幅) |
188
188
 
189
- **复刻一张图**的闭环:彩稿走 `posterize`(色阶分区铺色 ± 边界线稿),线稿走 `copy`/`trace` → 再 `fix` 补漏;想手工精修再按 `ref` 看细节 → `palette` 定配色 → `trace` 抽轮廓 → `pick` 确认某点在不在线上 → `draw`(长线用 `batches`)→ `view layer=… rect=… zoom=2` 看自己那块 → `compare` 看差多少(`coveragePct` 往 90+ 推、`extraPct` 压下去)→ 收尾前 `snapshot` 兜底。整段流程与协议文本都写进了会话提示词,模型看得到。
189
+ **复刻一张图**的闭环:彩稿分两种走法——平涂/线色分明的走 `posterize`(色阶分区铺色 ± 边界线稿);厚涂、渐变、火焰、毛发这种没有闭合边界的走 `copy style=paint`(笔触铺色,`maxStrokes=12000` 要质感);纯线稿走 `copy`/`trace` → 再 `fix` 补漏;想手工精修再按 `ref` 看细节 → `palette` 定配色 → `trace` 抽轮廓 → `pick` 确认某点在不在线上 → `draw`(长线用 `batches`)→ `view layer=… rect=… zoom=2` 看自己那块 → `compare` 看差多少(`coveragePct` 往 90+ 推、`extraPct` 压下去)→ 收尾前 `snapshot` 兜底。整段流程与协议文本都写进了会话提示词,模型看得到。
190
+
191
+ **`style=paint` 复刻出来的样子**(1080×1440 彩稿 → 12000 笔触,全矢量可编辑,无图片层):
192
+
193
+ ![笔触复刻](docs/assets/paint-replica.png)
194
+
195
+ **大批落笔能边画边看(0.1.40 起)**:`copy` / `draw batches` 不再一次性把几千笔塞进文档末尾才刷新,而是每 120 笔一块写进去、中间让出事件循环,同时 `state.painting = {layer, done, total}` 通过 `GET /canvas-api/doc` 的 `painting` 字段给面板。侧边标签页的进度条(左上角 ✎ 层名 + `1200/8000`)就是读这个字段,停顿和「卡住不动」能一眼分清。
190
196
 
191
197
  **改局部别糊整幅**:先 `select` 框住范围(`rect` 或套索 `points`),再 `draw` / `fill`,越界点会被裁掉;改完 `select clearSelection=true`。选区存在 `doc.json` 的 `selection` 字段里,会跟着文档走。
192
198
 
@@ -196,7 +202,7 @@ https://github.com/RUO-MO/dsh-draworld
196
202
  - **宿主侧(0.1.35 起)**:面板没开(`/jobs` 2.5 秒没人来取)时,宿主自己算——`pixels.js` 是纯 JS 的 PNG 解码/编码(8bit,colorType 0/2/4/6,不支持调色板/隔行/16bit)+ 光栅化 + marching squares / Zhang-Suen 骨架 / RDP / Chaikin / 三次贝塞尔,`pixelops.js` 跑 crop / ref / pick / palette / trace / copy / fill / compare。所以「不开界面也能 `copy` → `fix`」这条已经通了,不再 5 秒超时。非 PNG 参考图(JPEG 等)会用 PowerShell 的 `System.Drawing` 转一次临时 PNG 再读。
197
203
  - 宿主算不出来才回落到队列,超时默认 5 秒(`trace`/`copy`/`fill`/`compare`/`palette` 这类整幅重活 30 秒,`heavyTimeout` 可调)、话术直说「宿主侧没算成、面板也没接任务」。不想让宿主插手、只走浏览器:插件配置写 `headless: false`(也可 `POST /canvas-api/config {"headless": false}` 临时切)。
198
204
  - **`trace` 带调参反馈(0.1.39 起)**:返回体里多了 `stats` —— `inkRatio`(墨迹占比,判断阈值是不是把阴影也吃进来了)、`widthAvg/Min/Max`(量出来的线宽,拿来设笔刷 size)、`pointsPerLine`(重采样疏密,对应 `fitStep`/`step`)、`droppedPct`(被 `minLength` 丢掉的短段比例)。调 `threshold`/`tolerance`/`fitStep` 时看这几个数,不用只靠肉眼比成品。
199
- - **画的过程能看见了(0.1.40 起)**:前端 tick 里发现「最上层追加了普通笔迹、其他层没变」就直接 paintStroke 补画那一笔(paintAppended),不再整幅
200
- enderDoc 重绘;轮询 500ms。模型一批 300 笔过去,画布是逐笔长出来的,跳变间隔从 0.7 秒缩到半秒。
205
+ - **画的过程能看见了(0.1.40 起)**:前端 tick 里发现「最上层追加了普通笔迹、其他层没变」就直接 paintStroke 补画那一笔(paintAppended),不再整幅
206
+ enderDoc 重绘;轮询 500ms。模型一批 300 笔过去,画布是逐笔长出来的,跳变间隔从 0.7 秒缩到半秒。
201
207
  - **图片类型按内容判**:`import` 不看扩展名,读魔数认 PNG / JPEG / WebP / GIF,缓存名统一是 `img-<stamp>-<rand>.<真扩展名>`;`ref` 遇到非 PNG 会先转一份 `views/ref-…-<mtime>.png` 再交给 `read_image`(同一文件按 mtime 复用,原文件保留不动)。
202
208
 
203
209
  **填色边界**:`copy` 走中心线时,色块另跑一遍边界追踪取闭合轮廓(骨架不闭合),洞按嵌套层数 even-odd 挖掉;`fill` 的泛洪边界只认笔迹(不含已填色块),区域撞到「超过画布 62%」会拒填并提示先有线稿或用 `rect` 收窄。
package/client.js CHANGED
@@ -2562,6 +2562,9 @@ window.__ModuleLoader__.load({
2562
2562
  const [updateInfo, setUpdateInfo] = React.useState(null);
2563
2563
  const [applying, setApplying] = React.useState(false);
2564
2564
  const [applyNote, setApplyNote] = React.useState('');
2565
+ /** 宿主正在大批落笔时的进度(分块写入,面板能边画边看)。 */
2566
+ const [painting, setPainting] = React.useState(null);
2567
+ const paintingRef = React.useRef(null);
2565
2568
 
2566
2569
  /** 一键更新:宿主拿 pluginManager 按 tag 重装(git 安装也能收更新)。 */
2567
2570
  const applyUpdate = async () => {
@@ -2837,6 +2840,8 @@ window.__ModuleLoader__.load({
2837
2840
  // 宿主有没有 32 支笔刷:旧进程只认 5 支,落笔后笔刷会被丢掉,重画成圆头
2838
2841
  setStaleHost(!(Number(body.brushes) >= BRUSHES.length));
2839
2842
  setUpdateInfo(body.update || null);
2843
+ setPainting(body.painting || null);
2844
+ paintingRef.current = body.painting || null;
2840
2845
  if (body.version) setLocalVer(String(body.version));
2841
2846
  const prevDoc = docRef.current;
2842
2847
  const prevRev = revRef.current;
@@ -2862,7 +2867,8 @@ window.__ModuleLoader__.load({
2862
2867
  } catch {
2863
2868
  if (alive) setError(t('syncFailed'));
2864
2869
  } finally {
2865
- if (alive) timer = setTimeout(tick, 500);
2870
+ // 正在落笔就加密轮询,进度条和画布才是「长出来」而不是三跳到底
2871
+ if (alive) timer = setTimeout(tick, paintingRef.current ? 150 : 500);
2866
2872
  }
2867
2873
  };
2868
2874
  tick();
@@ -3331,6 +3337,44 @@ window.__ModuleLoader__.load({
3331
3337
  },
3332
3338
  }),
3333
3339
  ),
3340
+ painting
3341
+ ? h('div', {
3342
+ style: {
3343
+ position: 'absolute',
3344
+ left: 8,
3345
+ top: 8,
3346
+ display: 'flex',
3347
+ alignItems: 'center',
3348
+ gap: 8,
3349
+ padding: '4px 8px',
3350
+ borderRadius: 6,
3351
+ background: 'rgba(0,0,0,0.5)',
3352
+ color: '#f2f2f2',
3353
+ fontSize: 11,
3354
+ pointerEvents: 'none',
3355
+ },
3356
+ },
3357
+ h('span', null, `✎ ${painting.layer || ''}`),
3358
+ h('div', {
3359
+ style: {
3360
+ width: 92,
3361
+ height: 4,
3362
+ borderRadius: 2,
3363
+ background: 'rgba(255,255,255,0.25)',
3364
+ overflow: 'hidden',
3365
+ },
3366
+ }, h('div', {
3367
+ style: {
3368
+ width: `${Math.min(100, Math.round(((painting.done || 0) / Math.max(1, painting.total || 1)) * 100))}%`,
3369
+ height: '100%',
3370
+ background: 'var(--dsw-alias-brand-primary, #4c8bf5)',
3371
+ transition: 'width 120ms linear',
3372
+ },
3373
+ })),
3374
+ h('span', { style: { fontVariantNumeric: 'tabular-nums' } },
3375
+ `${painting.done || 0}/${painting.total || 0}`),
3376
+ )
3377
+ : null,
3334
3378
  h('div', {
3335
3379
  title: t('panHint'),
3336
3380
  style: {
package/index.js CHANGED
@@ -251,7 +251,8 @@ const PROTOCOL = `你可以用 \`paint_canvas\` 在界面里的一块真画布
251
251
  8. 画布本身也能改:\`action=canvas width=… height=… background=#rrggbb\`;\`action=export\` 把当前渲染另存成 PNG。
252
252
 
253
253
  **最省事的复刻就两条命令**(不需要自己估坐标、算配色、找缺口):
254
- - \`action=copy style=anime\`(或 lineart / flat):自动抽轮廓、按区域配主色、建「色块 / 线稿」两层,描线默认走三次贝塞尔拟合(长弧一条曲线走完,比磨圆更像手画),每根线按量出来的原线宽落笔,并顺带跑一次 compare,直接给出覆盖率;要粗细分层加 \`splitLines=true\`;
254
+ - \`action=copy style=anime\`(或 lineart / flat / paint):自动抽轮廓、按区域配主色、建「色块 / 线稿」两层,描线默认走三次贝塞尔拟合(长弧一条曲线走完,比磨圆更像手画),每根线按量出来的原线宽落笔,并顺带跑一次 compare,直接给出覆盖率;要粗细分层加 \`splitLines=true\`;
255
+ \`style=paint\` 是另一条路:不描闭合轮廓,先按大网格把整幅铺一遍色、再只在对比强的地方(脸、手、褶皱、火焰边缘)补细笔,颜色取局部均色、方向沿等色线——厚涂/渐变/火焰这类没有闭合边界的图用这个。默认 8000 笔出结构,\`maxStrokes=12000\` 才接近成图质感;默认不叠线稿(厚涂图没有清晰墨线,硬描会拖出大黑斜线),要叠给 \`lineart=true\`。
255
256
  - \`action=fix target=90 maxRounds=3\`:只看最漏的几块自动补描,到达标或没得补就停,返回每轮数字;落在色块洞里(高光)的缺口会跳过,不会把高光涂掉。
256
257
  - \`action=fill x=… y=…\`:点一片区域就按 palette 填色(边界来自已有笔迹,也能手动给 color),不用一笔笔涂;区域里的洞(高光、瞳孔)会按轮廓嵌套挖掉不涂;
257
258
  - \`action=select rect=[x,y,w,h]\` 或 \`points=[[x,y]…]\`(套索)把落笔限制在选区里,\`clearSelection=true\` 取消;
@@ -1213,6 +1214,8 @@ export function apply(ctx, config = {}) {
1213
1214
  bindError: null,
1214
1215
  // 端点信息:GUI 端口每次重启都可能变,写进 endpoint.json 给脚本用
1215
1216
  endpoint: null,
1217
+ // 正在大批落笔时的进度(/doc 里带出去,侧边面板据此画进度条,不用等全部写完才看见)
1218
+ painting: null,
1216
1219
  // 版本自检:插件自己去 GitHub 看有没有新 Release,界面上给个提示
1217
1220
  update: { checkedAt: null, latest: null, hasUpdate: false, url: null, error: null, enabled: config.updateCheck !== false },
1218
1221
  };
@@ -1249,6 +1252,43 @@ export function apply(ctx, config = {}) {
1249
1252
  }
1250
1253
  };
1251
1254
 
1255
+ /** 让出一次事件循环:大批笔迹分块落盘时,前端 700ms 轮询才看得到中间状态。 */
1256
+ const yieldTick = () => new Promise((resolve) => setImmediate(resolve));
1257
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1258
+
1259
+ /**
1260
+ * 分块追加:一次 append 2000 笔会在最后一次性 bump,界面上就是「卡住 → 突然全出来」。
1261
+ * 这里按 120 笔一段写,每段都 bump 一次,并把自己的进度记进 state.painting(/doc 里带出去)。
1262
+ *
1263
+ * 有人开着面板时还要慢放:只 yieldTick 的话 1 万笔在几十毫秒内就全落完,
1264
+ * 700ms 的轮询只能看到最终态,等于没过程。所以按「整批放完约 2 秒」反算每块之间的停顿,
1265
+ * 单块 15~180ms;没人看就全速,不白等。
1266
+ */
1267
+ const appendInChunks = async (strokes, layerRef, chunkSize = 120) => {
1268
+ const total = strokes.length;
1269
+ const chunks = Math.ceil(total / chunkSize);
1270
+ const showProgress = total > chunkSize;
1271
+ const pause = showProgress && panelLive()
1272
+ ? Math.max(15, Math.min(180, Math.round(2000 / chunks)))
1273
+ : 0;
1274
+ let layer = null;
1275
+ let done = 0;
1276
+ for (let i = 0; i < total; i += chunkSize) {
1277
+ const part = strokes.slice(i, i + chunkSize);
1278
+ layer = docs.append(part, layer ? layer.id : layerRef);
1279
+ done += part.length;
1280
+ state.painting = showProgress
1281
+ ? { action: "append", done, total, layer: layer.name, at: Date.now() }
1282
+ : null;
1283
+ if (showProgress) {
1284
+ if (pause > 0) await sleep(pause);
1285
+ else await yieldTick();
1286
+ }
1287
+ }
1288
+ state.painting = null;
1289
+ return layer;
1290
+ };
1291
+
1252
1292
  const runPixelJob = (kind, params = {}, timeoutMs) => new Promise((resolve) => {
1253
1293
  if (config.headless !== false && HEADLESS_KINDS.has(kind) && !panelLive()) {
1254
1294
  // 没有面板 → 直接宿主侧算,不再干等 5 秒超时
@@ -1722,6 +1762,7 @@ export function apply(ctx, config = {}) {
1722
1762
  revision: docs.revision,
1723
1763
  doc: { ...docs.doc, revision: docs.revision },
1724
1764
  update: state.update,
1765
+ painting: state.painting,
1725
1766
  version: localVersion,
1726
1767
  pixelJobs: jobs.size,
1727
1768
  });
@@ -2184,9 +2225,14 @@ export function apply(ctx, config = {}) {
2184
2225
  fitStep: { type: "number", description: "trace / copy: 拟合后采样间距(像素),默认 3。小一点更贴原线,点也更多。" },
2185
2226
  style: {
2186
2227
  type: "string",
2187
- enum: ["lineart", "flat", "anime"],
2188
- description: "copy: 复刻风格。lineart 只出线稿;flat 只出区域色块;anime 出线稿+色块(默认)。",
2228
+ enum: ["lineart", "flat", "anime", "paint"],
2229
+ description: "copy: 复刻风格。lineart 只出线稿;flat 只出区域色块;anime 出线稿+色块(默认);paint 笔触复刻——按网格铺彩色短线(颜色取局部均色、方向沿等色线、透明度随对比度),适合厚涂/渐变/火焰这种没有闭合边界的图,再叠一层线稿。",
2189
2230
  },
2231
+ paintStep: { type: "number", description: "copy style=paint: 细节网格边长(像素),默认按画布面积与 maxStrokes 自动算(一般 8~24)。越小越细,笔数也越多。" },
2232
+ maxStrokes: { type: "number", description: "copy style=paint: 笔触总额,默认 8000(上限 20000)。6000 快、看结构;12000 才接近成图质感,代价是面板重绘更慢。" },
2233
+ paintPasses: { type: "number", description: "copy style=paint: 2=先粗铺整幅再补细节(默认),1=只粗铺(快,适合先看大关系)。" },
2234
+ paintMinLum: { type: "number", description: "copy style=paint: 比这个亮度更白的格子当背景跳过,默认 240。" },
2235
+ lineart: { type: "boolean", description: "copy style=paint: 是否再叠一层线稿,默认 true;只要笔触就 false。" },
2190
2236
  colors: { type: "number", description: "copy / posterize / palette: 主色档数 2~12(copy 默认 6,posterize 默认 8)。彩稿要火、金、肤这些颜色都出来,给 10~12。" },
2191
2237
  minFill: { type: "number", description: "copy: 小于多少像素的闭合区域不填色,默认 320。" },
2192
2238
  target: { type: "number", description: "fix: 目标覆盖率百分比,默认 90。到了就停。" },
@@ -2313,7 +2359,7 @@ export function apply(ctx, config = {}) {
2313
2359
  // 镜像:一笔画两边(对称复刻人像/建筑)
2314
2360
  const axis = args.mirror === "x" || args.mirror === "y" ? args.mirror : null;
2315
2361
  const strokes = axis ? list.concat(list.map((s) => ({ ...s, points: mirrorPoints(s.points, axis, W, H) }))) : list;
2316
- const layer = docs.append(strokes, args.layer);
2362
+ const layer = await appendInChunks(strokes, args.layer);
2317
2363
  return {
2318
2364
  ok: true,
2319
2365
  revision: docs.revision,
@@ -2614,7 +2660,7 @@ export function apply(ctx, config = {}) {
2614
2660
  throw new Error("select 需要 rect=[x,y,w,h]、points=[[x,y]…](套索),或 clearSelection=true 清掉");
2615
2661
  }
2616
2662
  case "copy": {
2617
- const style = args.style === "lineart" || args.style === "flat" ? args.style : "anime";
2663
+ const style = args.style === "lineart" || args.style === "flat" || args.style === "paint" ? args.style : "anime";
2618
2664
  const rect = parseRect(args.rect, docs.doc.width, docs.doc.height);
2619
2665
  const job = await runPixelJob("copy", {
2620
2666
  rect,
@@ -2630,6 +2676,10 @@ export function apply(ctx, config = {}) {
2630
2676
  fit: args.fit === undefined ? true : args.fit === true,
2631
2677
  fitStep: args.fitStep,
2632
2678
  mode: args.mode,
2679
+ paintStep: args.paintStep,
2680
+ maxStrokes: args.maxStrokes,
2681
+ paintPasses: args.paintPasses,
2682
+ paintMinLum: args.paintMinLum,
2633
2683
  }, PIXEL_TIMEOUT_MS * 3);
2634
2684
  if (!job.ok) return { ok: false, error: job.error, revision: docs.revision };
2635
2685
  const created = [];
@@ -2640,16 +2690,32 @@ export function apply(ctx, config = {}) {
2640
2690
  if (found && !found.locked && !found.image && (found.strokes || []).length === 0) return found;
2641
2691
  return docs.addLayer(want || undefined);
2642
2692
  };
2643
- // 先铺色块(在线稿下面),再描线,顺序就是画师的习惯
2693
+ // 先铺底色(笔触 / 色块都在线稿下面),再描线,顺序就是画师的习惯
2694
+ if (style === "paint" && Array.isArray(job.paint) && job.paint.length > 0) {
2695
+ const layer = pickLayer(args.fillLayer || "笔触");
2696
+ await appendInChunks(
2697
+ job.paint.map((p) => ({
2698
+ mode: "brush",
2699
+ color: p.color,
2700
+ size: p.size,
2701
+ opacity: p.opacity,
2702
+ brush: BRUSH_IDS.includes(args.paintBrush) ? args.paintBrush : "round",
2703
+ points: p.points,
2704
+ })),
2705
+ layer.id,
2706
+ );
2707
+ created.push({ name: layer.name, kind: "paint", items: job.paint.length });
2708
+ }
2644
2709
  if (style !== "lineart" && job.fills.length > 0) {
2645
2710
  const layer = pickLayer(args.fillLayer || "色块");
2646
- docs.append(
2711
+ await appendInChunks(
2647
2712
  job.fills.map((f) => ({ mode: "fill", color: f.color, size: 1, opacity: 1, points: f.points, holes: f.holes })),
2648
2713
  layer.id,
2649
2714
  );
2650
2715
  created.push({ name: layer.name, kind: "fill", items: job.fills.length });
2651
2716
  }
2652
- if (style !== "flat" && job.paths.length > 0) {
2717
+ // 厚涂图没有清晰墨线,默认不描线(强行描会拖出大黑斜线);要就显式 lineart=true
2718
+ if (style !== "flat" && (style !== "paint" || args.lineart === true) && job.paths.length > 0) {
2653
2719
  const palette = job.palette || [];
2654
2720
  const darkest = palette.length
2655
2721
  ? palette.reduce((a, b) => (lumOf(a) <= lumOf(b) ? a : b))
@@ -2672,19 +2738,19 @@ export function apply(ctx, config = {}) {
2672
2738
  const thick = pairs.filter((p) => p.size >= avg * 0.8);
2673
2739
  if (thin.length === 0 || thick.length === 0) {
2674
2740
  const layer = pickLayer(args.layer || "线稿");
2675
- docs.append(pairs.map(strokeOf), layer.id);
2741
+ await appendInChunks(pairs.map(strokeOf), layer.id);
2676
2742
  created.push({ name: layer.name, kind: "line", items: pairs.length });
2677
2743
  } else {
2678
2744
  const lineLayer = pickLayer(args.layer || "线稿");
2679
- docs.append(thin.map(strokeOf), lineLayer.id);
2745
+ await appendInChunks(thin.map(strokeOf), lineLayer.id);
2680
2746
  created.push({ name: lineLayer.name, kind: "line", items: thin.length });
2681
2747
  const heavyLayer = pickLayer("粗线");
2682
- docs.append(thick.map(strokeOf), heavyLayer.id);
2748
+ await appendInChunks(thick.map(strokeOf), heavyLayer.id);
2683
2749
  created.push({ name: heavyLayer.name, kind: "line", items: thick.length });
2684
2750
  }
2685
2751
  } else {
2686
2752
  const layer = pickLayer(args.layer || "线稿");
2687
- docs.append(pairs.map(strokeOf), layer.id);
2753
+ await appendInChunks(pairs.map(strokeOf), layer.id);
2688
2754
  created.push({ name: layer.name, kind: "line", items: pairs.length });
2689
2755
  }
2690
2756
  }
@@ -2705,6 +2771,8 @@ export function apply(ctx, config = {}) {
2705
2771
  palette: job.palette,
2706
2772
  lines: job.lines,
2707
2773
  fills: job.fills.length,
2774
+ paint: Array.isArray(job.paint) ? job.paint.length : 0,
2775
+ paintStats: job.paintStats || null,
2708
2776
  points: job.points,
2709
2777
  metrics: cmp.ok ? cmp.metrics : null,
2710
2778
  hint: `已按 ${style} 复刻:${created.map((c) => `${c.name}(${c.items})`).join(" + ") || "没有可画的内容"}。`
@@ -3008,3 +3076,4 @@ export function apply(ctx, config = {}) {
3008
3076
  }
3009
3077
  };
3010
3078
  }
3079
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xenra/dsh-draworld",
3
- "version": "0.1.40",
3
+ "version": "0.1.41",
4
4
  "description": "星染世界:DeepSeek Harness 里的一块真画布: a right-sidebar canvas tab plus a paint_canvas tool, so the model and the human draw on the same document.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/pixelops.js CHANGED
@@ -11,6 +11,120 @@ import {
11
11
 
12
12
  const dataUrlOf = (surf) => `data:image/png;base64,${encodePng(surf.data, surf.w, surf.h).toString("base64")}`;
13
13
 
14
+ /** 某点的亮度(0~255),越界就夹回边缘。 */
15
+ function lumAt(data, w, h, x, y) {
16
+ const xi = Math.max(0, Math.min(w - 1, Math.round(x)));
17
+ const yi = Math.max(0, Math.min(h - 1, Math.round(y)));
18
+ const i = (yi * w + xi) * 4;
19
+ return 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
20
+ }
21
+
22
+ /**
23
+ * 笔触复刻(style=paint):把参考图按网格取样,每格出 1~2 笔
24
+ * 「沿等色线方向」的短线,颜色取该格均色、笔宽取格宽、不透明度随局部对比度走。
25
+ *
26
+ * 跟 copy 的 edge/中心线不同,这不是"描轮廓",而是像画师铺色:先大片铺,再靠笔触的边缘留给线稿层去压。
27
+ * 好处是不依赖闭合区域(厚涂、渐变、火焰这类没有明确边界的也能出效果),缺点是笔数多、只近似。
28
+ */
29
+ function paintStrokesFromBitmap(cut, rect, palette, opts = {}) {
30
+ const w = cut.w;
31
+ const h = cut.h;
32
+ const d = cut.data;
33
+ const maxStrokes = Math.max(100, Math.min(20000, Number(opts.maxStrokes) || 8000));
34
+ // 网格边长跟笔数上限挂钩:粗铺吃掉约 45% 预算,剩的留给细节
35
+ const coarseAuto = Math.sqrt((w * h) / Math.max(200, maxStrokes * 0.45));
36
+ const step = Math.max(4, Math.min(48, Math.round(Number(opts.step) || coarseAuto / 2)));
37
+ const minLum = opts.minLum === undefined ? 240 : Number(opts.minLum);
38
+ const passes = Number(opts.passes) === 1 ? 1 : 2;
39
+ const strokes = [];
40
+ let cells = 0;
41
+ let skippedBg = 0;
42
+ let seed = 20261128;
43
+ const rnd = () => {
44
+ seed = (seed * 1103515245 + 12345) % 2147483648;
45
+ return seed / 2147483648;
46
+ };
47
+ const hex2 = (v) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, "0");
48
+ // 取样一格:均色 + 平均亮度 + 局部对比度(mag)
49
+ const sample = (cx, cy, size) => {
50
+ let r = 0, g = 0, b = 0, n = 0, lumSum = 0;
51
+ const half = Math.max(1, Math.round(size / 2));
52
+ const wob = Math.max(2, Math.round(size / 8));
53
+ for (let y = Math.round(cy) - half; y < Math.round(cy) + half; y += wob) {
54
+ for (let x = Math.round(cx) - half; x < Math.round(cx) + half; x += wob) {
55
+ if (x < 0 || y < 0 || x >= w || y >= h) continue;
56
+ const i = (y * w + x) * 4;
57
+ if (d[i + 3] < 16) continue;
58
+ r += d[i]; g += d[i + 1]; b += d[i + 2];
59
+ n += 1;
60
+ lumSum += lumAt(d, w, h, x, y);
61
+ }
62
+ }
63
+ if (n === 0) return null;
64
+ const gx = lumAt(d, w, h, cx + size, cy) - lumAt(d, w, h, cx - size, cy);
65
+ const gy = lumAt(d, w, h, cx, cy + size) - lumAt(d, w, h, cx, cy - size);
66
+ return {
67
+ color: `#${hex2(r / n)}${hex2(g / n)}${hex2(b / n)}`,
68
+ lum: lumSum / n,
69
+ mag: Math.min(1, Math.hypot(gx, gy) / 90),
70
+ ang: Math.atan2(gy, gx) + Math.PI / 2,
71
+ };
72
+ };
73
+ // 落一笔:长度/抖动跟格子走,宽高都盖住格子的对角线,否则会透白底、整片发灰
74
+ const push = (cx, cy, size, s, wide, alpha) => {
75
+ const len = size * (1.15 + 0.5 * rnd());
76
+ const jx = (rnd() - 0.5) * size * 0.4;
77
+ const jy = (rnd() - 0.5) * size * 0.4;
78
+ const pts = [];
79
+ for (let t = -1; t <= 1; t += 1) {
80
+ pts.push([
81
+ Math.round(rect.x + cx + jx + Math.cos(s.ang) * (len / 2) * t),
82
+ Math.round(rect.y + cy + jy + Math.sin(s.ang) * (len / 2) * t),
83
+ ]);
84
+ }
85
+ strokes.push({
86
+ color: s.color,
87
+ size: Number((size * (wide + 0.25 * s.mag)).toFixed(2)),
88
+ opacity: Number((alpha + 0.1 * s.mag).toFixed(2)),
89
+ points: pts,
90
+ });
91
+ };
92
+
93
+ // 第一遍:粗铺。网格放大一倍,保证先整幅有颜色,不做成一半空白一半细节
94
+ const coarse = Math.min(48, Math.max(6, Math.round(step * 2)));
95
+ for (let cy = coarse / 2; cy < h; cy += coarse) {
96
+ for (let cx = coarse / 2; cx < w; cx += coarse) {
97
+ if (strokes.length >= maxStrokes) break;
98
+ const s = sample(cx, cy, coarse);
99
+ if (!s) continue;
100
+ if (s.lum >= minLum) { skippedBg += 1; continue; }
101
+ cells += 1;
102
+ push(cx, cy, coarse, s, 1.05, 0.9);
103
+ }
104
+ if (strokes.length >= maxStrokes) break;
105
+ }
106
+ // 第二遍:细节。只补局部对比强的地方(脸、手、火焰边缘、褶皱),平涂区不再叠
107
+ const wantDetail = Number(opts.passes) !== 1;
108
+ if (wantDetail) {
109
+ for (let cy = step / 2; cy < h; cy += step) {
110
+ for (let cx = step / 2; cx < w; cx += step) {
111
+ if (strokes.length >= maxStrokes) break;
112
+ const s = sample(cx, cy, step);
113
+ if (!s) continue;
114
+ if (s.lum >= minLum) continue;
115
+ if (s.mag < 0.16) continue;
116
+ cells += 1;
117
+ push(cx, cy, step, s, 1.15, 0.88);
118
+ }
119
+ if (strokes.length >= maxStrokes) break;
120
+ }
121
+ }
122
+ return {
123
+ strokes,
124
+ stats: { step, passes: wantDetail ? 2 : 1, coarse, cells, skippedBg, strokes: strokes.length, capped: strokes.length >= maxStrokes },
125
+ };
126
+ }
127
+
14
128
  function refLayer(doc, wanted) {
15
129
  const layers = (doc.layers || []).filter((l) => l.image);
16
130
  if (wanted) return layers.find((l) => l.id === wanted || l.name === wanted) || null;
@@ -173,6 +287,7 @@ export async function runHeadless(kind, params, doc, resolve) {
173
287
  const widths = pathWidths(inkMask(cut.data, cut.w, cut.h, params.threshold), cut.w, cut.h, t.paths);
174
288
  const lineWidth = widths.length ? Number((widths.reduce((a, b) => a + b, 0) / widths.length).toFixed(2)) : null;
175
289
  const wantFill = params.style === "flat" || params.style === "anime";
290
+ const wantPaint = params.style === "paint";
176
291
  // 色块必须靠闭合轮廓;中心线模式下的路径是骨架,不闭合,所以填色另跑一遍边界追踪
177
292
  let edgeTrace = t;
178
293
  if (wantFill && mode === "center") {
@@ -190,9 +305,18 @@ export async function runHeadless(kind, params, doc, resolve) {
190
305
  const fills = wantFill
191
306
  ? regionFillsFromBitmap(cut, edgeTrace, palette, { minFill: params.minFill, maxFills: params.maxFills || 40, rect })
192
307
  : [];
308
+ const paint = wantPaint
309
+ ? paintStrokesFromBitmap(cut, rect, palette, {
310
+ step: params.paintStep,
311
+ maxStrokes: params.maxStrokes,
312
+ minLum: params.paintMinLum,
313
+ passes: params.paintPasses,
314
+ })
315
+ : null;
193
316
  return {
194
317
  ok: true, rect, paths, widths, lineWidth, closed: t.closed, fills, palette, mode,
195
318
  smooth: t.smooth, fit: t.fit, inkRatio, lines: t.lines, points: t.points, dropped: t.dropped, headless: true,
319
+ ...(paint ? { paint: paint.strokes, paintStats: paint.stats } : {}),
196
320
  };
197
321
  }
198
322
  if (kind === "posterize") {