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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
//! Stroke lifecycle, flood fill, erase helpers, and paint infrastructure.
use super::rendering::commit_undo_region;
use super::types::StrokeOp;
use super::{DarklyEngine, PendingUndoCommit, ReadbackContext};
use crate::brush::checkpoint_ring::CheckpointRing;
use crate::brush::gpu_context::{BrushGpuContext, BrushPerfCounters, DabBatch, StrokeResources};
use crate::brush::paint_info::PaintInformation;
use crate::brush::spacing::SpacingConfig;
use crate::brush::stroke_buffer::StrokeBuffer;
use crate::brush::stroke_engine::StrokeEngine;
use crate::coord::CanvasRect;
use crate::gpu::flood_fill;
use crate::gpu::paint_target::{GpuPaintTarget, PaintPipelines};
use crate::gpu::region_store::UndoRegionEntry;
use crate::layer::LayerId;
use crate::undo::GpuRegionAction;
impl DarklyEngine {
/// Read the stabilize strength from the pen_input node's "stabilize" port
/// default in the active brush graph. Returns 0.0 if not found.
fn pen_input_stabilize_strength(&self) -> f32 {
use crate::brush::state::BrushState;
let tool = self.tool_session.read();
let brush = tool
.get::<BrushState>()
.expect("BrushState registered at session init");
crate::brush::nodes::pen_input::read_scalar_input(&brush.graph, "stabilize").unwrap_or(0.0)
}
/// Build the `SpacingConfig` for the active brush graph. Reads pen_input
/// port defaults — the same source the editor preview reads — so a real
/// stroke and its preview stamp at the same intervals.
fn active_spacing_config(&self) -> SpacingConfig {
use crate::brush::state::BrushState;
let tool = self.tool_session.read();
let brush = tool
.get::<BrushState>()
.expect("BrushState registered at session init");
crate::brush::nodes::pen_input::spacing_config(&brush.graph)
}
/// Flush any pending diff-based undo commit. Called before overwriting the
/// scratch texture (e.g. at the start of a new stroke). Uses Poll (not Wait)
/// — if the diff hasn't completed yet, falls back to a full-canvas rect.
pub(crate) fn flush_pending_undo_commit(&mut self) {
if !self.diff_rect.is_pending() {
return;
}
let Some(commit) = self.pending_undo_commit.take() else {
return;
};
// Try to collect the result without blocking.
let _ = self.gpu.device.poll(wgpu::PollType::Poll);
let rect = match self.diff_rect.poll(&self.gpu.device) {
Some(Some(rect)) => rect,
Some(None) => return, // Textures identical — no commit needed.
// Diff not ready — fall back to the full saved area. (NOT
// `scratch_dimensions()` — those diverge from `snapshot.saved`
// after a mid-stroke `grow_scratch_preserving`.)
None => commit.snapshot.saved,
};
let layer_frame = match self.compositor.node_texture(commit.layer_id) {
Some(t) => t.canvas_frame(),
None => return,
};
let entry = commit_undo_region(
&self.gpu,
&self.region_scratch,
&mut self.readbacks,
"brush-stroke-end-flush",
commit.layer_id,
&layer_frame,
&commit.snapshot,
rect,
);
self.push_undo(Box::new(GpuRegionAction::new(entry)));
}
// --- Painting ---
/// Snapshot `rect` of `node_id`'s texture, run an in-place GPU mutation
/// (encoded into the SAME command buffer, after the save), commit it as a
/// `GpuRegionAction`, and mark the node dirty. The canonical "edit a region
/// with undo" unit. `mutate` receives the node's paint target, the paint
/// pipelines, and the queue, so it never re-borrows `self`. The texture
/// format is resolved from the node. Returns `false` if the node has no
/// texture.
pub(crate) fn region_undo_inplace(
&mut self,
node_id: LayerId,
rect: CanvasRect,
label_save: &str,
label_commit: &'static str,
mutate: impl FnOnce(
&mut wgpu::CommandEncoder,
GpuPaintTarget<'_>,
&PaintPipelines,
&wgpu::Queue,
),
) -> bool {
let Some(tex) = self.compositor.node_texture(node_id) else {
return false;
};
let frame = tex.canvas_frame();
let format = tex.format();
let target = GpuPaintTarget::from_node(tex, self.doc.canvas_rect());
// Save then mutate in one command buffer — wgpu executes recorded
// commands in order, so the snapshot captures pre-mutation pixels.
let snap = self.gpu.encode_ret(label_save, |encoder| {
let snap =
self.region_scratch
.save_region(&self.gpu.device, encoder, &frame, format, rect);
mutate(encoder, target, &self.paint_pipelines, &self.gpu.queue);
snap
});
// `frame`'s last use; after this the shared `compositor` borrow is free
// for the `&mut` calls below (NLL).
let entry = commit_undo_region(
&self.gpu,
&self.region_scratch,
&mut self.readbacks,
label_commit,
node_id,
&frame,
&snap,
rect,
);
self.push_undo(Box::new(GpuRegionAction::new(entry)));
self.compositor.mark_node_pixels_dirty(node_id);
true
}
/// Snapshot+commit a node region into an `UndoRegionEntry` without pushing
/// or marking dirty — for callers that batch many entries into one compound
/// action (canvas transform, image rescale) and run the GPU permute
/// separately. Returns `None` if the node has no texture.
pub(crate) fn snapshot_region_entry(
&mut self,
node_id: LayerId,
rect: CanvasRect,
format: wgpu::TextureFormat,
label_save: &str,
label_commit: &'static str,
) -> Option<UndoRegionEntry> {
let frame = self.compositor.node_texture(node_id)?.canvas_frame();
let snap = self.gpu.encode_ret(label_save, |encoder| {
self.region_scratch
.save_region(&self.gpu.device, encoder, &frame, format, rect)
});
Some(commit_undo_region(
&self.gpu,
&self.region_scratch,
&mut self.readbacks,
label_commit,
node_id,
&frame,
&snap,
rect,
))
}
/// Fill the layer with the default background image, centered and clipped
/// to the canvas. The image is baked into the binary at build time.
pub fn fill_background(&mut self, layer_id: LayerId) {
if !self.is_node_paintable(layer_id) {
return;
}
const IMAGE_BYTES: &[u8] = include_bytes!("../../resources/backgrounds/quiet-night.jpg");
let canvas_w = self.compositor.canvas_width();
let canvas_h = self.compositor.canvas_height();
let rect = self.doc.canvas_rect();
let format = wgpu::TextureFormat::Rgba8Unorm;
let layer_tex = match self.compositor.node_texture(layer_id) {
Some(t) => t,
None => return,
};
let layer_frame = layer_tex.canvas_frame();
// Save current state to scratch for undo.
let snap = self.gpu.encode_ret("fill-background-save", |encoder| {
self.region_scratch
.save_region(&self.gpu.device, encoder, &layer_frame, format, rect)
});
let entry = commit_undo_region(
&self.gpu,
&self.region_scratch,
&mut self.readbacks,
"fill-background-commit",
layer_id,
&layer_frame,
&snap,
rect,
);
self.push_undo(Box::new(GpuRegionAction::new(entry)));
let decoded = image::load_from_memory(IMAGE_BYTES)
.expect("failed to decode embedded background image")
.to_rgba8();
let (img_w, img_h) = decoded.dimensions();
// Center the image on the canvas, clipped to canvas bounds.
let offset_x = (canvas_w as i32 - img_w as i32) / 2;
let offset_y = (canvas_h as i32 - img_h as i32) / 2;
let src_x = (-offset_x).max(0) as u32;
let src_y = (-offset_y).max(0) as u32;
let dst_x = offset_x.max(0) as u32;
let dst_y = offset_y.max(0) as u32;
let copy_w = (img_w - src_x).min(canvas_w - dst_x);
let copy_h = (img_h - src_y).min(canvas_h - dst_y);
if copy_w > 0 && copy_h > 0 {
let layer_tex = self.compositor.node_texture(layer_id).unwrap();
let row_bytes = copy_w as usize * 4;
let mut buf = vec![0u8; row_bytes * copy_h as usize];
let full = decoded.as_raw();
for row in 0..copy_h as usize {
let src_row = (src_y as usize + row) * img_w as usize * 4 + src_x as usize * 4;
let dst_row = row * row_bytes;
buf[dst_row..dst_row + row_bytes]
.copy_from_slice(&full[src_row..src_row + row_bytes]);
}
self.gpu.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: layer_tex.texture(),
mip_level: 0,
origin: wgpu::Origin3d {
x: dst_x,
y: dst_y,
z: 0,
},
aspect: wgpu::TextureAspect::All,
},
&buf,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(row_bytes as u32),
rows_per_image: None,
},
wgpu::Extent3d {
width: copy_w,
height: copy_h,
depth_or_array_layers: 1,
},
);
}
self.compositor.mark_node_pixels_dirty(layer_id);
}
/// Fill the layer with a solid RGBA color, clipped to the canvas. Used by
/// the "New Document" flow to seed a fresh raster layer with the user's
/// chosen background color. Pushes a `GpuRegionAction` for undo, matching
/// `fill_background`'s pattern.
pub fn fill_background_color(&mut self, layer_id: LayerId, color: [u8; 4]) {
if !self.is_node_paintable(layer_id) {
return;
}
let rect = self.doc.canvas_rect();
self.region_undo_inplace(
layer_id,
rect,
"fill-background-color",
"fill-background-color-commit",
|encoder, target, pipelines, queue| {
target.fill_rect(encoder, pipelines, queue, rect, color);
},
);
}
// --- Stroke lifecycle ---
// The active node id directly identifies the paint target — for a mask
// filter id, paint goes to the mask's R8 PixelBuffer; for a raster id,
// paint goes to the RGBA layer texture. No sidecar redirect.
//
// All stroke ops go through GPU render passes.
pub fn begin_stroke(&mut self, layer_id: LayerId) {
if !self.doc.is_node_editable(layer_id) || !self.is_node_paintable(layer_id) {
// Leave `active_stroke_layer` cleared so every queued stroke_to
// for this gesture no-ops uniformly — matches the "node missing"
// path and avoids partial-stroke state.
self.active_stroke_layer = None;
return;
}
self.auto_commit_floating();
self.active_stroke_layer = Some(layer_id);
// Reset the per-stroke counter accumulator. The bench-side
// per-event delta snapshot resets in lockstep so the first
// post-`begin_stroke` drain subtracts against zero rather than
// the previous stroke's totals.
self.brush_perf = BrushPerfCounters::default();
self.brush_full_rerender_events = 0;
self.last_brush_perf = BrushPerfCounters::default();
// GPU setup is deferred to first stroke_to (lazy init).
}
/// True when paint operations have somewhere to land. Raster layers and
/// mask filters carry a CPU-authoritative pixel buffer; groups and
/// voids don't, so paint there would either be a no-op or — for voids —
/// scribble onto a procedural texture that the compositor immediately
/// regenerates from params on the next dirty tick. Funnel every stroke
/// entry point through this predicate so the rejection is uniform.
pub fn is_node_paintable(&self, layer_id: LayerId) -> bool {
self.doc.pixel_buffer(layer_id).is_some()
}
/// Read the most recent `render()` sub-phase timings. Used by the WASM
/// bridge's slow-frame log to break down where the time went.
pub fn last_render_phases(&self) -> super::FrameRenderPhases {
self.last_frame_phases
}
pub fn stroke_to(&mut self, op: StrokeOp) {
let layer_id = match self.active_stroke_layer {
Some(id) => id,
None => return,
};
self.gpu_stroke_to(layer_id, op);
}
/// GPU paint path for all stroke operations.
fn gpu_stroke_to(&mut self, layer_id: LayerId, op: StrokeOp) {
// Defensive: `begin_stroke` already gates on the lock and paintability,
// but stroke ops can arrive from other paths (e.g. flood-fill StrokeOp
// routed directly). One predicate at the choke point covers all of them.
if !self.doc.is_node_editable(layer_id) || !self.is_node_paintable(layer_id) {
return;
}
let canvas_w = self.compositor.canvas_width();
let canvas_h = self.compositor.canvas_height();
// Brush strokes may extend past the layer's current canvas extent
// (e.g. paste-extent layers, or any stroke that wanders past the
// canvas). Grow the layer texture in chunked steps so the dab
// dispatch and undo paths see a sufficiently-large layer.
// Non-BrushStroke ops (gradient, flood fill, fill rect) operate on
// existing pixels and don't need preemptive growth.
if let StrokeOp::BrushStroke { x, y, .. } = op {
self.ensure_layer_covers_dab(layer_id, x, y);
}
// Lazy init: save the paint target to scratch for undo on first
// stroke_to. Uses the target's actual texture dimensions (not canvas)
// so paste-extent layers preserve off-canvas pixels through undo.
// The unified node-texture pool dispatches by node id; format dispatch
// is read off `LayerTexture.format` rather than a sidecar boolean.
if self.scratch_snapshot.is_none() {
self.flush_pending_undo_commit();
// Inline dispatch: the borrow checker treats `self.paint_target(...)`
// as borrowing all of &self, which conflicts with the
// &self.region_scratch call below. Direct field access via
// `self.compositor.node_texture(...)` borrows only that sub-field,
// so split borrowing of `region_scratch` works.
let (frame, format) = match self.compositor.node_texture(layer_id) {
Some(t) => (t.canvas_frame(), t.format()),
None => return,
};
let saved_rect = frame.canvas_extent;
let snap = self.gpu.encode_ret("stroke-begin", |encoder| {
self.region_scratch.save_region(
&self.gpu.device,
encoder,
&frame,
format,
saved_rect,
)
});
self.scratch_snapshot = Some(snap);
}
match op {
StrokeOp::LinearGradient {
x0,
y0,
x1,
y1,
r0,
g0,
b0,
a0,
r1,
g1,
b1,
a1,
} => {
let target = match self.paint_target(layer_id) {
Some(t) => t,
None => return,
};
self.gpu.encode("stroke-gradient", |encoder| {
target.linear_gradient(
encoder,
&self.paint_pipelines,
&self.gpu.queue,
x0,
y0,
x1,
y1,
[r0, g0, b0, a0],
[r1, g1, b1, a1],
None,
);
});
}
StrokeOp::FloodFill {
x,
y,
r,
g,
b,
a,
tolerance,
} => {
self.gpu_flood_fill(
layer_id,
crate::coord::CanvasPoint::new(x as i32, y as i32),
[r, g, b, a],
tolerance,
);
}
StrokeOp::BrushStroke {
x,
y,
pressure,
x_tilt,
y_tilt,
rotation,
tangential_pressure,
time_ms,
cr,
cg,
cb,
ca,
} => {
self.brush_stroke_to(
layer_id,
x,
y,
pressure,
x_tilt,
y_tilt,
rotation,
tangential_pressure,
time_ms,
[cr, cg, cb, ca],
canvas_w,
canvas_h,
);
}
}
// The compositor needs to recomposite the layer's pixels on
// the next render; thumbnail invalidation lives at the stroke
// boundary (end_stroke) rather than per-segment so the panel
// updates once per stroke instead of mid-flight.
self.compositor.mark_dirty();
}
/// Grow the layer texture if the next dab at canvas `(x, y)` would land
/// outside its current bounds. Triggered only when the dab CENTER falls
/// outside the layer's canvas extent — strokes within the layer don't
/// extend it (matching Krita's behavior of growing only when paint
/// actually escapes the layer's recorded bounds; dab footprints that
/// cross a layer edge are GPU-clipped).
///
/// On growth, the StrokeBuffer scratch and RegionScratch scratch are both
/// re-anchored to the new layer's local coordinate system so canvas-
/// space pre-stroke pixels remain in the right place; bind groups
/// referencing the old textures are rebuilt by their owners. Layer
/// blend uniforms are refreshed so the next composite pass sees the
/// new offset/size.
///
/// The `needed` rect padded outward by `DAB_REFERENCE_SIZE/2` so the new
/// chunk-aligned extent comfortably covers the dab's worst-case
/// footprint, not just its center pixel.
fn ensure_layer_covers_dab(&mut self, layer_id: LayerId, x: f32, y: f32) {
// Fetch the current paint-target extent before mutating the compositor.
// `paint_target()` resolves the node id against the unified texture
// pool; format dispatch lives behind that interface.
let current_extent = match self.paint_target(layer_id) {
Some(t) => t.canvas_frame().canvas_extent,
None => return,
};
// Trigger: dab center outside current extent. Doesn't grow when the
// user paints inside the canvas with a brush whose footprint
// happens to cross the canvas edge — those edge pixels would clip
// anyway with the canvas-aligned layer, matching pre-P2 behavior.
let cx = x.floor() as i32;
let cy = y.floor() as i32;
if cx >= current_extent.x0()
&& cx < current_extent.x1()
&& cy >= current_extent.y0()
&& cy < current_extent.y1()
{
return;
}
// Center-out-of-bounds: pad the requested rect by half of
// DAB_REFERENCE_SIZE so the grown extent includes the dab's footprint.
const HALF: i32 = (crate::brush::DAB_REFERENCE_SIZE / 2) as i32;
let needed = crate::coord::CanvasRect::from_xywh(
cx - HALF,
cy - HALF,
(HALF as u32) * 2,
(HALF as u32) * 2,
);
// Grow the stroke target itself — raster grows the raster, a mask
// stroke grows the mask (no host coupling).
let new_extent = match self.grow_node_to_fit(layer_id, needed) {
Some(e) => e,
None => return,
};
let dx = (current_extent.origin.x - new_extent.origin.x) as u32;
let dy = (current_extent.origin.y - new_extent.origin.y) as u32;
// Re-anchor the StrokeBuffer scratch + pre-stroke snapshot. The
// bind groups inside the StrokeBuffer reference the old textures
// and are rebuilt against the new ones.
if let Some(stroke_buffer) = self.stroke_buffer.as_mut() {
self.gpu.encode("stroke-buffer-grow", |encoder| {
stroke_buffer.grow_preserving(
&self.gpu.device,
encoder,
new_extent.width,
new_extent.height,
dx,
dy,
self.brush_pipelines.canvas_copy_bind_group_layout(),
);
});
}
// The brush engine's bbox metadata (`save_points`, `checkpoint_ring`)
// is in canvas coords (Storage Frame Rule). Canvas coords are stable
// across layer growth, so no metadata patch is needed — only the GPU
// textures got rebased above, and the metadata translates to the new
// layer-local frame on demand at the wgpu boundary.
// Re-anchor the region_scratch so the diff_rect at end_stroke
// compares matching coordinate frames. If the scratch hasn't been
// saved yet (this is the first dab and lazy init hasn't run), the
// rebase is a no-op on still-empty contents.
if let Some(snap) = self.scratch_snapshot.as_mut() {
self.gpu.encode("region-scratch-grow", |encoder| {
self.region_scratch.grow_scratch_preserving(
&self.gpu.device,
encoder,
new_extent.width,
new_extent.height,
dx,
dy,
);
});
// After grow_scratch_preserving, the new scratch holds:
// - old layer contents at (dx, dy) (translated from old origin)
// - zero-init in the newly-grown canvas regions
// Both are correct pre-stroke state — the newly-grown pixels
// didn't exist before the grow, so "zero / transparent" IS
// their pre-stroke value. Widen `saved` to cover the full
// new canvas extent so a diff_rect that spills into the
// newly-grown area is still contained at commit time.
snap.saved = new_extent;
} else {
// Lazy init will allocate the scratch at the new dimensions
// when it next saves; just bump capacity now so the save
// doesn't trigger another reallocation.
self.region_scratch.ensure_scratch_capacity(
&self.gpu.device,
new_extent.width,
new_extent.height,
);
}
}
/// Grow whichever pixel-bearing node `node_id` names to cover `needed`,
/// each growing **itself** — no host coupling.
///
/// - A raster layer grows its own bounds + texture ([`Self::grow_layer`]).
/// - A filter (e.g. a mask) grows its own bounds + texture
/// ([`Self::grow_filter`]); the host is untouched.
///
/// Lets callers that hold a generic node id (stroke target, transform
/// commit, paste commit) request growth without first disambiguating
/// between raster and filter ids.
pub(crate) fn grow_node_to_fit(
&mut self,
node_id: crate::layer::LayerId,
needed: crate::coord::CanvasRect,
) -> Option<crate::coord::CanvasRect> {
if self.doc.is_filter(node_id) {
self.grow_filter(node_id, needed)
} else {
self.grow_layer(node_id, needed)
}
}
/// Grow a filter's own pixel buffer (doc `PixelBuffer.bounds` + GPU
/// texture) to cover `needed`, honoring `MAX_LAYER_DIM`. Document-led, the
/// filter analogue of [`Self::grow_layer`] — the filter grows itself,
/// fully decoupled from its host. Returns `Some(new_extent)` when grown.
///
/// Growth is document-led (doc bounds and GPU texture move together), so
/// the stroke's region undo restores painted pixels with the same
/// constant-extent path raster grow uses — no separate bounds-undo op.
pub(crate) fn grow_filter(
&mut self,
mod_id: LayerId,
needed: crate::coord::CanvasRect,
) -> Option<crate::coord::CanvasRect> {
use crate::gpu::compositor::{LAYER_GROWTH_CHUNK, MAX_LAYER_DIM};
let current = self
.doc
.find_filter(mod_id)
.and_then(|m| m.pixels())
.map(|b| b.bounds)?;
if current.contains(needed) {
return None;
}
let new_extent = current.union(needed).round_outward(LAYER_GROWTH_CHUNK);
if new_extent.width > MAX_LAYER_DIM || new_extent.height > MAX_LAYER_DIM {
if !self.layer_growth_capped {
self.layer_growth_capped = true;
log::warn!(
"Filter {:?} growth refused: requested {}×{} exceeds MAX_LAYER_DIM ({})",
mod_id,
new_extent.width,
new_extent.height,
MAX_LAYER_DIM,
);
}
return None;
}
// Doc first — the filter's `PixelBuffer` is the source of truth.
self.doc
.find_filter_mut(mod_id)
.and_then(|m| m.pixels_mut())?
.bounds = new_extent;
self.gpu.encode("filter-grow", |encoder| {
self.compositor.resize_node_texture(
&self.gpu.device,
&self.gpu.queue,
encoder,
mod_id,
new_extent,
);
});
Some(new_extent)
}
/// Grow a raster layer's bounds to cover `needed` (canvas-space).
///
/// Document-led: writes `RasterLayer.bounds` first, then resizes the
/// compositor's GPU texture to match and refreshes blend uniforms.
/// Returns `Some(new_extent)` if the layer was actually grown,
/// `None` if no growth was needed or the cap was hit.
pub(crate) fn grow_layer(
&mut self,
layer_id: LayerId,
needed: crate::coord::CanvasRect,
) -> Option<crate::coord::CanvasRect> {
use crate::gpu::compositor::{LAYER_GROWTH_CHUNK, MAX_LAYER_DIM};
let current = match self.doc.layer(layer_id) {
Some(crate::layer::Layer::Raster(r)) => r.pixels.bounds,
_ => return None,
};
if current.contains(needed) {
return None;
}
let new_extent = current.union(needed).round_outward(LAYER_GROWTH_CHUNK);
if new_extent.width > MAX_LAYER_DIM || new_extent.height > MAX_LAYER_DIM {
if !self.layer_growth_capped {
self.layer_growth_capped = true;
log::warn!(
"Layer {:?} growth refused: requested {}×{} exceeds MAX_LAYER_DIM ({})",
layer_id,
new_extent.width,
new_extent.height,
MAX_LAYER_DIM,
);
}
return None;
}
// Doc first — the layer's `PixelBuffer` is the source of truth.
let isolated = self.host_renders_isolated(layer_id);
let (opacity, blend_mode_gpu) = match self.doc.layer_mut(layer_id) {
Some(crate::layer::Layer::Raster(r)) => {
r.pixels.bounds = new_extent;
(r.blend.opacity, r.blend.blend_mode.gpu_value)
}
_ => return None,
};
// Encoder discipline: the resize must run in its own encoder,
// submitted before any subsequent dab dispatch can start a new
// encoder against the new texture. `gpu.encode` already does
// one-encoder-per-call. A mask is no longer grown in lockstep — it
// owns its bounds and grows itself (`grow_filter`); the mask-apply
// pass samples it in its own space, so a divergent mask renders
// correctly without any shared-UV coupling.
self.gpu.encode("layer-grow", |encoder| {
self.compositor.resize_node_texture(
&self.gpu.device,
&self.gpu.queue,
encoder,
layer_id,
new_extent,
);
});
// Refresh the blend-uniform buffer so the composite pass sees the
// new offset/size on the next render.
self.compositor.update_layer_uniforms(
&self.gpu.queue,
layer_id,
opacity,
blend_mode_gpu,
isolated,
);
Some(new_extent)
}
/// Handle a BrushStroke event through the node-graph brush engine.
///
/// Lazy-inits a `StrokeEngine` + `StrokeBuffer` on the first event.
/// Each event feeds through the stabilizer, which may trigger rewind
/// and re-rendering of the stroke from scratch.
fn brush_stroke_to(
&mut self,
layer_id: LayerId,
x: f32,
y: f32,
pressure: f32,
x_tilt: f32,
y_tilt: f32,
rotation: f32,
tangential_pressure: f32,
time_ms: f64,
color: [f32; 4],
canvas_w: u32,
canvas_h: u32,
) {
// True on the lazy-init path below — the terminal's `begin_stroke`
// hook must run once before the first dab to initialise the scratch.
let mut need_begin_stroke = false;
// Lazy-init: compile the active brush graph + create stroke buffer.
if self.brush_stroke_engine.is_none() {
need_begin_stroke = true;
// Brief read guard around the compile — drop before any GPU
// work so other engines (multi-tab) can take the lock.
let runner = {
use crate::brush::state::BrushState;
let tool = self.tool_session.read();
let brush = tool
.get::<BrushState>()
.expect("BrushState registered at session init");
match crate::brush::compile_graph(&brush.graph) {
Ok(r) => r,
Err(e) => {
log::error!("brush graph compilation failed: {e:?}");
return;
}
}
};
// Derive stabilizer from the pen_input node's "stabilize" port.
let strength = self.pen_input_stabilize_strength();
let stabilizer_config = if strength > 0.0 {
crate::brush::stabilizer::StabilizerConfig {
algorithm: "laplacian".into(),
params: vec![crate::gpu::params::ParamValue::Float(strength)],
}
} else {
crate::brush::stabilizer::StabilizerConfig::default()
};
let stabilizer = self
.stabilizer_registry
.create_from_config(&stabilizer_config);
self.brush_stroke_engine = Some(StrokeEngine::new(
runner,
color,
self.active_spacing_config(),
stabilizer,
));
// Create the stroke buffer and save the pre-stroke snapshot.
// Inline dispatch (vs `self.paint_target(...)`) so the borrow of
// `self.compositor.node_textures[id]` is at the field level —
// letting `&self.gpu`, `&self.dab_pool`, etc. be borrowed
// alongside it without conflict.
let layer_tex = self.compositor.node_texture(layer_id);
if let Some(layer_tex) = layer_tex {
// Size the stroke scratch and pre-stroke snapshot to the
// layer's bounds. For paste-extent layers larger than the
// canvas this means dabs landing on off-canvas pixels are
// saved/restored correctly on undo.
let layer_extent = layer_tex.layer_extent();
let stroke_buffer = StrokeBuffer::new(
&self.gpu.device,
layer_extent.width,
layer_extent.height,
&self.brush_pipelines,
);
let paint_target = GpuPaintTarget::from_node(layer_tex, self.doc.canvas_rect());
self.gpu.encode("stroke-buffer-init", |encoder| {
stroke_buffer.save_pre_stroke(
&self.gpu.device,
encoder,
&self.brush_pipelines,
&paint_target,
);
});
// Scratch initialisation is now the terminal's responsibility
// (via `runner.begin_stroke`). Deferred until we have the
// engine + buffer in hand a few lines below — see the
// `begin_stroke` call guarded by `first_event`.
self.stroke_buffer = Some(stroke_buffer);
}
}
// Build PaintInformation from the raw tablet data.
let info = PaintInformation {
pos: [x, y],
pressure,
x_tilt,
y_tilt,
rotation,
tangential_pressure,
time: (time_ms / 1000.0) as f32,
..Default::default()
};
// Get the paint target (layer or mask) — encapsulates format and
// brush-side commit dispatch so the brush stack stays format-agnostic.
// Inline dispatch (vs `self.paint_target(...)`) for borrow-checker
// reasons — the BrushGpuContext construction below needs &mut
// self.dab_pool alongside this borrow.
let layer_tex = match self.compositor.node_texture(layer_id) {
Some(t) => t,
None => return,
};
let paint_target = GpuPaintTarget::from_node(layer_tex, self.doc.canvas_rect());
// Take the stroke engine and buffer out to avoid borrow conflicts.
let mut engine = self.brush_stroke_engine.take().unwrap();
let mut stroke_buffer = self.stroke_buffer.take();
let sel_bg = if self.has_selection() {
self.compositor
.selection_state()
.map(|s| s.selection_bind_group())
.unwrap_or(&self.brush_pipelines.default_selection_bind_group)
} else {
&self.brush_pipelines.default_selection_bind_group
};
if let Some(ref mut stroke_buffer) = stroke_buffer {
// Stabilized path: dabs render into the scratch, then the
// terminal's `commit` hook lands them on the layer.
self.brush_pipelines.reset_uniform_rings();
let result = engine.stabilize(info);
let max_div = engine.max_divergence_window();
let tip_vi = engine.stabilizer_len().saturating_sub(1);
// Synthesize divergence on the previously-rendered tip segment.
// It was drawn with a degenerate `p3 = p2` because the next
// sample hadn't arrived yet; now it has, so re-render that
// segment with proper Catmull-Rom lookahead. `tip_div` is
// the deeper of the two when the stabilizer also reports
// divergence (take the earliest vi that needs rebuild).
let tip_div = tip_vi.saturating_sub(1);
let div_idx = match result.divergence_index {
Some(k) => Some(k.min(tip_div)),
None if tip_vi >= 1 => Some(tip_div),
None => None,
};
// The checkpoint ring's coverage invariant depends on
// `max_divergence_window` being a true upper bound on
// `tip_vi - find_divergence().unwrap()`. Make any future drift
// between the stabilizer's bound and its detector loud in debug
// builds. (The synthetic tip-divergence path is always within
// bound by construction, but `result.divergence_index` is what
// the stabilizer reported.)
#[cfg(debug_assertions)]
if let Some(k) = result.divergence_index {
let earliest = tip_vi.saturating_sub(max_div);
debug_assert!(
k >= earliest,
"stabilizer returned divergence_index={k} but max_div={max_div} \
requires >= {earliest} (tip_vi={tip_vi})",
);
}
// Helper macro: create a BrushGpuContext wired with the stroke
// scratch, paint target (layer or mask), and pre-stroke snapshot.
// The paint target carries the destination format internally;
// `color_output::commit` calls `paint_target.commit_brush_dab(...)`
// and never branches on R8 vs RGBA8.
macro_rules! make_gpu_ctx {
($label:expr) => {{
// Re-borrow per invocation: each ctx holds &mut Scratch
// for its own lifetime, then is consumed by `submit_final()`
// before the next macro expansion reborrows.
let (scratch, pre_stroke_texture, pre_stroke_bind_group) =
stroke_buffer.parts_for_brush_ctx();
BrushGpuContext {
encoder: self.gpu.device.create_command_encoder(
&wgpu::CommandEncoderDescriptor {
label: Some($label),
},
),
device: &self.gpu.device,
queue: &self.gpu.queue,
pipelines: &self.brush_pipelines,
selection_bind_group: sel_bg,
canvas_width: canvas_w,
canvas_height: canvas_h,
canvas_origin: [self.doc.canvas_origin.x, self.doc.canvas_origin.y],
// blend_mode applies at commit (paint vs. erase).
// Per-dab passes hard-code source-over — the
// scratch is a coverage accumulator, and only the
// commit composite reads this value.
blend_mode: self.brush_blend_mode,
view_rotation: self.view_params.rotation,
perf: BrushPerfCounters::default(),
stroke: Some(StrokeResources {
scratch,
paint_target,
pre_stroke_texture,
pre_stroke_bind_group,
}),
preview: None,
dab_batch: DabBatch::default(),
}
}};
}
// First event of the stroke — let the terminal set up its scratch.
if need_begin_stroke {
let mut gpu_ctx = make_gpu_ctx!("brush-begin-stroke");
engine.begin_stroke(&mut gpu_ctx);
self.brush_perf += gpu_ctx.submit_final();
}
if let Some(div_idx) = div_idx {
// Divergence — try checkpoint-based partial re-render.
// The terminal's `begin_stroke` establishes outside-bbox
// state for whichever path we take below; the checkpoint
// ring no longer clears on its own.
{
let mut gpu_ctx = make_gpu_ctx!("brush-begin-stroke-rewind");
engine.begin_stroke(&mut gpu_ctx);
self.brush_perf += gpu_ctx.submit_final();
}
let stroke_frame = crate::gpu::atlas::CanvasFrame {
texture: stroke_buffer.scratch().write_texture(),
canvas_extent: paint_target.canvas_frame().canvas_extent,
};
let restore = self.gpu.encode_ret("stroke-checkpoint-restore", |encoder| {
self.checkpoint_ring
.restore_before(encoder, &stroke_frame, div_idx)
});
self.brush_perf.submits = self.brush_perf.submits.saturating_add(1);
let start_vi = if let Some(cp) = restore {
// Restored from checkpoint — truncate and resume.
engine.save_points.truncate(cp.save_point_index + 1);
engine.restore_render_state(&cp.render_state);
// Only invalidate from the divergence point onward —
// checkpoints between the restore point and div_idx
// are still valid (the stroke buffer content there
// didn't change, only positions >= div_idx diverged).
self.checkpoint_ring.invalidate_from(div_idx);
cp.vector_index + 1
} else {
// No checkpoint before divergence — full re-render.
//
// Two cases here. If the ring had valid slots but none
// satisfied `vi < div_idx`, the coverage invariant has
// failed (the architectural defect the ring's eviction
// policy is designed to prevent). If the ring was
// empty, this is initialization — the first divergence
// event of the stroke, before any checkpoint has been
// saved — which is structurally unavoidable and cheap
// (`tip_vi` is small, so the re-render is short).
// Only the former is a "mid-stroke full re-render
// fallback" worth counting.
if self.checkpoint_ring.has_any_valid() {
self.brush_full_rerender_events += 1;
}
engine.reset_render_state();
self.checkpoint_ring.clear();
0
};
// Render in segments with checkpoints at boundaries.
let boundaries =
CheckpointRing::compute_segment_boundaries(start_vi, tip_vi, max_div);
let mut seg_start = start_vi;
for &boundary in &boundaries {
// Strict `<` (not `<=`): `compute_segment_boundaries`
// prepends a `vi=0` anchor when `start_vi=0`, and we
// need that single-vi segment `[0..=0]` to actually
// render + save its checkpoint rather than being
// skipped.
if boundary < seg_start || boundary > tip_vi {
continue;
}
// Render segment.
let mut gpu_ctx = make_gpu_ctx!("brush-rerender-seg");
engine.render_from_stabilized_range_to(&mut gpu_ctx, seg_start, boundary);
self.brush_perf += gpu_ctx.submit_final();
// Save checkpoint at this boundary.
if let Some(bbox) = engine.save_points.full_bbox() {
let sp_idx = engine.save_points.len().saturating_sub(1);
let render_state = engine.capture_render_state();
let stroke_frame = crate::gpu::atlas::CanvasFrame {
texture: stroke_buffer.scratch().write_texture(),
canvas_extent: paint_target.canvas_frame().canvas_extent,
};
self.gpu.encode("checkpoint-save", |encoder| {
self.checkpoint_ring.save(
&self.gpu.device,
encoder,
&stroke_frame,
sp_idx,
boundary,
bbox,
render_state,
tip_vi,
max_div,
);
});
self.brush_perf.submits = self.brush_perf.submits.saturating_add(1);
}
seg_start = boundary + 1;
}
// Render any remaining dabs past the last boundary.
if seg_start <= tip_vi {
let mut gpu_ctx = make_gpu_ctx!("brush-rerender-tail");
engine.render_from_stabilized_range_to(&mut gpu_ctx, seg_start, tip_vi);
self.brush_perf += gpu_ctx.submit_final();
}
} else {
// No divergence — render tail only.
let mut gpu_ctx = make_gpu_ctx!("brush-dab");
engine.render_from_stabilized_tail(&mut gpu_ctx);
self.brush_perf += gpu_ctx.submit_final();
// Periodically save a checkpoint to keep the ring fresh.
let spacing = CheckpointRing::spacing(max_div);
let should_save = match self.checkpoint_ring.newest_vector_index() {
Some(newest_vi) => tip_vi.saturating_sub(newest_vi) >= spacing,
None => true,
};
if should_save && !engine.save_points.is_empty() {
if let Some(bbox) = engine.save_points.full_bbox() {
let sp_idx = engine.save_points.len() - 1;
let render_state = engine.capture_render_state();
let stroke_frame = crate::gpu::atlas::CanvasFrame {
texture: stroke_buffer.scratch().write_texture(),
canvas_extent: paint_target.canvas_frame().canvas_extent,
};
self.gpu.encode("checkpoint-save", |encoder| {
self.checkpoint_ring.save(
&self.gpu.device,
encoder,
&stroke_frame,
sp_idx,
tip_vi,
bbox,
render_state,
tip_vi,
max_div,
);
});
self.brush_perf.submits = self.brush_perf.submits.saturating_add(1);
}
}
}
// Ask the terminal to commit the stroke state onto the layer.
// For paint this is `source_over(scratch × opacity, pre_stroke)`;
// other terminals (warp, smudge, …) will do their own thing.
{
let mut gpu_ctx = make_gpu_ctx!("brush-commit");
engine.commit(&mut gpu_ctx);
self.brush_perf += gpu_ctx.submit_final();
}
} else {
// Fallback: no stroke buffer — render directly to the paint
// target (shouldn't happen in practice). Skips the lifecycle
// hooks since there's no scratch to clear or commit. Inline
// dispatch so the borrow of `self.compositor.X[id]` is at the
// field level, leaving `&mut self.dab_pool` free.
let layer_tex = self.compositor.node_texture(layer_id);
if let Some(layer_tex) = layer_tex {
let _paint_target = GpuPaintTarget::from_node(layer_tex, self.doc.canvas_rect());
let mut gpu_ctx = BrushGpuContext {
encoder: self.gpu.device.create_command_encoder(
&wgpu::CommandEncoderDescriptor {
label: Some("brush-dab"),
},
),
device: &self.gpu.device,
queue: &self.gpu.queue,
pipelines: &self.brush_pipelines,
selection_bind_group: sel_bg,
canvas_width: canvas_w,
canvas_height: canvas_h,
canvas_origin: [self.doc.canvas_origin.x, self.doc.canvas_origin.y],
blend_mode: self.brush_blend_mode,
view_rotation: self.view_params.rotation,
perf: BrushPerfCounters::default(),
// No stroke buffer in this defensive fallback — `move_to`
// only updates stabilizer state and never reaches into
// scratch. Anything that does would panic, which is the
// correct signal that the fallback was reached.
stroke: None,
preview: None,
dab_batch: DabBatch::default(),
};
self.brush_pipelines.reset_uniform_rings();
engine.move_to(info, &mut gpu_ctx);
let _ = gpu_ctx.submit_final();
}
}
// Put the engine and buffer back.
self.brush_stroke_engine = Some(engine);
self.stroke_buffer = stroke_buffer;
}
/// Start async GPU flood fill: readback paint target texture, then
/// complete on a subsequent frame when the data arrives.
fn gpu_flood_fill(
&mut self,
layer_id: LayerId,
seed_canvas: crate::coord::CanvasPoint,
color: [u8; 4],
tolerance: u8,
) {
let pt = match self.paint_target(layer_id) {
Some(t) => t,
None => return,
};
let mut encoder = self
.gpu
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("flood-fill-readback"),
});
let (request, extent) =
flood_fill::request_layer_flood_fill_readback(&self.gpu.device, &mut encoder, &pt);
self.gpu.queue.submit([encoder.finish()]);
self.readbacks.submit(
request,
ReadbackContext::FloodFill {
node_id: layer_id,
seed_canvas,
color,
tolerance,
extent,
},
);
}
/// Complete a pending flood fill once readback data is available.
/// Format-driven: the node id resolves to either an R8 mask or an RGBA
/// layer texture, and the CPU-side scanline fill picks the matching
/// flood-fill variant from the texture's format.
pub(crate) fn complete_flood_fill(
&mut self,
layer_id: LayerId,
seed_canvas: crate::coord::CanvasPoint,
color: [u8; 4],
tolerance: u8,
extent: flood_fill::LayerFloodFillExtent,
pixels: Vec<u8>,
) {
let fill_mask = extent.flood_fill_to_canvas_mask(&pixels, seed_canvas, tolerance);
let canvas_w = extent.canvas_width;
let canvas_h = extent.canvas_height;
// 2. Combine fill mask with active selection (if any), then upload.
let effective_mask = if self.has_selection() {
if let Some(sel) = self.selection_cpu_cache() {
fill_mask
.iter()
.zip(sel.iter())
.map(|(&f, &s)| ((f as u16 * s as u16) / 255) as u8)
.collect::<Vec<u8>>()
} else {
fill_mask
}
} else {
fill_mask
};
let mask_bind_group = self.paint_pipelines.upload_r8_bind_group(
&self.gpu.device,
&self.gpu.queue,
canvas_w,
canvas_h,
&effective_mask,
"flood-fill-mask",
);
let target = match self.paint_target(layer_id) {
Some(t) => t,
None => return,
};
self.gpu.encode("flood-fill-stamp", |encoder| {
target.fill_rect_with_selection(
encoder,
&self.paint_pipelines,
&self.gpu.queue,
self.doc.canvas_rect(),
color,
&mask_bind_group,
);
});
// 4. Commit undo. The lazy save in `gpu_stroke_to` populated
// `scratch_snapshot` with the full layer; flood fill can change
// any pixel inside the canvas, so commit the canvas-sized
// sub-rect of that snapshot.
let snap = match self.scratch_snapshot.take() {
Some(s) => s,
// No snapshot means the lazy save never ran (stroke_to was
// never called for this op) — extremely unusual; bail rather
// than fabricate an empty snapshot.
None => {
self.compositor.mark_node_pixels_dirty(layer_id);
return;
}
};
let layer_frame = match self.compositor.node_texture(layer_id) {
Some(t) => t.canvas_frame(),
None => {
self.compositor.mark_node_pixels_dirty(layer_id);
return;
}
};
let rect = self.doc.canvas_rect();
let entry = commit_undo_region(
&self.gpu,
&self.region_scratch,
&mut self.readbacks,
"flood-fill-undo",
layer_id,
&layer_frame,
&snap,
rect,
);
self.push_undo(Box::new(GpuRegionAction::new(entry)));
self.compositor.mark_node_pixels_dirty(layer_id);
}
pub fn end_stroke(&mut self) {
if let Some(layer_id) = self.active_stroke_layer.take() {
// Per-stroke thumbnail refresh — the node texture (raster or mask
// filter) now holds the cumulative pixels of every dab/op since
// begin_stroke. Live mid-stroke updates are intentionally skipped.
self.compositor.mark_node_pixels_dirty(layer_id);
// If a flood fill is pending, defer undo commit — complete_flood_fill
// will handle it when the readback arrives.
if self
.readbacks
.any(|c| matches!(c, ReadbackContext::FloodFill { .. }))
{
return;
}
// Finalize brush stroke engine and destroy stroke buffer + checkpoints.
if let Some(engine) = self.brush_stroke_engine.take() {
let _record = engine.end();
}
self.stroke_buffer = None;
self.checkpoint_ring.clear();
// Dispatch GPU diff to find the exact changed region for undo.
if let (Some(snap), true) = (
self.scratch_snapshot.take(),
self.pending_undo_commit.is_none(),
) {
let layer_extent = self
.compositor
.node_texture(layer_id)
.map(|t| (t.view(), t.canvas_extent()));
if let Some((current_view, layer_canvas_extent)) = layer_extent {
let scratch_view = self.region_scratch.scratch_view(snap.format);
self.diff_rect.request(
&self.gpu.device,
&self.gpu.queue,
&scratch_view,
current_view,
layer_canvas_extent,
);
self.pending_undo_commit = Some(PendingUndoCommit {
layer_id,
snapshot: snap,
});
}
}
}
}
// --- GPU erase helpers ---
/// Clear layer pixels within the current selection via GPU erase pass.
pub(crate) fn gpu_clear_selection(&mut self, layer_id: LayerId) {
if !self.has_selection() {
return;
}
let rect = self.doc.canvas_rect();
// Own the cached selection bind group so it doesn't borrow `self`
// across the `&mut self` helper call below.
let sel_bg = match self.compositor.selection_state() {
Some(s) => s.selection_bind_group().clone(),
None => return,
};
self.region_undo_inplace(
layer_id,
rect,
"clear-sel-save",
"clear-sel-commit",
|encoder, target, pipelines, queue| {
target.erase_with_selection(encoder, pipelines, queue, &sel_bg);
},
);
}
/// Clear entire layer to transparent via GPU.
pub(crate) fn gpu_clear_layer(&mut self, layer_id: LayerId) {
let rect = self.doc.canvas_rect();
self.region_undo_inplace(
layer_id,
rect,
"clear-layer-save",
"clear-layer-commit",
|encoder, target, pipelines, queue| {
target.clear_rect(encoder, pipelines, queue, rect);
},
);
}
/// Resolve the active paint target for a layer.
///
/// Resolve the GPU paint target for a node id. Format-driven dispatch
/// (R8 mask vs RGBA layer) lives behind the unified node-texture pool —
/// callers don't branch on the kind. Returns `None` for groups, unknown
/// ids, or any node without a `PixelBuffer`.
pub(crate) fn paint_target(&self, node_id: LayerId) -> Option<GpuPaintTarget<'_>> {
self.compositor
.node_texture(node_id)
.map(|t| GpuPaintTarget::from_node(t, self.doc.canvas_rect()))
}
/// Upload a cropped region of the GPU selection as an R8 texture bind group.
/// Reads from the CPU cache (populated by async readback or eagerly on upload).
pub(crate) fn upload_cropped_selection_r8(
&self,
origin: (i32, i32),
width: u32,
height: u32,
) -> Option<wgpu::BindGroup> {
let pixels = self.cropped_selection_pixels(origin, width, height)?;
Some(self.paint_pipelines.upload_r8_bind_group(
&self.gpu.device,
&self.gpu.queue,
width,
height,
&pixels,
"selection-cropped",
))
}
/// Crop the live selection's CPU cache to a `width`×`height` window-local
/// region at `origin`, returning straight R8 coverage (0 outside the
/// canvas). `None` if there's no selection or the cache hasn't landed.
/// Shared by the paint-mask bind-group path and the layer-flip mask.
pub(crate) fn cropped_selection_pixels(
&self,
origin: (i32, i32),
width: u32,
height: u32,
) -> Option<Vec<u8>> {
if !self.has_selection() {
return None;
}
let full = self.selection_cpu_cache()?;
let (ox, oy) = origin;
let cw = self.doc.width;
let ch = self.doc.height;
let mut pixels = vec![0u8; (width * height) as usize];
for py in 0..height {
for px in 0..width {
let sx = ox + px as i32;
let sy = oy + py as i32;
if sx >= 0 && sy >= 0 && (sx as u32) < cw && (sy as u32) < ch {
pixels[(py * width + px) as usize] =
full[(sy as u32 * cw + sx as u32) as usize];
}
}
}
Some(pixels)
}
/// Crop the live selection into a fresh `width`×`height` R8 texture (for
/// passes that `textureLoad` the mask directly, e.g. the layer-flip mirror).
/// `origin` is window-local; `None` if the cache isn't ready.
pub(crate) fn upload_cropped_selection_texture(
&self,
origin: (i32, i32),
width: u32,
height: u32,
) -> Option<wgpu::Texture> {
let pixels = self.cropped_selection_pixels(origin, width, height)?;
let (texture, _view) = crate::gpu::create_texture_with_view(
&self.gpu.device,
width,
height,
wgpu::TextureFormat::R8Unorm,
"selection-cropped-tex",
wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
);
self.gpu.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
&pixels,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(width),
rows_per_image: None,
},
wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
);
Some(texture)
}
}