Repository navigation
Expand file tree
/
Copy pathnodes_split.py
More file actions
1286 lines (1127 loc) · 55.4 KB
/
Copy pathnodes_split.py
File metadata and controls
1286 lines (1127 loc) · 55.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# nodes_split.py
"""ElementTileSplit — 纯几何分块 + 图像源(零模型依赖)。
- 图像来源:image 输入端口(优先)> 前端拖拽/粘贴上传的图(记录在 layout_data.source)
- 三种模式:manual(手画框图层)/ count / size(统一网格,忽略手画框)
- 未覆盖区域智能补块(fill_gaps,贪心最大矩形)
- 每层 upscale(生成分辨率)+ c×r 二次分割 + 层内 overlap
- 提示词合成:layer + ", " + global(层为空则仅 global)
- 输出:单个 tile_info(含 tile_images / original_image / prompt / negative_prompt / tile_masks / grid),由 ElementTileInfo 拆回
坐标系约定:
- 框/层坐标 = 源图像素空间(前端画布所见即所得,吸附 div)
- region/tile 坐标 = 输出画布空间(源 × unified_upscale,ceil 对齐 div);超出真实输出尺寸的边缘块向内平移(贴边整幅单块用边缘复制补边),merge 裁回真实尺寸
- gen(生成分辨率)= 源区域 × 该层 upscale,div 取整(VAE 合法尺寸,可超采样)
"""
import json
import logging
import math
import os
import random
import time
import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image, ImageOps
import comfy.utils
import folder_paths
GRID_TYPE = "ELEMENT_TILE_GRID"
TILEINFO_TYPE = "ELEMENT_TILE_INFO"
PREVIEW_MAX_EDGE = 2048 # 执行后节点内预览长边上限(仅预览,不影响输出)
MAX_TILES = 256
# 与前端 CORNER_RADIUS_SCALES_WITH_UPSCALE 保持一致
CORNER_RADIUS_SCALES_WITH_UPSCALE = True
# ================================================================
# Gap 规划 v4:core 禁区 + B&B 精确最少覆盖 + 块数目标驱动的自动加深覆盖
# ================================================================
GAP_MAX_ASPECT = 3.0 # 块长宽比上限(违例会触发下一档更深覆盖)
GAP_MIN_SHORT_DIVS = 2 # 块最短边下限(× div)
GAP_COVER_STEPS = (0, 8, 16, 25) # 允许覆盖手绘框短边的比例(%)
GAP_TARGET_TILES = 8 # 块数达标线(想更少就调小,如 4~6)
GAP_SEARCH_BUDGET = 1200 # 每轮 B&B 节点预算
def _clamp(v, lo, hi):
return max(lo, min(hi, v))
def _snap(v, div):
"""四舍五入到 div 的整数倍。"""
return int(round(v / div)) * div
def _snap_ceil(v, div):
"""向上取整到 div 的整数倍(画布只放大不裁切,保证边缘不被切掉)。"""
return max(div, int(math.ceil(v / div - 1e-6)) * div)
def _round_div(v, div):
return max(div, _snap(v, div))
def _compose(layer_p, global_p, append_mode=True):
"""根据模式组合提示词。"""
l_clean = str(layer_p).strip() if layer_p else ""
g_clean = str(global_p).strip() if global_p else ""
if append_mode:
parts = []
if l_clean: parts.append(l_clean)
if g_clean: parts.append(g_clean)
return ", ".join(parts)
else:
return l_clean if l_clean else g_clean
def _parse_state(raw):
try:
data = json.loads(raw) if isinstance(raw, str) else (raw or {})
except Exception:
data = {}
return data if isinstance(data, dict) else {}
def _norm_layers(data):
"""前端 JSON 里的手画框图层 → 后端结构化列表(数组顺序 = 图层顺序)。"""
layers = []
for i, l in enumerate(data.get("layers") or []):
if not isinstance(l, dict):
continue
try:
x, y = int(round(float(l.get("x", 0)))), int(round(float(l.get("y", 0))))
w, h = int(round(float(l.get("w", 0)))), int(round(float(l.get("h", 0))))
except Exception:
continue
if w <= 0 or h <= 0:
continue
try:
up = _clamp(float(l.get("upscale", 2.0) or 2.0), 0.1, 16.0)
except Exception:
up = 2.0
layers.append({
"id": l.get("id", i),
"color": str(l.get("color", "#888888")),
"x": x, "y": y, "w": w, "h": h,
"upscale": up,
"cols": _clamp(int(l.get("cols", 1) or 1), 1, 16),
"rows": _clamp(int(l.get("rows", 1) or 1), 1, 16),
"prompt": str(l.get("prompt", "") or ""),
"negative": str(l.get("negative", "") or ""),
"r_tl": max(0, int(l.get("r_tl", 0) or 0)),
"r_tr": max(0, int(l.get("r_tr", 0) or 0)),
"r_bl": max(0, int(l.get("r_bl", 0) or 0)),
"r_br": max(0, int(l.get("r_br", 0) or 0)),
})
return layers
def _overlap_px(mode, px_val, pct_val, tile_edge):
"""by px / by % 开关式二选一;% 基准 = 该层 tile 边长(输出空间)。"""
if mode == "pct":
return int(round(max(0.0, float(pct_val)) / 100.0 * tile_edge))
return max(0, int(px_val or 0))
def _inject_manual_overlap(tiles, default_ov, out_w, out_h):
"""对所有块(手绘框和背景块)强制向外扩展 default_ov/2。
因为每个块都往外扩了,所以边界必定产生物理重叠,Merge 节点才能正确羽化。
已越过真实输出尺寸的块(整幅单块)不回夹,避免把补边后的块压回。"""
if default_ov <= 0: return
half = max(0, default_ov // 2)
if half == 0: return
for t in tiles:
# 无论 layer 还是 gap,统一向外扩展,并限制在画布内;已越过真实输出的块不再回夹
lim_w = max(out_w, t["x"] + t["width"])
lim_h = max(out_h, t["y"] + t["height"])
nx = max(0, t["x"] - half)
ny = max(0, t["y"] - half)
nw = min(lim_w - nx, t["width"] + (t["x"] - nx) + half)
nh = min(lim_h - ny, t["height"] + (t["y"] - ny) + half)
t["x"] = nx
t["y"] = ny
t["width"] = nw
t["height"] = nh
def _compute_manual_fades(tiles, default_ov, out_w, out_h):
"""基于 tile 之间的真实 overlap 计算 fade_top/bottom/left/right。"""
n = len(tiles)
half = max(1, default_ov // 2)
for t in tiles:
t.setdefault("fade_top", 0)
t.setdefault("fade_bottom", 0)
t.setdefault("fade_left", 0)
t.setdefault("fade_right", 0)
for i in range(n):
for j in range(i + 1, n):
t, other = tiles[i], tiles[j]
# 如果其中一个是手绘框,直接跳过,后面会强制固定它
# if t.get("kind") == "layer" or other.get("kind") == "layer":
# continue
x_over = min(t["x"] + t["width"], other["x"] + other["width"]) - max(t["x"], other["x"])
y_over = min(t["y"] + t["height"], other["y"] + other["height"]) - max(t["y"], other["y"])
if x_over <= 0 or y_over <= 0:
continue
fade_val_x = min(x_over, default_ov)
fade_val_y = min(y_over, default_ov)
tcx = t["x"] + t["width"] / 2
ocx = other["x"] + other["width"] / 2
if ocx > tcx:
t["fade_right"] = max(t["fade_right"], fade_val_x)
other["fade_left"] = max(other["fade_left"], fade_val_x)
else:
t["fade_left"] = max(t["fade_left"], fade_val_x)
other["fade_right"] = max(other["fade_right"], fade_val_x)
tcy = t["y"] + t["height"] / 2
ocy = other["y"] + other["height"] / 2
if ocy > tcy:
t["fade_bottom"] = max(t["fade_bottom"], fade_val_y)
other["fade_top"] = max(other["fade_top"], fade_val_y)
else:
t["fade_top"] = max(t["fade_top"], fade_val_y)
other["fade_bottom"] = max(other["fade_bottom"], fade_val_y)
# 2. 强制手绘框的羽化四边绝对相等,并且等于外扩量
for t in tiles:
if t.get("kind") == "layer":
fw = min(half, t["width"] * 0.45)
fh = min(half, t["height"] * 0.45)
t["fade_top"] = fh if t["y"] > 0 else 0
t["fade_bottom"] = fh if t["y"] + t["height"] < out_h else 0
t["fade_left"] = fw if t["x"] > 0 else 0
t["fade_right"] = fw if t["x"] + t["width"] < out_w else 0
# 3. 全局绝对保护:所有块(无论 layer 还是 gap)的贴边处,羽化必须强制为 0
for t in tiles:
if t["x"] <= 0:
t["fade_left"] = 0
if t["y"] <= 0:
t["fade_top"] = 0
if t["x"] + t["width"] >= out_w:
t["fade_right"] = 0
if t["y"] + t["height"] >= out_h:
t["fade_bottom"] = 0
def _lock_band_mask(gen_w, gen_h, bands, feather):
"""锁边 mask:[1,h,w],1 = 允许重绘,0 = 只作参考。
bands = (left, top, right, bottom),锁定带宽度(<=0 表示该边不锁)。
feather 可为标量或 (left, top, right, bottom):外沿恒为 0,羽化落在锁定带内部
[band-feather, band];feather=band 时渐变正好覆盖整条带,不侵占带外的可重绘区。"""
gw, gh = max(1, int(gen_w)), max(1, int(gen_h))
if max(bands) <= 0:
return torch.ones((1, 1, 1), dtype=torch.float32)
if isinstance(feather, (tuple, list)):
fe = tuple(max(0.0, float(f)) for f in feather)
else:
fe = (max(0.0, float(feather)),) * 4
def _ramp(dist, band, f):
if band <= 0:
return None
f = min(max(0.0, f), band)
if f <= 0.0:
return (dist >= band).to(torch.float32)
t = ((dist - (band - f)) / f).clamp(0.0, 1.0)
return t * t * (3.0 - 2.0 * t)
xs = torch.arange(gw, dtype=torch.float32) + 0.5
ys = torch.arange(gh, dtype=torch.float32) + 0.5
mxs = [r for r in (_ramp(xs, bands[0], fe[0]), _ramp(gw - xs, bands[2], fe[2])) if r is not None]
mys = [r for r in (_ramp(ys, bands[1], fe[1]), _ramp(gh - ys, bands[3], fe[3])) if r is not None]
mx = torch.ones(gw) if not mxs else (mxs[0] if len(mxs) == 1 else torch.minimum(mxs[0], mxs[1]))
my = torch.ones(gh) if not mys else (mys[0] if len(mys) == 1 else torch.minimum(mys[0], mys[1]))
return torch.minimum(my[:, None], mx[None, :]).unsqueeze(0)
# ---------------------------------------------------------------- 几何切分
def _split_region(x, y, w, h, cols, rows, ov):
"""把一个 region 切成 cols×rows 个带 overlap 的子块,完整覆盖 [x,x+w]×[y,y+h]。
块宽 = (w + ov*(cols-1)) / cols(相邻块重叠 ov),末块贴齐右/下边界。"""
cols, rows, ov = max(1, int(cols)), max(1, int(rows)), max(0, int(ov))
if cols == 1 and rows == 1:
return [{"x": x, "y": y, "w": w, "h": h, "col": 0, "row": 0,
"fade_top": 0, "fade_bottom": 0, "fade_left": 0, "fade_right": 0}]
def _axis(total, n, o):
if n == 1:
return [(0, total)]
if o <= 0:
# 齐边切:累计取整保证相邻块首尾相接,外扩后每对相对边的距离恒等于重叠量。
# 若按固定 step 取整,块宽不能整除时会留下 1px 的错位,Merge 的中线就对不上。
b = [int(math.floor(i * total / n + 0.5)) for i in range(n + 1)]
return [(b[i], b[i + 1] - b[i]) for i in range(n)]
o = min(o, total) # 极端 overlap 下保持 step >= 0
cw = max(1, int(math.floor((total + o * (n - 1)) / n + 0.5)))
step = (total - cw) / (n - 1)
out = []
for i in range(n):
a = int(math.floor(i * step + 0.5))
end = a + cw if i < n - 1 else total
out.append((a, end - a))
return out
xs = _axis(w, cols, ov)
ys = _axis(h, rows, ov)
out = []
for j, (ty, th) in enumerate(ys):
fade_top = max(0, (ys[j-1][0] + ys[j-1][1]) - ty) if j > 0 else 0
fade_bottom = max(0, (ty + th) - ys[j+1][0]) if j < len(ys) - 1 else 0
for i, (tx, tw) in enumerate(xs):
fade_left = max(0, (xs[i-1][0] + xs[i-1][1]) - tx) if i > 0 else 0
fade_right = max(0, (tx + tw) - xs[i+1][0]) if i < len(xs) - 1 else 0
out.append({
"x": x + tx, "y": y + ty, "w": tw, "h": th, "col": i, "row": j,
"fade_top": fade_top, "fade_bottom": fade_bottom,
"fade_left": fade_left, "fade_right": fade_right
})
return out
def _snap(v, step):
return int(round(float(v) / step)) * step
def _round_js(v):
return int(math.floor(v + 0.5))
def _balanced_subsplit(rects, gap_max_px):
"""超 gap_max 的块做内部均衡切分(选子块长宽比最接近 1 的方案)。"""
out = []
for (rx, ry, rw, rh) in rects:
if rw <= gap_max_px and rh <= gap_max_px:
out.append((rx, ry, rw, rh))
continue
max_sc = max(1, math.ceil(rw / gap_max_px))
max_sr = max(1, math.ceil(rh / gap_max_px))
best = None
for sc in range(1, max_sc + 1):
sw = math.ceil(rw / sc)
if sw > gap_max_px: continue
for sr in range(1, max_sr + 1):
sh = math.ceil(rh / sr)
if sh > gap_max_px: continue
a = max(sw, sh) / max(1, min(sw, sh))
if best is None or a < best[0]: best = (a, sc, sr)
sc, sr = (max_sc, max_sr) if best is None else (best[1], best[2])
for i in range(sc):
x0 = rx + _round_js(i * rw / sc)
x1 = rx + _round_js((i + 1) * rw / sc)
for j in range(sr):
y0 = ry + _round_js(j * rh / sr)
y1 = ry + _round_js((j + 1) * rh / sr)
out.append((x0, y0, x1 - x0, y1 - y0))
return out
# ================================================================
# 圆弧求交 + 单刀切割 + 安全探测扩张(与前端逐位镜像)
# ================================================================
def _get_top_y(lx, R):
rx, ry, rw, rh = R["x"], R["y"], R["w"], R["h"]
rtl = R.get("rtl", 0) or 0
rtr = R.get("rtr", 0) or 0
if lx < rx: return ry
if lx > rx + rw: return ry
if lx < rx + rtl:
cx, cy = rx + rtl, ry + rtl
dx = cx - lx
return cy - math.sqrt(max(0.0, rtl * rtl - dx * dx))
if lx > rx + rw - rtr:
cx, cy = rx + rw - rtr, ry + rtr
dx = lx - cx
return cy - math.sqrt(max(0.0, rtr * rtr - dx * dx))
return ry
def _get_bottom_y(lx, R):
rx, ry, rw, rh = R["x"], R["y"], R["w"], R["h"]
rbl = R.get("rbl", 0) or 0
rbr = R.get("rbr", 0) or 0
if lx < rx: return ry + rh
if lx > rx + rw: return ry + rh
if lx < rx + rbl:
cx, cy = rx + rbl, ry + rh - rbl
dx = cx - lx
return cy + math.sqrt(max(0.0, rbl * rbl - dx * dx))
if lx > rx + rw - rbr:
cx, cy = rx + rw - rbr, ry + rh - rbr
dx = lx - cx
return cy + math.sqrt(max(0.0, rbr * rbr - dx * dx))
return ry + rh
def _get_left_x(ly, R):
rx, ry, rw, rh = R["x"], R["y"], R["w"], R["h"]
rtl = R.get("rtl", 0) or 0
rbl = R.get("rbl", 0) or 0
if ly < ry: return rx
if ly > ry + rh: return rx
if ly < ry + rtl:
cx, cy = rx + rtl, ry + rtl
dy = cy - ly
return cx - math.sqrt(max(0.0, rtl * rtl - dy * dy))
if ly > ry + rh - rbl:
cx, cy = rx + rbl, ry + rh - rbl
dy = ly - cy
return cx - math.sqrt(max(0.0, rbl * rbl - dy * dy))
return rx
def _get_right_x(ly, R):
rx, ry, rw, rh = R["x"], R["y"], R["w"], R["h"]
rtr = R.get("rtr", 0) or 0
rbr = R.get("rbr", 0) or 0
if ly < ry: return rx + rw
if ly > ry + rh: return rx + rw
if ly < ry + rtr:
cx, cy = rx + rw - rtr, ry + rtr
dy = cy - ly
return cx + math.sqrt(max(0.0, rtr * rtr - dy * dy))
if ly > ry + rh - rbr:
cx, cy = rx + rw - rbr, ry + rh - rbr
dy = ly - cy
return cx + math.sqrt(max(0.0, rbr * rbr - dy * dy))
return rx + rw
def _subtract_single_cut(p, R):
"""与前端 subtractSingleCut 逐位镜像。None 表示 B 完全被 A 包含。"""
px, py, pw, ph = p
pb, pr = py + ph, px + pw
ox = max(px, R["x"])
oy = max(py, R["y"])
ox2 = min(pr, R["x"] + R["w"])
oy2 = min(pb, R["y"] + R["h"])
if ox >= ox2 or oy >= oy2:
return p
rtl = R.get("rtl", 0) or 0
rtr = R.get("rtr", 0) or 0
rbl = R.get("rbl", 0) or 0
rbr = R.get("rbr", 0) or 0
def _inside(x, y):
if x < R["x"] - 1e-6 or x > R["x"] + R["w"] + 1e-6: return False
if y < R["y"] - 1e-6 or y > R["y"] + R["h"] + 1e-6: return False
if rtl > 0 and x < R["x"] + rtl and y < R["y"] + rtl:
return (x - (R["x"] + rtl))**2 + (y - (R["y"] + rtl))**2 <= rtl*rtl + 1e-4
if rtr > 0 and x > R["x"] + R["w"] - rtr and y < R["y"] + rtr:
return (x - (R["x"] + R["w"] - rtr))**2 + (y - (R["y"] + rtr))**2 <= rtr*rtr + 1e-4
if rbl > 0 and x < R["x"] + rbl and y > R["y"] + R["h"] - rbl:
return (x - (R["x"] + rbl))**2 + (y - (R["y"] + R["h"] - rbl))**2 <= rbl*rbl + 1e-4
if rbr > 0 and x > R["x"] + R["w"] - rbr and y > R["y"] + R["h"] - rbr:
return (x - (R["x"] + R["w"] - rbr))**2 + (y - (R["y"] + R["h"] - rbr))**2 <= rbr*rbr + 1e-4
return True
if _inside(px, py) and _inside(pr, py) and _inside(px, pb) and _inside(pr, pb):
return None
cov_top = (R["x"] <= px and R["x"] + R["w"] >= pr and R["y"] <= py and R["y"] + R["h"] > py) and _inside(px, py) and _inside(pr, py)
cov_bottom = (R["x"] <= px and R["x"] + R["w"] >= pr and R["y"] < pb and R["y"] + R["h"] >= pb) and _inside(px, pb) and _inside(pr, pb)
cov_left = (R["y"] <= py and R["y"] + R["h"] >= pb and R["x"] <= px and R["x"] + R["w"] > px) and _inside(px, py) and _inside(px, pb)
cov_right = (R["y"] <= py and R["y"] + R["h"] >= pb and R["x"] < pr and R["x"] + R["w"] >= pr) and _inside(pr, py) and _inside(pr, pb)
if not (cov_top or cov_bottom or cov_left or cov_right):
return p
best_area = float("inf")
best_type = None
best_cut = 0.0
if cov_top:
cut_y = min(_get_bottom_y(px, R), _get_bottom_y(pr, R))
cut_y = max(float(py), min(float(pb), cut_y))
area = pw * (pb - cut_y)
if 0 <= area < best_area:
best_area = area
best_type = 'top'
best_cut = cut_y
if cov_bottom:
cut_y = max(_get_top_y(px, R), _get_top_y(pr, R))
cut_y = max(float(py), min(float(pb), cut_y))
area = pw * (cut_y - py)
if 0 <= area < best_area:
best_area = area
best_type = 'bottom'
best_cut = cut_y
if cov_left:
cut_x = min(_get_right_x(py, R), _get_right_x(pb, R))
cut_x = max(float(px), min(float(pr), cut_x))
area = ph * (pr - cut_x)
if 0 <= area < best_area:
best_area = area
best_type = 'left'
best_cut = cut_x
if cov_right:
cut_x = max(_get_left_x(py, R), _get_left_x(pb, R))
cut_x = max(float(px), min(float(pr), cut_x))
area = ph * (cut_x - px)
if 0 <= area < best_area:
best_area = area
best_type = 'right'
best_cut = cut_x
if best_type is None:
return p
nx, ny, nw, nh = float(px), float(py), float(pw), float(ph)
if best_type == 'top':
ny = best_cut
nh = pb - best_cut
elif best_type == 'bottom':
ny = py
nh = best_cut - py
elif best_type == 'left':
nx = best_cut
nw = pr - best_cut
elif best_type == 'right':
nx = px
nw = best_cut - px
if nw <= 0 or nh <= 0:
return None
return (nx, ny, nw, nh)
def _rect_intersects_rounded_rect(rect, R):
rx, ry, rw, rh = rect
rx2, ry2 = rx + rw, ry + rh
if rx2 <= R["x"] or rx >= R["x"] + R["w"] or ry2 <= R["y"] or ry >= R["y"] + R["h"]:
return False
rtl = R.get("rtl", 0) or 0
rtr = R.get("rtr", 0) or 0
rbl = R.get("rbl", 0) or 0
rbr = R.get("rbr", 0) or 0
cx0 = R["x"] + max(rtl, rbl)
cx1 = R["x"] + R["w"] - max(rtr, rbr)
cy0 = R["y"] + max(rtl, rtr)
cy1 = R["y"] + R["h"] - max(rbl, rbr)
if rx < cx1 and rx2 > cx0 and ry < cy1 and ry2 > cy0:
return True
def circle_intersects(cx, cy, r):
nx = max(rx, min(cx, rx2))
ny = max(ry, min(cy, ry2))
return (nx - cx) ** 2 + (ny - cy) ** 2 < r * r
if rtl > 0:
cx = R["x"] + rtl
cy = R["y"] + rtl
nx = max(rx, min(cx, rx2))
ny = max(ry, min(cy, ry2))
if nx <= cx and ny <= cy and circle_intersects(cx, cy, rtl): return True
if rtr > 0:
cx = R["x"] + R["w"] - rtr
cy = R["y"] + rtr
nx = max(rx, min(cx, rx2))
ny = max(ry, min(cy, ry2))
if nx >= cx and ny <= cy and circle_intersects(cx, cy, rtr): return True
if rbl > 0:
cx = R["x"] + rbl
cy = R["y"] + R["h"] - rbl
nx = max(rx, min(cx, rx2))
ny = max(ry, min(cy, ry2))
if nx <= cx and ny >= cy and circle_intersects(cx, cy, rbl): return True
if rbr > 0:
cx = R["x"] + R["w"] - rbr
cy = R["y"] + R["h"] - rbr
nx = max(rx, min(cx, rx2))
ny = max(ry, min(cy, ry2))
if nx >= cx and ny >= cy and circle_intersects(cx, cy, rbr): return True
return False
def _get_safe_expand(rect, direction, max_dist, regions):
x, y, w, h = rect
safe = 0.0
step = 4.0
while safe < max_dist:
d = min(max_dist - safe, step)
if direction == 'top': test_rect = (x, y - safe - d, w, d)
elif direction == 'bottom': test_rect = (x, y + h + safe, w, d)
elif direction == 'left': test_rect = (x - safe - d, y, d, h)
elif direction == 'right': test_rect = (x + w + safe, y, d, h)
else: break
hit = any(_rect_intersects_rounded_rect(test_rect, rg) for rg in regions)
if hit:
if d > 1:
d = 1
if direction == 'top': test_rect = (x, y - safe - 1, w, 1)
elif direction == 'bottom': test_rect = (x, y + h + safe, w, 1)
elif direction == 'left': test_rect = (x - safe - 1, y, 1, h)
elif direction == 'right': test_rect = (x + w + safe, y, 1, h)
hit1 = any(_rect_intersects_rounded_rect(test_rect, rg) for rg in regions)
if hit1: break
safe += 1
continue
break
safe += d
return safe
def _can_merge(A, B, eps=5.0):
"""相切边等长(允许 eps 容差)+ 贴合才允许合并。"""
x, y, w, h = A
qx, qy, qw, qh = B
vert_align = abs(x - qx) <= eps and abs(w - qw) <= eps
vert_touch = abs((y + h) - qy) <= eps or abs((qy + qh) - y) <= eps
if vert_align and vert_touch:
return True
horz_align = abs(y - qy) <= eps and abs(h - qh) <= eps
horz_touch = abs((x + w) - qx) <= eps or abs((qx + qw) - x) <= eps
if horz_align and horz_touch:
return True
return False
def _plan_gap_tiles(covered, div, out_w, out_h, gap_max_px, overlap_px=0,
regions=None, target_tiles=GAP_TARGET_TILES):
"""与前端 planGaps 逐位镜像:均分 → 单刀切割 → 合并 → 变胖 → 超尺寸平分。"""
if regions is None:
regions = []
if not regions:
out = [(int(r[0]), int(r[1]), int(r[2]), int(r[3]))
for r in _balanced_subsplit([(0, 0, out_w, out_h)], gap_max_px)]
out.sort(key=lambda r: (r[1], r[0]))
return out
base_grid = _balanced_subsplit([(0, 0, out_w, out_h)], gap_max_px)
pieces = []
for b in base_grid:
parts = [b]
for rg in regions:
rr_dict = rg if isinstance(rg, dict) else {
"x": rg[0], "y": rg[1], "w": rg[2], "h": rg[3],
"rtl": 0, "rtr": 0, "rbl": 0, "rbr": 0
}
nxt = []
for p in parts:
res = _subtract_single_cut(p, rr_dict)
if res is not None:
nxt.append(res)
parts = nxt
if not parts:
break
pieces.extend(parts)
changed = True
iter_count = 0
max_iter = 60 + len(pieces) * 4
while changed and iter_count < max_iter:
changed = False
iter_count += 1
pieces.sort(key=lambda p: p[2] * p[3])
for i in range(len(pieces)):
if pieces[i] is None:
continue
x, y, w, h = pieces[i]
best_j = -1
best_area = float("inf")
for j in range(len(pieces)):
if i == j or pieces[j] is None:
continue
if not _can_merge((x, y, w, h), pieces[j]):
continue
a = pieces[j][2] * pieces[j][3]
if a < best_area:
best_area = a
best_j = j
if best_j >= 0:
qx, qy, qw, qh = pieces[best_j]
nx = min(x, qx)
ny = min(y, qy)
nx_end = max(x + w, qx + qw)
ny_end = max(y + h, qy + qh)
pieces[i] = (nx, ny, nx_end - nx, ny_end - ny)
pieces[best_j] = None
changed = True
break
if max(w, h) / max(1, min(w, h)) > 5.0:
target_w, target_h = w, h
if w > h:
target_h = math.ceil(w / 5.0)
else:
target_w = math.ceil(h / 5.0)
cands = []
if target_h > h:
diff = target_h - h
safe_t = _get_safe_expand((x, y, w, h), 'top',
min(diff, y), regions)
safe_b = _get_safe_expand((x, y - safe_t, w, h + safe_t), 'bottom',
min(diff - safe_t, out_h - (y + h)), regions)
if safe_t + safe_b > 0:
cands.append((x, y - safe_t, w, h + safe_t + safe_b))
if safe_t > 0:
cands.append((x, y - safe_t, w, h + safe_t))
if safe_b > 0:
cands.append((x, y, w, h + safe_b))
elif target_w > w:
diff = target_w - w
safe_l = _get_safe_expand((x, y, w, h), 'left',
min(diff, x), regions)
safe_r = _get_safe_expand((x - safe_l, y, w + safe_l, h), 'right',
min(diff - safe_l, out_w - (x + w)), regions)
if safe_l + safe_r > 0:
cands.append((x - safe_l, y, w + safe_l + safe_r, h))
if safe_l > 0:
cands.append((x - safe_l, y, w + safe_l, h))
if safe_r > 0:
cands.append((x, y, w + safe_r, h))
fattened = False
for bx, by, bw, bh in cands:
swallow = []
ok = True
for j in range(len(pieces)):
if i == j or pieces[j] is None:
continue
qx, qy, qw, qh = pieces[j]
ix = max(bx, qx)
iy = max(by, qy)
ix2 = min(bx + bw, qx + qw)
iy2 = min(by + bh, qy + qh)
if ix >= ix2 - 0.1 or iy >= iy2 - 0.1:
continue
if (qx < bx - 0.1 or qy < by - 0.1 or
qx + qw > bx + bw + 0.1 or qy + qh > by + bh + 0.1):
ok = False
break
swallow.append(j)
if not ok:
continue
pieces[i] = (bx, by, bw, bh)
for j in swallow:
pieces[j] = None
changed = True
fattened = True
break
if fattened:
break
if changed:
pieces = [p for p in pieces if p is not None]
final_pieces = []
for p in pieces:
p_int = (_round_js(p[0]), _round_js(p[1]),
_round_js(p[2]), _round_js(p[3]))
if p_int[2] > gap_max_px or p_int[3] > gap_max_px:
final_pieces.extend(_balanced_subsplit([p_int], gap_max_px))
else:
final_pieces.append(p_int)
# 输出顺序:先横向(同一行从左到右),再纵向(行从上到下)
final_pieces.sort(key=lambda r: (r[1], r[0]))
return final_pieces
# ---------------------------------------------------------------- 图像源 / 预览
def _load_source_image(data, image):
"""优先级:image 端口 > layout_data.source(拖拽/粘贴上传图)。"""
if image is not None:
img = image
if img.ndim == 2:
img = img.unsqueeze(0)
if img.ndim == 3:
img = img.unsqueeze(0)
if img.shape[0] > 1:
logging.warning("[TileSplit] batch of %d connected; using the first frame",
img.shape[0])
img = img[:1]
if img.shape[-1] == 4:
img = img[..., :3]
return img.contiguous()
src = data.get("source") or {}
name = str(src.get("filename", "") or "").strip()
if not name:
raise ValueError(
"ElementTileSplit: no image source. Connect an image input, or drop/paste "
"an image onto the node in the browser.")
subfolder = str(src.get("subfolder", "") or "").strip()
path = folder_paths.get_annotated_filepath(f"{subfolder}/{name}" if subfolder else name)
if not os.path.exists(path):
raise ValueError(f"ElementTileSplit: image file not found: {name} "
f"(re-drop or re-paste it in the node UI)")
i = ImageOps.exif_transpose(Image.open(path)).convert("RGB")
arr = np.array(i).astype(np.float32) / 255.0
return torch.from_numpy(arr).unsqueeze(0)
def _save_preview(image, unique_id):
"""执行后节点内预览,双写(对齐 Element_ImageCurve 链路):
- temp 目录 + 唯一文件名 → ui["bg_image"],前端 onExecuted 实时显示
- input 目录 + 固定文件名 → ui["preview"],持久引用,重启后仍可显示
"""
try:
_, h, w, _ = image.shape
src_meta = {"w": int(w), "h": int(h)}
scale = min(1.0, PREVIEW_MAX_EDGE / max(h, w))
if scale < 1.0:
nh, nw = max(1, round(h * scale)), max(1, round(w * scale))
image = comfy.utils.common_upscale(
image.permute(0, 3, 1, 2), nw, nh, "area", "disabled").permute(0, 2, 3, 1)
arr = (image[0].detach().cpu().numpy() * 255.0).clip(0, 255).astype(np.uint8)
pil = Image.fromarray(arr)
bg, ref = None, None
try:
temp_dir = folder_paths.get_temp_directory()
os.makedirs(temp_dir, exist_ok=True)
name = f"tilesplit_preview_{int(time.time() * 1000)}_{random.randint(1, 1000000)}.png"
pil.save(os.path.join(temp_dir, name), format="PNG")
bg = [{"filename": name, "subfolder": "", "type": "temp", **src_meta}]
except Exception as e:
logging.warning("[TileSplit] preview temp failed: %s", e)
try:
sub = "element_tile_split/preview"
out_dir = os.path.join(folder_paths.get_input_directory(), sub)
os.makedirs(out_dir, exist_ok=True)
name = f"ets_preview_{unique_id}.jpg"
pil.save(os.path.join(out_dir, name), format="JPEG", quality=92)
ref = {"filename": name, "subfolder": sub, "type": "input", **src_meta}
except Exception as e:
logging.warning("[TileSplit] preview persist failed: %s", e)
return bg, ref
except Exception as e:
logging.warning("[TileSplit] preview save failed: %s", e)
return None, None
# ---------------------------------------------------------------- 节点
class ElementTileSplit:
"""纯几何分块节点:画布/图层 UI 状态经 layout_data(JSON widget) 传入,
所有几何在执行时后端全量重算校验(前端仅为预览,防陈旧数据)。"""
CATEGORY = "Element TileEdit"
FUNCTION = "split"
OUTPUT_NODE = True
RETURN_TYPES = (TILEINFO_TYPE,)
RETURN_NAMES = ("tile_info",)
OUTPUT_IS_LIST = (False,)
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"layout_data": ("STRING", {"default": "{}", "multiline": True,
"tooltip": "Internal UI state (hidden)."}),
},
"optional": {
"image": ("IMAGE",),
},
"hidden": {
"unique_id": "UNIQUE_ID",
},
}
def split(self, layout_data="{}", image=None, unique_id=None):
data = _parse_state(layout_data)
div = _clamp(int(data.get("div", 16) or 16), 2, 256)
mode = str(data.get("mode", "manual") or "manual")
unified = data.get("unified") or {}
try:
u_up = _clamp(float(unified.get("upscale", 2.0) or 2.0), 0.1, 16.0)
except Exception:
u_up = 2.0
u_cols = _clamp(int(unified.get("columns", 2) or 2), 1, 16)
u_rows = _clamp(int(unified.get("rows", 2) or 2), 1, 16)
u_tile = _clamp(int(unified.get("tile_size", 1024) or 1024), div, 8192)
ov_mode = str(data.get("overlap_mode", "px") or "px")
ov_px = data.get("overlap_px", 64)
ov_pct = data.get("overlap_pct", 15)
fill_gaps = bool(data.get("fill_gaps", True))
gap_max = _clamp(int(data.get("gap_max_px", 1536) or 1536), div, 8192)
g_prompt = str(data.get("global_prompt", "") or "")
g_neg = str(data.get("global_negative", "") or "")
g_append = bool(data.get("global_append", True))
enable_lup = bool(data.get("enable_layer_upscale", False))
enable_mask = bool(data.get("enable_mask", False))
mask_band_pct = _clamp(float(data.get("edge_mask_pct", 90) or 0), 0.0, 100.0)
mask_feather_pct = _clamp(float(data.get("edge_mask_feather", 50) or 0), 0.0, 100.0)
layers = _norm_layers(data)
source = _load_source_image(data, image)
_, src_h, src_w, channels = source.shape
# 画布按 div 上取整会略大于真实输出尺寸;边缘块不补外部像素,
# 而是整块向画面内平移,合并后再裁回真实尺寸。
exact_w = max(1, int(round(src_w * u_up)))
exact_h = max(1, int(round(src_h * u_up)))
out_w = _snap_ceil(src_w * u_up, div)
out_h = _snap_ceil(src_h * u_up, div)
tiles, prompts, negatives, ov_values = [], [], [], []
def emit(subs, layer=None, layer_index=-1):
for t in subs:
up_val = u_up
if layer is not None and enable_lup:
up_val = layer["upscale"]
if layer is not None:
p = _compose(layer["prompt"], g_prompt, g_append)
n = _compose(layer["negative"], g_neg, g_append)
else:
p, n = g_prompt.strip(), g_neg.strip()
prompts.append(p)
negatives.append(n)
tiles.append({
"x": t["x"], "y": t["y"], "width": t["w"], "height": t["h"],
"col": t.get("col", 0), "row": t.get("row", 0),
"layer": layer_index, "layer_id": layer["id"] if layer else None,
"upscale": up_val,
"kind": t.get("kind", "layer"),
"fade_top": t.get("fade_top", 0),
"fade_bottom": t.get("fade_bottom", 0),
"fade_left": t.get("fade_left", 0),
"fade_right": t.get("fade_right", 0),
"radius_tl": t.get("radius_tl", 0),
"radius_tr": t.get("radius_tr", 0),
"radius_bl": t.get("radius_bl", 0),
"radius_br": t.get("radius_br", 0),
"layer_region": t.get("layer_region"),
})
manual_mode = mode == "manual"
covered = None
if manual_mode:
layer_regions = []
scale_r = u_up if CORNER_RADIUS_SCALES_WITH_UPSCALE else 1.0
for l in layers:
rx = _clamp(_snap(l["x"] * u_up, div), 0, out_w - div)
ry = _clamp(_snap(l["y"] * u_up, div), 0, out_h - div)
if l["x"] + l["w"] >= src_w - 0.5:
rw = out_w - rx
else:
rw = _clamp(_snap(l["w"] * u_up, div), div, out_w - rx)
if l["y"] + l["h"] >= src_h - 0.5:
rh = out_h - ry
else:
rh = _clamp(_snap(l["h"] * u_up, div), div, out_h - ry)
half_lim = max(1, min(rw, rh) // 2)
rtl = min(int(round(l.get("r_tl", 0) * scale_r)), half_lim)
rtr = min(int(round(l.get("r_tr", 0) * scale_r)), half_lim)
rbl = min(int(round(l.get("r_bl", 0) * scale_r)), half_lim)
rbr = min(int(round(l.get("r_br", 0) * scale_r)), half_lim)
layer_regions.append((l, {
"x": rx, "y": ry, "w": rw, "h": rh,
"rtl": rtl, "rtr": rtr, "rbl": rbl, "rbr": rbr,
}))
if fill_gaps:
cols_n, rows_n = out_w // div, out_h // div
covered = [[False] * cols_n for _ in range(rows_n)]
for _, rg in layer_regions:
c0, r0 = rg["x"] // div, rg["y"] // div
c1 = (rg["x"] + rg["w"] + div - 1) // div
r1 = (rg["y"] + rg["h"] + div - 1) // div
for r in range(max(0, r0), min(r1, rows_n)):
row = covered[r]
for c in range(max(0, c0), min(c1, cols_n)):
row[c] = True
for li, (l, rg) in enumerate(layer_regions):
# 子块先齐边切开,重叠统一由 _inject_manual_overlap 提供(每块各外扩
# default_ov/2),这样一层拆多块时的重叠宽度和块外重叠一样 = default_ov,
# 不会在切块这里再多叠一份。
subs = _split_region(rg["x"], rg["y"], rg["w"], rg["h"],
l["cols"], l["rows"], 0)
for s in subs:
s["kind"] = "layer"
s["radius_tl"] = rg["rtl"]
s["radius_tr"] = rg["rtr"]
s["radius_bl"] = rg["rbl"]
s["radius_br"] = rg["rbr"]
s["layer_w"] = rg["w"]
s["layer_h"] = rg["h"]
s["offset_x"] = s["x"] - rg["x"]
s["offset_y"] = s["y"] - rg["y"]
s["layer_region"] = (rg["x"], rg["y"], rg["w"], rg["h"])
emit(subs, layer=l, layer_index=li)
if not layer_regions and not fill_gaps:
logging.warning("[TileSplit] manual mode with no boxes; "
"whole canvas as one tile")
emit([{"x": 0, "y": 0, "w": out_w, "h": out_h,
"col": 0, "row": 0, "kind": "fallback"}])
if ov_mode == "px":
default_ov = max(0, int(ov_px or 0))
else:
default_ov = int(round(min(out_w, out_h) * (max(0.0, float(ov_pct)) / 100.0)))
if fill_gaps and covered is not None:
rg_list = [rg for _, rg in layer_regions]
# 传入 overlap_px=0,最后会对所有 tiles 统一外扩
for i, (gx, gy, gw, gh) in enumerate(
_plan_gap_tiles(covered, div, out_w, out_h, gap_max,
overlap_px=0, regions=rg_list)):
emit([{"x": gx, "y": gy, "w": gw, "h": gh,
"col": i, "row": 0, "kind": "gap"}])
else:
if mode == "size":
cols = max(1, -(-out_w // u_tile))
rows = max(1, -(-out_h // u_tile))