Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

rust big optimization's

sora5e405dd3970b
diff --git a/Cargo.toml b/Cargo.toml
index 9f1636d..7c9ec7b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -9,6 +9,18 @@ default-members = [
"src-tauri",
]
+# Fast dev builds with near-release runtime speed for wgpu/image/compression deps
+[profile.dev]
+opt-level = 1
+
+[profile.dev.package."*"]
+opt-level = 3
+
+[profile.dev.package.ink-engine]
+opt-level = 3
+debug-assertions = false
+overflow-checks = false
+
# Read the optimization guideline for more details: https://tauri.app/concept/size/#cargo-configuration
[profile.release]
codegen-units = 1
diff --git a/crates/ink-engine/src/audit_regression_tests.rs b/crates/ink-engine/src/audit_regression_tests.rs
new file mode 100644
index 0000000..6182e4a
--- /dev/null
+++ b/crates/ink-engine/src/audit_regression_tests.rs
@@ -0,0 +1,484 @@
+//! Pure-CPU regression unit tests covering IPC serde contracts, pixel formats,
+//! PNG safety, CoW history/selection atomicity, and collab bounds checks.
+
+use crate::brush::CspBrushCombineMode;
+use crate::collab::{
+ apply_tile_delta_packet, TILE_CODEC_LZ4, TILE_CODEC_SUBRECT_LZ4, TILE_PACKET_HEADER_BYTES,
+};
+use crate::document::{
+ BlendMode, CanvasColorMode, CanvasDimensions, Document, LayerNode, LayerNodeMeta,
+ LayerPropsPatch, LayerType,
+};
+use crate::history::{HistoryEntry, HistoryItemMeta, HistoryStack};
+use crate::io::png_codec::decode_png_rgba8;
+use crate::selection::{
+ move_selection_to_new_layer, paste_selection, select_rect, SelectionClipboard,
+ SelectionCombineMode,
+};
+use crate::tiles::{RectI32, TileCoord, TileData, TileFormat, TileKind, TILE_SIZE};
+use crate::tools::fill::{
+ flood_fill_document, pick_color_document_for_layer, FillReferMode, FloodFillParams,
+};
+use crate::tools::filters::{FilterSpec, TonalSpec};
+use crate::tools::liquify::LiquifyStepParams;
+use crate::tools::retouch::RetouchStepParams;
+use crate::tools::transform::TransformUpdatePayload;
+use std::sync::Arc;
+
+#[test]
+fn test_ipc_serde_contracts_match_typescript_camel_case_json() {
+ // 1. TonalSpec::LevelCorrection & ColorBalance camelCase fields
+ let level_json = r#"{
+ "kind": "level-correction",
+ "inBlack": 12,
+ "inWhite": 240,
+ "gamma": 1.25,
+ "outBlack": 5,
+ "outWhite": 250
+ }"#;
+ let level: TonalSpec = serde_json::from_str(level_json).expect("LevelCorrection serde failed");
+ match level {
+ TonalSpec::LevelCorrection {
+ in_black,
+ in_white,
+ out_black,
+ out_white,
+ ..
+ } => {
+ assert_eq!((in_black, in_white, out_black, out_white), (12, 240, 5, 250));
+ }
+ other => panic!("Unexpected variant: {other:?}"),
+ }
+
+ let cb_json = r#"{
+ "kind": "color-balance",
+ "shadows": [10, 0, -5],
+ "midtones": [0, 5, 0],
+ "highlights": [-5, 0, 10],
+ "preserveLuminosity": false
+ }"#;
+ let cb: TonalSpec = serde_json::from_str(cb_json).expect("ColorBalance serde failed");
+ match cb {
+ TonalSpec::ColorBalance {
+ preserve_luminosity,
+ ..
+ } => assert!(!preserve_luminosity),
+ other => panic!("Unexpected variant: {other:?}"),
+ }
+
+ // 2. FilterSpec::GaussianBlur
+ let blur: FilterSpec =
+ serde_json::from_str(r#"{"kind":"gaussian-blur","radius":4.5}"#).expect("GaussianBlur serde");
+ assert!(matches!(blur, FilterSpec::GaussianBlur { .. }));
+
+ // 3. LayerPropsPatch double-option parentId (null = unparent to root, omitted = untouched)
+ let unparent: LayerPropsPatch =
+ serde_json::from_str(r#"{"parentId": null}"#).expect("unparent patch");
+ assert_eq!(unparent.parent_id, Some(None));
+
+ let untouched: LayerPropsPatch = serde_json::from_str(r#"{}"#).expect("empty patch");
+ assert_eq!(untouched.parent_id, None);
+
+ let reparent: LayerPropsPatch =
+ serde_json::from_str(r#"{"parentId": "folder-1"}"#).expect("reparent patch");
+ assert_eq!(reparent.parent_id, Some(Some("folder-1".to_string())));
+
+ // 4. CspBrushCombineMode aliases
+ let pass_through: CspBrushCombineMode =
+ serde_json::from_str(r#""pass-through""#).expect("pass-through alias");
+ assert_eq!(pass_through, CspBrushCombineMode::Normal);
+ let glow_dodge: CspBrushCombineMode =
+ serde_json::from_str(r#""color-dodge-glow""#).expect("color-dodge-glow alias");
+ assert_eq!(glow_dodge, CspBrushCombineMode::GlowDodge);
+
+ // 5. LiquifyStepParams, RetouchStepParams, TransformUpdatePayload
+ let liq: LiquifyStepParams = serde_json::from_str(
+ r#"{"fromX":10.0,"fromY":20.0,"toX":14.0,"toY":25.0,"pressure":0.8,"settings":{"mode":"push","size":40,"strength":0.6,"hardness":0.5}}"#,
+ )
+ .expect("LiquifyStepParams serde");
+ assert_eq!((liq.from_x, liq.to_y), (10.0, 25.0));
+ assert_eq!(liq.settings.size, 40.0);
+
+ let ret: RetouchStepParams = serde_json::from_str(
+ r#"{"x":15.0,"y":25.0,"pressure":1.0,"cloneSource":[5.0,6.0],"settings":{"mode":"clone","size":30,"strength":80,"hardness":75,"sampleAllLayers":false,"cloneAligned":true}}"#,
+ )
+ .expect("RetouchStepParams serde");
+ assert_eq!(ret.clone_source, Some([5.0, 6.0]));
+
+ let tx: TransformUpdatePayload = serde_json::from_str(
+ r#"{"mode":"mesh","mesh":{"cols":2,"rows":2,"points":[{"x":0,"y":0}]}}"#,
+ )
+ .expect("TransformUpdatePayload serde");
+ assert!(tx.mesh.is_some());
+}
+
+#[test]
+fn test_transparent_ink_flood_fill_erases_pixels_and_respects_alpha_lock() {
+ let mut doc = Document::new_blank(
+ "doc-fill",
+ "Test",
+ CanvasDimensions {
+ width: 32,
+ height: 32,
+ dpi: 72,
+ },
+ CanvasColorMode::Color,
+ "#00000000",
+ 60.0,
+ 20,
+ );
+ let layer_id = doc.active_layer_id.clone().unwrap();
+ let red_block = vec![255, 0, 0, 255].repeat(32 * 32);
+ doc.layer_mut(&layer_id)
+ .unwrap()
+ .grid
+ .write_rgba8_rect(&red_block, RectI32::new(0, 0, 32, 32), 128, None)
+ .unwrap();
+
+ // Transparent ink should erase pixels when alpha_locked = false
+ let res = flood_fill_document(
+ &mut doc,
+ &FloodFillParams {
+ x: 16,
+ y: 16,
+ color: "#00000000".to_string(),
+ tolerance: 10,
+ close_gap: 0,
+ area_scale: 0,
+ anti_alias: false,
+ opacity: 1.0,
+ refer_mode: FillReferMode::ReferActive,
+ layer_id: Some(layer_id.clone()),
+ },
+ None,
+ )
+ .unwrap();
+ assert!(res.modified);
+ let px = pick_color_document_for_layer(&doc, 16, 16, false, Some(&layer_id), None);
+ assert_eq!(px.a, 0);
+
+ // Refill red, enable alpha_locked, and verify transparent ink is blocked
+ doc.layer_mut(&layer_id)
+ .unwrap()
+ .grid
+ .write_rgba8_rect(&red_block, RectI32::new(0, 0, 32, 32), 128, None)
+ .unwrap();
+ doc.layer_mut(&layer_id).unwrap().meta.alpha_locked = Some(true);
+ let res_locked = flood_fill_document(
+ &mut doc,
+ &FloodFillParams {
+ x: 16,
+ y: 16,
+ color: "#00000000".to_string(),
+ tolerance: 10,
+ close_gap: 0,
+ area_scale: 0,
+ anti_alias: false,
+ opacity: 1.0,
+ refer_mode: FillReferMode::ReferActive,
+ layer_id: Some(layer_id.clone()),
+ },
+ None,
+ )
+ .unwrap();
+ assert!(!res_locked.modified);
+ let px2 = pick_color_document_for_layer(&doc, 16, 16, false, Some(&layer_id), None);
+ assert_eq!(px2.a, 255);
+}
+
+#[test]
+fn test_eyedropper_grayscale_and_monochrome_no_panic_and_correct_msb_bit_order() {
+ let mut doc = Document::new_blank(
+ "doc-pick",
+ "Pick",
+ CanvasDimensions {
+ width: 256,
+ height: 256,
+ dpi: 72,
+ },
+ CanvasColorMode::Color,
+ "#00000000",
+ 60.0,
+ 20,
+ );
+
+ // 1. Grayscale8Bit layer sampled at y = 200 (previously panicked out-of-bounds!)
+ let mut gray_meta = LayerNodeMeta::new_raster("gray-1", "Gray");
+ gray_meta.visible = true;
+ let mut gray_node = LayerNode::new(gray_meta, TileFormat::Grayscale8Bit);
+ let mut gray_raw = vec![0u8; (TILE_SIZE * TILE_SIZE) as usize];
+ gray_raw[200 * (TILE_SIZE as usize) + 123] = 180;
+ gray_node.grid.set_tile(
+ TileCoord::new(0, 0),
+ Arc::new(TileData::from_raw(
+ TileFormat::Grayscale8Bit,
+ TileKind::Raster,
+ gray_raw,
+ )),
+ );
+ doc.layers.insert(0, gray_node);
+
+ let sampled_gray = pick_color_document_for_layer(&doc, 123, 200, false, Some("gray-1"), None);
+ assert_eq!(
+ (sampled_gray.r, sampled_gray.g, sampled_gray.b, sampled_gray.a),
+ (180, 180, 180, 255)
+ );
+
+ // 2. Monochrome1Bit layer: pixel (0, 0) uses MSB 0x80, pixel (7, 0) uses LSB 0x01
+ let mut mono_meta = LayerNodeMeta::new_raster("mono-1", "Mono");
+ mono_meta.visible = true;
+ let mut mono_node = LayerNode::new(mono_meta, TileFormat::Monochrome1Bit);
+ let mut mono_raw = vec![0u8; TileFormat::Monochrome1Bit.byte_size()];
+ mono_raw[0] = 0x80; // only bit 0 (x=0, y=0) set in MSB-first layout
+ mono_node.grid.set_tile(
+ TileCoord::new(0, 0),
+ Arc::new(TileData::from_raw(
+ TileFormat::Monochrome1Bit,
+ TileKind::Raster,
+ mono_raw,
+ )),
+ );
+ doc.layers.insert(0, mono_node);
+
+ let px0 = pick_color_document_for_layer(&doc, 0, 0, false, Some("mono-1"), None);
+ let px7 = pick_color_document_for_layer(&doc, 7, 0, false, Some("mono-1"), None);
+ assert_eq!(px0.a, 255);
+ assert_eq!(px7.a, 0);
+}
+
+#[test]
+fn test_png_decoder_rejects_invalid_palette_bit_depth_without_panicking() {
+ // Minimal PNG with IHDR (1x1, bit_depth=16, color_type=3 indexed palette - invalid per PNG spec)
+ let mut png = vec![137, 80, 78, 71, 13, 10, 26, 10];
+ // IHDR length = 13
+ png.extend_from_slice(&13u32.to_be_bytes());
+ png.extend_from_slice(b"IHDR");
+ png.extend_from_slice(&1u32.to_be_bytes()); // width
+ png.extend_from_slice(&1u32.to_be_bytes()); // height
+ png.push(16); // invalid bit_depth for color_type 3
+ png.push(3); // indexed color
+ png.push(0); // compression
+ png.push(0); // filter
+ png.push(0); // interlace
+ png.extend_from_slice(&0u32.to_be_bytes()); // dummy CRC
+ // IEND
+ png.extend_from_slice(&0u32.to_be_bytes());
+ png.extend_from_slice(b"IEND");
+ png.extend_from_slice(&0u32.to_be_bytes());
+
+ let res = decode_png_rgba8(&png);
+ assert!(res.is_err());
+}
+
+#[test]
+fn test_mask_add_undo_clears_has_mask_and_locked_clear_rejected() {
+ let mut doc = Document::new_blank(
+ "doc-mask",
+ "Mask",
+ CanvasDimensions {
+ width: 64,
+ height: 64,
+ dpi: 72,
+ },
+ CanvasColorMode::Color,
+ "#ffffff",
+ 60.0,
+ 20,
+ );
+ let layer_id = doc.active_layer_id.clone().unwrap();
+
+ // Locked layer cannot be cleared
+ doc.layer_mut(&layer_id).unwrap().meta.locked = true;
+ assert!(doc.clear_layer(&layer_id, true).is_err());
+ doc.layer_mut(&layer_id).unwrap().meta.locked = false;
+
+ // Add mask, then Undo -> both meta.has_mask and grid.has_mask must become false
+ doc.add_layer_mask(&layer_id, 255, true).unwrap();
+ assert!(doc.layer(&layer_id).unwrap().grid.has_mask);
+ let undo_change = doc.undo();
+ assert!(undo_change.layers_changed);
+ assert!(!doc.layer(&layer_id).unwrap().grid.has_mask);
+ assert!(!doc.layer(&layer_id).unwrap().meta.has_mask);
+}
+
+#[test]
+fn test_paste_and_move_selection_undo_atomically_without_orphan_layers() {
+ let mut doc = Document::new_blank(
+ "doc-sel",
+ "Sel",
+ CanvasDimensions {
+ width: 32,
+ height: 32,
+ dpi: 72,
+ },
+ CanvasColorMode::Color,
+ "#00000000",
+ 60.0,
+ 20,
+ );
+ let src_id = doc.active_layer_id.clone().unwrap();
+ let initial_count = doc.layers.len();
+
+ let blue = vec![0, 0, 255, 255].repeat(8 * 8);
+ doc.layer_mut(&src_id)
+ .unwrap()
+ .grid
+ .write_rgba8_rect(&blue, RectI32::new(4, 4, 8, 8), 128, None)
+ .unwrap();
+
+ // Paste selection into a new layer -> 1 Undo removes the pasted layer completely
+ let clip = SelectionClipboard {
+ x: 4,
+ y: 4,
+ width: 8,
+ height: 8,
+ rgba: blue.clone(),
+ source_layer_name: "Layer 1".to_string(),
+ };
+ paste_selection(&mut doc, &clip, "pasted-1".to_string(), None).unwrap();
+ assert_eq!(doc.layers.len(), initial_count + 1);
+ let _ = doc.undo();
+ assert_eq!(doc.layers.len(), initial_count);
+ assert!(doc.layer("pasted-1").is_none());
+
+ // Move selection to new layer -> 1 Undo removes moved layer AND restores source pixels
+ select_rect(&mut doc, RectI32::new(4, 4, 8, 8), SelectionCombineMode::Replace);
+ let moved = move_selection_to_new_layer(&mut doc, &src_id, "moved-1".to_string(), None).unwrap();
+ assert_eq!(moved.as_deref(), Some("moved-1"));
+ assert_eq!(doc.layers.len(), initial_count + 1);
+ assert_eq!(
+ pick_color_document_for_layer(&doc, 6, 6, false, Some(&src_id), None).a,
+ 0
+ );
+ let _ = doc.undo();
+ assert_eq!(doc.layers.len(), initial_count);
+ assert!(doc.layer("moved-1").is_none());
+ assert_eq!(
+ pick_color_document_for_layer(&doc, 6, 6, false, Some(&src_id), None).b,
+ 255
+ );
+}
+
+#[test]
+fn test_merge_folder_normalizes_passthrough_and_respects_nested_visibility() {
+ let mut doc = Document::new_blank(
+ "doc-merge",
+ "Merge",
+ CanvasDimensions {
+ width: 16,
+ height: 16,
+ dpi: 72,
+ },
+ CanvasColorMode::Color,
+ "#00000000",
+ 60.0,
+ 20,
+ );
+
+ let mut folder = LayerNodeMeta::new_folder("f-root", "Group");
+ folder.blend_mode = BlendMode::PassThrough;
+ doc.add_layer(folder, Some(0), false, false);
+
+ let mut hidden_sub = LayerNodeMeta::new_folder("f-hidden", "Hidden Sub");
+ hidden_sub.parent_id = Some("f-root".to_string());
+ hidden_sub.visible = false;
+ doc.add_layer(hidden_sub, Some(1), false, false);
+
+ let mut child = LayerNodeMeta::new_raster("c-hidden", "Hidden Child");
+ child.parent_id = Some("f-hidden".to_string());
+ child.visible = true;
+ doc.add_layer(child, Some(2), false, false);
+ let red = vec![255, 0, 0, 255].repeat(16 * 16);
+ doc.layer_mut("c-hidden")
+ .unwrap()
+ .grid
+ .write_rgba8_rect(&red, RectI32::new(0, 0, 16, 16), 128, None)
+ .unwrap();
+
+ doc.merge_folder("f-root", "merged-out", None).unwrap();
+ let merged = doc.layer("merged-out").expect("merged layer created");
+ assert_eq!(merged.meta.layer_type, LayerType::Raster);
+ assert_eq!(merged.meta.blend_mode, BlendMode::Normal);
+ // Child inside hidden subfolder must NOT bleed into merged pixels
+ let px = pick_color_document_for_layer(&doc, 4, 4, false, Some("merged-out"), None);
+ assert_eq!(px.a, 0);
+}
+
+#[test]
+fn test_history_plan_jump_skips_selectively_undone_tombstones() {
+ let mut stack = HistoryStack::new(10);
+ for i in 1..=3 {
+ let entry = HistoryEntry {
+ meta: HistoryItemMeta {
+ id: format!("e-{i}"),
+ action_type: "brush".to_string(),
+ label: format!("Stroke {i}"),
+ timestamp: i as u64,
+ time_formatted: "00:00:00".to_string(),
+ thumbnail_url: String::new(),
+ undone: false,
+ layer_id: Some("l1".to_string()),
+ },
+ tile_deltas: Vec::new(),
+ layer_tree_delta: None,
+ canvas_resize_delta: None,
+ document_state_delta: None,
+ peer_id: Some("peer-a".to_string()),
+ stroke_id: Some(format!("stroke-{i}")),
+ is_mask_edit: false,
+ };
+ stack.push(entry);
+ }
+ // Selectively undo entry 2 (index 2: entries are 0=init, 1=e-1, 2=e-2, 3=e-3)
+ let undone_idx = stack.find_and_mark_selective_undo(Some("peer-a"), Some("stroke-2"));
+ assert_eq!(undone_idx, Some(2));
+ let plan = stack.plan_jump(0);
+ // Should undo e-3 (idx 3) and e-1 (idx 1), skipping tombstoned e-2 (idx 2)
+ let indices: Vec<usize> = plan.iter().map(|&(idx, _)| idx).collect();
+ assert_eq!(indices, vec![3, 1]);
+}
+
+#[test]
+fn test_collab_tile_delta_rejects_truncated_lz4_and_subrect_without_panicking() {
+ let mut doc = Document::new_blank(
+ "doc-collab",
+ "Collab",
+ CanvasDimensions {
+ width: 256,
+ height: 256,
+ dpi: 72,
+ },
+ CanvasColorMode::Color,
+ "#00000000",
+ 60.0,
+ 20,
+ );
+ let layer_id = doc.active_layer_id.clone().unwrap();
+
+ // Build a malformed LZ4 packet whose decompressed length is 16 bytes (not 262,144)
+ let short_compressed = lz4_flex::compress_prepend_size(&[1u8; 16]);
+ let mut pkt = vec![0u8; TILE_PACKET_HEADER_BYTES];
+ pkt[0] = 0x54; // 'T'
+ pkt[1] = 0x44; // 'D'
+ pkt[2] = 1; // version
+ pkt[3] = TILE_CODEC_LZ4;
+ pkt[4] = 4; // Color32Bit
+ pkt[5] = 0; // Raster
+ pkt.extend_from_slice(&short_compressed);
+ let res = apply_tile_delta_packet(&mut doc, &layer_id, &pkt, false, None);
+ assert!(res.is_err());
+
+ // Build a malformed SUBRECT_LZ4 packet whose decompressed bytes are shorter than rw*rh*4
+ let mut sub_pkt = vec![0u8; TILE_PACKET_HEADER_BYTES];
+ sub_pkt[0] = 0x54;
+ sub_pkt[1] = 0x44;
+ sub_pkt[2] = 1;
+ sub_pkt[3] = TILE_CODEC_SUBRECT_LZ4;
+ sub_pkt[4] = 4;
+ sub_pkt[5] = 0;
+ // Subrect header: rx=0, ry=0, rw=16 (u16 LE), rh=16 (u16 LE) -> expects 1024 bytes, give 16
+ sub_pkt.extend_from_slice(&[0u8, 0u8, 16, 0, 16, 0]);
+ sub_pkt.extend_from_slice(&short_compressed);
+ let res2 = apply_tile_delta_packet(&mut doc, &layer_id, &sub_pkt, false, None);
+ assert!(res2.is_err());
+}
diff --git a/crates/ink-engine/src/brush/config.rs b/crates/ink-engine/src/brush/config.rs
index ebaad15..2de07ce 100644
--- a/crates/ink-engine/src/brush/config.rs
+++ b/crates/ink-engine/src/brush/config.rs
@@ -9,7 +9,7 @@ use crate::types::BrushParams;
use serde::{Deserialize, Serialize};
/// Per-parameter CSP multi-sensor dynamics (`CspSensorConfig`).
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CspSensorConfig {
#[serde(default)]
@@ -23,6 +23,8 @@ pub struct CspSensorConfig {
pub use_tilt: bool,
#[serde(default)]
pub tilt_min: f32,
+ #[serde(default = "default_tilt_max")]
+ pub tilt_max: f32,
#[serde(default)]
pub tilt_curve: Option<Vec<[f32; 2]>>,
@@ -50,15 +52,52 @@ pub struct CspSensorConfig {
pub distance_invert: bool,
}
+fn default_tilt_max() -> f32 {
+ 1.0
+}
+
fn default_distance_max() -> f32 {
300.0
}
+impl Default for CspSensorConfig {
+ fn default() -> Self {
+ Self {
+ use_pressure: false,
+ pressure_min: 0.0,
+ pressure_curve: None,
+ use_tilt: false,
+ tilt_min: 0.0,
+ tilt_max: default_tilt_max(),
+ tilt_curve: None,
+ use_velocity: false,
+ velocity_min: 0.0,
+ velocity_invert: false,
+ velocity_curve: None,
+ use_random: false,
+ random_min: 0.0,
+ use_distance: false,
+ distance_min: 0.0,
+ distance_max_px: default_distance_max(),
+ distance_invert: false,
+ }
+ }
+}
+
impl CspSensorConfig {
#[inline]
pub fn is_any_enabled(&self) -> bool {
self.use_pressure || self.use_tilt || self.use_velocity || self.use_random || self.use_distance
}
+
+ #[inline]
+ pub fn is_any_enabled_channels(&self, skip_pressure: bool) -> bool {
+ (!skip_pressure && self.use_pressure)
+ || self.use_tilt
+ || self.use_velocity
+ || self.use_random
+ || self.use_distance
+ }
}
/// Multi-axis brush jitter & color dynamics (`BrushDynamics`).
@@ -289,6 +328,7 @@ impl DualBrushCompositeMode {
#[serde(rename_all = "kebab-case")]
pub enum CspBrushCombineMode {
#[default]
+ #[serde(alias = "pass-through")]
Normal,
Multiply,
Screen,
@@ -308,6 +348,7 @@ pub enum CspBrushCombineMode {
LinearBurn,
LinearDodge,
AddGlow,
+ #[serde(alias = "color-dodge-glow")]
GlowDodge,
VividLight,
LinearLight,
diff --git a/crates/ink-engine/src/brush/dynamics.rs b/crates/ink-engine/src/brush/dynamics.rs
index 66377b3..3a8df4a 100644
--- a/crates/ink-engine/src/brush/dynamics.rs
+++ b/crates/ink-engine/src/brush/dynamics.rs
@@ -112,10 +112,10 @@ impl CompiledSensorLuts {
}
}
-/// Evaluates a multi-axis [`CspSensorConfig`] returning a combined multiplier in `[0.0, 1.0]`.
+/// Evaluates a multi-axis [`CspSensorConfig`] returning a combined multiplier.
///
-/// Exact parity with `BrushEngine.ts` `evaluateCspSensor`:
-/// Each active channel computes `min + (1 - min) * curved_input` and multiplies cleanly.
+/// Supports CSP `tilt_min..tilt_max` enlargement ceilings (e.g. `tilt_min: 1.0, tilt_max: 1.5`
+/// for pen tilt swell on G-Pen, Real G-Pen, Rough Pen, and Sumi Brush Pen).
#[allow(clippy::too_many_arguments)]
pub fn evaluate_csp_sensor(
sensor: &CspSensorConfig,
@@ -125,10 +125,34 @@ pub fn evaluate_csp_sensor(
velocity_doc_per_ms: f32,
arc_distance_doc: f32,
rand_01: f32,
+) -> f32 {
+ evaluate_csp_sensor_channels(
+ sensor,
+ luts,
+ pressure,
+ tilt_mag,
+ velocity_doc_per_ms,
+ arc_distance_doc,
+ rand_01,
+ false,
+ )
+}
+
+#[allow(clippy::too_many_arguments)]
+fn evaluate_csp_sensor_channels(
+ sensor: &CspSensorConfig,
+ luts: Option<&CompiledSensorLuts>,
+ pressure: f32,
+ tilt_mag: f32,
+ velocity_doc_per_ms: f32,
+ arc_distance_doc: f32,
+ rand_01: f32,
+ skip_pressure: bool,
) -> f32 {
let mut factor = 1.0f32;
+ let mut max_cap = 1.0f32;
- if sensor.use_pressure {
+ if !skip_pressure && sensor.use_pressure {
let raw = pressure.clamp(0.0, 1.0);
let mapped = luts
.and_then(|l| l.pressure_lut.as_ref())
@@ -144,8 +168,14 @@ pub fn evaluate_csp_sensor(
.and_then(|l| l.tilt_lut.as_ref())
.map(|lut| lut.evaluate(raw))
.unwrap_or(raw);
- let lo = sensor.tilt_min.clamp(0.0, 1.0);
- factor *= lo + (1.0 - lo) * mapped;
+ let lo = sensor.tilt_min.clamp(0.0, 10.0);
+ let hi = if sensor.tilt_max > 0.0 {
+ sensor.tilt_max.clamp(lo, 10.0)
+ } else {
+ 1.0f32.max(lo)
+ };
+ factor *= lo + (hi - lo) * mapped;
+ max_cap = max_cap.max(hi);
}
if sensor.use_velocity {
@@ -177,7 +207,7 @@ pub fn evaluate_csp_sensor(
factor *= lo + (1.0 - lo) * raw;
}
- factor.clamp(0.0, 1.0)
+ factor.clamp(0.0, max_cap)
}
/// Computes stamp half-extents `(half_w, half_h)` preserving tip natural aspect ratio
@@ -571,16 +601,19 @@ impl StrokeDabEmitter {
exit_vel: f64,
out: &mut Vec<GpuBrushDab>,
) {
- let base_spacing = self.config.spacing.clamp(0.02, 4.0);
- let thickness = self.config.thickness.clamp(0.10, 1.0);
- let thickness_vert = self.config.thickness_vertical;
+ let config = &self.config;
+ let base_spacing = config.spacing.clamp(0.02, 4.0);
+ let thickness = config.thickness.clamp(0.10, 1.0);
+ let thickness_vert = config.thickness_vertical;
let tip_aspect = self.tip_aspect;
- let base_angle_deg = self.config.custom_tip_angle;
- let angle_mode = self.config.custom_tip_angle_dynamics;
- let interval_sensor = self.config.interval_sensor.clone();
- let interval_luts = self.interval_luts.clone();
- let use_tilt = self.config.use_tilt;
- let tilt_scale = self.config.tilt_scale.clamp(0.2, 4.0);
+ let base_angle_deg = config.custom_tip_angle;
+ let angle_mode = config.custom_tip_angle_dynamics;
+ let interval_sensor = config.interval_sensor.as_ref();
+ let interval_luts = &self.interval_luts;
+ let use_tilt = config.use_tilt
+ || interval_sensor.is_some_and(|s| s.use_tilt)
+ || config.size_sensor.as_ref().is_some_and(|s| s.use_tilt);
+ let tilt_scale = config.tilt_scale.clamp(0.2, 4.0);
let current_arc = self.resampler.total_arc_length;
let samples = self.resampler.resample_segment(seg, |pt, angle_rad| {
@@ -597,11 +630,11 @@ impl StrokeDabEmitter {
}
_ => (base_angle_deg as f64).to_radians(),
};
- let interval_mult = if let Some(ref isen) = interval_sensor {
+ let interval_mult = if let Some(isen) = interval_sensor {
if isen.is_any_enabled() {
evaluate_csp_sensor(
isen,
- Some(&interval_luts),
+ Some(interval_luts),
pt.pressure,
tilt_mag,
pt.velocity as f32,
@@ -641,7 +674,13 @@ impl StrokeDabEmitter {
exit_vel: f64,
out: &mut Vec<GpuBrushDab>,
) {
- let tilt_mag = if self.config.use_tilt {
+ let any_tilt = self.config.use_tilt
+ || self.config.size_sensor.as_ref().is_some_and(|s| s.use_tilt)
+ || self.config.opacity_sensor.as_ref().is_some_and(|s| s.use_tilt)
+ || self.config.density_sensor.as_ref().is_some_and(|s| s.use_tilt)
+ || self.config.thickness_sensor.as_ref().is_some_and(|s| s.use_tilt)
+ || self.config.texture_density_sensor.as_ref().is_some_and(|s| s.use_tilt);
+ let tilt_mag = if any_tilt {
compute_csp_tilt_magnitude(pt.tilt_x, pt.tilt_y)
} else {
0.0
@@ -657,29 +696,23 @@ impl StrokeDabEmitter {
.map(|t| evaluate_csp_taper_factors(t, arc_dist, total_length, exit_vel))
.unwrap_or_default();
- // 2. Size sensor + tilt spread + taper
+ // 2. Size sensor + tilt spread + taper (borrowed by reference — ZERO per-dab clone!)
let mut diameter = pt.width.max(0.2);
if let Some(ref ss) = self.config.size_sensor {
- if ss.is_any_enabled() {
- // Note: pt.width already incorporated primary brush pressure curve if use_pressure=true;
- // apply non-pressure channels (tilt, velocity, random, distance) plus sensor pressure when pressure was disabled
- let mut non_p = ss.clone();
- if self.config.use_pressure {
- non_p.use_pressure = false;
- }
- if non_p.is_any_enabled() {
- let r = self.rng.next_f32();
- let mult = evaluate_csp_sensor(
- &non_p,
- Some(&self.size_luts),
- pt.pressure,
- tilt_mag,
- vel,
- arc_f,
- r,
- );
- diameter *= mult;
- }
+ let skip_pressure = self.config.use_pressure;
+ if ss.is_any_enabled_channels(skip_pressure) {
+ let r = self.rng.next_f32();
+ let mult = evaluate_csp_sensor_channels(
+ ss,
+ Some(&self.size_luts),
+ pt.pressure,
+ tilt_mag,
+ vel,
+ arc_f,
+ r,
+ skip_pressure,
+ );
+ diameter *= mult;
}
}
if self.config.use_tilt && tilt_mag > 0.01 {
@@ -768,8 +801,8 @@ impl StrokeDabEmitter {
stroke_angle_rad
};
- // 6. Spraying Effect mode (emits radial particle burst within brush diameter)
- if let Some(spray) = self.config.spray.clone() {
+ // 6. Spraying Effect mode (borrowed by reference — ZERO per-dab clone!)
+ if let Some(ref spray) = self.config.spray {
if spray.enabled {
let spray_radius = (diameter * 0.5).max(1.0);
let mut p_count_f = spray.density.clamp(1.0, 20.0);
@@ -859,7 +892,8 @@ impl StrokeDabEmitter {
self.rng.next_f32(),
self.rng.next_f32(),
);
- let dab_rgb = self.eval_dab_color();
+ let dab_rgb =
+ Self::eval_dab_color_split(&self.config, self.stroke_color, &mut self.rng);
let flow_j = 1.0 - self.rng.next_f32() * self.config.dynamics.flow_jitter.clamp(0.0, 0.95);
let dab_a = (alpha * flow_j).clamp(0.004, 1.0);
self.dab_counter = self.dab_counter.wrapping_add(1);
@@ -978,19 +1012,28 @@ impl StrokeDabEmitter {
#[inline]
fn eval_dab_color(&mut self) -> [f32; 3] {
- if self.config.dynamics.color_jitter_enabled && self.config.dynamics.color_jitter_per_dab {
+ Self::eval_dab_color_split(&self.config, self.stroke_color, &mut self.rng)
+ }
+
+ #[inline]
+ fn eval_dab_color_split(
+ config: &NativeBrushConfig,
+ stroke_color: [f32; 3],
+ rng: &mut Xoshiro256StarStar,
+ ) -> [f32; 3] {
+ if config.dynamics.color_jitter_enabled && config.dynamics.color_jitter_per_dab {
apply_color_dynamics(
- self.config.fg_color,
- self.config.bg_color,
- &self.config.dynamics,
- self.rng.next_f32(),
- self.rng.next_signed_f32(),
- self.rng.next_signed_f32(),
- self.rng.next_signed_f32(),
- self.rng.next_signed_f32(),
+ config.fg_color,
+ config.bg_color,
+ &config.dynamics,
+ rng.next_f32(),
+ rng.next_signed_f32(),
+ rng.next_signed_f32(),
+ rng.next_signed_f32(),
+ rng.next_signed_f32(),
)
} else {
- self.stroke_color
+ stroke_color
}
}
}
diff --git a/crates/ink-engine/src/brush/shaders.rs b/crates/ink-engine/src/brush/shaders.rs
index d19d578..330a87e 100644
--- a/crates/ink-engine/src/brush/shaders.rs
+++ b/crates/ink-engine/src/brush/shaders.rs
@@ -471,6 +471,69 @@ fn cs_main(@builtin(global_invocation_id) gid: vec3<u32>) {
}
"#;
+/// Shared WGSL helper implementing all 12 CSP Dual Brush composite modes (`DualBrushEngine.ts` parity).
+pub const DUAL_BRUSH_COMBINE_WGSL: &str = r#"
+fn combine_dual_alpha(a1: f32, a2: f32, mode: u32) -> f32 {
+ let p = clamp(a1, 0.0, 1.0);
+ let s = clamp(a2, 0.0, 1.0);
+ switch (mode) {
+ case 0u: {
+ // multiply
+ return p * s;
+ }
+ case 1u: {
+ // darken
+ return min(p, s);
+ }
+ case 2u: {
+ // subtract (cuts secondary mask out of primary)
+ return max(0.0, p - s);
+ }
+ case 3u: {
+ // compare-density
+ return min(p, max(0.0, s));
+ }
+ case 4u: {
+ // linear-burn
+ return max(0.0, p + s - 1.0);
+ }
+ case 5u: {
+ // color-burn
+ if (p <= 0.0005) { return 0.0; }
+ if (s <= 0.0005) { return 0.0; }
+ return clamp(1.0 - min(1.0, (1.0 - p) / max(0.005, s)), 0.0, 1.0) * step(0.001, p);
+ }
+ case 6u: {
+ // height (physical tooth cut modulated by secondary alpha)
+ return clamp(smoothstep(0.0, 0.55, p + s - 0.85) * p, 0.0, 1.0);
+ }
+ case 7u: {
+ // overlay (masked to primary stroke silhouette so empty canvas stays clean)
+ if (p <= 0.0005) { return 0.0; }
+ let ov = select(1.0 - 2.0 * (1.0 - p) * (1.0 - s), 2.0 * p * s, p < 0.5);
+ return clamp(ov, 0.0, 1.0);
+ }
+ case 8u: {
+ // screen
+ return clamp(p + s - p * s, 0.0, 1.0);
+ }
+ case 9u: {
+ // lighten
+ return max(p, s);
+ }
+ case 10u: {
+ // hard-mix
+ if (p <= 0.0005) { return 0.0; }
+ return step(1.0, p + s);
+ }
+ default: {
+ // 11: normal (unmasked primary over secondary union)
+ return clamp(p + s * (1.0 - p), 0.0, 1.0);
+ }
+ }
+}
+"#;
+
/// Per-tile post-processing compute shader implementing:
/// 1. All 12 CSP Dual Brush composite modes (`primary_slot` + `secondary_slot`), AND
/// 2. Per-stroke Paper Grain (`paperTextureApplyEachPlot == false`, i.e., `TextureForPlot = 0`)
@@ -508,66 +571,7 @@ struct StrokePostUniforms {{
{PAPER_GRAIN_WGSL}
-/// All 12 CSP Dual Brush composite modes (`DualBrushEngine.ts` parity).
-fn combine_dual_alpha(a1: f32, a2: f32, mode: u32) -> f32 {{
- let p = clamp(a1, 0.0, 1.0);
- let s = clamp(a2, 0.0, 1.0);
- switch (mode) {{
- case 0u: {{
- // multiply
- return p * s;
- }}
- case 1u: {{
- // darken
- return min(p, s);
- }}
- case 2u: {{
- // subtract (cuts secondary mask out of primary)
- return max(0.0, p - s);
- }}
- case 3u: {{
- // compare-density
- return min(p, max(0.0, s));
- }}
- case 4u: {{
- // linear-burn
- return max(0.0, p + s - 1.0);
- }}
- case 5u: {{
- // color-burn
- if (p <= 0.0005) {{ return 0.0; }}
- if (s <= 0.0005) {{ return 0.0; }}
- return clamp(1.0 - min(1.0, (1.0 - p) / max(0.005, s)), 0.0, 1.0) * step(0.001, p);
- }}
- case 6u: {{
- // height (physical tooth cut modulated by secondary alpha)
- return clamp(smoothstep(0.0, 0.55, p + s - 0.85) * p, 0.0, 1.0);
- }}
- case 7u: {{
- // overlay (masked to primary stroke silhouette so empty canvas stays clean)
- if (p <= 0.0005) {{ return 0.0; }}
- let ov = select(1.0 - 2.0 * (1.0 - p) * (1.0 - s), 2.0 * p * s, p < 0.5);
- return clamp(ov, 0.0, 1.0);
- }}
- case 8u: {{
- // screen
- return clamp(p + s - p * s, 0.0, 1.0);
- }}
- case 9u: {{
- // lighten
- return max(p, s);
- }}
- case 10u: {{
- // hard-mix
- if (p <= 0.0005) {{ return 0.0; }}
- return step(1.0, p + s);
- }}
- default: {{
- // 11: normal (unmasked primary over secondary union)
- return clamp(p + s * (1.0 - p), 0.0, 1.0);
- }}
- }}
-}}
+{DUAL_BRUSH_COMBINE_WGSL}
@compute @workgroup_size(16, 16, 1)
fn cs_main(@builtin(global_invocation_id) gid: vec3<u32>) {{
diff --git a/crates/ink-engine/src/brush/sparse_stroke.rs b/crates/ink-engine/src/brush/sparse_stroke.rs
index 89f4c48..d7a82bc 100644
--- a/crates/ink-engine/src/brush/sparse_stroke.rs
+++ b/crates/ink-engine/src/brush/sparse_stroke.rs
@@ -104,6 +104,7 @@ struct SparseStrokePool {
array_view: wgpu::TextureView,
slice_views: Vec<wgpu::TextureView>,
capacity: u32,
+ gen: u64,
coord_to_slot: HashMap<TileCoord, u32>,
next_slot: u32,
}
@@ -118,6 +119,7 @@ impl SparseStrokePool {
array_view,
slice_views,
capacity: cap,
+ gen: 1,
coord_to_slot: HashMap::with_capacity(cap as usize),
next_slot: 0,
}
@@ -219,6 +221,7 @@ impl SparseStrokePool {
self.array_view = new_array_view;
self.slice_views = new_slices;
self.capacity = new_cap;
+ self.gen = self.gen.saturating_add(1);
}
/// Returns `(slot, is_newly_allocated)`.
@@ -273,11 +276,15 @@ pub struct GpuBrushEngine {
dab_instance_cap: usize,
dab_uniform_buf: wgpu::Buffer,
dab_uniform_cap: usize,
+ dab_uniform_buf_gen: u64,
+ cached_dab_bgs: [Option<((u64, u64, u64), wgpu::BindGroup)>; 2],
+ dab_bg_next_evict: usize,
// Darken tip-blend helper (256×256 batch scratch + compute merge)
darken_bgl: wgpu::BindGroupLayout,
darken_pipeline: wgpu::ComputePipeline,
darken_uniform_buf: wgpu::Buffer,
+ darken_uniform_cap: usize,
_darken_batch_tex: wgpu::Texture,
darken_batch_view: wgpu::TextureView,
@@ -308,7 +315,8 @@ pub struct GpuBrushEngine {
_commit_dummy_sel_tex: wgpu::Texture,
commit_dummy_sel_view: wgpu::TextureView,
commit_rgba8_storage_buf: wgpu::Buffer,
- commit_rgba8_readback_buf: wgpu::Buffer,
+ commit_rgba8_readback_bufs: [wgpu::Buffer; 2],
+ commit_rb_idx: usize,
commit_buf_tile_cap: usize,
// Sparse GPU stroke tile pools (never full-canvas FBOs!)
@@ -531,7 +539,7 @@ impl GpuBrushEngine {
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
- has_dynamic_offset: false,
+ has_dynamic_offset: true,
min_binding_size: None,
},
count: None,
@@ -585,9 +593,10 @@ impl GpuBrushEngine {
compilation_options: Default::default(),
cache: None,
});
+ let darken_uniform_cap = 256usize;
let darken_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("ink-brush-darken-uniforms"),
- size: std::mem::size_of::<DarkenParamsUniform>() as u64,
+ size: darken_uniform_cap as u64 * UNIFORM_STRIDE,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
@@ -960,12 +969,20 @@ impl GpuBrushEngine {
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
- let commit_rgba8_readback_buf = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("ink-tile-commit-rgba8-readback"),
- size: commit_buf_bytes,
- usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
- mapped_at_creation: false,
- });
+ let commit_rgba8_readback_bufs = [
+ device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-tile-commit-rgba8-readback-0"),
+ size: commit_buf_bytes,
+ usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ }),
+ device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-tile-commit-rgba8-readback-1"),
+ size: commit_buf_bytes,
+ usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ }),
+ ];
// Lean sparse pools (only allocate tiles touched by active stroke; grow dynamically)
let primary_pool = SparseStrokePool::new(device, "ink-stroke-primary-pool", 32);
@@ -989,9 +1006,13 @@ impl GpuBrushEngine {
dab_instance_cap,
dab_uniform_buf,
dab_uniform_cap,
+ dab_uniform_buf_gen: 1,
+ cached_dab_bgs: [None, None],
+ dab_bg_next_evict: 0,
darken_bgl,
darken_pipeline,
darken_uniform_buf,
+ darken_uniform_cap,
_darken_batch_tex: darken_batch_tex,
darken_batch_view,
post_bgl,
@@ -1016,7 +1037,8 @@ impl GpuBrushEngine {
_commit_dummy_sel_tex: commit_dummy_sel_tex,
commit_dummy_sel_view,
commit_rgba8_storage_buf,
- commit_rgba8_readback_buf,
+ commit_rgba8_readback_bufs,
+ commit_rb_idx: 0,
commit_buf_tile_cap,
primary_pool,
secondary_pool,
@@ -1092,6 +1114,21 @@ impl GpuBrushEngine {
&self.active_brush
}
+ /// Returns the tile coordinates currently touched by the active stroke so callers can
+ /// snapshot ONLY those `Arc<TileData>` entries under a brief read lock before GPU commit!
+ pub fn touched_tile_coords(&self) -> Vec<TileCoord> {
+ if self.natural_paint.is_active() {
+ self.natural_paint.pools.coord_to_slot.keys().copied().collect()
+ } else if self.use_resolved_output {
+ let mut set: HashSet<TileCoord> = self.resolved_pool.coord_to_slot.keys().copied().collect();
+ set.extend(self.primary_pool.coord_to_slot.keys().copied());
+ set.extend(self.dirty_post_tiles.iter().copied());
+ set.into_iter().collect()
+ } else {
+ self.primary_pool.coord_to_slot.keys().copied().collect()
+ }
+ }
+
#[inline]
pub fn touched_tile_count(&self) -> usize {
if self.natural_paint.is_active() {
@@ -1106,12 +1143,30 @@ impl GpuBrushEngine {
/// Exposes the active sparse stroke tile atlas & `(TileCoord -> slot)` map for
/// `WgpuCompositor` in-stack WYSIWYG preview!
pub fn active_stroke_atlas(&self) -> (&wgpu::TextureView, &HashMap<TileCoord, u32>) {
+ let (_, view, map) = self.active_stroke_atlas_with_id();
+ (view, map)
+ }
+
+ /// Exposes `((pool_kind, pool_gen), atlas_view, coord_to_slot)` so `WgpuCompositor` can
+ /// safely cache its `sparse_stroke_bg` bind group with zero per-frame allocation!
+ pub fn active_stroke_atlas_with_id(
+ &self,
+ ) -> ((u8, u64), &wgpu::TextureView, &HashMap<TileCoord, u32>) {
if self.natural_paint.is_active() {
- self.natural_paint.active_color_atlas()
+ let (v, m) = self.natural_paint.active_color_atlas();
+ ((3, self.natural_paint.pools.atlas_gen), v, m)
} else if self.use_resolved_output {
- (&self.resolved_pool.array_view, &self.resolved_pool.coord_to_slot)
+ (
+ (2, self.resolved_pool.gen),
+ &self.resolved_pool.array_view,
+ &self.resolved_pool.coord_to_slot,
+ )
} else {
- (&self.primary_pool.array_view, &self.primary_pool.coord_to_slot)
+ (
+ (1, self.primary_pool.gen),
+ &self.primary_pool.array_view,
+ &self.primary_pool.coord_to_slot,
+ )
}
}
@@ -1119,12 +1174,21 @@ impl GpuBrushEngine {
pub fn active_impasto_overlay(
&self,
) -> Option<(&wgpu::TextureView, &HashMap<TileCoord, u32>, ImpastoLayerLight)> {
+ self.active_impasto_overlay_with_id()
+ .map(|(_, view, map, light)| (view, map, light))
+ }
+
+ /// Exposes `(atlas_gen, height_view, tile_map, light)` so `WgpuCompositor` can cache
+ /// its impasto height projection bind group with zero per-frame allocation!
+ pub fn active_impasto_overlay_with_id(
+ &self,
+ ) -> Option<(u64, &wgpu::TextureView, &HashMap<TileCoord, u32>, ImpastoLayerLight)> {
if !self.natural_paint.has_live_impasto() {
return None;
}
let light = self.active_brush.impasto_layer_light()?;
let (view, map) = self.natural_paint.active_impasto_atlas();
- Some((view, map, light))
+ Some((self.natural_paint.pools.atlas_gen.max(1), view, map, light))
}
/// Resolves `(tip_w, tip_h, sub_tip_count)` for continuous ribbon aspect-preserving UV tiling.
@@ -1289,6 +1353,14 @@ impl GpuBrushEngine {
(newly_touched, bounds)
}
+ /// Sets the per-stroke random paper grain offset for `GrainMappingMode::RandomPerStroke`
+ /// on Natural Paint & Color Mixing strokes.
+ #[inline]
+ pub fn set_natural_paint_stroke_rand_offset(&mut self, offset: [f32; 2]) {
+ self.stroke_rand_offset = offset;
+ self.natural_paint.set_stroke_rand_offset(offset);
+ }
+
/// Dispatches standard CSP `colorMixing` dabs on GPU (zero-readback 16×16 SpatialTipMixer).
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
pub fn dispatch_color_mixing_dabs(
@@ -1301,13 +1373,14 @@ impl GpuBrushEngine {
dabs: &[GpuBrushDab],
scratch: Option<&dyn ScratchBackend>,
) -> (Vec<TileCoord>, Option<(f32, f32, f32, f32)>) {
- self.dispatch_color_mixing_dabs_with_selection(
+ self.dispatch_color_mixing_dabs_with_dual_and_selection(
device,
queue,
tile_pool,
doc,
active_layer,
dabs,
+ &[],
scratch,
None,
)
@@ -1325,10 +1398,69 @@ impl GpuBrushEngine {
dabs: &[GpuBrushDab],
scratch: Option<&dyn ScratchBackend>,
selection: Option<&crate::selection::GpuSelectionOverlay>,
+ ) -> (Vec<TileCoord>, Option<(f32, f32, f32, f32)>) {
+ self.dispatch_color_mixing_dabs_with_dual_and_selection(
+ device,
+ queue,
+ tile_pool,
+ doc,
+ active_layer,
+ dabs,
+ &[],
+ scratch,
+ selection,
+ )
+ }
+
+ /// Dispatches standard CSP `colorMixing` dabs with optional Dual Brush secondary dabs and
+ /// active [`GpuSelectionOverlay`]!
+ #[allow(clippy::too_many_arguments, clippy::type_complexity)]
+ pub fn dispatch_color_mixing_dabs_with_dual_and_selection(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ tile_pool: &mut GpuTilePool,
+ doc: &Document,
+ active_layer: &LayerNode,
+ dabs: &[GpuBrushDab],
+ secondary_dabs: &[GpuBrushDab],
+ scratch: Option<&dyn ScratchBackend>,
+ selection: Option<&crate::selection::GpuSelectionOverlay>,
) -> (Vec<TileCoord>, Option<(f32, f32, f32, f32)>) {
if !self.natural_paint.is_active() || dabs.is_empty() {
return (Vec::new(), None);
}
+ let brush = self.active_brush.clone();
+
+ // Stamp Dual Brush secondary mask dabs into `secondary_pool` via hardware instanced quads!
+ if !secondary_dabs.is_empty() {
+ if let Some(sec_brush) = brush.build_secondary_brush_config() {
+ let _ = self.stamp_stream_into_pool(
+ device,
+ queue,
+ false,
+ &sec_brush,
+ secondary_dabs,
+ false,
+ );
+ }
+ }
+ let dual_secondary = if brush.is_dual_brush_active() && self.secondary_pool.next_slot > 0 {
+ let mode = brush
+ .dual_brush_config
+ .as_ref()
+ .map(|d| d.combine_mode)
+ .unwrap_or(DualBrushCompositeMode::Multiply);
+ Some((
+ &self.secondary_pool.array_view,
+ self.secondary_pool.gen,
+ &self.secondary_pool.coord_to_slot,
+ mode,
+ ))
+ } else {
+ None
+ };
+
let prev_coords: HashSet<TileCoord> = self
.natural_paint
.pools
@@ -1336,7 +1468,6 @@ impl GpuBrushEngine {
.keys()
.copied()
.collect();
- let brush = self.active_brush.clone();
let (is_tex, tip_arr, paper_tex, fallback_tip, default_paper) =
self.tip_cache.resolve_tip_and_paper_with_fallbacks(
device,
@@ -1360,6 +1491,7 @@ impl GpuBrushEngine {
default_paper,
scratch,
selection,
+ dual_secondary,
);
let newly_touched: Vec<TileCoord> = self
.natural_paint
@@ -1436,30 +1568,38 @@ impl GpuBrushEngine {
None
};
+ let mut allocs: Vec<(TileCoord, u32, bool)> = Vec::with_capacity(touched.len());
for coord in touched {
if let Some((slot, is_new)) = self.primary_pool.get_or_alloc(device, queue, coord) {
if is_new {
newly_touched.push(coord);
}
- self.ribbon_pipeline.render_into_tile(
- device,
- queue,
- &self.primary_pool.slice_views[slot as usize],
- coord,
- primary_verts,
- &brush,
- tip_opt,
- fallback_tip,
- paper_opt,
- default_paper,
- is_new || clear_existing,
- use_max,
- );
if self.use_resolved_output {
self.dirty_post_tiles.insert(coord);
}
+ allocs.push((coord, slot, is_new || clear_existing));
}
}
+ if !allocs.is_empty() {
+ let targets: Vec<(TileCoord, &wgpu::TextureView, bool)> = allocs
+ .iter()
+ .map(|&(coord, slot, clear_first)| {
+ (coord, &self.primary_pool.slice_views[slot as usize], clear_first)
+ })
+ .collect();
+ self.ribbon_pipeline.render_into_tiles_batch(
+ device,
+ queue,
+ &targets,
+ primary_verts,
+ &brush,
+ tip_opt,
+ fallback_tip,
+ paper_opt,
+ default_paper,
+ use_max,
+ );
+ }
}
if !secondary_verts.is_empty() {
@@ -1475,29 +1615,41 @@ impl GpuBrushEngine {
None,
);
let tip_opt = if is_tex { Some(tip_arr) } else { None };
+ let mut allocs: Vec<(TileCoord, u32, bool)> = Vec::with_capacity(touched.len());
for coord in touched {
if let Some((slot, is_new)) =
self.secondary_pool.get_or_alloc(device, queue, coord)
{
- self.ribbon_pipeline.render_into_tile(
- device,
- queue,
- &self.secondary_pool.slice_views[slot as usize],
- coord,
- secondary_verts,
- &sec_brush,
- tip_opt,
- fallback_tip,
- None,
- default_paper,
- is_new || clear_existing,
- false,
- );
if self.use_resolved_output {
self.dirty_post_tiles.insert(coord);
}
+ allocs.push((coord, slot, is_new || clear_existing));
}
}
+ if !allocs.is_empty() {
+ let targets: Vec<(TileCoord, &wgpu::TextureView, bool)> = allocs
+ .iter()
+ .map(|&(coord, slot, clear_first)| {
+ (
+ coord,
+ &self.secondary_pool.slice_views[slot as usize],
+ clear_first,
+ )
+ })
+ .collect();
+ self.ribbon_pipeline.render_into_tiles_batch(
+ device,
+ queue,
+ &targets,
+ secondary_verts,
+ &sec_brush,
+ tip_opt,
+ fallback_tip,
+ None,
+ default_paper,
+ false,
+ );
+ }
}
}
@@ -1554,8 +1706,9 @@ impl GpuBrushEngine {
}
/// Stamps batches of primary (and optional dual-brush secondary) [`GpuBrushDab`]s into
- /// the sparse GPU stroke tile pools and returns the newly touched `TileCoord`s so the
- /// caller can lazily capture CoW undo tile snapshots BEFORE pen-up!
+ /// the sparse GPU stroke tile pools and runs any Dual Brush / Per-Stroke Paper Grain /
+ /// 2-Pass Wet Edge post-passes in **ONE `CommandEncoder` + ONE `queue.submit`**!
+ /// Returns the newly touched `TileCoord`s so the caller can lazily capture CoW undo snapshots.
pub fn stamp_dabs(
&mut self,
device: &wgpu::Device,
@@ -1572,82 +1725,413 @@ impl GpuBrushEngine {
self.last_stroke_angle_rad = last.extra[3];
}
+ let primary_brush = self.active_brush.clone();
+ let secondary_brush = if !secondary_dabs.is_empty() {
+ self.active_brush.build_secondary_brush_config()
+ } else {
+ None
+ };
+
+ let mut flat_instances: Vec<GpuBrushDab> =
+ Vec::with_capacity((primary_dabs.len() + secondary_dabs.len()) * 2);
let mut newly_touched = Vec::new();
- // 1. Stamp primary brush dabs into `primary_pool`
- if !primary_dabs.is_empty() {
- let brush = self.active_brush.clone();
- let touched = self.stamp_stream_into_pool(
+ // 1. Bin primary & secondary dabs into overlapping tiles and allocate ALL pool slots BEFORE
+ // creating any BindGroups or our single CommandEncoder!
+ let primary_jobs = if !primary_dabs.is_empty() {
+ let (jobs, touched) = self.bin_and_alloc_stream(
device,
queue,
true,
- &brush,
primary_dabs,
- true,
+ &mut flat_instances,
);
newly_touched.extend(touched);
+ jobs
+ } else {
+ Vec::new()
+ };
+
+ let secondary_jobs = if !secondary_dabs.is_empty() && secondary_brush.is_some() {
+ let (jobs, touched) = self.bin_and_alloc_stream(
+ device,
+ queue,
+ false,
+ secondary_dabs,
+ &mut flat_instances,
+ );
+ if matches!(
+ self.active_brush
+ .dual_brush_config
+ .as_ref()
+ .map(|d| d.combine_mode),
+ Some(
+ DualBrushCompositeMode::Screen
+ | DualBrushCompositeMode::Lighten
+ | DualBrushCompositeMode::Normal
+ )
+ ) {
+ newly_touched.extend(touched);
+ }
+ jobs
+ } else {
+ Vec::new()
+ };
+
+ let total_tile_jobs = primary_jobs.len() + secondary_jobs.len();
+ let run_post = self.use_resolved_output && !self.dirty_post_tiles.is_empty();
+ if total_tile_jobs == 0 && !run_post {
+ return newly_touched;
}
- // 2. Stamp Dual Brush secondary dabs into `secondary_pool`
- if !secondary_dabs.is_empty() {
- if let Some(sec_brush) = self.active_brush.build_secondary_brush_config() {
- let touched = self.stamp_stream_into_pool(
+ // 2. Upload combined instance buffer + combined dynamic dab uniforms in 2 single writes
+ let mut prim_bg_slot: Option<usize> = None;
+ let mut sec_bg_slot: Option<usize> = None;
+ let mut darken_bg: Option<wgpu::BindGroup> = None;
+ let use_darken =
+ !primary_jobs.is_empty() && primary_brush.blend_tips_mode == CspBlendTipsMode::Darken;
+
+ if total_tile_jobs > 0 {
+ self.ensure_instance_buf(device, flat_instances.len());
+ if Self::ensure_uniform_buf(
+ device,
+ &mut self.dab_uniform_buf,
+ &mut self.dab_uniform_cap,
+ total_tile_jobs,
+ "ink-brush-dab-uniforms",
+ ) {
+ self.dab_uniform_buf_gen = self.dab_uniform_buf_gen.saturating_add(1);
+ self.cached_dab_bgs = [None, None];
+ }
+ queue.write_buffer(
+ &self.dab_instance_buf,
+ 0,
+ bytemuck::cast_slice(&flat_instances),
+ );
+
+ let mut uniform_bytes = vec![0u8; total_tile_jobs * UNIFORM_STRIDE as usize];
+ if !primary_jobs.is_empty() {
+ let (slot, is_textured, tip_layers, paper_size) =
+ self.resolve_and_cache_dab_bg_protected(device, queue, &primary_brush, None);
+ prim_bg_slot = Some(slot);
+ for (i, (coord, _, _, _, _)) in primary_jobs.iter().enumerate() {
+ let u = self.build_dab_uniforms(
+ &primary_brush,
+ [
+ (coord.tx * TILE_SIZE as i32) as f32,
+ (coord.ty * TILE_SIZE as i32) as f32,
+ ],
+ is_textured,
+ tip_layers,
+ paper_size,
+ true,
+ );
+ let off = i * UNIFORM_STRIDE as usize;
+ let src = bytemuck::bytes_of(&u);
+ uniform_bytes[off..off + src.len()].copy_from_slice(src);
+ }
+ }
+ if !secondary_jobs.is_empty() {
+ if let Some(ref sec_brush) = secondary_brush {
+ let (slot, is_textured, tip_layers, paper_size) = self
+ .resolve_and_cache_dab_bg_protected(device, queue, sec_brush, prim_bg_slot);
+ sec_bg_slot = Some(slot);
+ let base_idx = primary_jobs.len();
+ for (j, (coord, _, _, _, _)) in secondary_jobs.iter().enumerate() {
+ let u = self.build_dab_uniforms(
+ sec_brush,
+ [
+ (coord.tx * TILE_SIZE as i32) as f32,
+ (coord.ty * TILE_SIZE as i32) as f32,
+ ],
+ is_textured,
+ tip_layers,
+ paper_size,
+ false,
+ );
+ let off = (base_idx + j) * UNIFORM_STRIDE as usize;
+ let src = bytemuck::bytes_of(&u);
+ uniform_bytes[off..off + src.len()].copy_from_slice(src);
+ }
+ }
+ }
+ queue.write_buffer(&self.dab_uniform_buf, 0, &uniform_bytes);
+
+ if use_darken && primary_jobs.iter().any(|&(_, _, is_new, _, _)| !is_new) {
+ Self::ensure_uniform_buf(
device,
- queue,
- false,
- &sec_brush,
- secondary_dabs,
- false,
+ &mut self.darken_uniform_buf,
+ &mut self.darken_uniform_cap,
+ primary_jobs.len(),
+ "ink-brush-darken-uniforms",
);
- // If additive Dual modes (Screen/Lighten/Normal), secondary-only tiles also matter
- if matches!(
- self.active_brush
- .dual_brush_config
- .as_ref()
- .map(|d| d.combine_mode),
- Some(
- DualBrushCompositeMode::Screen
- | DualBrushCompositeMode::Lighten
- | DualBrushCompositeMode::Normal
- )
- ) {
- newly_touched.extend(touched);
+ let mut darken_bytes = vec![0u8; primary_jobs.len() * UNIFORM_STRIDE as usize];
+ for (i, &(_, slot, _, _, _)) in primary_jobs.iter().enumerate() {
+ let dp = DarkenParamsUniform {
+ dst_slot: slot as i32,
+ _pad: [0; 3],
+ };
+ let off = i * UNIFORM_STRIDE as usize;
+ let src = bytemuck::bytes_of(&dp);
+ darken_bytes[off..off + src.len()].copy_from_slice(src);
}
+ queue.write_buffer(&self.darken_uniform_buf, 0, &darken_bytes);
+ darken_bg = Some(device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-brush-darken-bg"),
+ layout: &self.darken_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.darken_uniform_buf,
+ offset: 0,
+ size: wgpu::BufferSize::new(
+ std::mem::size_of::<DarkenParamsUniform>() as u64,
+ ),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(
+ &self.primary_pool.array_view,
+ ),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(&self.darken_batch_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::TextureView(&self.post_scratch_view),
+ },
+ ],
+ }));
}
}
- // 3. Refresh dirty resolved tiles (Dual Combine, Per-Stroke Paper Grain, 2-Pass Wet Edge)
- if self.use_resolved_output && !self.dirty_post_tiles.is_empty() {
- self.refresh_resolved_tiles(device, queue);
+ // 3. Encode Primary + Secondary + Dual Combine + Per-Stroke Paper + 2-Pass Wet Edge
+ // into ONE SINGLE CommandEncoder and ONE SINGLE queue.submit!
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-brush-unified-stamp-and-post-encoder"),
+ });
+
+ if let Some(p_bg_idx) = prim_bg_slot {
+ let p_bg = &self.cached_dab_bgs[p_bg_idx]
+ .as_ref()
+ .expect("cached primary dab_bg")
+ .1;
+ let p_pipe = match primary_brush.blend_tips_mode {
+ CspBlendTipsMode::Compare => &self.dab_tile_compare_pipeline,
+ _ => &self.dab_tile_normal_pipeline,
+ };
+ for (i, &(_, slot, is_new, start, count)) in primary_jobs.iter().enumerate() {
+ let dyn_off = (i as u32) * (UNIFORM_STRIDE as u32);
+ if use_darken && !is_new {
+ {
+ let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("ink-brush-darken-batch"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &self.darken_batch_view,
+ depth_slice: None,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ multiview_mask: None,
+ });
+ rp.set_pipeline(p_pipe);
+ rp.set_bind_group(0, p_bg, &[dyn_off]);
+ rp.set_vertex_buffer(0, self.dab_instance_buf.slice(..));
+ rp.draw(0..6, start..(start + count));
+ }
+ if let Some(dbg) = darken_bg.as_ref() {
+ let mut cp = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("ink-brush-darken-merge"),
+ timestamp_writes: None,
+ });
+ cp.set_pipeline(&self.darken_pipeline);
+ cp.set_bind_group(0, dbg, &[dyn_off]);
+ cp.dispatch_workgroups(16, 16, 1);
+ }
+ encoder.copy_texture_to_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: &self.post_scratch_tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::TexelCopyTextureInfo {
+ texture: &self.primary_pool.texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d {
+ x: 0,
+ y: 0,
+ z: slot,
+ },
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::Extent3d {
+ width: TILE_SIZE as u32,
+ height: TILE_SIZE as u32,
+ depth_or_array_layers: 1,
+ },
+ );
+ } else {
+ let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("ink-brush-tile-stamp"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &self.primary_pool.slice_views[slot as usize],
+ depth_slice: None,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: if is_new {
+ wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT)
+ } else {
+ wgpu::LoadOp::Load
+ },
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ multiview_mask: None,
+ });
+ rp.set_pipeline(p_pipe);
+ rp.set_bind_group(0, p_bg, &[dyn_off]);
+ rp.set_vertex_buffer(0, self.dab_instance_buf.slice(..));
+ rp.draw(0..6, start..(start + count));
+ }
+ }
}
- newly_touched
- }
+ if let Some(s_bg_idx) = sec_bg_slot {
+ let s_bg = &self.cached_dab_bgs[s_bg_idx]
+ .as_ref()
+ .expect("cached secondary dab_bg")
+ .1;
+ let base_idx = primary_jobs.len();
+ for (j, &(_, slot, is_new, start, count)) in secondary_jobs.iter().enumerate() {
+ let dyn_off = ((base_idx + j) as u32) * (UNIFORM_STRIDE as u32);
+ let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("ink-brush-secondary-tile-stamp"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &self.secondary_pool.slice_views[slot as usize],
+ depth_slice: None,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: if is_new {
+ wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT)
+ } else {
+ wgpu::LoadOp::Load
+ },
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ multiview_mask: None,
+ });
+ rp.set_pipeline(&self.dab_tile_normal_pipeline);
+ rp.set_bind_group(0, s_bg, &[dyn_off]);
+ rp.set_vertex_buffer(0, self.dab_instance_buf.slice(..));
+ rp.draw(0..6, start..(start + count));
+ }
+ }
- fn ensure_instance_buf(&mut self, device: &wgpu::Device, needed: usize) {
- if needed <= self.dab_instance_cap {
- return;
+ // Encode Dual Combine / Per-Stroke Paper Grain / 2-Pass Wet Edge into the SAME CommandEncoder!
+ if run_post {
+ self.encode_refresh_resolved_tiles(device, queue, &mut encoder);
}
- let new_cap = needed.next_power_of_two().max(1024);
- self.dab_instance_buf = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("ink-brush-dab-instances"),
- size: (new_cap * std::mem::size_of::<GpuBrushDab>()) as u64,
- usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
- mapped_at_creation: false,
- });
- self.dab_instance_cap = new_cap;
+
+ queue.submit(Some(encoder.finish()));
+ newly_touched
}
- fn ensure_uniform_buf(
+ fn bin_and_alloc_stream(
+ &mut self,
device: &wgpu::Device,
- buf: &mut wgpu::Buffer,
- cap: &mut usize,
- needed: usize,
- label: &str,
- ) {
- if needed <= *cap {
- return;
- }
+ queue: &wgpu::Queue,
+ is_primary: bool,
+ dabs: &[GpuBrushDab],
+ flat_instances: &mut Vec<GpuBrushDab>,
+ ) -> (Vec<(TileCoord, u32, bool, u32, u32)>, Vec<TileCoord>) {
+ let max_tx = (self.doc_width.saturating_sub(1) / TILE_SIZE as u32) as i32;
+ let max_ty = (self.doc_height.saturating_sub(1) / TILE_SIZE as u32) as i32;
+
+ let mut bins: HashMap<TileCoord, Vec<GpuBrushDab>> = HashMap::new();
+ for &dab in dabs {
+ let (min_x, min_y, max_x, max_y) = dab.doc_bounds();
+ let tx0 = (min_x.floor() as i32).div_euclid(TILE_SIZE as i32).max(0);
+ let ty0 = (min_y.floor() as i32).div_euclid(TILE_SIZE as i32).max(0);
+ let tx1 = (max_x.ceil() as i32).div_euclid(TILE_SIZE as i32).min(max_tx);
+ let ty1 = (max_y.ceil() as i32).div_euclid(TILE_SIZE as i32).min(max_ty);
+ if tx0 > tx1 || ty0 > ty1 {
+ continue;
+ }
+ for ty in ty0..=ty1 {
+ for tx in tx0..=tx1 {
+ bins.entry(TileCoord::new(tx, ty)).or_default().push(dab);
+ }
+ }
+ }
+ if bins.is_empty() {
+ return (Vec::new(), Vec::new());
+ }
+
+ let mut tile_jobs: Vec<(TileCoord, u32, bool, u32, u32)> = Vec::with_capacity(bins.len());
+ let mut newly_touched = Vec::new();
+ for (coord, list) in bins {
+ let alloc = if is_primary {
+ self.primary_pool.get_or_alloc(device, queue, coord)
+ } else {
+ self.secondary_pool.get_or_alloc(device, queue, coord)
+ };
+ let Some((slot, is_new)) = alloc else {
+ continue;
+ };
+ if is_new {
+ newly_touched.push(coord);
+ }
+ self.dirty_post_tiles.insert(coord);
+ let start = flat_instances.len() as u32;
+ let count = list.len() as u32;
+ flat_instances.extend_from_slice(&list);
+ tile_jobs.push((coord, slot, is_new, start, count));
+ }
+ (tile_jobs, newly_touched)
+ }
+
+ fn ensure_instance_buf(&mut self, device: &wgpu::Device, needed: usize) {
+ if needed <= self.dab_instance_cap {
+ return;
+ }
+ let new_cap = needed.next_power_of_two().max(1024);
+ self.dab_instance_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-brush-dab-instances"),
+ size: (new_cap * std::mem::size_of::<GpuBrushDab>()) as u64,
+ usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ self.dab_instance_cap = new_cap;
+ }
+
+ fn ensure_uniform_buf(
+ device: &wgpu::Device,
+ buf: &mut wgpu::Buffer,
+ cap: &mut usize,
+ needed: usize,
+ label: &str,
+ ) -> bool {
+ if needed <= *cap {
+ return false;
+ }
let new_cap = needed.next_power_of_two().max(64);
*buf = device.create_buffer(&wgpu::BufferDescriptor {
label: Some(label),
@@ -1656,6 +2140,92 @@ impl GpuBrushEngine {
mapped_at_creation: false,
});
*cap = new_cap;
+ true
+ }
+
+ /// Resolves tip + paper textures ONCE and looks up (or caches) `dab_bg` keyed by
+ /// `(dab_uniform_buf_gen, tip_arr.id, paper.id)` so consecutive stamps & predicted-head draws
+ /// incur zero `BindGroup` allocations!
+ fn resolve_and_cache_dab_bg(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ brush: &NativeBrushConfig,
+ ) -> (usize, bool, u32, [f32; 2]) {
+ self.resolve_and_cache_dab_bg_protected(device, queue, brush, None)
+ }
+
+ fn resolve_and_cache_dab_bg_protected(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ brush: &NativeBrushConfig,
+ protect_slot: Option<usize>,
+ ) -> (usize, bool, u32, [f32; 2]) {
+ let (is_tex, tip_arr, paper) = self.tip_cache.resolve_tip_and_paper(
+ device,
+ queue,
+ brush.tip_key.as_deref(),
+ &brush.sub_tip_keys,
+ brush.paper_texture_key.as_deref(),
+ brush.surface_texture_id.as_deref(),
+ );
+ let key = (self.dab_uniform_buf_gen, tip_arr.id, paper.id);
+ let tip_layers = tip_arr.layer_count;
+ let paper_size = [paper.width as f32, paper.height as f32];
+
+ for (idx, slot) in self.cached_dab_bgs.iter().enumerate() {
+ if let Some((k, _)) = slot {
+ if *k == key {
+ return (idx, is_tex, tip_layers, paper_size);
+ }
+ }
+ }
+
+ let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-brush-dab-bg"),
+ layout: &self.dab_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.dab_uniform_buf,
+ offset: 0,
+ size: wgpu::BufferSize::new(std::mem::size_of::<DabPassUniforms>() as u64),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(&tip_arr.view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::Sampler(&self.tip_sampler),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::TextureView(&paper.view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 4,
+ resource: wgpu::BindingResource::Sampler(&self.paper_sampler),
+ },
+ ],
+ });
+
+ let dst_idx = if self.cached_dab_bgs[0].is_none() && protect_slot != Some(0) {
+ 0
+ } else if self.cached_dab_bgs[1].is_none() && protect_slot != Some(1) {
+ 1
+ } else if let Some(p) = protect_slot {
+ p ^ 1
+ } else {
+ let i = self.dab_bg_next_evict;
+ self.dab_bg_next_evict ^= 1;
+ i
+ };
+ self.cached_dab_bgs[dst_idx] = Some((key, bg));
+ (dst_idx, is_tex, tip_layers, paper_size)
}
fn build_dab_uniforms(
@@ -1774,32 +2344,21 @@ impl GpuBrushEngine {
// 3. Upload flattened instance buffer + dynamic uniform table in 2 single writes
self.ensure_instance_buf(device, flat_instances.len());
- Self::ensure_uniform_buf(
+ if Self::ensure_uniform_buf(
device,
&mut self.dab_uniform_buf,
&mut self.dab_uniform_cap,
tile_jobs.len(),
"ink-brush-dab-uniforms",
- );
+ ) {
+ self.dab_uniform_buf_gen = self.dab_uniform_buf_gen.saturating_add(1);
+ self.cached_dab_bgs = [None, None];
+ }
queue.write_buffer(&self.dab_instance_buf, 0, bytemuck::cast_slice(&flat_instances));
- // Resolve tip array & paper texture from cache
- let (is_textured, tip_layers, paper_size) = {
- let (is_tex, tip_arr) = self.tip_cache.resolve_tip_set(
- device,
- queue,
- brush.tip_key.as_deref(),
- &brush.sub_tip_keys,
- );
- let layers = tip_arr.layer_count;
- let paper = self.tip_cache.resolve_paper_texture(
- device,
- queue,
- brush.paper_texture_key.as_deref(),
- brush.surface_texture_id.as_deref(),
- );
- (is_tex, layers, [paper.width as f32, paper.height as f32])
- };
+ // Resolve tip array + paper texture ONCE and fetch cached `dab_bg` (zero per-stamp churn!)
+ let (dab_bg_slot, is_textured, tip_layers, paper_size) =
+ self.resolve_and_cache_dab_bg(device, queue, brush);
let mut uniform_bytes = vec![0u8; tile_jobs.len() * UNIFORM_STRIDE as usize];
for (i, (coord, _, _, _, _)) in tile_jobs.iter().enumerate() {
@@ -1820,51 +2379,72 @@ impl GpuBrushEngine {
}
queue.write_buffer(&self.dab_uniform_buf, 0, &uniform_bytes);
- let (_, tip_arr, paper) = self.tip_cache.resolve_tip_and_paper(
- device,
- queue,
- brush.tip_key.as_deref(),
- &brush.sub_tip_keys,
- brush.paper_texture_key.as_deref(),
- brush.surface_texture_id.as_deref(),
- );
- let dab_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-brush-dab-bg"),
- layout: &self.dab_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &self.dab_uniform_buf,
- offset: 0,
- size: wgpu::BufferSize::new(std::mem::size_of::<DabPassUniforms>() as u64),
- }),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(&tip_arr.view),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::Sampler(&self.tip_sampler),
- },
- wgpu::BindGroupEntry {
- binding: 3,
- resource: wgpu::BindingResource::TextureView(&paper.view),
- },
- wgpu::BindGroupEntry {
- binding: 4,
- resource: wgpu::BindingResource::Sampler(&self.paper_sampler),
- },
- ],
- });
-
let use_darken = is_primary && brush.blend_tips_mode == CspBlendTipsMode::Darken;
let pipeline = match brush.blend_tips_mode {
CspBlendTipsMode::Compare if is_primary => &self.dab_tile_compare_pipeline,
_ => &self.dab_tile_normal_pipeline,
};
+ // Upload all DarkenParamsUniform slots in ONE dynamic uniform buffer write BEFORE the loop
+ // so every tile in a multi-tile Darken stroke reads its own `dst_slot`.
+ let darken_bg = if use_darken && tile_jobs.iter().any(|&(_, _, is_new, _, _)| !is_new) {
+ Self::ensure_uniform_buf(
+ device,
+ &mut self.darken_uniform_buf,
+ &mut self.darken_uniform_cap,
+ tile_jobs.len(),
+ "ink-brush-darken-uniforms",
+ );
+ let mut darken_bytes = vec![0u8; tile_jobs.len() * UNIFORM_STRIDE as usize];
+ for (i, &(_, slot, _, _, _)) in tile_jobs.iter().enumerate() {
+ let dp = DarkenParamsUniform {
+ dst_slot: slot as i32,
+ _pad: [0; 3],
+ };
+ let off = i * UNIFORM_STRIDE as usize;
+ let src = bytemuck::bytes_of(&dp);
+ darken_bytes[off..off + src.len()].copy_from_slice(src);
+ }
+ queue.write_buffer(&self.darken_uniform_buf, 0, &darken_bytes);
+ Some(device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-brush-darken-bg"),
+ layout: &self.darken_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.darken_uniform_buf,
+ offset: 0,
+ size: wgpu::BufferSize::new(
+ std::mem::size_of::<DarkenParamsUniform>() as u64,
+ ),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(
+ &self.primary_pool.array_view,
+ ),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(&self.darken_batch_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::TextureView(&self.post_scratch_view),
+ },
+ ],
+ }))
+ } else {
+ None
+ };
+
+ let dab_bg = &self.cached_dab_bgs[dab_bg_slot]
+ .as_ref()
+ .expect("cached dab_bg")
+ .1;
+
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("ink-brush-stamp-encoder"),
});
@@ -1891,46 +2471,17 @@ impl GpuBrushEngine {
multiview_mask: None,
});
rp.set_pipeline(pipeline);
- rp.set_bind_group(0, &dab_bg, &[dyn_off]);
+ rp.set_bind_group(0, dab_bg, &[dyn_off]);
rp.set_vertex_buffer(0, self.dab_instance_buf.slice(..));
rp.draw(0..6, start..(start + count));
}
- let dp = DarkenParamsUniform {
- dst_slot: slot as i32,
- _pad: [0; 3],
- };
- queue.write_buffer(&self.darken_uniform_buf, 0, bytemuck::bytes_of(&dp));
- let dbg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-brush-darken-bg"),
- layout: &self.darken_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: self.darken_uniform_buf.as_entire_binding(),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(
- &self.primary_pool.array_view,
- ),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::TextureView(&self.darken_batch_view),
- },
- wgpu::BindGroupEntry {
- binding: 3,
- resource: wgpu::BindingResource::TextureView(&self.post_scratch_view),
- },
- ],
- });
- {
+ if let Some(dbg) = darken_bg.as_ref() {
let mut cp = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("ink-brush-darken-merge"),
timestamp_writes: None,
});
cp.set_pipeline(&self.darken_pipeline);
- cp.set_bind_group(0, &dbg, &[]);
+ cp.set_bind_group(0, dbg, &[dyn_off]);
cp.dispatch_workgroups(16, 16, 1);
}
encoder.copy_texture_to_texture(
@@ -1983,7 +2534,7 @@ impl GpuBrushEngine {
multiview_mask: None,
});
rp.set_pipeline(pipeline);
- rp.set_bind_group(0, &dab_bg, &[dyn_off]);
+ rp.set_bind_group(0, dab_bg, &[dyn_off]);
rp.set_vertex_buffer(0, self.dab_instance_buf.slice(..));
rp.draw(0..6, start..(start + count));
}
@@ -1996,6 +2547,24 @@ impl GpuBrushEngine {
/// Runs Dual Brush combine, Per-Stroke Paper Grain (`applyEachPlot == false`), and
/// 2-Pass Seamless Watercolor Wet Edge strictly on dirty tiles touched since last update.
fn refresh_resolved_tiles(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {
+ if self.dirty_post_tiles.is_empty() {
+ return;
+ }
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-brush-post-encoder"),
+ });
+ self.encode_refresh_resolved_tiles(device, queue, &mut encoder);
+ queue.submit(Some(encoder.finish()));
+ }
+
+ /// Encodes Dual Brush combine, Per-Stroke Paper Grain, and 2-Pass Seamless Watercolor Wet Edge
+ /// directly into the caller's `CommandEncoder` (allowing `stamp_dabs` to issue ONE `queue.submit`!).
+ fn encode_refresh_resolved_tiles(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ encoder: &mut wgpu::CommandEncoder,
+ ) {
let dirty: Vec<TileCoord> = self.dirty_post_tiles.drain().collect();
if dirty.is_empty() {
return;
@@ -2013,10 +2582,6 @@ impl GpuBrushEngine {
let wet_active = self.active_brush.wet_edge > 0.01;
let need_mid = dual_enabled || apply_stroke_paper;
- let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-brush-post-encoder"),
- });
-
// Step A: Dual Combine & Per-Stroke Paper Grain into `mid_pool` (or directly `resolved_pool` if no wet edge)
if need_mid {
Self::ensure_uniform_buf(
@@ -2363,12 +2928,12 @@ impl GpuBrushEngine {
}
}
}
-
- queue.submit(Some(encoder.finish()));
}
/// Renders transient predicted-head [`GpuBrushDab`]s directly into `WgpuCompositor`'s
- /// viewport `live_stroke_surface` inside an active render pass (zero `#ink-predicted-canvas`!).
+ /// viewport `live_stroke_surface` inside an active render pass (zero `#ink-predicted-canvas`!),
+ /// clipped strictly to `scissor` (`[x, y, width, height]`) so predicted dabs can never bleed
+ /// outside `update_scissor` and leave ghost trails.
#[allow(clippy::too_many_arguments)]
pub fn render_predicted_dabs_into_viewport(
&mut self,
@@ -2383,30 +2948,23 @@ impl GpuBrushEngine {
rotation_rad: f32,
flip: [f32; 2],
dpr: f32,
+ scissor: [u32; 4],
) {
- if !self.active || predicted_dabs.is_empty() {
+ if !self.active || predicted_dabs.is_empty() || scissor[2] == 0 || scissor[3] == 0 {
return;
}
self.ensure_instance_buf(device, predicted_dabs.len());
queue.write_buffer(&self.dab_instance_buf, 0, bytemuck::cast_slice(predicted_dabs));
let brush = self.active_brush.clone();
- let (is_textured, tip_layers, paper_size) = {
- let (is_tex, tip_arr) = self.tip_cache.resolve_tip_set(
- device,
- queue,
- brush.tip_key.as_deref(),
- &brush.sub_tip_keys,
- );
- let layers = tip_arr.layer_count;
- let paper = self.tip_cache.resolve_paper_texture(
- device,
- queue,
- brush.paper_texture_key.as_deref(),
- brush.surface_texture_id.as_deref(),
- );
- (is_tex, layers, [paper.width as f32, paper.height as f32])
- };
+ let is_direct_replace = self.is_direct_replace_mode();
+ let (dab_bg_slot, raw_is_textured, tip_layers, paper_size) =
+ self.resolve_and_cache_dab_bg(device, queue, &brush);
+ // NaturalPaint uses bristle capsules rather than stamp tips (unless BristleHybrid),
+ // so analytical SDF preview dabs cleanly match the brush radius & softness.
+ let is_textured = raw_is_textured
+ && (!brush.is_natural_paint_brush()
+ || brush.render_mode == crate::brush::BrushRenderMode::BristleHybrid);
let mut u = self.build_dab_uniforms(
&brush,
@@ -2414,7 +2972,7 @@ impl GpuBrushEngine {
is_textured,
tip_layers,
paper_size,
- true,
+ !is_direct_replace,
);
u.viewport_size_phys = viewport_size_phys;
u.pan_css = pan_css;
@@ -2424,48 +2982,20 @@ impl GpuBrushEngine {
u.dpr = dpr;
queue.write_buffer(&self.dab_uniform_buf, 0, bytemuck::bytes_of(&u));
- let (_, tip_arr, paper) = self.tip_cache.resolve_tip_and_paper(
- device,
- queue,
- brush.tip_key.as_deref(),
- &brush.sub_tip_keys,
- brush.paper_texture_key.as_deref(),
- brush.surface_texture_id.as_deref(),
- );
- let dab_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-brush-pred-bg"),
- layout: &self.dab_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &self.dab_uniform_buf,
- offset: 0,
- size: wgpu::BufferSize::new(std::mem::size_of::<DabPassUniforms>() as u64),
- }),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(&tip_arr.view),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::Sampler(&self.tip_sampler),
- },
- wgpu::BindGroupEntry {
- binding: 3,
- resource: wgpu::BindingResource::TextureView(&paper.view),
- },
- wgpu::BindGroupEntry {
- binding: 4,
- resource: wgpu::BindingResource::Sampler(&self.paper_sampler),
- },
- ],
- });
+ let dab_bg = &self.cached_dab_bgs[dab_bg_slot]
+ .as_ref()
+ .expect("cached dab_bg")
+ .1;
- let pipeline = match brush.blend_tips_mode {
- CspBlendTipsMode::Compare => &self.dab_viewport_compare_pipeline,
- _ => &self.dab_viewport_normal_pipeline,
+ let pipeline = if is_direct_replace {
+ // Direct-replace LiveStroke already contains ActiveBase + stroke tiles;
+ // always overlay transient predicted head with Source-Over!
+ &self.dab_viewport_normal_pipeline
+ } else {
+ match brush.blend_tips_mode {
+ CspBlendTipsMode::Compare => &self.dab_viewport_compare_pipeline,
+ _ => &self.dab_viewport_normal_pipeline,
+ }
};
let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
@@ -2484,8 +3014,10 @@ impl GpuBrushEngine {
occlusion_query_set: None,
multiview_mask: None,
});
+ rp.set_viewport(0.0, 0.0, viewport_size_phys[0], viewport_size_phys[1], 0.0, 1.0);
+ rp.set_scissor_rect(scissor[0], scissor[1], scissor[2], scissor[3]);
rp.set_pipeline(pipeline);
- rp.set_bind_group(0, &dab_bg, &[0]);
+ rp.set_bind_group(0, dab_bg, &[0]);
rp.set_vertex_buffer(0, self.dab_instance_buf.slice(..));
rp.draw(0..6, 0..predicted_dabs.len() as u32);
}
@@ -2570,16 +3102,26 @@ impl GpuBrushEngine {
});
}
- // Ensure commit uniform & packed RGBA8 readback buffers fit all touched tiles
+ // Chunk commits cleanly and pin every `base_slot` + `dst_slot` in the active chunk so no
+ // two tiles in flight can EVER collide on a VRAM atlas slot. When spanning multiple chunks,
+ // halve chunk size so 2 double-buffered staging buffers overlap GPU execution with CPU readback!
+ let max_single_chunk = ((gpu_pool.capacity() as usize) / 2).max(1);
+ let max_chunk_tiles = if jobs.len() > max_single_chunk {
+ (max_single_chunk / 2).max(1)
+ } else {
+ max_single_chunk
+ };
+ let buf_tile_req = jobs.len().min(max_chunk_tiles);
+
Self::ensure_uniform_buf(
device,
&mut self.commit_uniform_buf,
&mut self.commit_uniform_cap,
- jobs.len(),
+ buf_tile_req,
"ink-tile-commit-uniforms",
);
- if jobs.len() > self.commit_buf_tile_cap {
- let new_cap = jobs.len().next_power_of_two().max(32);
+ if buf_tile_req > self.commit_buf_tile_cap {
+ let new_cap = buf_tile_req.next_power_of_two().max(32);
let bytes = (new_cap * TILE_SIZE * TILE_SIZE * 4) as u64;
self.commit_rgba8_storage_buf = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("ink-tile-commit-rgba8-storage"),
@@ -2587,45 +3129,23 @@ impl GpuBrushEngine {
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
- self.commit_rgba8_readback_buf = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("ink-tile-commit-rgba8-readback"),
- size: bytes,
- usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
- mapped_at_creation: false,
- });
+ self.commit_rgba8_readback_bufs = [
+ device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-tile-commit-rgba8-readback-0"),
+ size: bytes,
+ usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ }),
+ device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-tile-commit-rgba8-readback-1"),
+ size: bytes,
+ usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ }),
+ ];
self.commit_buf_tile_cap = new_cap;
}
- // Ensure every existing base tile is resident in GpuTilePool and acquire target slots
- let mut resolved_jobs: Vec<(TileCoord, i32, u32, u32, u64)> = Vec::with_capacity(jobs.len());
- let mut dirty_rect = RectI32::empty();
-
- for (coord, stroke_slot) in jobs {
- let key = GpuTileKey {
- doc_id: doc_id.to_string(),
- layer_id: layer_id.to_string(),
- lod: 0,
- coord,
- };
- let base_slot: i32 = if let Some(existing_tile) = layer_grid.tiles.get(&coord) {
- gpu_pool.ensure_tile_uploaded(queue, key.clone(), existing_tile, scratch)? as i32
- } else {
- -1
- };
- let new_ver = crate::tiles::allocate_tile_version();
- let dst_slot = gpu_pool.acquire_slot(key, new_ver);
- resolved_jobs.push((coord, base_slot, stroke_slot, dst_slot, new_ver));
-
- let tile_rect = RectI32::new(
- coord.tx * TILE_SIZE as i32,
- coord.ty * TILE_SIZE as i32,
- TILE_SIZE as u32,
- TILE_SIZE as u32,
- );
- dirty_rect = dirty_rect.union(tile_rect);
- }
-
- // Write dynamic commit uniforms for all touched tiles in 1 buffer upload
let combine_code = self.active_brush.brush_combine_mode.as_u32();
let is_eraser = u32::from(
self.active_brush.is_eraser
@@ -2635,6 +3155,7 @@ impl GpuBrushEngine {
let is_bg_eraser = u32::from(self.active_brush.is_bg_eraser);
let mono_flag = u32::from(mono_layer);
let brush_opacity = self.active_brush.opacity.clamp(0.0, 1.0);
+ let bg_color = self.active_brush.bg_color;
let active_sel = selection.filter(|s| s.is_active());
let sel_default_u8 = active_sel
@@ -2644,146 +3165,274 @@ impl GpuBrushEngine {
.map(|s| s.atlas_view())
.unwrap_or(&self.commit_dummy_sel_view);
- let mut ubytes = vec![0u8; resolved_jobs.len() * UNIFORM_STRIDE as usize];
- for (i, &(coord, base_slot, stroke_slot, _, _)) in resolved_jobs.iter().enumerate() {
- let sel_slot: i32 = match active_sel {
- Some(s) => s.tile_slot(&coord).map(|v| v as i32).unwrap_or(-1),
- None => -2,
- };
- let u = TileCommitUniforms {
- slots: [base_slot, stroke_slot as i32, sel_slot, i as i32],
- flags: [combine_code, is_eraser, u32::from(alpha_locked), mono_flag],
- extra: [is_bg_eraser, sel_default_u8, 0, 0],
- params: [
- brush_opacity,
- self.active_brush.bg_color[0],
- self.active_brush.bg_color[1],
- self.active_brush.bg_color[2],
- ],
- };
- let off = i * UNIFORM_STRIDE as usize;
- let src = bytemuck::bytes_of(&u);
- ubytes[off..off + src.len()].copy_from_slice(src);
- }
- queue.write_buffer(&self.commit_uniform_buf, 0, &ubytes);
-
let stroke_view = if self.use_resolved_output {
&self.resolved_pool.array_view
} else {
&self.primary_pool.array_view
};
- let commit_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-tile-commit-bg"),
- layout: &self.commit_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &self.commit_uniform_buf,
- offset: 0,
- size: wgpu::BufferSize::new(
- std::mem::size_of::<TileCommitUniforms>() as u64,
- ),
- }),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(gpu_pool.atlas_view()),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::TextureView(stroke_view),
- },
- wgpu::BindGroupEntry {
- binding: 3,
- resource: wgpu::BindingResource::TextureView(sel_atlas_view),
- },
- wgpu::BindGroupEntry {
- binding: 4,
- resource: wgpu::BindingResource::TextureView(&self.commit_scratch_16f_view),
- },
- wgpu::BindGroupEntry {
- binding: 5,
- resource: self.commit_rgba8_storage_buf.as_entire_binding(),
- },
- ],
- });
+ let tile_bytes = TILE_SIZE * TILE_SIZE * 4;
+ let mut tiles = Vec::with_capacity(jobs.len());
+ let mut dirty_rect = RectI32::empty();
- let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-tile-commit-encoder"),
- });
+ struct InFlightStampCommit {
+ rb_idx: usize,
+ sub_idx: wgpu::SubmissionIndex,
+ total_readback_bytes: u64,
+ rx: std::sync::mpsc::Receiver<Result<(), wgpu::BufferAsyncError>>,
+ resolved_jobs: Vec<(TileCoord, i32, u32, u32, u64)>,
+ chunk_pins: Vec<u32>,
+ }
- for (i, &(_, _, _, dst_slot, _)) in resolved_jobs.iter().enumerate() {
- let dyn_off = (i as u32) * (UNIFORM_STRIDE as u32);
- {
- let mut cp = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
- label: Some("ink-tile-commit-pass"),
- timestamp_writes: None,
- });
- cp.set_pipeline(&self.commit_pipeline);
- cp.set_bind_group(0, &commit_bg, &[dyn_off]);
- cp.dispatch_workgroups(16, 16, 1);
+ let drain_in_flight = |readback_bufs: &[wgpu::Buffer; 2],
+ gpu_pool: &mut GpuTilePool,
+ fl: InFlightStampCommit,
+ tiles: &mut Vec<(TileCoord, Vec<u8>, u64)>|
+ -> Result<(), String> {
+ let _ = device.poll(wgpu::PollType::Wait {
+ submission_index: Some(fl.sub_idx),
+ timeout: None,
+ });
+ let map_res = fl
+ .rx
+ .recv()
+ .map_err(|_| "GPU tile commit readback channel closed".to_string())
+ .and_then(|r| r.map_err(|e| format!("GPU tile commit readback failed: {e:?}")));
+ if let Err(err) = map_res {
+ for s in fl.chunk_pins {
+ gpu_pool.unpin_slot(s);
+ }
+ return Err(err);
}
- encoder.copy_texture_to_texture(
- wgpu::TexelCopyTextureInfo {
- texture: &self.commit_scratch_16f,
- mip_level: 0,
- origin: wgpu::Origin3d::ZERO,
- aspect: wgpu::TextureAspect::All,
- },
- wgpu::TexelCopyTextureInfo {
- texture: gpu_pool.atlas_texture(),
- mip_level: 0,
- origin: wgpu::Origin3d {
- x: 0,
- y: 0,
- z: dst_slot,
+ let readback_buf = &readback_bufs[fl.rb_idx];
+ let slice = readback_buf.slice(0..fl.total_readback_bytes);
+ let mapped = match slice.get_mapped_range() {
+ Ok(m) => m,
+ Err(e) => {
+ readback_buf.unmap();
+ for s in fl.chunk_pins {
+ gpu_pool.unpin_slot(s);
+ }
+ return Err(format!("GPU tile commit get_mapped_range failed: {e}"));
+ }
+ };
+ for (i, &(coord, _, _, _, new_ver)) in fl.resolved_jobs.iter().enumerate() {
+ let start = i * tile_bytes;
+ let bytes = mapped[start..start + tile_bytes].to_vec();
+ tiles.push((coord, bytes, new_ver));
+ }
+ drop(mapped);
+ readback_buf.unmap();
+
+ for s in fl.chunk_pins {
+ gpu_pool.unpin_slot(s);
+ }
+ Ok(())
+ };
+
+ let mut ubytes = Vec::with_capacity(buf_tile_req * UNIFORM_STRIDE as usize);
+ let mut prev_in_flight: Option<InFlightStampCommit> = None;
+
+ let doc_key = gpu_pool.intern_doc(doc_id);
+ let layer_key = gpu_pool.intern_layer(layer_id);
+
+ for chunk in jobs.chunks(max_chunk_tiles) {
+ let mut resolved_jobs: Vec<(TileCoord, i32, u32, u32, u64)> =
+ Vec::with_capacity(chunk.len());
+ let mut chunk_pins: Vec<u32> = Vec::with_capacity(chunk.len() * 2);
+
+ for &(coord, stroke_slot) in chunk {
+ let key = GpuTileKey {
+ doc_id: doc_key,
+ layer_id: layer_key,
+ lod: 0,
+ coord,
+ };
+ let base_slot: i32 = if let Some(existing_tile) = layer_grid.tiles.get(&coord) {
+ match gpu_pool.ensure_tile_uploaded(queue, key, existing_tile, scratch)
+ {
+ Ok(bs) => {
+ gpu_pool.pin_slot(bs);
+ chunk_pins.push(bs);
+ bs as i32
+ }
+ Err(e) => {
+ for s in chunk_pins {
+ gpu_pool.unpin_slot(s);
+ }
+ if let Some(prev) = prev_in_flight.take() {
+ let _ = drain_in_flight(
+ &self.commit_rgba8_readback_bufs,
+ gpu_pool,
+ prev,
+ &mut tiles,
+ );
+ }
+ return Err(e);
+ }
+ }
+ } else {
+ -1
+ };
+ let new_ver = crate::tiles::allocate_tile_version();
+ let dst_slot = gpu_pool.acquire_slot(key, new_ver);
+ gpu_pool.pin_slot(dst_slot);
+ chunk_pins.push(dst_slot);
+ resolved_jobs.push((coord, base_slot, stroke_slot, dst_slot, new_ver));
+
+ let tile_rect = RectI32::new(
+ coord.tx * TILE_SIZE as i32,
+ coord.ty * TILE_SIZE as i32,
+ TILE_SIZE as u32,
+ TILE_SIZE as u32,
+ );
+ dirty_rect = dirty_rect.union(tile_rect);
+ }
+
+ ubytes.clear();
+ ubytes.resize(resolved_jobs.len() * UNIFORM_STRIDE as usize, 0u8);
+ for (i, &(coord, base_slot, stroke_slot, _, _)) in resolved_jobs.iter().enumerate() {
+ let sel_slot: i32 = match active_sel {
+ Some(s) => s.tile_slot(&coord).map(|v| v as i32).unwrap_or(-1),
+ None => -2,
+ };
+ let u = TileCommitUniforms {
+ slots: [base_slot, stroke_slot as i32, sel_slot, i as i32],
+ flags: [combine_code, is_eraser, u32::from(alpha_locked), mono_flag],
+ extra: [is_bg_eraser, sel_default_u8, 0, 0],
+ params: [brush_opacity, bg_color[0], bg_color[1], bg_color[2]],
+ };
+ let off = i * UNIFORM_STRIDE as usize;
+ let src = bytemuck::bytes_of(&u);
+ ubytes[off..off + src.len()].copy_from_slice(src);
+ }
+ queue.write_buffer(&self.commit_uniform_buf, 0, &ubytes);
+
+ let commit_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-tile-commit-bg"),
+ layout: &self.commit_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.commit_uniform_buf,
+ offset: 0,
+ size: wgpu::BufferSize::new(
+ std::mem::size_of::<TileCommitUniforms>() as u64,
+ ),
+ }),
},
- aspect: wgpu::TextureAspect::All,
- },
- wgpu::Extent3d {
- width: TILE_SIZE as u32,
- height: TILE_SIZE as u32,
- depth_or_array_layers: 1,
- },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(gpu_pool.atlas_view()),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(stroke_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::TextureView(sel_atlas_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 4,
+ resource: wgpu::BindingResource::TextureView(&self.commit_scratch_16f_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 5,
+ resource: self.commit_rgba8_storage_buf.as_entire_binding(),
+ },
+ ],
+ });
+
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-tile-commit-encoder"),
+ });
+
+ for (i, &(_, _, _, dst_slot, _)) in resolved_jobs.iter().enumerate() {
+ let dyn_off = (i as u32) * (UNIFORM_STRIDE as u32);
+ {
+ let mut cp = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("ink-tile-commit-pass"),
+ timestamp_writes: None,
+ });
+ cp.set_pipeline(&self.commit_pipeline);
+ cp.set_bind_group(0, &commit_bg, &[dyn_off]);
+ cp.dispatch_workgroups(16, 16, 1);
+ }
+ encoder.copy_texture_to_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: &self.commit_scratch_16f,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::TexelCopyTextureInfo {
+ texture: gpu_pool.atlas_texture(),
+ mip_level: 0,
+ origin: wgpu::Origin3d {
+ x: 0,
+ y: 0,
+ z: dst_slot,
+ },
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::Extent3d {
+ width: TILE_SIZE as u32,
+ height: TILE_SIZE as u32,
+ depth_or_array_layers: 1,
+ },
+ );
+ }
+
+ let rb_idx = self.commit_rb_idx;
+ self.commit_rb_idx ^= 1;
+ let readback_buf = &self.commit_rgba8_readback_bufs[rb_idx];
+
+ let total_readback_bytes = (resolved_jobs.len() * tile_bytes) as u64;
+ encoder.copy_buffer_to_buffer(
+ &self.commit_rgba8_storage_buf,
+ 0,
+ readback_buf,
+ 0,
+ total_readback_bytes,
);
- }
- let total_readback_bytes = (resolved_jobs.len() * TILE_SIZE * TILE_SIZE * 4) as u64;
- encoder.copy_buffer_to_buffer(
- &self.commit_rgba8_storage_buf,
- 0,
- &self.commit_rgba8_readback_buf,
- 0,
- total_readback_bytes,
- );
+ let sub_idx = queue.submit(Some(encoder.finish()));
- queue.submit(Some(encoder.finish()));
+ // Kick off async map immediately, then drain previous chunk while GPU runs this one!
+ let slice = readback_buf.slice(0..total_readback_bytes);
+ let (tx, rx) = std::sync::mpsc::channel();
+ slice.map_async(wgpu::MapMode::Read, move |res| {
+ let _ = tx.send(res);
+ });
+ let cur = InFlightStampCommit {
+ rb_idx,
+ sub_idx,
+ total_readback_bytes,
+ rx,
+ resolved_jobs,
+ chunk_pins,
+ };
+ if let Some(prev) = prev_in_flight.take() {
+ if let Err(err) =
+ drain_in_flight(&self.commit_rgba8_readback_bufs, gpu_pool, prev, &mut tiles)
+ {
+ let _ = drain_in_flight(
+ &self.commit_rgba8_readback_bufs,
+ gpu_pool,
+ cur,
+ &mut tiles,
+ );
+ return Err(err);
+ }
+ }
+ prev_in_flight = Some(cur);
+ }
- // Single batched map + poll for ALL committed tiles
- let slice = self.commit_rgba8_readback_buf.slice(0..total_readback_bytes);
- let (tx, rx) = std::sync::mpsc::channel();
- slice.map_async(wgpu::MapMode::Read, move |res| {
- let _ = tx.send(res);
- });
- let _ = device.poll(wgpu::PollType::wait_indefinitely());
- rx.recv()
- .map_err(|_| "GPU tile commit readback channel closed".to_string())?
- .map_err(|e| format!("GPU tile commit readback failed: {e:?}"))?;
-
- let mapped = slice
- .get_mapped_range()
- .map_err(|e| format!("GPU tile commit get_mapped_range failed: {e}"))?;
- let tile_bytes = TILE_SIZE * TILE_SIZE * 4;
- let mut tiles = Vec::with_capacity(resolved_jobs.len());
- for (i, &(coord, _, _, _, new_ver)) in resolved_jobs.iter().enumerate() {
- let start = i * tile_bytes;
- let bytes = mapped[start..start + tile_bytes].to_vec();
- tiles.push((coord, bytes, new_ver));
+ if let Some(last) = prev_in_flight {
+ drain_in_flight(&self.commit_rgba8_readback_bufs, gpu_pool, last, &mut tiles)?;
}
- drop(mapped);
- self.commit_rgba8_readback_buf.unmap();
// Clamp dirty rect to document bounds
let doc_rect = RectI32::new(0, 0, self.doc_width, self.doc_height);
diff --git a/crates/ink-engine/src/brush/tip_cache.rs b/crates/ink-engine/src/brush/tip_cache.rs
index 2b44878..cdbeb44 100644
--- a/crates/ink-engine/src/brush/tip_cache.rs
+++ b/crates/ink-engine/src/brush/tip_cache.rs
@@ -11,6 +11,9 @@ use super::procedural_tips::{generate_builtin_paper_texture, generate_builtin_ti
use crate::io::png_codec::decode_png_rgba8;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
+use std::sync::atomic::{AtomicU64, Ordering};
+
+static NEXT_TIP_CACHE_TEX_ID: AtomicU64 = AtomicU64::new(1);
/// Kind of uploaded brush image asset.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
@@ -29,6 +32,7 @@ struct CpuImageAsset {
/// GPU-resident tip set (`texture_2d_array<f32>` of `1..=N` sub-tips).
pub struct GpuTipArray {
+ pub id: u64,
pub texture: wgpu::Texture,
pub view: wgpu::TextureView,
pub width: u32,
@@ -39,20 +43,27 @@ pub struct GpuTipArray {
/// GPU-resident seamless paper / surface texture (`texture_2d<f32>`).
pub struct GpuPaperTexture {
+ pub id: u64,
pub texture: wgpu::Texture,
pub view: wgpu::TextureView,
pub width: u32,
pub height: u32,
}
-/// Manages content-hashed CPU+GPU caches for brush tips, sub-tip arrays, and paper textures.
+const MAX_GPU_TIP_ARRAYS: usize = 64;
+const MAX_GPU_PAPERS: usize = 32;
+
+/// Manages content-hashed CPU+GPU caches for brush tips, sub-tip arrays, and paper textures
+/// with true LRU eviction (zero full-cache `.clear()` hitches).
pub struct TipTextureCache {
/// Raw uploaded / lazily-generated single images keyed by content hash or built-in key.
cpu_tips: HashMap<String, CpuImageAsset>,
- /// Assembled GPU `D2Array` tip sets keyed by canonical joined key list.
- gpu_tip_arrays: HashMap<String, GpuTipArray>,
- /// GPU paper textures keyed by content hash or `SurfaceTextureId`.
- gpu_papers: HashMap<String, GpuPaperTexture>,
+ /// Assembled GPU `D2Array` tip sets keyed by canonical joined key list + monotonic LRU tick.
+ gpu_tip_arrays: HashMap<String, (GpuTipArray, u64)>,
+ /// GPU paper textures keyed by content hash or `SurfaceTextureId` + monotonic LRU tick.
+ gpu_papers: HashMap<String, (GpuPaperTexture, u64)>,
+ /// Monotonic access clock for LRU eviction.
+ lru_clock: u64,
/// Always-valid fallback 1×1 white tip `D2Array` (1 layer).
fallback_tip: GpuTipArray,
/// Always-valid default 512×512 cold-press paper texture.
@@ -71,11 +82,49 @@ impl TipTextureCache {
cpu_tips: HashMap::new(),
gpu_tip_arrays: HashMap::new(),
gpu_papers: HashMap::new(),
+ lru_clock: 1,
fallback_tip,
default_paper,
}
}
+ #[inline]
+ fn next_lru_tick(&mut self) -> u64 {
+ let t = self.lru_clock;
+ self.lru_clock = self.lru_clock.wrapping_add(1);
+ t
+ }
+
+ fn evict_lru_tip_arrays_if_needed(&mut self) {
+ while self.gpu_tip_arrays.len() >= MAX_GPU_TIP_ARRAYS {
+ if let Some(oldest_key) = self
+ .gpu_tip_arrays
+ .iter()
+ .min_by_key(|(_, (_, tick))| *tick)
+ .map(|(k, _)| k.clone())
+ {
+ self.gpu_tip_arrays.remove(&oldest_key);
+ } else {
+ break;
+ }
+ }
+ }
+
+ fn evict_lru_papers_if_needed(&mut self) {
+ while self.gpu_papers.len() >= MAX_GPU_PAPERS {
+ if let Some(oldest_key) = self
+ .gpu_papers
+ .iter()
+ .min_by_key(|(_, (_, tick))| *tick)
+ .map(|(k, _)| k.clone())
+ {
+ self.gpu_papers.remove(&oldest_key);
+ } else {
+ break;
+ }
+ }
+ }
+
pub fn fallback_tip(&self) -> &GpuTipArray {
&self.fallback_tip
}
@@ -119,10 +168,8 @@ impl TipTextureCache {
match kind {
BrushTextureKind::Tip => {
- // Keep cache bounded reasonably (evict assembled arrays if huge)
- if self.gpu_tip_arrays.len() > 64 {
- self.gpu_tip_arrays.clear();
- }
+ // Evict only the least-recently-used assembled tip array if at capacity (never .clear()!)
+ self.evict_lru_tip_arrays_if_needed();
self.cpu_tips.insert(
hash,
CpuImageAsset {
@@ -133,11 +180,12 @@ impl TipTextureCache {
);
}
BrushTextureKind::Paper => {
- if self.gpu_papers.len() > 32 {
- self.gpu_papers.clear();
+ if !self.gpu_papers.contains_key(&hash) {
+ self.evict_lru_papers_if_needed();
}
+ let tick = self.next_lru_tick();
let gpu = Self::upload_paper_2d(device, queue, width, height, &rgba8);
- self.gpu_papers.insert(hash, gpu);
+ self.gpu_papers.insert(hash, (gpu, tick));
}
}
Ok(())
@@ -185,7 +233,10 @@ impl TipTextureCache {
let joined_key = keys.join("|");
if self.gpu_tip_arrays.contains_key(&joined_key) {
- return (true, self.gpu_tip_arrays.get(&joined_key).unwrap());
+ let tick = self.next_lru_tick();
+ let entry = self.gpu_tip_arrays.get_mut(&joined_key).unwrap();
+ entry.1 = tick;
+ return (true, &entry.0);
}
// Ensure every requested key is loaded (either uploaded or lazily generated built-in)
@@ -222,9 +273,11 @@ impl TipTextureCache {
})
.collect();
+ self.evict_lru_tip_arrays_if_needed();
+ let tick = self.next_lru_tick();
let gpu = Self::upload_tip_array(device, queue, target_w, target_h, &layers);
- self.gpu_tip_arrays.insert(joined_key.clone(), gpu);
- (true, self.gpu_tip_arrays.get(&joined_key).unwrap())
+ self.gpu_tip_arrays.insert(joined_key.clone(), (gpu, tick));
+ (true, &self.gpu_tip_arrays.get(&joined_key).unwrap().0)
}
/// Resolves a paper / surface heightfield texture (`paper_texture_key` > `surface_texture_id` > default).
@@ -244,25 +297,35 @@ impl TipTextureCache {
};
if self.gpu_papers.contains_key(key) {
- return self.gpu_papers.get(key).unwrap();
+ let tick = self.next_lru_tick();
+ let entry = self.gpu_papers.get_mut(key).unwrap();
+ entry.1 = tick;
+ return &entry.0;
}
// Try built-in procedural surface heightfield / paper texture
if let Some((w, h, rgba8)) = generate_builtin_paper_texture(key) {
+ self.evict_lru_papers_if_needed();
+ let tick = self.next_lru_tick();
let gpu = Self::upload_paper_2d(device, queue, w, h, &rgba8);
- self.gpu_papers.insert(key.to_string(), gpu);
- return self.gpu_papers.get(key).unwrap();
+ self.gpu_papers.insert(key.to_string(), (gpu, tick));
+ return &self.gpu_papers.get(key).unwrap().0;
}
// Fall back to surface_id if paper_key wasn't uploaded yet
if let Some(sid) = surface_id.filter(|s| !s.is_empty() && *s != key) {
if self.gpu_papers.contains_key(sid) {
- return self.gpu_papers.get(sid).unwrap();
+ let tick = self.next_lru_tick();
+ let entry = self.gpu_papers.get_mut(sid).unwrap();
+ entry.1 = tick;
+ return &entry.0;
}
if let Some((w, h, rgba8)) = generate_builtin_paper_texture(sid) {
+ self.evict_lru_papers_if_needed();
+ let tick = self.next_lru_tick();
let gpu = Self::upload_paper_2d(device, queue, w, h, &rgba8);
- self.gpu_papers.insert(sid.to_string(), gpu);
- return self.gpu_papers.get(sid).unwrap();
+ self.gpu_papers.insert(sid.to_string(), (gpu, tick));
+ return &self.gpu_papers.get(sid).unwrap().0;
}
}
@@ -300,18 +363,21 @@ impl TipTextureCache {
}
let tip_ref = if is_tex && !keys.is_empty() {
let joined = keys.join("|");
- self.gpu_tip_arrays.get(&joined).unwrap_or(&self.fallback_tip)
+ self.gpu_tip_arrays
+ .get(&joined)
+ .map(|(t, _)| t)
+ .unwrap_or(&self.fallback_tip)
} else {
&self.fallback_tip
};
let paper_ref = paper_key
.filter(|s| !s.is_empty())
- .and_then(|k| self.gpu_papers.get(k))
+ .and_then(|k| self.gpu_papers.get(k).map(|(p, _)| p))
.or_else(|| {
surface_id
.filter(|s| !s.is_empty())
- .and_then(|k| self.gpu_papers.get(k))
+ .and_then(|k| self.gpu_papers.get(k).map(|(p, _)| p))
})
.unwrap_or(&self.default_paper);
@@ -352,17 +418,20 @@ impl TipTextureCache {
}
let tip_ref = if is_tex && !keys.is_empty() {
let joined = keys.join("|");
- self.gpu_tip_arrays.get(&joined).unwrap_or(&self.fallback_tip)
+ self.gpu_tip_arrays
+ .get(&joined)
+ .map(|(t, _)| t)
+ .unwrap_or(&self.fallback_tip)
} else {
&self.fallback_tip
};
let paper_ref = paper_key
.filter(|s| !s.is_empty())
- .and_then(|k| self.gpu_papers.get(k))
+ .and_then(|k| self.gpu_papers.get(k).map(|(p, _)| p))
.or_else(|| {
surface_id
.filter(|s| !s.is_empty())
- .and_then(|k| self.gpu_papers.get(k))
+ .and_then(|k| self.gpu_papers.get(k).map(|(p, _)| p))
})
.unwrap_or(&self.default_paper);
@@ -418,18 +487,21 @@ impl TipTextureCache {
}
let tip_ref = if is_tex && !keys.is_empty() {
let joined = keys.join("|");
- self.gpu_tip_arrays.get(&joined).unwrap_or(&self.fallback_tip)
+ self.gpu_tip_arrays
+ .get(&joined)
+ .map(|(t, _)| t)
+ .unwrap_or(&self.fallback_tip)
} else {
&self.fallback_tip
};
let paper_ref = paper_key
.filter(|s| !s.is_empty())
- .and_then(|k| self.gpu_papers.get(k))
- .or_else(|| eff_surf.and_then(|k| self.gpu_papers.get(k)))
+ .and_then(|k| self.gpu_papers.get(k).map(|(p, _)| p))
+ .or_else(|| eff_surf.and_then(|k| self.gpu_papers.get(k).map(|(p, _)| p)))
.unwrap_or(&self.default_paper);
let dual_ref = dual_surface_id
.filter(|s| !s.is_empty())
- .and_then(|k| self.gpu_papers.get(k));
+ .and_then(|k| self.gpu_papers.get(k).map(|(p, _)| p));
(
is_tex,
@@ -509,6 +581,7 @@ impl TipTextureCache {
});
GpuTipArray {
+ id: NEXT_TIP_CACHE_TEX_ID.fetch_add(1, Ordering::Relaxed),
texture,
view,
width,
@@ -560,6 +633,7 @@ impl TipTextureCache {
);
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
GpuPaperTexture {
+ id: NEXT_TIP_CACHE_TEX_ID.fetch_add(1, Ordering::Relaxed),
texture,
view,
width,
diff --git a/crates/ink-engine/src/brush_parity_dx12_tests.rs b/crates/ink-engine/src/brush_parity_dx12_tests.rs
new file mode 100644
index 0000000..b055b86
--- /dev/null
+++ b/crates/ink-engine/src/brush_parity_dx12_tests.rs
@@ -0,0 +1,1742 @@
+//! Comprehensive Headless DX12 Brush Pipeline & Tile-Boundary Visual Parity Tests
+//! plus End-to-End WinTab / Windows Ink / Mouse / Navigation Input Handoff Tests.
+//!
+//! Exercises EVERY brush execution mode across the `256×256` tile boundary
+//! (`x = 128..384, y = 128..384` crossing both `x = 256` and `y = 256` seams),
+//! followed by GPU commit + `apply_gpu_committed_tiles` + `regenerate_layer_mipmaps` +
+//! CoW `undo` + `redo`:
+//! 1. G-Pen (`Stamp`, analytical, pressure taper, `sharp_corners = true`)
+//! 2. Real G-Pen (`Stamp`, textured tip + random rotation)
+//! 3. Textured Pen (`CspBrushCombineMode::CompareDensity`)
+//! 4. Darken tip-blend (`CspBlendTipsMode::Darken`)
+//! 5. Rough Pen (`Ribbon` continuous mesh)
+//! 6. Watercolor (`wet_edge > 0` + `paper_texture` across tile boundary)
+//! 7. Dual Brush (primary + secondary combine)
+//! 8. ColorMixingStamp (`color_mixing = true`)
+//! 9. NaturalPaint (`BristleRibbon` + `Impasto` 3D relief lighting)
+//! 10. Eraser + AlphaLock + LayerMask painting + Selection clipped stroke
+
+use crate::brush::{
+ BristleProfilePreset, BristleSettings, BrushRenderMode, BrushTextureKind,
+ CspAngleDynamicsMode, CspBlendTipsMode, CspBrushCombineMode, CspDualBrushConfig,
+ CspPaperTextureMode, DualBrushCompositeMode, ImpastoSettings, NativeBrushConfig,
+ NaturalMixingMode, NaturalPaintSettings, RibbonRepeatMode, StrokeDabEmitter,
+};
+use crate::clock;
+use crate::compositor::{CompositorDisplayConfig, FlattenOptions};
+use crate::document::{CanvasColorMode, CanvasDimensions, Document, ImpastoLayerLight};
+use crate::engine::{EngineConfig, EngineHandle};
+use crate::gpu::GpuRenderer;
+use crate::natural_paint::{BristleRibbonSimulator, RibbonMeshBuilder};
+use crate::selection::{SelectionCombineMode, SparseSelectionMask};
+use crate::stroke::{
+ polyline_to_bezier_segments, NativeStrokePipeline, StrokePipelineConfig, StrokePoint,
+};
+use crate::tiles::{RectI32, SparseLayerGrid, TileCoord, TileData, TileFormat, TileKind, TILE_SIZE};
+use crate::types::{
+ CameraState, CursorConfig, EngineCommand, EngineEvent, NativeInputSample, NativeNavEvent,
+ NativeNavGesture, SurfaceTarget, ViewportRect,
+};
+use std::collections::HashMap;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+const DOC_W: u32 = 512;
+const DOC_H: u32 = 512;
+
+fn make_headless_renderer(w: u32, h: u32) -> Option<GpuRenderer> {
+ match GpuRenderer::new(
+ SurfaceTarget::Headless {
+ width: w,
+ height: h,
+ },
+ DOC_W,
+ DOC_H,
+ ) {
+ Ok(r) => Some(r),
+ Err(err) => {
+ eprintln!("Skipping headless DX12 parity test (no DX12 adapter): {err}");
+ None
+ }
+ }
+}
+
+fn make_parity_doc(id: &str) -> Document {
+ let mut doc = Document::new_blank(
+ id,
+ id,
+ CanvasDimensions {
+ width: DOC_W,
+ height: DOC_H,
+ dpi: 300,
+ },
+ CanvasColorMode::Color,
+ "transparent",
+ 60.0,
+ 50,
+ );
+ // Keep only the primary transparent raster drawing layer for exact byte-for-byte checks.
+ doc.layers
+ .retain(|l| !Document::is_background_layer_id(&l.meta.id));
+ if doc.layers.is_empty() {
+ let _ = doc.add_layer(
+ crate::document::LayerNodeMeta::new_raster("layer-1", "Layer 1"),
+ None,
+ true,
+ false,
+ );
+ }
+ let lid = doc.layers[0].meta.id.clone();
+ doc.active_layer_id = Some(lid);
+ doc
+}
+
+fn read_full_layer_rgba8(doc: &Document, layer_id: &str) -> Vec<u8> {
+ let layer = doc.layer(layer_id).expect("layer exists");
+ let mut out = vec![0u8; (DOC_W * DOC_H * 4) as usize];
+ for y in 0..DOC_H as i32 {
+ for x in 0..DOC_W as i32 {
+ let px = layer.grid.get_pixel_rgba8(x, y, None);
+ let off = ((y as u32 * DOC_W + x as u32) * 4) as usize;
+ out[off..off + 4].copy_from_slice(&px);
+ }
+ }
+ out
+}
+
+fn read_full_mask_u8(doc: &Document, layer_id: &str) -> Vec<u8> {
+ let layer = doc.layer(layer_id).expect("layer exists");
+ let mut out = vec![layer.grid.mask_default_value; (DOC_W * DOC_H) as usize];
+ for (&coord, tile) in &layer.grid.mask_tiles {
+ let raw = tile.materialize_raw(None).expect("materialize mask tile");
+ for ly in 0..TILE_SIZE {
+ let y = coord.ty * TILE_SIZE as i32 + ly as i32;
+ if y < 0 || y >= DOC_H as i32 {
+ continue;
+ }
+ for lx in 0..TILE_SIZE {
+ let x = coord.tx * TILE_SIZE as i32 + lx as i32;
+ if x < 0 || x >= DOC_W as i32 {
+ continue;
+ }
+ out[(y as u32 * DOC_W + x as u32) as usize] = raw[ly * TILE_SIZE + lx];
+ }
+ }
+ }
+ out
+}
+
+fn read_full_impasto_f32(doc: &Document, layer_id: &str) -> Vec<f32> {
+ let layer = doc.layer(layer_id).expect("layer exists");
+ let mut out = vec![0.0f32; (DOC_W * DOC_H) as usize];
+ for y in 0..DOC_H as i32 {
+ for x in 0..DOC_W as i32 {
+ out[(y as u32 * DOC_W + x as u32) as usize] =
+ layer.grid.get_impasto_height_f32(x, y, None);
+ }
+ }
+ out
+}
+
+/// Checks every stored tile (raster + impasto) in `grid` for finite non-NaN/Inf data.
+fn assert_no_nan_or_inf_in_grid(grid: &SparseLayerGrid, label: &str) {
+ for (&coord, tile) in &grid.tiles {
+ if let crate::tiles::TileStorage::SolidColor { rgba16f, .. } = tile.storage {
+ for bits in rgba16f {
+ let v = half::f16::from_bits(bits).to_f32();
+ assert!(
+ v.is_finite(),
+ "[{label}] non-finite solid rgba16f value {v} at tile {coord:?}"
+ );
+ }
+ } else if tile.format == TileFormat::Rgba16Float {
+ let raw = tile.materialize_raw(None).expect("materialize 16f tile");
+ for chunk in raw.chunks_exact(2) {
+ let v = half::f16::from_bits(u16::from_le_bytes([chunk[0], chunk[1]])).to_f32();
+ assert!(
+ v.is_finite(),
+ "[{label}] non-finite Rgba16Float pixel {v} at tile {coord:?}"
+ );
+ }
+ }
+ }
+ for (&coord, tile) in &grid.impasto_tiles {
+ let raw = tile.materialize_raw(None).expect("materialize impasto tile");
+ for chunk in raw.chunks_exact(2) {
+ let v = half::f16::from_bits(u16::from_le_bytes([chunk[0], chunk[1]])).to_f32();
+ assert!(
+ v.is_finite(),
+ "[{label}] non-finite R16Float impasto pixel {v} at tile {coord:?}"
+ );
+ }
+ }
+}
+
+/// Counts pixels in `rect` whose RGBA8 differs from `base_rgba` (or alpha > 0 when blank).
+fn count_changed_pixels_in_rect(
+ before: &[u8],
+ after: &[u8],
+ x0: u32,
+ y0: u32,
+ x1: u32,
+ y1: u32,
+) -> usize {
+ let mut count = 0usize;
+ for y in y0.min(DOC_H)..y1.min(DOC_H) {
+ for x in x0.min(DOC_W)..x1.min(DOC_W) {
+ let off = ((y * DOC_W + x) * 4) as usize;
+ if before[off..off + 4] != after[off..off + 4] {
+ count += 1;
+ }
+ }
+ }
+ count
+}
+
+/// Asserts:
+/// 1. Non-zero inked/changed pixels on BOTH sides of the `x = 256` tile seam (including
+/// adjacent strips `[248..256)` and `[256..264)` right across the boundary).
+/// 2. Zero unexplained empty `64×64` windows along the diagonal stroke `(128,128) -> (384,384)`.
+/// 3. Non-empty tiles on BOTH sides of `x = 256` (no dropped `256×256` tile).
+fn assert_tile_boundary_continuity_rgba(
+ label: &str,
+ before: &[u8],
+ after: &[u8],
+ window_centers: &[(u32, u32)],
+) {
+ let left_half = count_changed_pixels_in_rect(before, after, 128, 128, 256, 384);
+ let right_half = count_changed_pixels_in_rect(before, after, 256, 128, 384, 384);
+ assert!(
+ left_half > 0,
+ "[{label}] Expected non-zero inked/modified pixels on left side of x=256 tile seam"
+ );
+ assert!(
+ right_half > 0,
+ "[{label}] Expected non-zero inked/modified pixels on right side of x=256 tile seam"
+ );
+
+ // Check immediate seam neighborhood [248..256) and [256..264) around y=256
+ let seam_left = count_changed_pixels_in_rect(before, after, 240, 232, 256, 280);
+ let seam_right = count_changed_pixels_in_rect(before, after, 256, 232, 272, 280);
+ assert!(
+ seam_left > 0 && seam_right > 0,
+ "[{label}] Tile seam gap detected at x=256 (left={seam_left}, right={seam_right})"
+ );
+
+ // Verify every 64x64 window along the stroke has modified pixels (zero 64x64/256x256 gaps)
+ for &(cx, cy) in window_centers {
+ let x0 = cx.saturating_sub(32);
+ let y0 = cy.saturating_sub(32);
+ let x1 = (cx + 32).min(DOC_W);
+ let y1 = (cy + 32).min(DOC_H);
+ let changed = count_changed_pixels_in_rect(before, after, x0, y0, x1, y1);
+ assert!(
+ changed > 0,
+ "[{label}] Unexplained empty 64x64 gap centered at ({cx}, {cy}) along stroke!"
+ );
+ }
+}
+
+/// Builds diagonal stroke points from `(128, 128)` to `(384, 384)` crossing both `x = 256` and `y = 256`.
+fn make_diagonal_seam_points(
+ count: usize,
+ base_size: f32,
+ taper_pressure: bool,
+) -> Vec<StrokePoint> {
+ let mut pts = Vec::with_capacity(count);
+ for i in 0..count {
+ let t = if count <= 1 {
+ 0.0
+ } else {
+ i as f64 / (count - 1) as f64
+ };
+ let pressure = if taper_pressure {
+ (0.2 + 0.8 * (t * std::f64::consts::PI).sin() as f32).clamp(0.15, 1.0)
+ } else {
+ 0.85
+ };
+ pts.push(StrokePoint {
+ x: 128.0 + 256.0 * t,
+ y: 128.0 + 256.0 * t,
+ pressure,
+ width: base_size * (0.35 + 0.65 * pressure),
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ velocity: 0.4,
+ timestamp_ms: 100.0 + i as f64 * 4.0,
+ is_corner: false,
+ });
+ }
+ pts
+}
+
+/// Runs a Stamp or Ribbon brush stroke through the full GPU pipeline:
+/// begin -> stamp -> commit -> apply_gpu_committed_tiles -> record_stroke_deltas ->
+/// regenerate_layer_mipmaps -> render_document_flattened -> zoom-0.25 viewport render ->
+/// CoW undo -> exact byte-for-byte check -> CoW redo -> exact byte-for-byte check.
+fn verify_stamp_or_ribbon_parity(
+ renderer: &mut GpuRenderer,
+ label: &str,
+ brush: NativeBrushConfig,
+ pts: &[StrokePoint],
+ base_fill_rect: Option<(RectI32, [u8; 4])>,
+ alpha_locked: bool,
+ selection: Option<SparseSelectionMask>,
+ window_centers: &[(u32, u32)],
+) -> (Vec<u8>, Vec<u8>) {
+ let mut doc = make_parity_doc(&format!("parity-{label}"));
+ let doc_id = doc.id.clone();
+ let layer_id = doc.active_layer_id.clone().expect("active layer");
+
+ if let Some((rect, rgba)) = base_fill_rect {
+ let mut pixels = vec![0u8; (rect.width * rect.height * 4) as usize];
+ for px in pixels.chunks_exact_mut(4) {
+ px.copy_from_slice(&rgba);
+ }
+ let layer = doc.layer_mut(&layer_id).unwrap();
+ let _ = layer.grid.write_rgba8_rect(&pixels, rect, 128, None);
+ layer.meta.alpha_locked = Some(alpha_locked);
+ }
+ doc.selection = selection;
+
+ renderer.sync_document(&mut doc, None).expect("initial sync");
+ let before_bytes = read_full_layer_rgba8(&doc, &layer_id);
+
+ // Snapshot CoW before tiles
+ let before_tiles: HashMap<TileCoord, Option<Arc<TileData>>> = {
+ let layer = doc.layer(&layer_id).unwrap();
+ let mut map = HashMap::new();
+ for ty in 0..2 {
+ for tx in 0..2 {
+ let c = TileCoord::new(tx, ty);
+ map.insert(c, layer.grid.tiles.get(&c).cloned());
+ }
+ }
+ map
+ };
+
+ if brush.is_ribbon_brush() {
+ let (tw, th, sub_c) = renderer.resolve_ribbon_tip_dims(&brush);
+ let mut rb = RibbonMeshBuilder::new(tw, th, sub_c, 0xA1B2_C3D4);
+ let mut verts = Vec::with_capacity(512);
+ rb.push_points(pts, &brush, &mut verts);
+ rb.finish(&brush, &mut verts);
+ assert!(!verts.is_empty(), "[{label}] RibbonMeshBuilder must emit vertices");
+
+ renderer.begin_gpu_stroke(DOC_W, DOC_H, false, brush.clone(), [0.0, 0.0]);
+ let _ = renderer.stamp_gpu_ribbon_vertices(&verts, &[], false);
+ } else {
+ let (tip_count, tip_aspect) = renderer.resolve_brush_tip_metrics(&brush);
+ let mut primary = StrokeDabEmitter::new(brush.clone(), 0x1122_3344, tip_count, tip_aspect);
+ let mut secondary = brush.build_secondary_brush_config().map(|sc| {
+ let (sc_n, sc_a) = renderer.resolve_brush_tip_metrics(&sc);
+ StrokeDabEmitter::new(sc, 0x5566_7788, sc_n, sc_a)
+ });
+ let rand_off = primary.stroke_grain_offset;
+ renderer.begin_gpu_stroke(DOC_W, DOC_H, false, brush.clone(), rand_off);
+
+ let segs = polyline_to_bezier_segments(pts, 0.0);
+ let mut p_dabs = Vec::with_capacity(512);
+ let mut s_dabs = Vec::with_capacity(512);
+ if let Some(first) = pts.first() {
+ primary.emit_initial_point(first, None, 0.0, &mut p_dabs);
+ if let Some(ref mut se) = secondary {
+ se.emit_initial_point(first, None, 0.0, &mut s_dabs);
+ }
+ }
+ for seg in &segs {
+ primary.emit_segment(seg, None, 0.0, &mut p_dabs);
+ if let Some(ref mut se) = secondary {
+ se.emit_segment(seg, None, 0.0, &mut s_dabs);
+ }
+ }
+ assert!(!p_dabs.is_empty(), "[{label}] primary emitter must emit dabs");
+ let _ = renderer.stamp_gpu_stroke_dabs(&p_dabs, &s_dabs);
+ }
+
+ let committed = {
+ let layer = doc.layer(&layer_id).unwrap();
+ renderer
+ .commit_gpu_stroke_to_layer_with_selection(
+ &doc_id,
+ &layer_id,
+ &layer.grid,
+ doc.selection.as_ref(),
+ None,
+ alpha_locked,
+ false,
+ )
+ .expect("commit_gpu_stroke_to_layer_with_selection")
+ };
+ assert!(
+ !committed.tiles.is_empty(),
+ "[{label}] GPU commit must touch at least one tile"
+ );
+
+ let deltas = {
+ let layer = doc.layer_mut(&layer_id).unwrap();
+ let (deltas, cleared) = layer.grid.apply_gpu_committed_tiles(
+ &layer_id,
+ committed.tiles,
+ &before_tiles,
+ 128,
+ );
+ renderer.regenerate_layer_mipmaps(&doc_id, &layer_id, &mut layer.grid, &cleared, None);
+ assert_no_nan_or_inf_in_grid(&layer.grid, label);
+ deltas
+ };
+ renderer.clear_live_stroke();
+ assert!(!deltas.is_empty(), "[{label}] CoW deltas must be non-empty");
+ doc.record_stroke_deltas(&layer_id, "brush", label, deltas, Some("local".into()), None);
+
+ // Exercise GPU flatten & mipmap viewport presentation to verify zero DX12 validation/render failures
+ let (fw, fh, flat_after) = renderer
+ .render_document_flattened(&doc, None, &FlattenOptions::default())
+ .expect("GPU flatten after stroke");
+ assert_eq!((fw, fh), (DOC_W, DOC_H));
+ assert_eq!(flat_after.len(), (DOC_W * DOC_H * 4) as usize);
+
+ let vp = ViewportRect {
+ x_px: 0,
+ y_px: 0,
+ width_px: 256,
+ height_px: 256,
+ dpr: 1.25,
+ };
+ let cam = CameraState {
+ pan_x: 102.4,
+ pan_y: 102.4,
+ zoom: 0.25,
+ rotation: 0.0,
+ flip_x: false,
+ flip_y: false,
+ };
+ let _ = renderer.render_document_frame(
+ &doc,
+ None,
+ &CompositorDisplayConfig::default(),
+ &vp,
+ &cam,
+ &[],
+ false,
+ false,
+ &CursorConfig::default(),
+ None,
+ true,
+ );
+
+ let after_bytes = read_full_layer_rgba8(&doc, &layer_id);
+ assert_tile_boundary_continuity_rgba(label, &before_bytes, &after_bytes, window_centers);
+
+ // CoW Undo -> must restore original base/blank layer byte-for-byte
+ doc.undo();
+ renderer.sync_document(&mut doc, None).expect("sync after undo");
+ let undone_bytes = read_full_layer_rgba8(&doc, &layer_id);
+ assert_eq!(
+ undone_bytes, before_bytes,
+ "[{label}] CoW Undo must restore original layer byte-for-byte"
+ );
+
+ // CoW Redo -> must restore exact committed stroke byte-for-byte
+ doc.redo();
+ renderer.sync_document(&mut doc, None).expect("sync after redo");
+ let redone_bytes = read_full_layer_rgba8(&doc, &layer_id);
+ assert_eq!(
+ redone_bytes, after_bytes,
+ "[{label}] CoW Redo must restore committed stroke byte-for-byte"
+ );
+
+ renderer.tile_pool_mut().invalidate_document(&doc_id);
+ (before_bytes, after_bytes)
+}
+
+#[test]
+fn test_all_10_brush_pipelines_tile_boundary_visual_parity_and_cow_undo_redo() {
+ let _dx12_guard = crate::lock_dx12_test();
+ let Some(mut renderer) = make_headless_renderer(256, 256) else {
+ return;
+ };
+
+ let diag_windows: &[(u32, u32)] = &[
+ (160, 160),
+ (208, 208),
+ (256, 256),
+ (304, 304),
+ (352, 352),
+ ];
+
+ // ------------------------------------------------------------------------
+ // 1. G-Pen (Stamp, analytical, pressure taper, sharp_corners = true)
+ // ------------------------------------------------------------------------
+ {
+ let mut pipeline = NativeStrokePipeline::new();
+ let pipe_cfg = StrokePipelineConfig {
+ base_size: 26.0,
+ min_size_factor: 0.12,
+ use_pressure: true,
+ stabilization: 0.0,
+ sharp_corners: true,
+ smoothing: true,
+ ..Default::default()
+ };
+ let raw_pts = make_diagonal_seam_points(48, 26.0, true);
+ let mut pts = Vec::new();
+ let first = raw_pts[0];
+ let s0 = pipeline.begin(
+ first.x,
+ first.y,
+ first.pressure,
+ 0.0,
+ 0.0,
+ 0.0,
+ first.timestamp_ms,
+ false,
+ None,
+ pipe_cfg,
+ );
+ if let Some(p) = s0.initial_point {
+ pts.push(p);
+ }
+ for p in raw_pts.iter().skip(1) {
+ let _ = pipeline.push_move(
+ p.x,
+ p.y,
+ p.pressure,
+ 0.0,
+ 0.0,
+ 0.0,
+ p.timestamp_ms,
+ false,
+ );
+ }
+ let end = pipeline.end(raw_pts.last().unwrap().timestamp_ms + 8.0);
+ let finalized = end
+ .finalized_points
+ .unwrap_or_else(|| pipeline.committed_points().to_vec());
+ assert!(finalized.len() >= 10, "[G-Pen] pipeline produced too few points");
+
+ let g_pen = NativeBrushConfig {
+ fg_color: [0.08, 0.08, 0.12],
+ size: 26.0,
+ min_size_factor: 0.12,
+ opacity: 1.0,
+ hardness: 0.96,
+ spacing: 0.08,
+ sharp_corners: true,
+ use_pressure: true,
+ ..Default::default()
+ };
+ verify_stamp_or_ribbon_parity(
+ &mut renderer,
+ "1-g-pen",
+ g_pen,
+ &finalized,
+ None,
+ false,
+ None,
+ diag_windows,
+ );
+ }
+
+ // ------------------------------------------------------------------------
+ // 2. Real G-Pen (Stamp, textured tip + random rotation)
+ // ------------------------------------------------------------------------
+ {
+ let pts = make_diagonal_seam_points(40, 28.0, true);
+ let real_g_pen = NativeBrushConfig {
+ fg_color: [0.10, 0.09, 0.14],
+ size: 28.0,
+ min_size_factor: 0.15,
+ opacity: 1.0,
+ hardness: 0.9,
+ spacing: 0.10,
+ tip_key: Some("tip:real-g-pen".to_string()),
+ custom_tip_angle_dynamics: CspAngleDynamicsMode::Random,
+ custom_tip_rotation_random_scale: 1.0,
+ ..Default::default()
+ };
+ verify_stamp_or_ribbon_parity(
+ &mut renderer,
+ "2-real-g-pen",
+ real_g_pen,
+ &pts,
+ None,
+ false,
+ None,
+ diag_windows,
+ );
+ }
+
+ // ------------------------------------------------------------------------
+ // 3. Textured Pen (CspBrushCombineMode::CompareDensity)
+ // ------------------------------------------------------------------------
+ {
+ let pts = make_diagonal_seam_points(40, 28.0, false);
+ let textured_pen = NativeBrushConfig {
+ fg_color: [0.18, 0.15, 0.22],
+ size: 28.0,
+ opacity: 0.78,
+ brush_density: 0.85,
+ hardness: 0.85,
+ spacing: 0.10,
+ tip_key: Some("tip:pencil-hb-2b".to_string()),
+ brush_combine_mode: CspBrushCombineMode::CompareDensity,
+ ..Default::default()
+ };
+ verify_stamp_or_ribbon_parity(
+ &mut renderer,
+ "3-textured-pen-compare-density",
+ textured_pen,
+ &pts,
+ None,
+ false,
+ None,
+ diag_windows,
+ );
+ }
+
+ // ------------------------------------------------------------------------
+ // 4. Darken tip-blend (CspBlendTipsMode::Darken)
+ // ------------------------------------------------------------------------
+ {
+ let pts = make_diagonal_seam_points(40, 30.0, false);
+ let darken_tip = NativeBrushConfig {
+ fg_color: [0.12, 0.22, 0.42],
+ size: 30.0,
+ opacity: 0.85,
+ brush_density: 0.8,
+ hardness: 0.8,
+ spacing: 0.12,
+ tip_key: Some("tip:pencil-6b-8b".to_string()),
+ blend_tips_mode: CspBlendTipsMode::Darken,
+ ..Default::default()
+ };
+ verify_stamp_or_ribbon_parity(
+ &mut renderer,
+ "4-darken-tip-blend",
+ darken_tip,
+ &pts,
+ None,
+ false,
+ None,
+ diag_windows,
+ );
+ }
+
+ // ------------------------------------------------------------------------
+ // 5. Rough Pen (Ribbon continuous mesh)
+ // ------------------------------------------------------------------------
+ {
+ // Upload a deterministic 64x128 organic ribbon tip texture
+ let rw = 64u32;
+ let rh = 128u32;
+ let mut tip_rgba = vec![0u8; (rw * rh * 4) as usize];
+ for y in 0..rh {
+ for x in 0..rw {
+ let nx = (x as f32 + 0.5) / rw as f32 * 2.0 - 1.0;
+ let edge = (1.0 - nx.abs()).clamp(0.0, 1.0);
+ let grain = 0.72 + 0.28 * (((x * 13 + y * 7) % 17) as f32 / 16.0);
+ let a = ((edge * 1.4).clamp(0.0, 1.0) * grain * 255.0).round() as u8;
+ let off = ((y * rw + x) * 4) as usize;
+ tip_rgba[off] = 255;
+ tip_rgba[off + 1] = 255;
+ tip_rgba[off + 2] = 255;
+ tip_rgba[off + 3] = a;
+ }
+ }
+ renderer
+ .upload_brush_texture(
+ "parity-rough-ribbon-tip".to_string(),
+ BrushTextureKind::Tip,
+ false,
+ rw,
+ rh,
+ tip_rgba,
+ )
+ .expect("upload ribbon tip");
+
+ let pts = make_diagonal_seam_points(44, 28.0, true);
+ let rough_pen = NativeBrushConfig {
+ fg_color: [0.12, 0.10, 0.10],
+ size: 28.0,
+ opacity: 0.95,
+ hardness: 0.9,
+ is_ribbon: true,
+ ribbon_repeat_mode: RibbonRepeatMode::Repeat,
+ tip_key: Some("parity-rough-ribbon-tip".to_string()),
+ ..Default::default()
+ };
+ verify_stamp_or_ribbon_parity(
+ &mut renderer,
+ "5-rough-pen-ribbon",
+ rough_pen,
+ &pts,
+ None,
+ false,
+ None,
+ diag_windows,
+ );
+ }
+
+ // ------------------------------------------------------------------------
+ // 6. Watercolor (wet_edge > 0 + paper_texture across tile boundary)
+ // ------------------------------------------------------------------------
+ {
+ let pts = make_diagonal_seam_points(40, 36.0, false);
+ let watercolor = NativeBrushConfig {
+ fg_color: [0.16, 0.44, 0.76],
+ size: 36.0,
+ opacity: 0.80,
+ brush_density: 0.75,
+ hardness: 0.65,
+ spacing: 0.10,
+ tip_key: Some("pro:watercolor-wash".to_string()),
+ surface_texture_id: Some("cold-press-watercolor".to_string()),
+ grain: 0.40,
+ texture_density: 0.55,
+ paper_texture_mode: CspPaperTextureMode::Subtract,
+ paper_texture_apply_each_plot: false,
+ wet_edge: 0.85,
+ wet_edge_radius: 4.0,
+ wet_edge_alpha_power: 1.0,
+ wet_edge_value_power: 1.0,
+ ..Default::default()
+ };
+ verify_stamp_or_ribbon_parity(
+ &mut renderer,
+ "6-watercolor-wet-edge-paper",
+ watercolor,
+ &pts,
+ None,
+ false,
+ None,
+ diag_windows,
+ );
+ }
+
+ // ------------------------------------------------------------------------
+ // 7. Dual Brush (primary + secondary combine)
+ // ------------------------------------------------------------------------
+ {
+ let pts = make_diagonal_seam_points(40, 34.0, false);
+ let dual_brush = NativeBrushConfig {
+ fg_color: [0.55, 0.14, 0.28],
+ size: 34.0,
+ opacity: 0.95,
+ hardness: 0.85,
+ spacing: 0.10,
+ tip_key: Some("tip:charcoal-pencil".to_string()),
+ dual_brush: true,
+ dual_brush_config: Some(CspDualBrushConfig {
+ enabled: true,
+ combine_mode: DualBrushCompositeMode::Multiply,
+ size: 34.0,
+ link_size: true,
+ size_ratio: 1.0,
+ spacing: 0.14,
+ hardness: 0.8,
+ density: 0.9,
+ tip_key: Some("tip:mineral-grain-dual".to_string()),
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+ verify_stamp_or_ribbon_parity(
+ &mut renderer,
+ "7-dual-brush",
+ dual_brush,
+ &pts,
+ None,
+ false,
+ None,
+ diag_windows,
+ );
+ }
+
+ // ------------------------------------------------------------------------
+ // 8. ColorMixingStamp (color_mixing = true)
+ // ------------------------------------------------------------------------
+ {
+ let mut doc = make_parity_doc("parity-8-color-mixing");
+ let doc_id = doc.id.clone();
+ let layer_id = doc.active_layer_id.clone().unwrap();
+ // Pre-fill a warm yellow ground band crossing x=256 so pigment pickup & mixing engage
+ let base_rect = RectI32::new(96, 96, 320, 320);
+ let mut base_px = vec![0u8; (base_rect.width * base_rect.height * 4) as usize];
+ for px in base_px.chunks_exact_mut(4) {
+ px.copy_from_slice(&[240, 200, 50, 255]);
+ }
+ let _ = doc
+ .layer_mut(&layer_id)
+ .unwrap()
+ .grid
+ .write_rgba8_rect(&base_px, base_rect, 128, None);
+ renderer.sync_document(&mut doc, None).expect("sync cmix base");
+ let before_bytes = read_full_layer_rgba8(&doc, &layer_id);
+
+ let before_tiles: HashMap<TileCoord, Option<Arc<TileData>>> = {
+ let layer = doc.layer(&layer_id).unwrap();
+ (0..2)
+ .flat_map(|ty| (0..2).map(move |tx| TileCoord::new(tx, ty)))
+ .map(|c| (c, layer.grid.tiles.get(&c).cloned()))
+ .collect()
+ };
+
+ let cmix_brush = NativeBrushConfig {
+ fg_color: [0.10, 0.35, 0.88],
+ size: 32.0,
+ opacity: 0.95,
+ hardness: 0.8,
+ spacing: 0.10,
+ color_mixing: true,
+ perceptual_mixing: true,
+ amount_of_paint: 0.72,
+ density_of_paint: 0.85,
+ color_stretch: 0.65,
+ ..Default::default()
+ };
+ assert!(cmix_brush.is_color_mixing_stamp_brush());
+
+ let pts = make_diagonal_seam_points(40, 32.0, false);
+ let (tc, ta) = renderer.resolve_brush_tip_metrics(&cmix_brush);
+ let mut emitter = StrokeDabEmitter::new(cmix_brush.clone(), 0x8899_AABB, tc, ta);
+ let segs = polyline_to_bezier_segments(&pts, 0.0);
+ let mut dabs = Vec::with_capacity(256);
+ emitter.emit_initial_point(&pts[0], None, 0.0, &mut dabs);
+ for seg in &segs {
+ emitter.emit_segment(seg, None, 0.0, &mut dabs);
+ }
+
+ renderer.begin_natural_paint_stroke(&doc_id, &layer_id, DOC_W, DOC_H, cmix_brush);
+ let layer_clone = doc.layer(&layer_id).cloned().unwrap();
+ let _ = renderer.dispatch_color_mixing_dabs(&doc, &layer_clone, &dabs, None);
+ let batch = renderer
+ .commit_natural_paint_to_layer()
+ .expect("commit ColorMixingStamp");
+
+ let deltas = {
+ let layer = doc.layer_mut(&layer_id).unwrap();
+ let (deltas, cleared) = layer.grid.apply_gpu_committed_tiles(
+ &layer_id,
+ batch.color_tiles,
+ &before_tiles,
+ 128,
+ );
+ renderer.regenerate_layer_mipmaps(&doc_id, &layer_id, &mut layer.grid, &cleared, None);
+ assert_no_nan_or_inf_in_grid(&layer.grid, "8-color-mixing-stamp");
+ deltas
+ };
+ assert!(!deltas.is_empty());
+ doc.record_stroke_deltas(&layer_id, "brush", "ColorMixingStamp", deltas, None, None);
+
+ let after_bytes = read_full_layer_rgba8(&doc, &layer_id);
+ assert_tile_boundary_continuity_rgba(
+ "8-color-mixing-stamp",
+ &before_bytes,
+ &after_bytes,
+ diag_windows,
+ );
+
+ doc.undo();
+ renderer.sync_document(&mut doc, None).unwrap();
+ assert_eq!(
+ read_full_layer_rgba8(&doc, &layer_id),
+ before_bytes,
+ "[8-color-mixing-stamp] Undo must restore base byte-for-byte"
+ );
+ doc.redo();
+ renderer.sync_document(&mut doc, None).unwrap();
+ assert_eq!(
+ read_full_layer_rgba8(&doc, &layer_id),
+ after_bytes,
+ "[8-color-mixing-stamp] Redo must restore stroke byte-for-byte"
+ );
+ renderer.tile_pool_mut().invalidate_document(&doc_id);
+ }
+
+ // ------------------------------------------------------------------------
+ // 9. NaturalPaint (BristleRibbon + Impasto 3D relief lighting)
+ // ------------------------------------------------------------------------
+ {
+ let mut doc = make_parity_doc("parity-9-natural-paint-impasto");
+ let doc_id = doc.id.clone();
+ let layer_id = doc.active_layer_id.clone().unwrap();
+ renderer.sync_document(&mut doc, None).unwrap();
+ let before_bytes = read_full_layer_rgba8(&doc, &layer_id);
+ let before_impasto = read_full_impasto_f32(&doc, &layer_id);
+
+ let before_tiles: HashMap<TileCoord, Option<Arc<TileData>>> = (0..2)
+ .flat_map(|ty| (0..2).map(move |tx| TileCoord::new(tx, ty)))
+ .map(|c| (c, None))
+ .collect();
+
+ let np_brush = NativeBrushConfig {
+ fg_color: [0.82, 0.22, 0.16],
+ size: 36.0,
+ min_size_factor: 0.4,
+ opacity: 1.0,
+ flow: 0.95,
+ brush_density: 0.95,
+ hardness: 0.85,
+ spacing: 0.08,
+ preset_key: Some("parity-impasto-oil".to_string()),
+ render_mode: BrushRenderMode::BristleRibbon,
+ color_mixing: true,
+ perceptual_mixing: true,
+ amount_of_paint: 0.82,
+ density_of_paint: 0.92,
+ color_stretch: 0.55,
+ mixing_mode: NaturalMixingMode::ImpastoMix,
+ surface_texture_id: Some("canvas-linen".to_string()),
+ grain: 0.2,
+ bristle: Some(BristleSettings {
+ profile: BristleProfilePreset::Filbert,
+ count: 24,
+ clumping: 0.3,
+ stiffness: 0.65,
+ length: 1.0,
+ splay: 0.35,
+ irregularity: 0.25,
+ edge_ridge: 0.5,
+ }),
+ natural_paint: Some(NaturalPaintSettings {
+ enabled: true,
+ spatial_mixing: true,
+ pigment_mixing_strength: 0.85,
+ paint_load: 0.92,
+ depletion_rate: 0.12,
+ wetness: 0.4,
+ viscosity: 0.7,
+ auto_clean: true,
+ charge_per_pressure: 0.6,
+ dry_brush: 0.0,
+ granulation: 0.0,
+ penetration_curve: 1.0,
+ }),
+ impasto: Some(ImpastoSettings {
+ enabled: true,
+ depth: 0.95,
+ bristle_relief: 0.85,
+ gloss: 0.55,
+ relief_contrast: 1.4,
+ light_azimuth: 315.0,
+ light_elevation: 45.0,
+ }),
+ ..Default::default()
+ };
+ assert!(np_brush.is_natural_paint_brush());
+
+ let pts = make_diagonal_seam_points(48, 36.0, false);
+ let mut sim = BristleRibbonSimulator::new(&np_brush, 0xCAFE_BABE);
+ let mut caps = Vec::with_capacity(1024);
+ sim.step_points(&pts, &np_brush, &mut caps);
+ assert!(!caps.is_empty());
+
+ renderer.begin_natural_paint_stroke(&doc_id, &layer_id, DOC_W, DOC_H, np_brush.clone());
+ let layer_clone = doc.layer(&layer_id).cloned().unwrap();
+ let _ = renderer.dispatch_natural_paint_capsules(&doc, &layer_clone, &caps, None);
+ let batch = renderer
+ .commit_natural_paint_to_layer()
+ .expect("commit NaturalPaint");
+ assert!(
+ !batch.impasto_tiles.is_empty(),
+ "[9-natural-paint] Impasto R16Float height tiles must be populated"
+ );
+
+ let all_deltas = {
+ let layer = doc.layer_mut(&layer_id).unwrap();
+ let (mut color_deltas, cleared) = layer.grid.apply_gpu_committed_tiles(
+ &layer_id,
+ batch.color_tiles,
+ &before_tiles,
+ 128,
+ );
+ let (imp_deltas, _) = layer.grid.apply_gpu_committed_impasto_tiles(
+ &layer_id,
+ batch.impasto_tiles,
+ &before_tiles,
+ );
+ color_deltas.extend(imp_deltas);
+ layer.meta.impasto_light = np_brush.impasto_layer_light();
+ renderer.regenerate_layer_mipmaps(&doc_id, &layer_id, &mut layer.grid, &cleared, None);
+ assert_no_nan_or_inf_in_grid(&layer.grid, "9-natural-paint-impasto");
+ color_deltas
+ };
+ doc.record_stroke_deltas(&layer_id, "brush", "NaturalPaint", all_deltas, None, None);
+
+ let after_bytes = read_full_layer_rgba8(&doc, &layer_id);
+ let after_impasto = read_full_impasto_f32(&doc, &layer_id);
+ assert_tile_boundary_continuity_rgba(
+ "9-natural-paint-impasto",
+ &before_bytes,
+ &after_bytes,
+ diag_windows,
+ );
+
+ // Verify Impasto heightfield exists on BOTH sides of x = 256 and 3D relief lighting reacts to azimuth
+ let imp_slice = after_impasto.as_slice();
+ let imp_left = (128..256)
+ .flat_map(|x| (128..384).map(move |y| imp_slice[y * DOC_W as usize + x]))
+ .filter(|&h| h > 0.01)
+ .count();
+ let imp_right = (256..384)
+ .flat_map(|x| (128..384).map(move |y| imp_slice[y * DOC_W as usize + x]))
+ .filter(|&h| h > 0.01)
+ .count();
+ assert!(
+ imp_left > 0 && imp_right > 0,
+ "[9-natural-paint] Impasto heightfield must cross x=256 (left={imp_left}, right={imp_right})"
+ );
+
+ let (_, _, lit_a) = renderer
+ .render_document_flattened(&doc, None, &FlattenOptions::default())
+ .expect("flatten impasto light A");
+ doc.layer_mut(&layer_id).unwrap().meta.impasto_light = Some(ImpastoLayerLight {
+ enabled: true,
+ depth: 1.0,
+ gloss: 0.65,
+ relief_contrast: 1.6,
+ light_azimuth: 135.0,
+ light_elevation: 35.0,
+ });
+ renderer.invalidate_compositor_cache();
+ let (_, _, lit_b) = renderer
+ .render_document_flattened(&doc, None, &FlattenOptions::default())
+ .expect("flatten impasto light B");
+ assert_ne!(
+ lit_a, lit_b,
+ "[9-natural-paint] Impasto 3D relief lighting must respond to directional light azimuth"
+ );
+
+ doc.undo();
+ renderer.sync_document(&mut doc, None).unwrap();
+ assert_eq!(read_full_layer_rgba8(&doc, &layer_id), before_bytes);
+ assert_eq!(read_full_impasto_f32(&doc, &layer_id), before_impasto);
+
+ doc.redo();
+ renderer.sync_document(&mut doc, None).unwrap();
+ assert_eq!(read_full_layer_rgba8(&doc, &layer_id), after_bytes);
+ assert_eq!(read_full_impasto_f32(&doc, &layer_id), after_impasto);
+ renderer.tile_pool_mut().invalidate_document(&doc_id);
+ }
+
+ // ------------------------------------------------------------------------
+ // 10a. Eraser across tile boundary
+ // ------------------------------------------------------------------------
+ {
+ let pts = make_diagonal_seam_points(40, 32.0, false);
+ let eraser = NativeBrushConfig {
+ size: 32.0,
+ opacity: 1.0,
+ hardness: 0.95,
+ spacing: 0.08,
+ is_eraser: true,
+ ..Default::default()
+ };
+ let (_before, after) = verify_stamp_or_ribbon_parity(
+ &mut renderer,
+ "10a-eraser",
+ eraser,
+ &pts,
+ Some((RectI32::new(64, 64, 384, 384), [40, 120, 210, 255])),
+ false,
+ None,
+ diag_windows,
+ );
+ // Verify untouched region away from stroke remains fully opaque (no accidental full-tile wipe)
+ let corner_off = ((90 * DOC_W + 380) * 4) as usize;
+ assert_eq!(
+ &after[corner_off..corner_off + 4],
+ &[40, 120, 210, 255],
+ "[10a-eraser] Untouched tile corner must remain intact"
+ );
+ }
+
+ // ------------------------------------------------------------------------
+ // 10b. AlphaLock across tile boundary
+ // ------------------------------------------------------------------------
+ {
+ let pts = make_diagonal_seam_points(40, 32.0, false);
+ let brush = NativeBrushConfig {
+ fg_color: [0.95, 0.15, 0.15],
+ size: 32.0,
+ opacity: 1.0,
+ hardness: 0.95,
+ spacing: 0.08,
+ ..Default::default()
+ };
+ // Band y=200..312, x=96..416 crosses x=256 while y=128..190 and y=320..384 are transparent
+ let (_before, after) = verify_stamp_or_ribbon_parity(
+ &mut renderer,
+ "10b-alpha-lock",
+ brush,
+ &pts,
+ Some((RectI32::new(96, 200, 320, 112), [30, 180, 70, 255])),
+ true,
+ None,
+ &[(224, 224), (256, 256), (288, 288)],
+ );
+ // Transparent pixels outside the alpha-locked band MUST remain strictly alpha == 0
+ for &(tx, ty) in &[(140u32, 140u32), (160, 160), (352, 352), (370, 370)] {
+ let off = ((ty * DOC_W + tx) * 4) as usize;
+ assert_eq!(
+ after[off + 3],
+ 0,
+ "[10b-alpha-lock] Transparent pixel ({tx},{ty}) leaked ink outside alpha lock!"
+ );
+ }
+ }
+
+ // ------------------------------------------------------------------------
+ // 10c. LayerMask painting across tile boundary
+ // ------------------------------------------------------------------------
+ {
+ let mut doc = make_parity_doc("parity-10c-layer-mask");
+ let doc_id = doc.id.clone();
+ let layer_id = doc.active_layer_id.clone().unwrap();
+ {
+ let layer = doc.layer_mut(&layer_id).unwrap();
+ layer.grid.fill_solid_layer(DOC_W, DOC_H, [60, 90, 220, 255]);
+ layer.grid.init_mask(255);
+ }
+ renderer.sync_document(&mut doc, None).unwrap();
+ let before_mask = read_full_mask_u8(&doc, &layer_id);
+
+ let before_mask_tiles: HashMap<TileCoord, Option<Arc<TileData>>> = (0..2)
+ .flat_map(|ty| (0..2).map(move |tx| TileCoord::new(tx, ty)))
+ .map(|c| (c, None))
+ .collect();
+
+ // Paint black (lum = 0) onto the reveal-all mask across (128,128) -> (384,384)
+ let mask_brush = NativeBrushConfig {
+ fg_color: [0.0, 0.0, 0.0],
+ size: 32.0,
+ opacity: 1.0,
+ hardness: 0.95,
+ spacing: 0.08,
+ ..Default::default()
+ };
+ let pts = make_diagonal_seam_points(40, 32.0, false);
+ let (tc, ta) = renderer.resolve_brush_tip_metrics(&mask_brush);
+ let mut emitter = StrokeDabEmitter::new(mask_brush.clone(), 0x10C0_10C0, tc, ta);
+ let segs = polyline_to_bezier_segments(&pts, 0.0);
+ let mut dabs = Vec::with_capacity(256);
+ emitter.emit_initial_point(&pts[0], None, 0.0, &mut dabs);
+ for seg in &segs {
+ emitter.emit_segment(seg, None, 0.0, &mut dabs);
+ }
+ renderer.begin_gpu_stroke(DOC_W, DOC_H, false, mask_brush, [0.0, 0.0]);
+ let _ = renderer.stamp_gpu_stroke_dabs(&dabs, &[]);
+
+ let mut mask_base = SparseLayerGrid::new(TileFormat::Color32Bit);
+ for &c in before_mask_tiles.keys() {
+ mask_base.set_tile(
+ c,
+ Arc::new(TileData::new_solid(
+ TileFormat::Color32Bit,
+ TileKind::Raster,
+ [255, 255, 255, 255],
+ )),
+ );
+ }
+ let mask_tmp_id = format!("{layer_id}__mask_tmp");
+ let batch = renderer
+ .commit_gpu_stroke_to_layer(&doc_id, &mask_tmp_id, &mask_base, None, false, false)
+ .expect("commit mask stroke");
+ let mask_deltas = {
+ let layer = doc.layer_mut(&layer_id).unwrap();
+ let (deltas, _) = layer.grid.apply_gpu_committed_mask_tiles(
+ &layer_id,
+ batch.tiles,
+ &before_mask_tiles,
+ );
+ layer.meta.mask_version = Some(layer.grid.mask_version);
+ deltas
+ };
+ renderer.clear_live_stroke();
+ assert!(!mask_deltas.is_empty());
+ doc.record_stroke_deltas(&layer_id, "mask", "Mask Stroke", mask_deltas, None, None);
+
+ let after_mask = read_full_mask_u8(&doc, &layer_id);
+ let mask_slice = after_mask.as_slice();
+ let mask_left = (128..256)
+ .flat_map(|x| (128..384).map(move |y| mask_slice[y * DOC_W as usize + x]))
+ .filter(|&m| m < 250)
+ .count();
+ let mask_right = (256..384)
+ .flat_map(|x| (128..384).map(move |y| mask_slice[y * DOC_W as usize + x]))
+ .filter(|&m| m < 250)
+ .count();
+ assert!(
+ mask_left > 0 && mask_right > 0,
+ "[10c-layer-mask] Mask stroke must cross x=256 (left={mask_left}, right={mask_right})"
+ );
+ for &(cx, cy) in diag_windows {
+ let mut changed = 0usize;
+ for y in cy.saturating_sub(32)..(cy + 32).min(DOC_H) {
+ for x in cx.saturating_sub(32)..(cx + 32).min(DOC_W) {
+ if after_mask[(y * DOC_W + x) as usize] < 250 {
+ changed += 1;
+ }
+ }
+ }
+ assert!(
+ changed > 0,
+ "[10c-layer-mask] Empty 64x64 gap at ({cx},{cy}) in layer mask!"
+ );
+ }
+
+ doc.undo();
+ renderer.sync_document(&mut doc, None).unwrap();
+ assert_eq!(
+ read_full_mask_u8(&doc, &layer_id),
+ before_mask,
+ "[10c-layer-mask] Undo must restore mask byte-for-byte"
+ );
+ doc.redo();
+ renderer.sync_document(&mut doc, None).unwrap();
+ assert_eq!(
+ read_full_mask_u8(&doc, &layer_id),
+ after_mask,
+ "[10c-layer-mask] Redo must restore mask stroke byte-for-byte"
+ );
+ renderer.tile_pool_mut().invalidate_document(&doc_id);
+ }
+
+ // ------------------------------------------------------------------------
+ // 10d. Selection clipped stroke across tile boundary
+ // ------------------------------------------------------------------------
+ {
+ let mut sel = SparseSelectionMask::new_empty(DOC_W, DOC_H);
+ let rect_mask = vec![255u8; 192 * 192];
+ sel.combine_rect(
+ RectI32::new(160, 160, 192, 192), // [160..352) x [160..352) straddling x=256
+ &rect_mask,
+ SelectionCombineMode::Replace,
+ );
+ let pts = make_diagonal_seam_points(40, 30.0, false);
+ let brush = NativeBrushConfig {
+ fg_color: [0.20, 0.72, 0.35],
+ size: 30.0,
+ opacity: 1.0,
+ hardness: 0.95,
+ spacing: 0.08,
+ ..Default::default()
+ };
+ let (_before, after) = verify_stamp_or_ribbon_parity(
+ &mut renderer,
+ "10d-selection-clipped",
+ brush,
+ &pts,
+ None,
+ false,
+ Some(sel),
+ &[(192, 192), (256, 256), (320, 320)],
+ );
+ // Pixels outside [160..352) x [160..352) MUST remain strictly un-inked (alpha == 0)
+ for &(tx, ty) in &[(136u32, 136u32), (150, 150), (362, 362), (376, 376)] {
+ let off = ((ty * DOC_W + tx) * 4) as usize;
+ assert_eq!(
+ after[off + 3],
+ 0,
+ "[10d-selection-clipped] Ink leaked outside active selection at ({tx},{ty})!"
+ );
+ }
+ }
+}
+
+// ============================================================================
+// Area 2 End-to-End Input Handoff & Navigation Interruption Tests (Headless DX12)
+// ============================================================================
+
+fn spawn_handoff_engine() -> Option<(EngineHandle, crate::ring::InputProducers, String, String)> {
+ let (handle, producers) = match EngineHandle::spawn(
+ SurfaceTarget::Headless {
+ width: 512,
+ height: 512,
+ },
+ EngineConfig {
+ doc_width: 512,
+ doc_height: 512,
+ ..Default::default()
+ },
+ ) {
+ Ok(pair) => pair,
+ Err(err) => {
+ eprintln!("Skipping headless DX12 handoff test (no DX12 adapter): {err}");
+ return None;
+ }
+ };
+
+ let (doc_id, layer_id) = {
+ let docs = handle.documents();
+ let mut mgr = docs.write();
+ let doc = make_parity_doc("handoff-doc");
+ let did = doc.id.clone();
+ let lid = doc.active_layer_id.clone().unwrap();
+ mgr.insert_and_activate(doc);
+ (did, lid)
+ };
+
+ handle.send_command(EngineCommand::SetVisible(true));
+ handle.send_command(EngineCommand::SetViewport(ViewportRect {
+ x_px: 0,
+ y_px: 0,
+ width_px: 512,
+ height_px: 512,
+ dpr: 1.0,
+ }));
+ handle.send_command(EngineCommand::SetCamera(CameraState {
+ pan_x: 256.0,
+ pan_y: 256.0,
+ zoom: 1.0,
+ rotation: 0.0,
+ flip_x: false,
+ flip_y: false,
+ }));
+ handle.send_command(EngineCommand::SetFullBrushConfig(Box::new(
+ NativeBrushConfig {
+ fg_color: [0.05, 0.05, 0.08],
+ size: 16.0,
+ hardness: 0.95,
+ spacing: 0.12,
+ stabilization: 0.0,
+ smoothing: false,
+ post_correction: 0,
+ ..Default::default()
+ },
+ )));
+ handle.send_command(EngineCommand::SyncActiveDocument);
+ std::thread::sleep(Duration::from_millis(60));
+ // Drain initial startup events
+ for _ in handle.events().try_iter() {}
+
+ Some((handle, producers, doc_id, layer_id))
+}
+
+fn wait_for_stroke_committed_count(
+ handle: &EngineHandle,
+ expected: usize,
+ timeout: Duration,
+) -> (usize, usize, usize) {
+ let mut strokes = 0usize;
+ let mut histories = 0usize;
+ let mut thumbs = 0usize;
+ let deadline = Instant::now() + timeout;
+ while Instant::now() < deadline {
+ for ev in handle.events().try_iter() {
+ match ev {
+ EngineEvent::StrokeCommitted { .. } => strokes += 1,
+ EngineEvent::HistoryChanged { .. } => histories += 1,
+ EngineEvent::ThumbnailsUpdated { .. } => thumbs += 1,
+ _ => {}
+ }
+ }
+ if strokes >= expected && histories >= expected {
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ (strokes, histories, thumbs)
+}
+
+#[test]
+fn test_wintab_winink_mouse_seamless_handoff_and_stroke_sync() {
+ let _dx12_guard = crate::lock_dx12_test();
+ let Some((handle, mut producers, doc_id, _layer_id)) = spawn_handoff_engine() else {
+ return;
+ };
+
+ let t0 = clock::now_ms();
+
+ // 1. WinTab stroke (backend = 1)
+ assert_eq!(
+ producers.wintab.push_batch(&[
+ NativeInputSample {
+ phys_x: 120.0,
+ phys_y: 120.0,
+ pressure: 0.6,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: t0,
+ buttons: 1,
+ phase: 1,
+ backend: 1,
+ },
+ NativeInputSample {
+ phys_x: 200.0,
+ phys_y: 120.0,
+ pressure: 0.8,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: t0 + 8.0,
+ buttons: 1,
+ phase: 2,
+ backend: 1,
+ },
+ NativeInputSample {
+ phys_x: 200.0,
+ phys_y: 120.0,
+ pressure: 0.0,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: t0 + 16.0,
+ buttons: 0,
+ phase: 3,
+ backend: 1,
+ },
+ ]),
+ 3
+ );
+ let (s1, h1, _) = wait_for_stroke_committed_count(&handle, 1, Duration::from_secs(3));
+ assert_eq!(s1, 1, "WinTab stroke 1 must commit once");
+ assert_eq!(
+ h1, 0,
+ "Duplicate HistoryChanged must NOT emit alongside StrokeCommitted (which already embeds history)"
+ );
+
+ // 2. Switch WinTab -> Mouse (115 ms after WinTab end — outside 100 ms WinTab CXO_SYSTEM echo window)
+ let tm = t0 + 131.0;
+ assert!(producers.nav.push(NativeNavEvent::MouseDraw {
+ phys_x: 120.0,
+ phys_y: 200.0,
+ phase: 1,
+ shift_held: false,
+ timestamp_ms: tm,
+ }));
+ assert!(producers.nav.push(NativeNavEvent::MouseDraw {
+ phys_x: 240.0,
+ phys_y: 200.0,
+ phase: 2,
+ shift_held: false,
+ timestamp_ms: tm + 8.0,
+ }));
+ assert!(producers.nav.push(NativeNavEvent::MouseDraw {
+ phys_x: 240.0,
+ phys_y: 200.0,
+ phase: 3,
+ shift_held: false,
+ timestamp_ms: tm + 16.0,
+ }));
+ let (s2, h2, _) = wait_for_stroke_committed_count(&handle, 1, Duration::from_secs(3));
+ assert_eq!(s2, 1, "Mouse stroke after WinTab must commit without dropped click");
+ assert_eq!(h2, 0);
+
+ // 3. Switch Mouse -> Windows Ink (backend = 2) -> Mouse (immediate 20ms handoff!) -> Windows Ink
+ let ti = tm + 40.0;
+ assert_eq!(
+ producers.winink.push_batch(&[
+ NativeInputSample {
+ phys_x: 120.0,
+ phys_y: 280.0,
+ pressure: 0.7,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: ti,
+ buttons: 1,
+ phase: 1,
+ backend: 2,
+ },
+ NativeInputSample {
+ phys_x: 240.0,
+ phys_y: 280.0,
+ pressure: 0.9,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: ti + 8.0,
+ buttons: 1,
+ phase: 2,
+ backend: 2,
+ },
+ NativeInputSample {
+ phys_x: 240.0,
+ phys_y: 280.0,
+ pressure: 0.0,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: ti + 16.0,
+ buttons: 0,
+ phase: 3,
+ backend: 2,
+ },
+ ]),
+ 3
+ );
+ let (s3, _, _) = wait_for_stroke_committed_count(&handle, 1, Duration::from_secs(3));
+ assert_eq!(s3, 1, "Windows Ink stroke must commit cleanly");
+
+ // Immediate Mouse click 20 ms after Windows Ink lift (must NOT be locked out for 250 ms!)
+ let tm2 = ti + 36.0;
+ assert!(producers.nav.push(NativeNavEvent::MouseDraw {
+ phys_x: 120.0,
+ phys_y: 340.0,
+ phase: 1,
+ shift_held: false,
+ timestamp_ms: tm2,
+ }));
+ assert!(producers.nav.push(NativeNavEvent::MouseDraw {
+ phys_x: 240.0,
+ phys_y: 340.0,
+ phase: 2,
+ shift_held: false,
+ timestamp_ms: tm2 + 8.0,
+ }));
+ assert!(producers.nav.push(NativeNavEvent::MouseDraw {
+ phys_x: 240.0,
+ phys_y: 340.0,
+ phase: 3,
+ shift_held: false,
+ timestamp_ms: tm2 + 16.0,
+ }));
+ let (s4, _, _) = wait_for_stroke_committed_count(&handle, 1, Duration::from_secs(3));
+ assert_eq!(s4, 1, "Mouse stroke 20 ms after Windows Ink lift must not be dropped");
+
+ // Verify all 4 strokes recorded distinct CoW history entries and async thumbnails finish
+ let history_len = {
+ let docs = handle.documents();
+ let mgr = docs.read();
+ mgr.get_document(&doc_id).unwrap().history.len()
+ };
+ assert!(
+ history_len >= 5,
+ "Expected initial entry + 4 committed strokes in CoW history, got {history_len}"
+ );
+ let thumb_deadline = Instant::now() + Duration::from_secs(3);
+ while Instant::now() < thumb_deadline && handle.perf_snapshot().async_thumbnails_completed == 0 {
+ std::thread::sleep(Duration::from_millis(15));
+ }
+ assert!(
+ handle.perf_snapshot().async_thumbnails_completed >= 1,
+ "Async thumbnail worker must produce updated layer thumbnails"
+ );
+
+ handle.shutdown();
+}
+
+#[test]
+fn test_navigation_interrupts_active_stroke_cleanly_without_spurious_resume() {
+ let _dx12_guard = crate::lock_dx12_test();
+ let Some((handle, mut producers, _doc_id, _layer_id)) = spawn_handoff_engine() else {
+ return;
+ };
+
+ let mut ts = clock::now_ms();
+ let gestures: &[(NativeNavGesture, bool)] = &[
+ (NativeNavGesture::Pan, false),
+ (NativeNavGesture::Rotate, false), // Space+Shift+Drag smooth rotation (NOT 15° snapped)
+ (NativeNavGesture::ZoomDrag, false),
+ ];
+
+ for (idx, &(gesture, snap)) in gestures.iter().enumerate() {
+ let y = 100.0 + idx as f32 * 80.0;
+ // Start an active stylus stroke
+ assert_eq!(
+ producers.wintab.push_batch(&[
+ NativeInputSample {
+ phys_x: 120.0,
+ phys_y: y,
+ pressure: 0.7,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: ts,
+ buttons: 1,
+ phase: 1,
+ backend: 1,
+ },
+ NativeInputSample {
+ phys_x: 200.0,
+ phys_y: y,
+ pressure: 0.8,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: ts + 8.0,
+ buttons: 1,
+ phase: 2,
+ backend: 1,
+ },
+ ]),
+ 2
+ );
+ std::thread::sleep(Duration::from_millis(35));
+
+ // Interrupt active stroke with navigation gesture
+ assert!(producers.nav.push(NativeNavEvent::GestureStart {
+ gesture,
+ phys_x: 200.0,
+ phys_y: y,
+ timestamp_ms: ts + 20.0,
+ }));
+ assert!(producers.nav.push(NativeNavEvent::GestureMove {
+ phys_x: 260.0,
+ phys_y: y + 40.0,
+ snap_15_deg: snap,
+ timestamp_ms: ts + 28.0,
+ }));
+ assert!(producers.nav.push(NativeNavEvent::GestureEnd {
+ timestamp_ms: ts + 36.0,
+ }));
+
+ let (committed, _, _) = wait_for_stroke_committed_count(&handle, 1, Duration::from_secs(3));
+ assert_eq!(
+ committed, 1,
+ "Active stroke must commit cleanly when {gesture:?} navigation begins"
+ );
+
+ // Trailing phase=2 move & phase=3 up AFTER navigation ends must NEVER resume or double-commit!
+ assert_eq!(
+ producers.wintab.push_batch(&[
+ NativeInputSample {
+ phys_x: 320.0,
+ phys_y: y,
+ pressure: 0.8,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: ts + 50.0,
+ buttons: 1,
+ phase: 2,
+ backend: 1,
+ },
+ NativeInputSample {
+ phys_x: 320.0,
+ phys_y: y,
+ pressure: 0.0,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: ts + 58.0,
+ buttons: 0,
+ phase: 3,
+ backend: 1,
+ },
+ ]),
+ 2
+ );
+ std::thread::sleep(Duration::from_millis(60));
+ let spurious = handle
+ .events()
+ .try_iter()
+ .filter(|e| matches!(e, EngineEvent::StrokeCommitted { .. }))
+ .count();
+ assert_eq!(
+ spurious, 0,
+ "Stroke must NEVER resume spuriously after {gesture:?} ends"
+ );
+ ts += 200.0;
+ }
+
+ // Mouse Wheel zoom mid-stroke must ALSO commit the active stroke cleanly!
+ assert_eq!(
+ producers.winink.push_batch(&[
+ NativeInputSample {
+ phys_x: 150.0,
+ phys_y: 350.0,
+ pressure: 0.75,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: ts,
+ buttons: 1,
+ phase: 1,
+ backend: 2,
+ },
+ NativeInputSample {
+ phys_x: 240.0,
+ phys_y: 350.0,
+ pressure: 0.85,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: ts + 8.0,
+ buttons: 1,
+ phase: 2,
+ backend: 2,
+ },
+ ]),
+ 2
+ );
+ std::thread::sleep(Duration::from_millis(35));
+
+ assert!(producers.nav.push(NativeNavEvent::Wheel {
+ phys_x: 240.0,
+ phys_y: 350.0,
+ delta_x: 0.0,
+ delta_y: -100.0,
+ ctrl_held: false,
+ shift_held: false,
+ timestamp_ms: ts + 20.0,
+ }));
+ let (wheel_committed, _, _) =
+ wait_for_stroke_committed_count(&handle, 1, Duration::from_secs(3));
+ assert_eq!(
+ wheel_committed, 1,
+ "Mouse Wheel zoom mid-stroke must commit the active stroke cleanly"
+ );
+
+ // Stylus phase=1 while Space bit (0x0400) is held must NEVER paint a stray dot!
+ assert_eq!(
+ producers.wintab.push_batch(&[
+ NativeInputSample {
+ phys_x: 256.0,
+ phys_y: 256.0,
+ pressure: 0.9,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: ts + 100.0,
+ buttons: 1 | 0x0400, // Space held
+ phase: 1,
+ backend: 1,
+ },
+ NativeInputSample {
+ phys_x: 280.0,
+ phys_y: 256.0,
+ pressure: 0.0,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: ts + 116.0,
+ buttons: 0x0400,
+ phase: 3,
+ backend: 1,
+ },
+ ]),
+ 2
+ );
+ std::thread::sleep(Duration::from_millis(60));
+ let stray = handle
+ .events()
+ .try_iter()
+ .filter(|e| matches!(e, EngineEvent::StrokeCommitted { .. }))
+ .count();
+ assert_eq!(stray, 0, "Stylus down while Space is held must never paint a stray stroke");
+
+ // Verify NotifySurfaceInvalidated emits ViewportInvalidated cleanly
+ handle.send_command(EngineCommand::NotifySurfaceInvalidated);
+ let mut got_invalidated = false;
+ let deadline = Instant::now() + Duration::from_secs(2);
+ while Instant::now() < deadline && !got_invalidated {
+ for ev in handle.events().try_iter() {
+ if matches!(ev, EngineEvent::ViewportInvalidated) {
+ got_invalidated = true;
+ break;
+ }
+ }
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ assert!(
+ got_invalidated,
+ "NotifySurfaceInvalidated must emit ViewportInvalidated to trigger UI re-measurement"
+ );
+
+ handle.shutdown();
+}
diff --git a/crates/ink-engine/src/collab/mod.rs b/crates/ink-engine/src/collab/mod.rs
index fd7995b..6b83c70 100644
--- a/crates/ink-engine/src/collab/mod.rs
+++ b/crates/ink-engine/src/collab/mod.rs
@@ -312,6 +312,13 @@ pub fn apply_tile_delta_packet(
TILE_CODEC_LZ4 => {
let raw = lz4_flex::block::decompress(body, expected_len)
.map_err(|e| format!("LZ4 tile decompress failed: {e}"))?;
+ if raw.len() != expected_len {
+ return Err(format!(
+ "LZ4 tile size mismatch: got {}, expected {}",
+ raw.len(),
+ expected_len
+ ));
+ }
let td = TileData::from_raw_auto_compact(tile_fmt, TileKind::Raster, raw);
if td.is_empty(scratch) {
layer.grid.remove_tile(coord);
@@ -338,18 +345,37 @@ pub fn apply_tile_delta_packet(
4 => (rw * 4, 1024usize, rx * 4),
_ => return Err("Unsupported subrect format".to_string()),
};
- let sub_raw = lz4_flex::block::decompress(&body[TILE_SUBRECT_HEADER_BYTES..], row_bytes * rh)
+ let expected_sub = row_bytes * rh;
+ let sub_raw = lz4_flex::block::decompress(&body[TILE_SUBRECT_HEADER_BYTES..], expected_sub)
.map_err(|e| format!("SUBRECT_LZ4 decompress failed: {e}"))?;
+ if sub_raw.len() != expected_sub {
+ return Err(format!(
+ "SUBRECT_LZ4 size mismatch: got {}, expected {}",
+ sub_raw.len(),
+ expected_sub
+ ));
+ }
let mut base_raw = match layer.grid.tiles.get(&coord) {
- Some(t) => match tile_fmt {
- TileFormat::Monochrome1Bit | TileFormat::Grayscale8Bit => {
+ Some(t) => {
+ if t.format == tile_fmt {
t.materialize_raw(scratch)?
+ } else {
+ let rgba = t.to_rgba8(scratch, false)?;
+ crate::tiles::convert_tile_bytes(
+ &rgba,
+ TileFormat::Color32Bit,
+ tile_fmt,
+ layer.meta.mono_threshold.unwrap_or(128),
+ false,
+ )
}
- _ => t.to_rgba8(scratch, false)?,
- },
+ }
None => vec![0u8; expected_len],
};
+ if base_raw.len() != expected_len {
+ base_raw.resize(expected_len, 0);
+ }
for r in 0..rh {
let dst_off = (ry + r) * stride + col_off;
let src_off = r * row_bytes;
@@ -677,14 +703,19 @@ pub struct RemotePeerDraftManager {
dab_bgl: wgpu::BindGroupLayout,
dab_pipeline: wgpu::RenderPipeline,
dab_uniform_buf: wgpu::Buffer,
+ dab_uniform_cap_slots: usize,
+ dab_bg: wgpu::BindGroup,
dab_inst_buf: wgpu::Buffer,
dab_inst_cap: usize,
proj_bgl: wgpu::BindGroupLayout,
proj_pipeline: wgpu::RenderPipeline,
proj_uniform_buf: wgpu::Buffer,
+ proj_uniform_cap_slots: usize,
+ proj_bg: wgpu::BindGroup,
proj_inst_buf: wgpu::Buffer,
proj_inst_cap: usize,
+ uniform_slot_align: u32,
sampler: wgpu::Sampler,
sessions: HashMap<(String, String), PeerStrokeDraft>,
@@ -725,6 +756,8 @@ impl RemotePeerDraftManager {
free_slots.push(capacity - 1 - i);
}
+ let uniform_slot_align = device.limits().min_uniform_buffer_offset_alignment.max(256);
+
let dab_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("ink-collab-dab-bgl"),
entries: &[wgpu::BindGroupLayoutEntry {
@@ -732,8 +765,10 @@ impl RemotePeerDraftManager {
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
- has_dynamic_offset: false,
- min_binding_size: None,
+ has_dynamic_offset: true,
+ min_binding_size: std::num::NonZeroU64::new(
+ std::mem::size_of::<RemoteDabUniforms>() as u64,
+ ),
},
count: None,
}],
@@ -798,12 +833,27 @@ impl RemotePeerDraftManager {
multiview_mask: None,
cache: None,
});
+ let dab_uniform_cap_slots = 64usize;
let dab_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("ink-collab-dab-uniforms"),
- size: std::mem::size_of::<RemoteDabUniforms>() as u64,
+ size: (dab_uniform_cap_slots as u64) * (uniform_slot_align as u64),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
+ let dab_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-collab-dab-bg"),
+ layout: &dab_bgl,
+ entries: &[wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &dab_uniform_buf,
+ offset: 0,
+ size: std::num::NonZeroU64::new(
+ std::mem::size_of::<RemoteDabUniforms>() as u64,
+ ),
+ }),
+ }],
+ });
let dab_inst_cap = 2048usize;
let dab_inst_buf = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("ink-collab-dab-insts"),
@@ -820,8 +870,10 @@ impl RemotePeerDraftManager {
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
- has_dynamic_offset: false,
- min_binding_size: None,
+ has_dynamic_offset: true,
+ min_binding_size: std::num::NonZeroU64::new(
+ std::mem::size_of::<RemoteProjectUniforms>() as u64,
+ ),
},
count: None,
},
@@ -898,9 +950,10 @@ impl RemotePeerDraftManager {
multiview_mask: None,
cache: None,
});
+ let proj_uniform_cap_slots = 32usize;
let proj_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("ink-collab-proj-uniforms"),
- size: std::mem::size_of::<RemoteProjectUniforms>() as u64,
+ size: (proj_uniform_cap_slots as u64) * (uniform_slot_align as u64),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
@@ -917,6 +970,30 @@ impl RemotePeerDraftManager {
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
+ let proj_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-collab-proj-bg"),
+ layout: &proj_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &proj_uniform_buf,
+ offset: 0,
+ size: std::num::NonZeroU64::new(
+ std::mem::size_of::<RemoteProjectUniforms>() as u64,
+ ),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(&atlas_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::Sampler(&sampler),
+ },
+ ],
+ });
Self {
atlas_tex,
@@ -927,13 +1004,18 @@ impl RemotePeerDraftManager {
dab_bgl,
dab_pipeline,
dab_uniform_buf,
+ dab_uniform_cap_slots,
+ dab_bg,
dab_inst_buf,
dab_inst_cap,
proj_bgl,
proj_pipeline,
proj_uniform_buf,
+ proj_uniform_cap_slots,
+ proj_bg,
proj_inst_buf,
proj_inst_cap,
+ uniform_slot_align,
sampler,
sessions: HashMap::new(),
}
@@ -1072,7 +1154,20 @@ impl RemotePeerDraftManager {
}
}
+ // Pack all binned tiles' instances & uniforms into ONE encoder + ONE queue.submit!
+ struct TileStampJob {
+ slot: u32,
+ is_new: bool,
+ coord: TileCoord,
+ inst_start: usize,
+ inst_count: u32,
+ }
+ let mut jobs: Vec<TileStampJob> = Vec::with_capacity(bins.len());
+ let mut packed_insts: Vec<RemoteDabInst> = Vec::new();
for (coord, list) in bins {
+ if list.is_empty() {
+ continue;
+ }
let (slot, is_new) = if let Some(&s) = sess.tile_slots.get(&coord) {
(s, false)
} else if let Some(s) = self.free_slots.pop() {
@@ -1081,67 +1176,103 @@ impl RemotePeerDraftManager {
} else {
continue;
};
+ let inst_start = packed_insts.len();
+ let inst_count = list.len() as u32;
+ packed_insts.extend_from_slice(&list);
+ jobs.push(TileStampJob {
+ slot,
+ is_new,
+ coord,
+ inst_start,
+ inst_count,
+ });
+ }
+ if jobs.is_empty() {
+ return;
+ }
- if list.len() > self.dab_inst_cap {
- self.dab_inst_cap = list.len().next_power_of_two();
- self.dab_inst_buf = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("ink-collab-dab-insts"),
- size: (self.dab_inst_cap * std::mem::size_of::<RemoteDabInst>()) as u64,
- usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
- mapped_at_creation: false,
- });
- }
- queue.write_buffer(&self.dab_inst_buf, 0, bytemuck::cast_slice(&list));
-
- let u = RemoteDabUniforms {
- tile_origin_doc: [
- (coord.tx * TILE_SIZE as i32) as f32,
- (coord.ty * TILE_SIZE as i32) as f32,
- ],
- _pad: [0.0, 0.0],
- };
- queue.write_buffer(&self.dab_uniform_buf, 0, bytemuck::bytes_of(&u));
-
- let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ if packed_insts.len() > self.dab_inst_cap {
+ self.dab_inst_cap = packed_insts.len().next_power_of_two();
+ self.dab_inst_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-collab-dab-insts"),
+ size: (self.dab_inst_cap * std::mem::size_of::<RemoteDabInst>()) as u64,
+ usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ }
+ queue.write_buffer(&self.dab_inst_buf, 0, bytemuck::cast_slice(&packed_insts));
+
+ let stride = self.uniform_slot_align as usize;
+ let u_size = std::mem::size_of::<RemoteDabUniforms>();
+ if jobs.len() > self.dab_uniform_cap_slots {
+ self.dab_uniform_cap_slots = jobs.len().next_power_of_two();
+ self.dab_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-collab-dab-uniforms"),
+ size: (self.dab_uniform_cap_slots as u64) * (self.uniform_slot_align as u64),
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ self.dab_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("ink-collab-dab-bg"),
layout: &self.dab_bgl,
entries: &[wgpu::BindGroupEntry {
binding: 0,
- resource: self.dab_uniform_buf.as_entire_binding(),
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.dab_uniform_buf,
+ offset: 0,
+ size: std::num::NonZeroU64::new(u_size as u64),
+ }),
}],
});
+ }
+ let mut uniform_staging = vec![0u8; jobs.len() * stride];
+ for (idx, job) in jobs.iter().enumerate() {
+ let u = RemoteDabUniforms {
+ tile_origin_doc: [
+ (job.coord.tx * TILE_SIZE as i32) as f32,
+ (job.coord.ty * TILE_SIZE as i32) as f32,
+ ],
+ _pad: [0.0, 0.0],
+ };
+ let dst = idx * stride;
+ uniform_staging[dst..dst + u_size].copy_from_slice(bytemuck::bytes_of(&u));
+ }
+ queue.write_buffer(&self.dab_uniform_buf, 0, &uniform_staging);
- let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-collab-dab-enc"),
- });
- {
- let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
- label: Some("ink-collab-dab-pass"),
- color_attachments: &[Some(wgpu::RenderPassColorAttachment {
- view: &self.slice_views[slot as usize],
- depth_slice: None,
- resolve_target: None,
- ops: wgpu::Operations {
- load: if is_new {
- wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT)
- } else {
- wgpu::LoadOp::Load
- },
- store: wgpu::StoreOp::Store,
+ let inst_stride = std::mem::size_of::<RemoteDabInst>() as u64;
+ let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-collab-dab-enc"),
+ });
+ for (idx, job) in jobs.iter().enumerate() {
+ let dyn_off = (idx as u32) * self.uniform_slot_align;
+ let byte_start = (job.inst_start as u64) * inst_stride;
+ let byte_end = byte_start + (job.inst_count as u64) * inst_stride;
+ let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("ink-collab-dab-pass"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &self.slice_views[job.slot as usize],
+ depth_slice: None,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: if job.is_new {
+ wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT)
+ } else {
+ wgpu::LoadOp::Load
},
- })],
- depth_stencil_attachment: None,
- timestamp_writes: None,
- occlusion_query_set: None,
- multiview_mask: None,
- });
- pass.set_pipeline(&self.dab_pipeline);
- pass.set_bind_group(0, &bg, &[]);
- pass.set_vertex_buffer(0, self.dab_inst_buf.slice(..));
- pass.draw(0..6, 0..list.len() as u32);
- }
- queue.submit(Some(enc.finish()));
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ multiview_mask: None,
+ });
+ pass.set_pipeline(&self.dab_pipeline);
+ pass.set_bind_group(0, &self.dab_bg, &[dyn_off]);
+ pass.set_vertex_buffer(0, self.dab_inst_buf.slice(byte_start..byte_end));
+ pass.draw(0..6, 0..job.inst_count);
}
+ queue.submit(Some(enc.finish()));
}
/// Transitions a finished remote stroke into zero-flicker handoff until its committed tile deltas arrive.
@@ -1206,12 +1337,13 @@ impl RemotePeerDraftManager {
}
}
- /// Composites all active remote peer GPU draft strokes directly onto `target_view` at 120+ FPS!
+ /// Encodes all active remote peer GPU draft strokes directly into `encoder` (zero extra `queue.submit`!).
#[allow(clippy::too_many_arguments)]
- pub fn render_drafts(
+ pub fn encode_drafts(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
+ encoder: &mut wgpu::CommandEncoder,
doc_w: u32,
doc_h: u32,
camera: &CameraState,
@@ -1241,57 +1373,63 @@ impl RemotePeerDraftManager {
return;
}
- let _ = self.capacity;
+ let _ = (self.capacity, &self.atlas_tex);
+ let mut packed_insts: Vec<RemoteTileInst> = Vec::new();
+ let mut draw_ranges: Vec<(usize, u32, f32)> = Vec::new();
for sess in self.sessions.values() {
+ let _ = (&sess.peer_id, &sess.stroke_id);
if sess.tile_slots.is_empty() {
continue;
}
- let insts: Vec<RemoteTileInst> = sess
- .tile_slots
- .iter()
- .map(|(&coord, &slot)| RemoteTileInst {
+ let start = packed_insts.len();
+ for (&coord, &slot) in &sess.tile_slots {
+ packed_insts.push(RemoteTileInst {
tile_origin_doc: [
(coord.tx * TILE_SIZE as i32) as f32,
(coord.ty * TILE_SIZE as i32) as f32,
],
slot_f: slot as f32,
_pad: 0.0,
- })
- .collect();
-
- if insts.len() > self.proj_inst_cap {
- self.proj_inst_cap = insts.len().next_power_of_two();
- self.proj_inst_buf = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("ink-collab-proj-insts"),
- size: (self.proj_inst_cap * std::mem::size_of::<RemoteTileInst>()) as u64,
- usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
- mapped_at_creation: false,
});
}
- queue.write_buffer(&self.proj_inst_buf, 0, bytemuck::cast_slice(&insts));
-
- let u = RemoteProjectUniforms {
- viewport_size_phys: [vp_w as f32, vp_h as f32],
- doc_size: [doc_w as f32, doc_h as f32],
- pan_css: [camera.pan_x, camera.pan_y],
- zoom: camera.zoom.max(0.01),
- rotation_rad: camera.rotation.to_radians(),
- flip: [
- if camera.flip_x { -1.0 } else { 1.0 },
- if camera.flip_y { -1.0 } else { 1.0 },
- ],
- dpr: dpr.max(0.05),
- opacity: sess.opacity,
- };
- queue.write_buffer(&self.proj_uniform_buf, 0, bytemuck::bytes_of(&u));
+ draw_ranges.push((start, (packed_insts.len() - start) as u32, sess.opacity));
+ }
+ if draw_ranges.is_empty() {
+ return;
+ }
- let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ if packed_insts.len() > self.proj_inst_cap {
+ self.proj_inst_cap = packed_insts.len().next_power_of_two();
+ self.proj_inst_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-collab-proj-insts"),
+ size: (self.proj_inst_cap * std::mem::size_of::<RemoteTileInst>()) as u64,
+ usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ }
+ queue.write_buffer(&self.proj_inst_buf, 0, bytemuck::cast_slice(&packed_insts));
+
+ let stride = self.uniform_slot_align as usize;
+ let u_size = std::mem::size_of::<RemoteProjectUniforms>();
+ if draw_ranges.len() > self.proj_uniform_cap_slots {
+ self.proj_uniform_cap_slots = draw_ranges.len().next_power_of_two();
+ self.proj_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-collab-proj-uniforms"),
+ size: (self.proj_uniform_cap_slots as u64) * (self.uniform_slot_align as u64),
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ self.proj_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("ink-collab-proj-bg"),
layout: &self.proj_bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
- resource: self.proj_uniform_buf.as_entire_binding(),
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.proj_uniform_buf,
+ offset: 0,
+ size: std::num::NonZeroU64::new(u_size as u64),
+ }),
},
wgpu::BindGroupEntry {
binding: 1,
@@ -1303,34 +1441,87 @@ impl RemotePeerDraftManager {
},
],
});
+ }
+ let mut uniform_staging = vec![0u8; draw_ranges.len() * stride];
+ for (idx, &(_, _, opacity)) in draw_ranges.iter().enumerate() {
+ let u = RemoteProjectUniforms {
+ viewport_size_phys: [vp_w as f32, vp_h as f32],
+ doc_size: [doc_w as f32, doc_h as f32],
+ pan_css: [camera.pan_x, camera.pan_y],
+ zoom: camera.zoom.max(0.01),
+ rotation_rad: camera.rotation.to_radians(),
+ flip: [
+ if camera.flip_x { -1.0 } else { 1.0 },
+ if camera.flip_y { -1.0 } else { 1.0 },
+ ],
+ dpr: dpr.max(0.05),
+ opacity,
+ };
+ let dst = idx * stride;
+ uniform_staging[dst..dst + u_size].copy_from_slice(bytemuck::bytes_of(&u));
+ }
+ queue.write_buffer(&self.proj_uniform_buf, 0, &uniform_staging);
+
+ let inst_stride = std::mem::size_of::<RemoteTileInst>() as u64;
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("ink-collab-proj-pass"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: target_view,
+ depth_slice: None,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Load,
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ multiview_mask: None,
+ });
+ pass.set_pipeline(&self.proj_pipeline);
+ for (idx, &(start, count, _)) in draw_ranges.iter().enumerate() {
+ let dyn_off = (idx as u32) * self.uniform_slot_align;
+ let byte_start = (start as u64) * inst_stride;
+ let byte_end = byte_start + (count as u64) * inst_stride;
+ pass.set_bind_group(0, &self.proj_bg, &[dyn_off]);
+ pass.set_vertex_buffer(0, self.proj_inst_buf.slice(byte_start..byte_end));
+ pass.draw(0..6, 0..count);
+ }
+ }
- let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-collab-proj-enc"),
- });
- {
- let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
- label: Some("ink-collab-proj-pass"),
- color_attachments: &[Some(wgpu::RenderPassColorAttachment {
- view: target_view,
- depth_slice: None,
- resolve_target: None,
- ops: wgpu::Operations {
- load: wgpu::LoadOp::Load,
- store: wgpu::StoreOp::Store,
- },
- })],
- depth_stencil_attachment: None,
- timestamp_writes: None,
- occlusion_query_set: None,
- multiview_mask: None,
- });
- pass.set_pipeline(&self.proj_pipeline);
- pass.set_bind_group(0, &bg, &[]);
- pass.set_vertex_buffer(0, self.proj_inst_buf.slice(..));
- pass.draw(0..6, 0..insts.len() as u32);
- }
- queue.submit(Some(enc.finish()));
- let _ = (&sess.peer_id, &sess.stroke_id, &self.atlas_tex);
+ /// Composites all active remote peer GPU draft strokes directly onto `target_view` at 120+ FPS!
+ #[allow(clippy::too_many_arguments)]
+ pub fn render_drafts(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ doc_w: u32,
+ doc_h: u32,
+ camera: &CameraState,
+ vp_w: u32,
+ vp_h: u32,
+ dpr: f32,
+ target_view: &wgpu::TextureView,
+ ) {
+ if self.sessions.is_empty() || vp_w == 0 || vp_h == 0 {
+ return;
}
+ let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-collab-proj-enc"),
+ });
+ self.encode_drafts(
+ device,
+ queue,
+ &mut enc,
+ doc_w,
+ doc_h,
+ camera,
+ vp_w,
+ vp_h,
+ dpr,
+ target_view,
+ );
+ queue.submit(Some(enc.finish()));
}
}
diff --git a/crates/ink-engine/src/compositor/layer_tree.rs b/crates/ink-engine/src/compositor/layer_tree.rs
index c03073e..c9649f4 100644
--- a/crates/ink-engine/src/compositor/layer_tree.rs
+++ b/crates/ink-engine/src/compositor/layer_tree.rs
@@ -4,6 +4,7 @@
//! Direct Rust port of `src/utils/compositor/layerTree.ts` with animation cel visibility
//! override support and index-based tree nodes.
+use super::parse_layer_styles;
use crate::document::{BlendMode, LayerNode, LayerType};
use std::collections::{HashMap, HashSet};
@@ -83,6 +84,19 @@ pub fn layer_has_active_mask(layer: &LayerNode) -> bool {
(layer.grid.has_mask || layer.meta.has_mask) && layer.meta.mask_enabled.unwrap_or(true)
}
+/// Returns true ONLY when a folder-like node truly composites as non-isolated `PassThrough`
+/// (unmasked, unstyled, `opacity == 1.0`, and `blend_mode == PassThrough`).
+/// Any folder with a mask, active styles, or `opacity < 1.0` MUST be isolated so its children
+/// composite as a group and then blend onto the backdrop with `Normal`.
+#[inline]
+pub fn folder_is_true_pass_through(layer: &LayerNode) -> bool {
+ layer.meta.layer_type.is_folder_like()
+ && layer.meta.blend_mode == BlendMode::PassThrough
+ && layer.meta.opacity >= 0.999
+ && !layer_has_active_mask(layer)
+ && !parse_layer_styles(layer.meta.styles.as_ref()).has_active()
+}
+
/// Builds a hierarchical top-to-bottom tree from InkStudio's flat top-to-bottom `layers` slice.
pub fn build_layer_tree(layers: &[LayerNode]) -> Vec<LayerTreeNode> {
let id_to_idx: HashMap<&str, usize> = layers
@@ -193,10 +207,8 @@ pub fn flatten_layer_tree_to_units(
continue;
}
- let has_folder_mask = layer_has_active_mask(base_layer);
if base_layer.meta.layer_type == LayerType::Folder
- && base_layer.meta.blend_mode == BlendMode::PassThrough
- && !has_folder_mask
+ && folder_is_true_pass_through(base_layer)
&& group.clipped_nodes.is_empty()
{
let nested = flatten_layer_tree_to_units(
@@ -228,6 +240,39 @@ pub fn flatten_layer_tree_to_units(
/// Returns true if a compositing unit is strictly Porter-Duff source-over associative with
/// respect to the backdrop below it (safe to pre-bake onto transparent target and composite
/// with `Normal` blend mode).
+fn subtree_is_normal_associative(
+ node: &LayerTreeNode,
+ layers: &[LayerNode],
+ cel_overrides: &HashMap<String, bool>,
+) -> bool {
+ let Some(layer) = layers.get(node.layer_index) else {
+ return true;
+ };
+ if !is_node_visible(layer, cel_overrides) || layer.meta.opacity <= 0.001 {
+ return true;
+ }
+ if layer.meta.layer_type == LayerType::Adjustment {
+ return false;
+ }
+ if !matches!(
+ layer.meta.blend_mode,
+ BlendMode::Normal | BlendMode::PassThrough
+ ) {
+ return false;
+ }
+ // Only true non-isolated PassThrough folders allow inner blend modes / adjustments
+ // to interact with the backdrop below. Masked, styled, or translucent PassThrough
+ // folders are isolated and composite with Normal -> strictly associative!
+ if folder_is_true_pass_through(layer) {
+ for child in &node.children {
+ if !subtree_is_normal_associative(child, layers, cel_overrides) {
+ return false;
+ }
+ }
+ }
+ true
+}
+
pub fn is_unit_normal_associative(
unit: &CompositingUnit,
layers: &[LayerNode],
@@ -239,35 +284,23 @@ pub fn is_unit_normal_associative(
if base_layer.meta.layer_type == LayerType::Adjustment {
return false;
}
- if base_layer.meta.layer_type.is_folder_like() {
- return matches!(
- base_layer.meta.blend_mode,
- BlendMode::Normal | BlendMode::PassThrough
- );
- }
if !matches!(
base_layer.meta.blend_mode,
BlendMode::Normal | BlendMode::PassThrough
) {
return false;
}
- for cn in &unit.group.clipped_nodes {
- let Some(cl) = layers.get(cn.layer_index) else {
- continue;
- };
- if !is_node_visible(cl, cel_overrides)
- || cl.meta.opacity <= 0.001
- || cl.meta.layer_type.is_folder_like()
- {
- continue;
- }
- if !matches!(
- cl.meta.blend_mode,
- BlendMode::Normal | BlendMode::PassThrough
- ) {
- return false;
+ if folder_is_true_pass_through(base_layer) {
+ for child in &unit.group.base_node.children {
+ if !subtree_is_normal_associative(child, layers, cel_overrides) {
+ return false;
+ }
}
}
+ // Because clipped children are composited onto an isolated clip group containing `base`
+ // using `source-atop` and then composited onto `dst` once with `base`'s blend mode,
+ // a clipping chain with Normal/PassThrough base is associative even when clipped children
+ // use non-Normal blend modes or Adjustment layers!
true
}
@@ -282,15 +315,6 @@ pub fn can_single_unit_bake_with_blend_mode(
if base_layer.meta.layer_type == LayerType::Adjustment {
return None;
}
- if base_layer.meta.layer_type.is_folder_like() {
- if !matches!(
- base_layer.meta.blend_mode,
- BlendMode::Normal | BlendMode::PassThrough
- ) {
- return Some(base_layer.meta.blend_mode);
- }
- return None;
- }
let has_visible_clipped = unit.group.clipped_nodes.iter().any(|cn| {
layers.get(cn.layer_index).is_some_and(|cl| {
is_node_visible(cl, cel_overrides)
@@ -298,12 +322,22 @@ pub fn can_single_unit_bake_with_blend_mode(
&& !cl.meta.layer_type.is_folder_like()
})
});
- if !has_visible_clipped
- && !matches!(
+ if has_visible_clipped {
+ return None;
+ }
+ if base_layer.meta.layer_type.is_folder_like() {
+ if !matches!(
base_layer.meta.blend_mode,
BlendMode::Normal | BlendMode::PassThrough
- )
- {
+ ) {
+ return Some(base_layer.meta.blend_mode);
+ }
+ return None;
+ }
+ if !matches!(
+ base_layer.meta.blend_mode,
+ BlendMode::Normal | BlendMode::PassThrough
+ ) {
return Some(base_layer.meta.blend_mode);
}
None
diff --git a/crates/ink-engine/src/compositor/lut.rs b/crates/ink-engine/src/compositor/lut.rs
index 1483417..f7c8668 100644
--- a/crates/ink-engine/src/compositor/lut.rs
+++ b/crates/ink-engine/src/compositor/lut.rs
@@ -453,10 +453,13 @@ pub fn build_adjustment_lut_rgba8(adj: &ParsedAdjustment) -> (u32, [u8; 1024]) {
}
}
+static NEXT_LUT_VIEW_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
+
/// GPU 256×1 `Rgba8Unorm` LUT texture cache keyed per adjustment layer ID & content hash.
pub struct CachedLutEntry {
pub texture: wgpu::Texture,
pub view: wgpu::TextureView,
+ pub view_id: u64,
pub hash: u64,
pub adj_mode: u32,
}
@@ -505,6 +508,7 @@ impl AdjustmentLutCache {
CachedLutEntry {
texture,
view,
+ view_id: NEXT_LUT_VIEW_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
hash: u64::MAX,
adj_mode: 0,
},
@@ -543,6 +547,10 @@ impl AdjustmentLutCache {
self.entries.get(layer_id).map(|e| &e.view)
}
+ pub fn get_view_with_id(&self, layer_id: &str) -> Option<(&wgpu::TextureView, u64)> {
+ self.entries.get(layer_id).map(|e| (&e.view, e.view_id))
+ }
+
pub fn retain_layers(&mut self, valid_ids: &std::collections::HashSet<&str>) {
self.entries.retain(|k, _| valid_ids.contains(k.as_str()));
}
diff --git a/crates/ink-engine/src/compositor/renderer.rs b/crates/ink-engine/src/compositor/renderer.rs
index baa09f4..5083ebc 100644
--- a/crates/ink-engine/src/compositor/renderer.rs
+++ b/crates/ink-engine/src/compositor/renderer.rs
@@ -13,23 +13,27 @@
use super::frame_geometry::{build_frame_border_triangles, triangulate_polygon};
use super::layer_tree::{
- build_layer_tree, flatten_layer_tree_to_units, group_tree_nodes_for_compositing,
- is_node_visible, layer_has_active_mask, AboveSliceStrategy, CompositingUnit, LayerTreeNode,
- TreeNodeRenderGroup,
+ build_layer_tree, flatten_layer_tree_to_units, folder_is_true_pass_through,
+ group_tree_nodes_for_compositing, is_node_visible, layer_has_active_mask, AboveSliceStrategy,
+ CompositingUnit, LayerTreeNode, TreeNodeRenderGroup,
};
use super::lut::{parse_adjustment_data, AdjustmentLutCache, ParsedAdjustment};
use super::shaders::{
- blend_mode_needs_backdrop, blend_mode_to_code, build_blit_shader_wgsl,
- build_layer_tile_shader_wgsl, build_live_stroke_merge_wgsl, ADJUSTMENT_SHADER_WGSL,
+ blend_mode_needs_backdrop, blend_mode_to_code, build_adjustment_shader_wgsl,
+ build_blit_shader_wgsl, build_layer_tile_shader_wgsl, build_live_stroke_merge_wgsl,
FRAME_POLY_SHADER_WGSL, IMPASTO_HEIGHT_PROJECT_WGSL, IMPASTO_LIGHTING_WGSL,
LAYER_STYLES_COMPOSITE_WGSL, LIVE_DAB_VIEWPORT_WGSL, SEPARABLE_ALPHA_BLUR_WGSL,
- SPARSE_STROKE_PROJECT_WGSL, VIEWPORT_PRESENT_WGSL,
+ SPARSE_MASK_PROJECT_WGSL, SPARSE_STROKE_PROJECT_WGSL, STROKE_SDF_HORIZ_WGSL,
+ STROKE_SDF_VERT_WGSL, VIEWPORT_PRESENT_WGSL,
};
use super::stack_cache::{
calculate_visible_doc_bounds, doc_bounds_to_scissor, hash_camera_and_viewport,
- select_lod_for_zoom, DocBounds, Fnv1a64, LayerStackCacheTracker, ScissorRect, StackCacheStats,
+ hash_compositing_unit, select_lod_for_zoom, DocBounds, Fnv1a64, LayerStackCacheTracker,
+ ScissorRect, StackCacheStats,
+};
+use super::targets::{
+ CompositorTargets, DocMaskCache, DocMaskSig, StyledLayerCache, SurfaceRgba16F, SurfaceRgba8,
};
-use super::targets::{CompositorTargets, DocMaskCache, StyledLayerCache, SurfaceRgba16F};
use super::{
hex_to_rgb_f32, parse_layer_styles, CompositorDisplayConfig, FlattenOptions, OnionSkinFrame,
ParsedLayerStyles, SoftProofConfig,
@@ -39,7 +43,10 @@ use crate::document::{
BlendMode, CanvasColorMode, CanvasDimensions, Document, ExpressionColor, ImpastoLayerLight,
LayerNode, LayerType, ToneDensityType, ToneDotShape,
};
-use crate::memory::{GpuTileKey, GpuTilePool, ScratchBackend};
+use crate::memory::{
+ ensure_grid_lod_tile_recursive, regenerate_grid_lods_batched, uniform_solid_color_for_lod_tile,
+ GpuTileKey, GpuTilePool, ScratchBackend,
+};
use crate::stroke::DabInstance;
use crate::tiles::{TileCoord, TILE_SIZE};
use crate::types::CameraState;
@@ -88,13 +95,13 @@ struct LayerTileUniforms {
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
-struct TileInstanceGpu {
- tile_origin_doc: [f32; 2],
- tile_size_doc: [f32; 2],
- atlas_slice: i32,
- mask_slice: i32,
- mask_default: f32,
- _pad: f32,
+pub(crate) struct TileInstanceGpu {
+ pub(crate) tile_origin_doc: [f32; 2],
+ pub(crate) tile_size_doc: [f32; 2],
+ pub(crate) atlas_slice: i32,
+ pub(crate) mask_slice: i32,
+ pub(crate) mask_default: f32,
+ pub(crate) _pad: f32,
}
#[repr(C)]
@@ -126,6 +133,7 @@ struct AdjustmentUniforms {
cb_shadows: [f32; 4],
cb_midtones: [f32; 4],
cb_highlights: [f32; 4],
+ blend_flags: [u32; 4],
}
#[repr(C)]
@@ -208,6 +216,16 @@ struct SparseTileInst {
tile_span: f32,
}
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Pod, Zeroable)]
+struct ImpastoTileInst {
+ tile_origin_doc: [f32; 2],
+ tile_span: f32,
+ slot_center: i32,
+ neighbors_cardinal: [i32; 4], // (L, R, T, B)
+ neighbors_diag: [i32; 4], // (TL, TR, BL, BR)
+}
+
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct ImpastoLightUniforms {
@@ -242,7 +260,7 @@ struct LiveStrokeMergeUniforms {
// Surface addressing & per-frame staging arenas (zero per-pass buffer allocs)
// ============================================================================
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum SurfaceId {
FinalScene,
BackdropScratch,
@@ -258,6 +276,9 @@ enum SurfaceId {
StyleBlurTmp,
StyleShadowBlur,
StyleGlowBlur,
+ StyleStrokeDilateTmp,
+ StyleStrokeDilate,
+ StyleCompositeOut,
ImpastoColorScratch,
ImpastoLitScratch,
}
@@ -265,19 +286,58 @@ enum SurfaceId {
fn get_surface(targets: &CompositorTargets, id: SurfaceId) -> &SurfaceRgba16F {
match id {
SurfaceId::FinalScene => &targets.final_scene,
- SurfaceId::BackdropScratch => &targets.backdrop_scratch,
- SurfaceId::BelowCache => &targets.below_active_cache,
- SurfaceId::AboveCache => &targets.above_active_cache,
- SurfaceId::ActiveUnit => &targets.active_unit_surface,
- SurfaceId::ActiveBase => &targets.active_layer_base_surface,
- SurfaceId::LiveStroke => &targets.live_stroke_surface,
+ SurfaceId::BackdropScratch => targets
+ .backdrop_scratch
+ .as_ref()
+ .expect("backdrop_scratch ensured"),
+ SurfaceId::BelowCache => targets
+ .below_active_cache
+ .as_ref()
+ .expect("below_active_cache ensured"),
+ SurfaceId::AboveCache => targets
+ .above_active_cache
+ .as_ref()
+ .expect("above_active_cache ensured"),
+ SurfaceId::ActiveUnit => targets
+ .active_unit_surface
+ .as_ref()
+ .expect("active_unit_surface ensured"),
+ SurfaceId::ActiveBase => targets
+ .active_layer_base_surface
+ .as_ref()
+ .expect("active_layer_base_surface ensured"),
+ SurfaceId::LiveStroke => targets
+ .live_stroke_surface
+ .as_ref()
+ .expect("live_stroke_surface ensured"),
SurfaceId::Folder(d) => &targets.folder_stack[d],
SurfaceId::ClipMask(d) => &targets.clip_mask_stack[d],
SurfaceId::FrameMask(d) => &targets.frame_mask_stack[d],
- SurfaceId::StyleSrc => &targets.style_src,
- SurfaceId::StyleBlurTmp => &targets.style_blur_tmp,
- SurfaceId::StyleShadowBlur => &targets.style_shadow_blur,
- SurfaceId::StyleGlowBlur => &targets.style_glow_blur,
+ SurfaceId::StyleSrc => targets.style_src.as_ref().expect("style_src ensured"),
+ SurfaceId::StyleBlurTmp => targets
+ .style_blur_tmp
+ .as_ref()
+ .expect("style_blur_tmp ensured"),
+ SurfaceId::StyleShadowBlur => targets
+ .style_shadow_blur
+ .as_ref()
+ .expect("style_shadow_blur ensured"),
+ SurfaceId::StyleGlowBlur => targets
+ .style_glow_blur
+ .as_ref()
+ .expect("style_glow_blur ensured"),
+ SurfaceId::StyleStrokeDilateTmp => targets
+ .style_stroke_dilate_tmp
+ .as_ref()
+ .expect("style_stroke_dilate_tmp ensured"),
+ SurfaceId::StyleStrokeDilate => targets
+ .style_stroke_dilate
+ .as_ref()
+ .expect("style_stroke_dilate ensured"),
+ SurfaceId::StyleCompositeOut => targets
+ .style_composite_out
+ .as_ref()
+ .expect("style_composite_out ensured"),
SurfaceId::ImpastoColorScratch => targets
.impasto_color_scratch
.as_ref()
@@ -289,7 +349,7 @@ fn get_surface(targets: &CompositorTargets, id: SurfaceId) -> &SurfaceRgba16F {
}
}
-struct FrameArenas {
+pub(crate) struct FrameArenas {
uniform_buf: wgpu::Buffer,
uniform_capacity: usize,
uniform_align: usize,
@@ -306,15 +366,33 @@ struct FrameArenas {
dab_inst_buf: wgpu::Buffer,
dab_inst_capacity: usize,
dab_inst_staging: Vec<u8>,
+
+ flush_count: u64,
}
impl FrameArenas {
fn new(device: &wgpu::Device) -> Self {
+ Self::new_with_capacities(
+ device,
+ 4 * 1024 * 1024, // 4 MB = 16,384 passes per frame
+ 4 * 1024 * 1024, // 4 MB = 131,072 tile instances
+ 1024 * 1024, // 1 MB = 131,072 vertices
+ 1024 * 1024, // 1 MB = 32,768 dabs
+ )
+ }
+
+ pub(crate) fn new_with_capacities(
+ device: &wgpu::Device,
+ uniform_capacity: usize,
+ tile_inst_capacity: usize,
+ poly_vert_capacity: usize,
+ dab_inst_capacity: usize,
+ ) -> Self {
let uniform_align = (device.limits().min_uniform_buffer_offset_alignment as usize).max(256);
- let uniform_capacity = 4 * 1024 * 1024; // 4 MB = 16,384 passes per frame
- let tile_inst_capacity = 4 * 1024 * 1024; // 4 MB = 131,072 tile instances
- let poly_vert_capacity = 1024 * 1024; // 1 MB = 131,072 vertices
- let dab_inst_capacity = 1024 * 1024; // 1 MB = 32,768 dabs
+ let uniform_capacity = uniform_capacity.max(uniform_align);
+ let tile_inst_capacity = tile_inst_capacity.max(64);
+ let poly_vert_capacity = poly_vert_capacity.max(64);
+ let dab_inst_capacity = dab_inst_capacity.max(64);
let uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("ink-comp-uniform-arena"),
@@ -345,17 +423,101 @@ impl FrameArenas {
uniform_buf,
uniform_capacity,
uniform_align,
- uniform_staging: Vec::with_capacity(64 * 1024),
+ uniform_staging: Vec::with_capacity(uniform_capacity.min(64 * 1024)),
tile_inst_buf,
tile_inst_capacity,
- tile_inst_staging: Vec::with_capacity(64 * 1024),
+ tile_inst_staging: Vec::with_capacity(tile_inst_capacity.min(64 * 1024)),
poly_vert_buf,
poly_vert_capacity,
- poly_vert_staging: Vec::with_capacity(16 * 1024),
+ poly_vert_staging: Vec::with_capacity(poly_vert_capacity.min(16 * 1024)),
dab_inst_buf,
dab_inst_capacity,
- dab_inst_staging: Vec::with_capacity(16 * 1024),
+ dab_inst_staging: Vec::with_capacity(dab_inst_capacity.min(16 * 1024)),
+ flush_count: 0,
+ }
+ }
+
+ #[inline]
+ fn aligned_uniform_size(&self, raw_bytes: usize) -> usize {
+ if raw_bytes == 0 {
+ 0
+ } else {
+ raw_bytes.div_ceil(self.uniform_align) * self.uniform_align
+ }
+ }
+
+ /// Atomically guarantees room for a paired draw's uniform AND geometry/instance payloads
+ /// BEFORE pushing either, so a mid-frame flush can NEVER split a draw's uniform offset
+ /// from its vertex/instance slice.
+ pub(crate) fn ensure_capacity(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ encoder: &mut wgpu::CommandEncoder,
+ uniform_bytes: usize,
+ tile_inst_bytes: usize,
+ poly_vert_bytes: usize,
+ dab_inst_bytes: usize,
+ ) {
+ let u_slot = self.aligned_uniform_size(uniform_bytes);
+ let need_flush = (u_slot > 0 && self.uniform_staging.len() + u_slot > self.uniform_capacity)
+ || (tile_inst_bytes > 0
+ && (tile_inst_bytes > self.tile_inst_capacity
+ || self.tile_inst_staging.len() + tile_inst_bytes > self.tile_inst_capacity))
+ || (poly_vert_bytes > 0
+ && (poly_vert_bytes > self.poly_vert_capacity
+ || self.poly_vert_staging.len() + poly_vert_bytes > self.poly_vert_capacity))
+ || (dab_inst_bytes > 0
+ && (dab_inst_bytes > self.dab_inst_capacity
+ || self.dab_inst_staging.len() + dab_inst_bytes > self.dab_inst_capacity));
+
+ if need_flush {
+ let old = std::mem::replace(
+ encoder,
+ device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-compositor-encoder-tmp"),
+ }),
+ );
+ *encoder = self.flush_and_submit(device, queue, old);
+ }
+
+ if tile_inst_bytes > self.tile_inst_capacity {
+ self.tile_inst_capacity = tile_inst_bytes.next_power_of_two();
+ self.tile_inst_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-comp-tile-inst-arena"),
+ size: self.tile_inst_capacity as u64,
+ usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ }
+ if poly_vert_bytes > self.poly_vert_capacity {
+ self.poly_vert_capacity = poly_vert_bytes.next_power_of_two();
+ self.poly_vert_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-comp-poly-vert-arena"),
+ size: self.poly_vert_capacity as u64,
+ usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
}
+ if dab_inst_bytes > self.dab_inst_capacity {
+ self.dab_inst_capacity = dab_inst_bytes.next_power_of_two();
+ self.dab_inst_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-comp-dab-inst-arena"),
+ size: self.dab_inst_capacity as u64,
+ usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ }
+ }
+
+ #[cfg(test)]
+ pub(crate) fn flush_count(&self) -> u64 {
+ self.flush_count
+ }
+
+ #[cfg(test)]
+ pub(crate) fn uniform_staging_slice(&self) -> &[u8] {
+ &self.uniform_staging
}
fn clear(&mut self) {
@@ -365,12 +527,7 @@ impl FrameArenas {
self.dab_inst_staging.clear();
}
- fn flush_and_submit(
- &mut self,
- device: &wgpu::Device,
- queue: &wgpu::Queue,
- encoder: wgpu::CommandEncoder,
- ) -> wgpu::CommandEncoder {
+ fn upload_staging_buffers(&mut self, queue: &wgpu::Queue) {
if !self.uniform_staging.is_empty() {
queue.write_buffer(&self.uniform_buf, 0, &self.uniform_staging);
}
@@ -383,31 +540,29 @@ impl FrameArenas {
if !self.dab_inst_staging.is_empty() {
queue.write_buffer(&self.dab_inst_buf, 0, &self.dab_inst_staging);
}
- queue.submit(Some(encoder.finish()));
self.clear();
+ }
+
+ fn flush_and_submit(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ encoder: wgpu::CommandEncoder,
+ ) -> wgpu::CommandEncoder {
+ self.flush_count = self.flush_count.saturating_add(1);
+ self.upload_staging_buffers(queue);
+ queue.submit(Some(encoder.finish()));
device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("ink-compositor-encoder"),
})
}
fn finish_and_submit(&mut self, queue: &wgpu::Queue, encoder: wgpu::CommandEncoder) {
- if !self.uniform_staging.is_empty() {
- queue.write_buffer(&self.uniform_buf, 0, &self.uniform_staging);
- }
- if !self.tile_inst_staging.is_empty() {
- queue.write_buffer(&self.tile_inst_buf, 0, &self.tile_inst_staging);
- }
- if !self.poly_vert_staging.is_empty() {
- queue.write_buffer(&self.poly_vert_buf, 0, &self.poly_vert_staging);
- }
- if !self.dab_inst_staging.is_empty() {
- queue.write_buffer(&self.dab_inst_buf, 0, &self.dab_inst_staging);
- }
+ self.upload_staging_buffers(queue);
queue.submit(Some(encoder.finish()));
- self.clear();
}
- fn push_uniform<T: Pod>(
+ pub(crate) fn push_uniform<T: Pod>(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
@@ -415,23 +570,15 @@ impl FrameArenas {
val: &T,
) -> u32 {
let bytes = bytemuck::bytes_of(val);
- let slot_size = bytes.len().div_ceil(self.uniform_align) * self.uniform_align;
- if self.uniform_staging.len() + slot_size > self.uniform_capacity {
- let old = std::mem::replace(
- encoder,
- device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-compositor-encoder-tmp"),
- }),
- );
- *encoder = self.flush_and_submit(device, queue, old);
- }
+ let slot_size = self.aligned_uniform_size(bytes.len());
+ self.ensure_capacity(device, queue, encoder, bytes.len(), 0, 0, 0);
let offset = self.uniform_staging.len();
self.uniform_staging.extend_from_slice(bytes);
self.uniform_staging.resize(offset + slot_size, 0);
offset as u32
}
- fn push_tile_instances(
+ pub(crate) fn push_tile_instances(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
@@ -439,30 +586,7 @@ impl FrameArenas {
instances: &[TileInstanceGpu],
) -> (u64, u64) {
let bytes = bytemuck::cast_slice(instances);
- if bytes.len() > self.tile_inst_capacity {
- let old = std::mem::replace(
- encoder,
- device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-compositor-encoder-tmp"),
- }),
- );
- *encoder = self.flush_and_submit(device, queue, old);
- self.tile_inst_capacity = bytes.len().next_power_of_two();
- self.tile_inst_buf = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("ink-comp-tile-inst-arena"),
- size: self.tile_inst_capacity as u64,
- usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
- mapped_at_creation: false,
- });
- } else if self.tile_inst_staging.len() + bytes.len() > self.tile_inst_capacity {
- let old = std::mem::replace(
- encoder,
- device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-compositor-encoder-tmp"),
- }),
- );
- *encoder = self.flush_and_submit(device, queue, old);
- }
+ self.ensure_capacity(device, queue, encoder, 0, bytes.len(), 0, 0);
let start = self.tile_inst_staging.len() as u64;
self.tile_inst_staging.extend_from_slice(bytes);
let end = self.tile_inst_staging.len() as u64;
@@ -477,30 +601,22 @@ impl FrameArenas {
instances: &[SparseTileInst],
) -> (u64, u64) {
let bytes = bytemuck::cast_slice(instances);
- if bytes.len() > self.tile_inst_capacity {
- let old = std::mem::replace(
- encoder,
- device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-compositor-encoder-tmp"),
- }),
- );
- *encoder = self.flush_and_submit(device, queue, old);
- self.tile_inst_capacity = bytes.len().next_power_of_two();
- self.tile_inst_buf = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("ink-comp-tile-inst-arena"),
- size: self.tile_inst_capacity as u64,
- usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
- mapped_at_creation: false,
- });
- } else if self.tile_inst_staging.len() + bytes.len() > self.tile_inst_capacity {
- let old = std::mem::replace(
- encoder,
- device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-compositor-encoder-tmp"),
- }),
- );
- *encoder = self.flush_and_submit(device, queue, old);
- }
+ self.ensure_capacity(device, queue, encoder, 0, bytes.len(), 0, 0);
+ let start = self.tile_inst_staging.len() as u64;
+ self.tile_inst_staging.extend_from_slice(bytes);
+ let end = self.tile_inst_staging.len() as u64;
+ (start, end)
+ }
+
+ fn push_impasto_tiles(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ encoder: &mut wgpu::CommandEncoder,
+ instances: &[ImpastoTileInst],
+ ) -> (u64, u64) {
+ let bytes = bytemuck::cast_slice(instances);
+ self.ensure_capacity(device, queue, encoder, 0, bytes.len(), 0, 0);
let start = self.tile_inst_staging.len() as u64;
self.tile_inst_staging.extend_from_slice(bytes);
let end = self.tile_inst_staging.len() as u64;
@@ -515,30 +631,7 @@ impl FrameArenas {
verts: &[FramePolyVertex],
) -> (u64, u64) {
let bytes = bytemuck::cast_slice(verts);
- if bytes.len() > self.poly_vert_capacity {
- let old = std::mem::replace(
- encoder,
- device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-compositor-encoder-tmp"),
- }),
- );
- *encoder = self.flush_and_submit(device, queue, old);
- self.poly_vert_capacity = bytes.len().next_power_of_two();
- self.poly_vert_buf = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("ink-comp-poly-vert-arena"),
- size: self.poly_vert_capacity as u64,
- usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
- mapped_at_creation: false,
- });
- } else if self.poly_vert_staging.len() + bytes.len() > self.poly_vert_capacity {
- let old = std::mem::replace(
- encoder,
- device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-compositor-encoder-tmp"),
- }),
- );
- *encoder = self.flush_and_submit(device, queue, old);
- }
+ self.ensure_capacity(device, queue, encoder, 0, 0, bytes.len(), 0);
let start = self.poly_vert_staging.len() as u64;
self.poly_vert_staging.extend_from_slice(bytes);
let end = self.poly_vert_staging.len() as u64;
@@ -553,30 +646,7 @@ impl FrameArenas {
dabs: &[DabInstance],
) -> (u64, u64) {
let bytes = bytemuck::cast_slice(dabs);
- if bytes.len() > self.dab_inst_capacity {
- let old = std::mem::replace(
- encoder,
- device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-compositor-encoder-tmp"),
- }),
- );
- *encoder = self.flush_and_submit(device, queue, old);
- self.dab_inst_capacity = bytes.len().next_power_of_two();
- self.dab_inst_buf = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("ink-comp-dab-inst-arena"),
- size: self.dab_inst_capacity as u64,
- usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
- mapped_at_creation: false,
- });
- } else if self.dab_inst_staging.len() + bytes.len() > self.dab_inst_capacity {
- let old = std::mem::replace(
- encoder,
- device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-compositor-encoder-tmp"),
- }),
- );
- *encoder = self.flush_and_submit(device, queue, old);
- }
+ self.ensure_capacity(device, queue, encoder, 0, 0, 0, bytes.len());
let start = self.dab_inst_staging.len() as u64;
self.dab_inst_staging.extend_from_slice(bytes);
let end = self.dab_inst_staging.len() as u64;
@@ -588,22 +658,40 @@ impl FrameArenas {
// Compiled wgpu RenderPipelines & BindGroupLayouts
// ============================================================================
+const SOURCE_ATOP_BLEND: wgpu::BlendState = wgpu::BlendState {
+ color: wgpu::BlendComponent {
+ src_factor: wgpu::BlendFactor::DstAlpha,
+ dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
+ operation: wgpu::BlendOperation::Add,
+ },
+ alpha: wgpu::BlendComponent {
+ src_factor: wgpu::BlendFactor::Zero,
+ dst_factor: wgpu::BlendFactor::One,
+ operation: wgpu::BlendOperation::Add,
+ },
+};
+
struct CompositorPipelines {
linear_sampler: wgpu::Sampler,
clear_rect: wgpu::RenderPipeline,
+ clear_rect_r16f: wgpu::RenderPipeline,
layer_tile_bgl: wgpu::BindGroupLayout,
layer_tile_blend: wgpu::RenderPipeline,
+ layer_tile_atop: wgpu::RenderPipeline,
blit_bgl: wgpu::BindGroupLayout,
blit_blend: wgpu::RenderPipeline,
+ blit_atop: wgpu::RenderPipeline,
adjustment_bgl: wgpu::BindGroupLayout,
adjustment: wgpu::RenderPipeline,
blur_bgl: wgpu::BindGroupLayout,
separable_blur: wgpu::RenderPipeline,
+ stroke_sdf_horiz: wgpu::RenderPipeline,
+ stroke_sdf_vert: wgpu::RenderPipeline,
layer_styles_bgl: wgpu::BindGroupLayout,
layer_styles: wgpu::RenderPipeline,
@@ -617,16 +705,20 @@ struct CompositorPipelines {
sparse_stroke_bgl: wgpu::BindGroupLayout,
sparse_stroke_project: wgpu::RenderPipeline,
+ sparse_mask_bgl: wgpu::BindGroupLayout,
+ sparse_mask_project: wgpu::RenderPipeline,
+
live_merge_bgl: wgpu::BindGroupLayout,
live_stroke_merge: wgpu::RenderPipeline,
+ impasto_proj_bgl: wgpu::BindGroupLayout,
impasto_height_project: wgpu::RenderPipeline,
impasto_light_bgl: wgpu::BindGroupLayout,
impasto_lighting: wgpu::RenderPipeline,
present_bgl: wgpu::BindGroupLayout,
present_surface: wgpu::RenderPipeline,
- present_rgba16f: wgpu::RenderPipeline,
+ present_rgba8: wgpu::RenderPipeline,
}
impl CompositorPipelines {
@@ -676,6 +768,31 @@ impl CompositorPipelines {
multiview_mask: None,
cache: None,
});
+ let clear_rect_r16f = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("ink-comp-clear-r16f-pipeline"),
+ layout: Some(&clear_pl),
+ vertex: wgpu::VertexState {
+ module: &clear_shader,
+ entry_point: Some("vs_main"),
+ buffers: &[],
+ compilation_options: Default::default(),
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &clear_shader,
+ entry_point: Some("fs_main"),
+ targets: &[Some(wgpu::ColorTargetState {
+ format: wgpu::TextureFormat::R16Float,
+ blend: Some(wgpu::BlendState::REPLACE),
+ write_mask: wgpu::ColorWrites::RED,
+ })],
+ compilation_options: Default::default(),
+ }),
+ primitive: wgpu::PrimitiveState::default(),
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ multiview_mask: None,
+ cache: None,
+ });
// 2. Instanced Layer Tile Pipeline
let layer_tile_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
@@ -718,7 +835,7 @@ impl CompositorPipelines {
vertex: wgpu::VertexState {
module: &layer_tile_shader,
entry_point: Some("vs_main"),
- buffers: &[Some(tile_instance_layout)],
+ buffers: &[Some(tile_instance_layout.clone())],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
@@ -737,6 +854,31 @@ impl CompositorPipelines {
multiview_mask: None,
cache: None,
});
+ let layer_tile_atop = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("ink-comp-layer-tile-atop-pipeline"),
+ layout: Some(&layer_tile_pl),
+ vertex: wgpu::VertexState {
+ module: &layer_tile_shader,
+ entry_point: Some("vs_main"),
+ buffers: &[Some(tile_instance_layout)],
+ compilation_options: Default::default(),
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &layer_tile_shader,
+ entry_point: Some("fs_main"),
+ targets: &[Some(wgpu::ColorTargetState {
+ format: wgpu::TextureFormat::Rgba16Float,
+ blend: Some(SOURCE_ATOP_BLEND),
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ compilation_options: Default::default(),
+ }),
+ primitive: wgpu::PrimitiveState::default(),
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ multiview_mask: None,
+ cache: None,
+ });
// 3. Fullscreen Blit / Folder / Cache Composite Pipelines
let blit_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
@@ -768,7 +910,15 @@ impl CompositorPipelines {
wgpu::TextureFormat::Rgba16Float,
Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
);
-
+ let blit_atop = make_fullscreen_pipeline(
+ device,
+ "ink-comp-blit-atop",
+ &blit_pl,
+ &blit_shader,
+ wgpu::TextureFormat::Rgba16Float,
+ Some(SOURCE_ATOP_BLEND),
+ );
+
// 4. Adjustment Layer Pipeline
let adjustment_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("ink-comp-adjustment-bgl"),
@@ -781,9 +931,10 @@ impl CompositorPipelines {
sampler_entry(5),
],
});
+ let adjustment_wgsl = build_adjustment_shader_wgsl();
let adjustment_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("ink-comp-adjustment-shader"),
- source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(ADJUSTMENT_SHADER_WGSL)),
+ source: wgpu::ShaderSource::Wgsl(Cow::Owned(adjustment_wgsl)),
});
let adjustment_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("ink-comp-adjustment-pl"),
@@ -799,7 +950,7 @@ impl CompositorPipelines {
Some(wgpu::BlendState::REPLACE),
);
- // 5. Separable Gaussian Alpha Blur Pipeline
+ // 5. Separable Gaussian Alpha Blur + Separable 2-Pass Exact Euclidean Stroke SDF Pipelines
let blur_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("ink-comp-blur-bgl"),
entries: &[
@@ -825,6 +976,30 @@ impl CompositorPipelines {
wgpu::TextureFormat::Rgba16Float,
Some(wgpu::BlendState::REPLACE),
);
+ let stroke_sdf_h_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("ink-comp-stroke-sdf-h-shader"),
+ source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(STROKE_SDF_HORIZ_WGSL)),
+ });
+ let stroke_sdf_horiz = make_fullscreen_pipeline(
+ device,
+ "ink-comp-stroke-sdf-horiz",
+ &blur_pl,
+ &stroke_sdf_h_shader,
+ wgpu::TextureFormat::Rgba16Float,
+ Some(wgpu::BlendState::REPLACE),
+ );
+ let stroke_sdf_v_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("ink-comp-stroke-sdf-v-shader"),
+ source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(STROKE_SDF_VERT_WGSL)),
+ });
+ let stroke_sdf_vert = make_fullscreen_pipeline(
+ device,
+ "ink-comp-stroke-sdf-vert",
+ &blur_pl,
+ &stroke_sdf_v_shader,
+ wgpu::TextureFormat::Rgba16Float,
+ Some(wgpu::BlendState::REPLACE),
+ );
// 6. Layer Styles Composite Pipeline
let layer_styles_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
@@ -835,6 +1010,7 @@ impl CompositorPipelines {
tex_2d_entry(2, true),
tex_2d_entry(3, true),
sampler_entry(4),
+ tex_2d_entry(5, false),
],
});
let styles_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
@@ -1031,6 +1207,74 @@ impl CompositorPipelines {
cache: None,
});
+ // 8c. GPU Viewport-Resolution Sparse R8Unorm Layer Mask Projector
+ let sparse_mask_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("ink-comp-sparse-mask-bgl"),
+ entries: &[
+ dyn_uniform_entry(
+ 0,
+ wgpu::ShaderStages::VERTEX_FRAGMENT,
+ std::mem::size_of::<LiveDabUniforms>(),
+ ),
+ tex_array_entry(1, false),
+ ],
+ });
+ let sparse_mask_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("ink-comp-sparse-mask-shader"),
+ source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(SPARSE_MASK_PROJECT_WGSL)),
+ });
+ let sparse_mask_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("ink-comp-sparse-mask-pl"),
+ bind_group_layouts: &[Some(&sparse_mask_bgl)],
+ immediate_size: 0,
+ });
+ let sparse_mask_tile_layout = wgpu::VertexBufferLayout {
+ array_stride: std::mem::size_of::<SparseTileInst>() as wgpu::BufferAddress,
+ step_mode: wgpu::VertexStepMode::Instance,
+ attributes: &[
+ wgpu::VertexAttribute {
+ offset: 0,
+ shader_location: 0,
+ format: wgpu::VertexFormat::Float32x2,
+ },
+ wgpu::VertexAttribute {
+ offset: 8,
+ shader_location: 1,
+ format: wgpu::VertexFormat::Float32,
+ },
+ wgpu::VertexAttribute {
+ offset: 12,
+ shader_location: 2,
+ format: wgpu::VertexFormat::Float32,
+ },
+ ],
+ };
+ let sparse_mask_project = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("ink-comp-sparse-mask-project"),
+ layout: Some(&sparse_mask_pl),
+ vertex: wgpu::VertexState {
+ module: &sparse_mask_shader,
+ entry_point: Some("vs_main"),
+ buffers: &[Some(sparse_mask_tile_layout)],
+ compilation_options: Default::default(),
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &sparse_mask_shader,
+ entry_point: Some("fs_main"),
+ targets: &[Some(wgpu::ColorTargetState {
+ format: wgpu::TextureFormat::R8Unorm,
+ blend: Some(wgpu::BlendState::REPLACE),
+ write_mask: wgpu::ColorWrites::RED,
+ })],
+ compilation_options: Default::default(),
+ }),
+ primitive: wgpu::PrimitiveState::default(),
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ multiview_mask: None,
+ cache: None,
+ });
+
// 9. Live Stroke In-Stack Merge Pipeline
let live_merge_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("ink-comp-live-merge-bgl"),
@@ -1067,12 +1311,29 @@ impl CompositorPipelines {
);
// 9b. Phase 5 Live Impasto Heightfield Projection & Directional Relief Lighting
+ let impasto_proj_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("ink-comp-impasto-proj-bgl"),
+ entries: &[
+ dyn_uniform_entry(
+ 0,
+ wgpu::ShaderStages::VERTEX_FRAGMENT,
+ std::mem::size_of::<LiveDabUniforms>(),
+ ),
+ tex_array_entry(1, false),
+ tex_array_entry(2, false),
+ ],
+ });
+ let impasto_proj_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("ink-comp-impasto-proj-pl"),
+ bind_group_layouts: &[Some(&impasto_proj_bgl)],
+ immediate_size: 0,
+ });
let impasto_proj_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("ink-comp-impasto-proj-shader"),
source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(IMPASTO_HEIGHT_PROJECT_WGSL)),
});
let impasto_tile_layout = wgpu::VertexBufferLayout {
- array_stride: std::mem::size_of::<SparseTileInst>() as wgpu::BufferAddress,
+ array_stride: std::mem::size_of::<ImpastoTileInst>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &[
wgpu::VertexAttribute {
@@ -1088,14 +1349,24 @@ impl CompositorPipelines {
wgpu::VertexAttribute {
offset: 12,
shader_location: 2,
- format: wgpu::VertexFormat::Float32,
+ format: wgpu::VertexFormat::Sint32,
+ },
+ wgpu::VertexAttribute {
+ offset: 16,
+ shader_location: 3,
+ format: wgpu::VertexFormat::Sint32x4,
+ },
+ wgpu::VertexAttribute {
+ offset: 32,
+ shader_location: 4,
+ format: wgpu::VertexFormat::Sint32x4,
},
],
};
let impasto_height_project =
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("ink-comp-impasto-height-project"),
- layout: Some(&sparse_stroke_pl),
+ layout: Some(&impasto_proj_pl),
vertex: wgpu::VertexState {
module: &impasto_proj_shader,
entry_point: Some("vs_main"),
@@ -1179,26 +1450,32 @@ impl CompositorPipelines {
surface_format,
None,
);
- let present_rgba16f = make_fullscreen_pipeline(
+ let present_rgba8 = make_fullscreen_pipeline_entry(
device,
- "ink-comp-present-rgba16f",
+ "ink-comp-present-rgba8",
&present_pl,
&present_shader,
- wgpu::TextureFormat::Rgba16Float,
+ "fs_export_rgba8",
+ wgpu::TextureFormat::Rgba8Unorm,
None,
);
Self {
linear_sampler,
clear_rect,
+ clear_rect_r16f,
layer_tile_bgl,
layer_tile_blend,
+ layer_tile_atop,
blit_bgl,
blit_blend,
+ blit_atop,
adjustment_bgl,
adjustment,
blur_bgl,
separable_blur,
+ stroke_sdf_horiz,
+ stroke_sdf_vert,
layer_styles_bgl,
layer_styles,
frame_poly_bgl,
@@ -1207,14 +1484,17 @@ impl CompositorPipelines {
live_dab_paint,
sparse_stroke_bgl,
sparse_stroke_project,
+ sparse_mask_bgl,
+ sparse_mask_project,
live_merge_bgl,
live_stroke_merge,
+ impasto_proj_bgl,
impasto_height_project,
impasto_light_bgl,
impasto_lighting,
present_bgl,
present_surface,
- present_rgba16f,
+ present_rgba8,
}
}
}
@@ -1278,6 +1558,18 @@ fn make_fullscreen_pipeline(
shader: &wgpu::ShaderModule,
format: wgpu::TextureFormat,
blend: Option<wgpu::BlendState>,
+) -> wgpu::RenderPipeline {
+ make_fullscreen_pipeline_entry(device, label, layout, shader, "fs_main", format, blend)
+}
+
+fn make_fullscreen_pipeline_entry(
+ device: &wgpu::Device,
+ label: &str,
+ layout: &wgpu::PipelineLayout,
+ shader: &wgpu::ShaderModule,
+ fs_entry: &str,
+ format: wgpu::TextureFormat,
+ blend: Option<wgpu::BlendState>,
) -> wgpu::RenderPipeline {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
@@ -1290,7 +1582,7 @@ fn make_fullscreen_pipeline(
},
fragment: Some(wgpu::FragmentState {
module: shader,
- entry_point: Some("fs_main"),
+ entry_point: Some(fs_entry),
targets: &[Some(wgpu::ColorTargetState {
format,
blend,
@@ -1329,6 +1621,8 @@ pub struct LiveGpuStrokeOverlay<'a> {
pub live_impasto: Option<LiveImpastoOverlay<'a>>,
/// Optional viewport-projected `R8Unorm` selection mask view for real-time stroke clipping.
pub selection_vp_mask: Option<&'a wgpu::TextureView>,
+ /// True when actively editing the active layer's 8-bit layer mask (modulates mask alpha live).
+ pub is_mask_stroke: bool,
}
#[derive(Debug, Default)]
@@ -1409,21 +1703,69 @@ impl FrameRenderView {
}
}
+/// Per-viewport cached `wgpu::BindGroup`s that depend only on `CompositorTargets` views
+/// and fixed `FrameArenas::uniform_buf`. Invalidated automatically on viewport texture reallocation.
+#[derive(Default)]
+struct ViewportBindGroupCache {
+ present_bg: Option<wgpu::BindGroup>,
+ live_merge_default_bg: Option<wgpu::BindGroup>,
+ live_merge_masked_bgs: HashMap<u64, wgpu::BindGroup>,
+ live_dab_bg: Option<wgpu::BindGroup>,
+ frame_poly_bg: Option<wgpu::BindGroup>,
+ blit_bgs: HashMap<(SurfaceId, bool, Option<SurfaceId>, u64), wgpu::BindGroup>,
+ blit_view_bgs: HashMap<(u64, bool, Option<SurfaceId>, u64), wgpu::BindGroup>,
+ adjustment_bgs: HashMap<(u64, u64, Option<SurfaceId>), wgpu::BindGroup>,
+ layer_styles_bgs: HashMap<(SurfaceId, bool, bool, bool), wgpu::BindGroup>,
+ sparse_stroke_bg: Option<((u8, u64), wgpu::BindGroup)>,
+ sparse_mask_bg: Option<(u64, wgpu::BindGroup)>,
+ impasto_proj_bg: Option<((u64, u64), wgpu::BindGroup)>,
+ layer_tile_atlas_id: u64,
+ layer_tile_bgs: HashMap<(bool, Option<SurfaceId>, u64), wgpu::BindGroup>,
+ blur_bgs: HashMap<SurfaceId, wgpu::BindGroup>,
+ impasto_light_bgs: HashMap<SurfaceId, wgpu::BindGroup>,
+}
+
+impl ViewportBindGroupCache {
+ fn clear(&mut self) {
+ self.present_bg = None;
+ self.live_merge_default_bg = None;
+ self.live_merge_masked_bgs.clear();
+ self.live_dab_bg = None;
+ self.frame_poly_bg = None;
+ self.blit_bgs.clear();
+ self.blit_view_bgs.clear();
+ self.adjustment_bgs.clear();
+ self.layer_styles_bgs.clear();
+ self.sparse_stroke_bg = None;
+ self.sparse_mask_bg = None;
+ self.impasto_proj_bg = None;
+ self.layer_tile_atlas_id = 0;
+ self.layer_tile_bgs.clear();
+ self.blur_bgs.clear();
+ self.impasto_light_bgs.clear();
+ }
+}
+
/// Complete native `wgpu` + WGSL Layer Compositor.
pub struct WgpuCompositor {
pipelines: CompositorPipelines,
arenas: FrameArenas,
targets: CompositorTargets,
+ bg_cache: ViewportBindGroupCache,
export_targets: Option<CompositorTargets>,
- export_readback_surface: Option<SurfaceRgba16F>,
+ export_readback_rgba8: Option<SurfaceRgba8>,
+ export_readback_staging: Option<(wgpu::Buffer, u64)>,
lut_cache: AdjustmentLutCache,
doc_mask_cache: DocMaskCache,
+ export_doc_mask_cache: DocMaskCache,
styled_cache: StyledLayerCache,
stack_tracker: LayerStackCacheTracker,
live_stroke: LiveStrokeSession,
last_camera_sig: Option<u64>,
+ last_final_scene_sig: Option<u64>,
+ last_composite_scissor: Option<ScissorRect>,
}
impl WgpuCompositor {
@@ -1441,31 +1783,77 @@ impl WgpuCompositor {
pipelines,
arenas,
targets,
+ bg_cache: ViewportBindGroupCache::default(),
export_targets: None,
- export_readback_surface: None,
+ export_readback_rgba8: None,
+ export_readback_staging: None,
lut_cache: AdjustmentLutCache::new(),
doc_mask_cache: DocMaskCache::new(),
+ export_doc_mask_cache: DocMaskCache::new(),
styled_cache: StyledLayerCache::new(8),
stack_tracker: LayerStackCacheTracker::new(),
live_stroke: LiveStrokeSession::default(),
last_camera_sig: None,
+ last_final_scene_sig: None,
+ last_composite_scissor: None,
}
}
pub fn resize(&mut self, device: &wgpu::Device, width: u32, height: u32) {
- if self.targets.ensure_size(device, width, height) {
+ let (logical_changed, reallocated) = self.targets.ensure_size_detailed(device, width, height);
+ if reallocated {
+ self.bg_cache.clear();
+ }
+ if logical_changed || reallocated {
self.stack_tracker.invalidate_all();
self.styled_cache.clear();
self.live_stroke.active_key = None;
+ self.last_final_scene_sig = None;
}
}
+ /// Shrinks oversized slack-allocated viewport targets and trims unused nested stacks when idle.
+ pub fn trim_on_idle(&mut self, device: &wgpu::Device) {
+ let trimmed_size = self.targets.trim_to_logical_size(device);
+ let trimmed_stacks = self.targets.trim_unused_stacks(0, 0, 0, false, false, false);
+ if trimmed_size || trimmed_stacks {
+ self.bg_cache.clear();
+ if trimmed_size {
+ self.stack_tracker.invalidate_all();
+ self.styled_cache.clear();
+ self.live_stroke.active_key = None;
+ self.last_final_scene_sig = None;
+ }
+ }
+ }
+
+ pub fn targets_allocated_vram_bytes(&self) -> u64 {
+ self.targets.allocated_vram_bytes()
+ }
+
+ pub fn targets_allocated_surface_count(&self) -> usize {
+ self.targets.allocated_surface_count()
+ }
+
+ pub fn has_export_targets(&self) -> bool {
+ self.export_targets.is_some()
+ || self.export_readback_rgba8.is_some()
+ || self.export_readback_staging.is_some()
+ }
+
pub fn invalidate_all_caches(&mut self) {
+ self.bg_cache.clear();
self.stack_tracker.invalidate_all();
self.styled_cache.clear();
self.doc_mask_cache.clear();
+ self.export_doc_mask_cache.clear();
self.lut_cache.clear();
self.live_stroke.active_key = None;
+ self.last_final_scene_sig = None;
+ }
+
+ pub fn invalidate_final_scene_cache(&mut self) {
+ self.last_final_scene_sig = None;
}
pub fn clear_live_stroke(&mut self) {
@@ -1473,6 +1861,7 @@ impl WgpuCompositor {
self.live_stroke.has_live_dabs = false;
self.live_stroke.is_eraser = false;
self.live_stroke.last_predicted_scissor = None;
+ self.last_final_scene_sig = None;
}
pub fn stack_cache_stats(&self) -> StackCacheStats {
@@ -1483,6 +1872,14 @@ impl WgpuCompositor {
(self.styled_cache.hits, self.styled_cache.rebuilds)
}
+ pub fn last_composite_scissor(&self) -> Option<ScissorRect> {
+ self.last_composite_scissor
+ }
+
+ pub fn doc_mask_rebuilds(&self) -> u64 {
+ self.doc_mask_cache.rebuilds
+ }
+
// ========================================================================
// Main Real-Time Viewport Render Entry Point (3-Slice Cache + Dirty Scissor)
// ========================================================================
@@ -1579,6 +1976,56 @@ impl WgpuCompositor {
pending_dabs: &[DabInstance],
live_is_eraser: bool,
stroke_active: bool,
+ gpu_stroke_overlay: Option<LiveGpuStrokeOverlay<'_>>,
+ liquify_engine: Option<&crate::tools::GpuLiquifyEngine>,
+ output_view: &wgpu::TextureView,
+ ) {
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-compositor-viewport-encoder"),
+ });
+ self.encode_viewport_frame_full(
+ device,
+ queue,
+ &mut encoder,
+ tile_pool,
+ doc,
+ scratch,
+ display,
+ camera,
+ viewport_w,
+ viewport_h,
+ dpr,
+ pending_dabs,
+ live_is_eraser,
+ stroke_active,
+ gpu_stroke_overlay,
+ liquify_engine,
+ output_view,
+ );
+ queue.submit(Some(encoder.finish()));
+ }
+
+ /// Encodes the full viewport compositor frame into a caller-supplied `CommandEncoder`
+ /// and uploads staged arena buffers to `queue` WITHOUT submitting, allowing the caller
+ /// (`GpuRenderer`) to combine selection projection, compositing, marching ants, and
+ /// cursor overlay into ONE `queue.submit` per frame!
+ #[allow(clippy::too_many_arguments)]
+ pub fn encode_viewport_frame_full(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ encoder: &mut wgpu::CommandEncoder,
+ tile_pool: &mut GpuTilePool,
+ doc: &Document,
+ scratch: Option<&dyn ScratchBackend>,
+ display: &CompositorDisplayConfig,
+ camera: &CameraState,
+ viewport_w: u32,
+ viewport_h: u32,
+ dpr: f32,
+ pending_dabs: &[DabInstance],
+ live_is_eraser: bool,
+ stroke_active: bool,
mut gpu_stroke_overlay: Option<LiveGpuStrokeOverlay<'_>>,
liquify_engine: Option<&crate::tools::GpuLiquifyEngine>,
output_view: &wgpu::TextureView,
@@ -1587,27 +2034,13 @@ impl WgpuCompositor {
let vp_h = viewport_h.max(1);
self.resize(device, vp_w, vp_h);
tile_pool.begin_frame();
+ tile_pool.unpin_all_pinned();
self.styled_cache.begin_frame();
let liquify_active = liquify_engine.is_some_and(|l| l.is_active());
let view = FrameRenderView::new(doc, *camera, vp_w, vp_h, dpr, liquify_active, false);
let full_scissor = ScissorRect::full(vp_w, vp_h);
- // Pre-upload all visible frustum tiles, compute LOD mipmaps, LUTs, and doc-level masks
- // strictly BEFORE encoding graphics passes so queue ordering is 100% deterministic.
- prepare_document_gpu_resources(
- device,
- queue,
- tile_pool,
- &mut self.lut_cache,
- &mut self.doc_mask_cache,
- doc,
- scratch,
- &display.cel_visibility_overrides,
- &display.onion_skin_frames,
- &view,
- );
-
let gpu_overlay_active = gpu_stroke_overlay
.as_ref()
.is_some_and(|ov| ov.brush_engine.is_active());
@@ -1624,94 +2057,333 @@ impl WgpuCompositor {
&& !is_live_stroke;
self.last_camera_sig = Some(view.camera_sig);
- let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-compositor-viewport-encoder"),
- });
-
let use_stack_cache = display.layer_stack_caching && !is_camera_moving && !liquify_active;
if use_stack_cache {
+ // Evaluate 3-slice stack cache FIRST so untouched below/above cache layers are never
+ // scanned, uploaded, or pinned, and pure hover / marching-ants frames skip compositing!
let eval = self.stack_tracker.evaluate(doc, display, vp_w, vp_h, view.dpr, camera);
let partition = &eval.partition;
- // Step 1: Rebuild above_active_cache if dirty
- if eval.above_dirty {
- clear_surface(
- &self.pipelines,
- &self.targets,
- &mut encoder,
- SurfaceId::AboveCache,
- full_scissor,
- );
- let override_blend = partition.above_strategy == AboveSliceStrategy::BakedSingleBlend;
- for unit in &partition.above_cached_units {
- let mut ctx = PassCtx {
+ // Fast Path A: Pure hover cursor move or marching-ants tick with unchanged FinalScene
+ let final_scene_sig = if !is_live_stroke {
+ Some(compute_final_scene_sig(&eval, doc, display))
+ } else {
+ None
+ };
+
+ if let Some(sig) = final_scene_sig {
+ if !eval.below_dirty
+ && !eval.above_dirty
+ && self.last_final_scene_sig == Some(sig)
+ {
+ self.stack_tracker.stats.cache_hits += 1;
+ self.stack_tracker.stats.final_scene_hits += 1;
+ self.last_composite_scissor = Some(ScissorRect::full(0, 0));
+ present_scene_to_view(
device,
queue,
- pipelines: &self.pipelines,
- arenas: &mut self.arenas,
- targets: &mut self.targets,
- tile_pool,
- lut_cache: &self.lut_cache,
- doc_mask_cache: &self.doc_mask_cache,
- styled_cache: &mut self.styled_cache,
- doc,
- cel_overrides: &display.cel_visibility_overrides,
- view: &view,
- live_stroke_layer_id: None,
- allow_style_cache: true,
- liquify_engine: None,
- };
- render_compositing_unit(
- &mut ctx,
- &mut encoder,
- unit,
- SurfaceId::AboveCache,
- None,
- 0,
- 0,
- 0,
- override_blend,
- full_scissor,
+ &self.pipelines,
+ &mut self.arenas,
+ &self.targets,
+ Some(&mut self.bg_cache),
+ encoder,
+ output_view,
+ &view,
+ display.show_checkerboard,
+ display.matte_color,
+ &display.soft_proof,
+ display.value_check_enabled,
+ display.show_pixel_grid,
+ false,
+ false,
+ false,
);
+ self.arenas.upload_staging_buffers(queue);
+ return;
}
- self.stack_tracker.stats.above_rebuilds += 1;
}
- // Step 2: Rebuild below_active_cache if dirty (onion skins + below_units)
- if eval.below_dirty {
- clear_surface(
- &self.pipelines,
- &self.targets,
- &mut encoder,
- SurfaceId::BelowCache,
- full_scissor,
- );
- {
- let mut ctx = PassCtx {
- device,
- queue,
- pipelines: &self.pipelines,
- arenas: &mut self.arenas,
- targets: &mut self.targets,
- tile_pool,
- lut_cache: &self.lut_cache,
- doc_mask_cache: &self.doc_mask_cache,
- styled_cache: &mut self.styled_cache,
- doc,
- cel_overrides: &display.cel_visibility_overrides,
- view: &view,
- live_stroke_layer_id: None,
- allow_style_cache: true,
- liquify_engine: None,
+ // Pre-evaluate live-stroke init & dirty scissor so zero-change live-stroke frames
+ // (e.g. stabilizer hold with no sealed segments & no predicted dabs) skip ALL work!
+ let active_layer_opt = doc
+ .active_layer_id
+ .as_deref()
+ .and_then(|id| doc.layers.iter().find(|l| l.meta.id == id))
+ .filter(|l| l.meta.layer_type.has_tiles());
+
+ let mut precomputed_gpu_update_scissor: Option<ScissorRect> = None;
+ let mut precomputed_pred_scissor: Option<ScissorRect> = None;
+ let mut skip_live_stroke_frame = false;
+
+ if is_live_stroke {
+ if let Some(active_layer) = active_layer_opt {
+ let desired_key = (
+ doc.id.as_str(),
+ active_layer.meta.id.as_str(),
+ view.camera_sig,
+ active_layer.grid.layer_version,
+ );
+ let needs_init = match self.live_stroke.active_key.as_ref() {
+ Some((d, l, cs, lv)) => {
+ (d.as_str(), l.as_str(), *cs, *lv) != desired_key
+ }
+ None => true,
};
- for unit in &partition.below_units {
- render_compositing_unit(
+
+ if let Some(overlay) =
+ gpu_stroke_overlay.as_ref().filter(|ov| ov.brush_engine.is_active())
+ {
+ let styles = parse_layer_styles(active_layer.meta.styles.as_ref());
+ let style_pad =
+ (styles.max_margin_doc_px() * view.camera.zoom * view.dpr).ceil() as i32;
+ let has_live_impasto = overlay
+ .live_impasto
+ .as_ref()
+ .map(|li| li.light)
+ .or_else(|| {
+ overlay
+ .brush_engine
+ .active_impasto_overlay_with_id()
+ .map(|(_, _, _, l)| l)
+ })
+ .or_else(|| {
+ if active_layer.grid.has_impasto() {
+ Some(active_layer.meta.impasto_light.unwrap_or_default())
+ } else {
+ None
+ }
+ })
+ .is_some_and(|l| l.enabled && l.depth > 0.001 && l.relief_contrast > 0.001);
+ // Cover 18 px impasto shadow raymarch + 2 px Sobel + bilinear margin
+ let base_pad = if has_live_impasto { 24 } else { 8 };
+
+ let cur_pred_scissor = if !overlay.predicted_dabs.is_empty() {
+ gpu_dabs_dirty_scissor(overlay.predicted_dabs, &view, base_pad + style_pad)
+ } else {
+ None
+ };
+ let dirty_doc_scissor = overlay.dirty_doc_bounds.and_then(|b| {
+ doc_bounds_to_scissor(
+ b,
+ &view.camera,
+ view.dimensions.width,
+ view.dimensions.height,
+ view.viewport_w,
+ view.viewport_h,
+ view.dpr,
+ base_pad + style_pad,
+ )
+ });
+ let clamped_pred =
+ cur_pred_scissor.map(|s| s.clamp(view.viewport_w, view.viewport_h));
+ precomputed_pred_scissor = clamped_pred;
+
+ if needs_init || eval.below_dirty || eval.above_dirty {
+ precomputed_gpu_update_scissor = Some(full_scissor);
+ } else {
+ let mut acc: Option<ScissorRect> = dirty_doc_scissor;
+ if let Some(prev_p) = self.live_stroke.last_predicted_scissor {
+ acc = Some(match acc {
+ Some(a) => a.union(prev_p),
+ None => prev_p,
+ });
+ }
+ if let Some(cur_p) = cur_pred_scissor {
+ acc = Some(match acc {
+ Some(a) => a.union(cur_p),
+ None => cur_p,
+ });
+ }
+ match acc {
+ Some(sc) => {
+ let clamped = sc.clamp(view.viewport_w, view.viewport_h);
+ if clamped.is_empty() {
+ skip_live_stroke_frame = true;
+ } else {
+ precomputed_gpu_update_scissor = Some(clamped);
+ }
+ }
+ None => {
+ // Zero stroke pixels changed (e.g. stabilizer hold): DO NOT fall back to full_scissor!
+ skip_live_stroke_frame = true;
+ }
+ }
+ }
+ } else if !needs_init
+ && !eval.below_dirty
+ && !eval.above_dirty
+ && pending_dabs.is_empty()
+ && self.live_stroke.has_live_dabs
+ {
+ skip_live_stroke_frame = true;
+ }
+ }
+ }
+
+ if skip_live_stroke_frame {
+ self.live_stroke.last_predicted_scissor = precomputed_pred_scissor;
+ self.stack_tracker.stats.cache_hits += 1;
+ self.stack_tracker.stats.live_stroke_zero_skips += 1;
+ self.last_composite_scissor = Some(ScissorRect::full(0, 0));
+ present_scene_to_view(
+ device,
+ queue,
+ &self.pipelines,
+ &mut self.arenas,
+ &self.targets,
+ Some(&mut self.bg_cache),
+ encoder,
+ output_view,
+ &view,
+ display.show_checkerboard,
+ display.matte_color,
+ &display.soft_proof,
+ display.value_check_enabled,
+ display.show_pixel_grid,
+ false,
+ false,
+ false,
+ );
+ self.arenas.upload_staging_buffers(queue);
+ return;
+ }
+
+ // Prepare GPU resources ONLY for layers that will actually be rendered this frame!
+ let mut needed_layers = vec![false; doc.layers.len()];
+ if eval.below_dirty {
+ for unit in &partition.below_units {
+ mark_unit_layers(unit, &mut needed_layers);
+ }
+ if !display.onion_skin_frames.is_empty() {
+ for (idx, layer) in doc.layers.iter().enumerate() {
+ if layer.meta.visible
+ && display
+ .onion_skin_frames
+ .iter()
+ .any(|f| f.layer_id == layer.meta.id)
+ {
+ needed_layers[idx] = true;
+ }
+ }
+ }
+ }
+ if eval.above_dirty {
+ for unit in &partition.above_cached_units {
+ mark_unit_layers(unit, &mut needed_layers);
+ }
+ }
+ if let Some(active_unit) = &partition.active_unit {
+ mark_unit_layers(active_unit, &mut needed_layers);
+ }
+ for dyn_unit in &partition.above_dynamic_units {
+ mark_unit_layers(dyn_unit, &mut needed_layers);
+ }
+
+ prepare_document_gpu_resources(
+ device,
+ queue,
+ &self.pipelines,
+ &mut self.arenas,
+ Some(&mut self.bg_cache),
+ encoder,
+ tile_pool,
+ &mut self.lut_cache,
+ &mut self.doc_mask_cache,
+ doc,
+ scratch,
+ &display.cel_visibility_overrides,
+ &display.onion_skin_frames,
+ Some(&needed_layers),
+ &view,
+ );
+
+ // Step 1: Rebuild above_active_cache if dirty (lazily allocated ONLY when above units exist!)
+ if eval.above_dirty && !partition.above_cached_units.is_empty() {
+ self.targets.ensure_above_cache(device);
+ clear_surface(
+ &self.pipelines,
+ &self.targets,
+ encoder,
+ SurfaceId::AboveCache,
+ full_scissor,
+ );
+ let override_blend = partition.above_strategy == AboveSliceStrategy::BakedSingleBlend;
+ for unit in &partition.above_cached_units {
+ let mut ctx = PassCtx {
+ device,
+ queue,
+ pipelines: &self.pipelines,
+ arenas: &mut self.arenas,
+ targets: &mut self.targets,
+ bg_cache: Some(&mut self.bg_cache),
+ tile_pool,
+ lut_cache: &self.lut_cache,
+ doc_mask_cache: &self.doc_mask_cache,
+ styled_cache: &mut self.styled_cache,
+ doc,
+ cel_overrides: &display.cel_visibility_overrides,
+ view: &view,
+ live_stroke_layer_id: None,
+ allow_style_cache: true,
+ liquify_engine: None,
+ };
+ render_compositing_unit(
+ &mut ctx,
+ encoder,
+ unit,
+ SurfaceId::AboveCache,
+ None,
+ false,
+ 0,
+ 0,
+ 0,
+ override_blend,
+ full_scissor,
+ );
+ }
+ self.stack_tracker.stats.above_rebuilds += 1;
+ }
+
+ // Step 2: Rebuild below_active_cache if dirty (lazily allocated ONLY when below units or onion skins exist!)
+ let has_below_content =
+ !partition.below_units.is_empty() || !display.onion_skin_frames.is_empty();
+ if eval.below_dirty && has_below_content {
+ self.targets.ensure_below_cache(device);
+ clear_surface(
+ &self.pipelines,
+ &self.targets,
+ encoder,
+ SurfaceId::BelowCache,
+ full_scissor,
+ );
+ {
+ let mut ctx = PassCtx {
+ device,
+ queue,
+ pipelines: &self.pipelines,
+ arenas: &mut self.arenas,
+ targets: &mut self.targets,
+ bg_cache: Some(&mut self.bg_cache),
+ tile_pool,
+ lut_cache: &self.lut_cache,
+ doc_mask_cache: &self.doc_mask_cache,
+ styled_cache: &mut self.styled_cache,
+ doc,
+ cel_overrides: &display.cel_visibility_overrides,
+ view: &view,
+ live_stroke_layer_id: None,
+ allow_style_cache: true,
+ liquify_engine: None,
+ };
+ for unit in &partition.below_units {
+ render_compositing_unit(
&mut ctx,
- &mut encoder,
+ encoder,
unit,
SurfaceId::BelowCache,
None,
+ false,
0,
0,
0,
@@ -1722,7 +2394,7 @@ impl WgpuCompositor {
// Render onion skin ghosts ON TOP of paper/background layers (underneath active cel)
render_onion_skins(
&mut ctx,
- &mut encoder,
+ encoder,
&display.onion_skin_frames,
SurfaceId::BelowCache,
full_scissor,
@@ -1736,17 +2408,17 @@ impl WgpuCompositor {
}
// Step 3: Live WYSIWYG stroke update + tight dirty-rect scissor computation
- let active_layer_opt = doc
- .active_layer_id
- .as_deref()
- .and_then(|id| doc.layers.iter().find(|l| l.meta.id == id))
- .filter(|l| l.meta.layer_type.has_tiles());
-
let mut use_live_layer_id: Option<&str> = None;
let mut composite_scissor = full_scissor;
if is_live_stroke {
if let Some(active_layer) = active_layer_opt {
+ self.targets.ensure_active_base(device);
+ self.targets.ensure_live_stroke(device);
+ self.targets.ensure_active_unit(device);
+ let active_has_styles =
+ parse_layer_styles(active_layer.meta.styles.as_ref()).has_active();
+
let desired_key = (
doc.id.clone(),
active_layer.meta.id.clone(),
@@ -1760,14 +2432,14 @@ impl WgpuCompositor {
clear_surface(
&self.pipelines,
&self.targets,
- &mut encoder,
+ encoder,
SurfaceId::ActiveBase,
full_scissor,
);
clear_surface(
&self.pipelines,
&self.targets,
- &mut encoder,
+ encoder,
SurfaceId::LiveStroke,
full_scissor,
);
@@ -1778,6 +2450,7 @@ impl WgpuCompositor {
pipelines: &self.pipelines,
arenas: &mut self.arenas,
targets: &mut self.targets,
+ bg_cache: Some(&mut self.bg_cache),
tile_pool,
lut_cache: &self.lut_cache,
doc_mask_cache: &self.doc_mask_cache,
@@ -1791,7 +2464,7 @@ impl WgpuCompositor {
};
render_layer_raw_tiles(
&mut ctx,
- &mut encoder,
+ encoder,
active_layer,
SurfaceId::ActiveBase,
full_scissor,
@@ -1803,58 +2476,22 @@ impl WgpuCompositor {
}
if let Some(overlay) = gpu_stroke_overlay.as_mut().filter(|ov| ov.brush_engine.is_active()) {
- // Phase 4 Sparse GPU Stroke Tiles + Ephemeral Predicted Stroke Head!
- let styles = parse_layer_styles(active_layer.meta.styles.as_ref());
- let style_pad = (styles.max_margin_doc_px() * view.camera.zoom * view.dpr).ceil() as i32;
+ let update_scissor = precomputed_gpu_update_scissor
+ .unwrap_or(full_scissor)
+ .clamp(view.viewport_w, view.viewport_h);
+ let clamped_pred_scissor = precomputed_pred_scissor;
+ self.live_stroke.last_predicted_scissor = clamped_pred_scissor;
- // Compute scissor covering newly stamped tiles + previous & current predicted head
- let cur_pred_scissor = if !overlay.predicted_dabs.is_empty() {
- gpu_dabs_dirty_scissor(overlay.predicted_dabs, &view, 8 + style_pad)
- } else {
- None
- };
- let dirty_doc_scissor = overlay.dirty_doc_bounds.and_then(|b| {
- doc_bounds_to_scissor(
- b,
- &view.camera,
- view.dimensions.width,
- view.dimensions.height,
- view.viewport_w,
- view.viewport_h,
- view.dpr,
- 8 + style_pad,
- )
- });
-
- let mut update_scissor = if needs_init || eval.below_dirty || eval.above_dirty {
- full_scissor
- } else {
- let mut acc: Option<ScissorRect> = dirty_doc_scissor;
- if let Some(prev_p) = self.live_stroke.last_predicted_scissor {
- acc = Some(match acc {
- Some(a) => a.union(prev_p),
- None => prev_p,
- });
- }
- if let Some(cur_p) = cur_pred_scissor {
- acc = Some(match acc {
- Some(a) => a.union(cur_p),
- None => cur_p,
- });
- }
- acc.unwrap_or(full_scissor)
- };
- update_scissor = update_scissor.clamp(view.viewport_w, view.viewport_h);
- self.live_stroke.last_predicted_scissor = cur_pred_scissor;
-
- let is_direct_replace = overlay.brush_engine.is_direct_replace_mode();
+ let is_mask_stroke = overlay.is_mask_stroke;
+ let is_direct_replace =
+ !is_mask_stroke && overlay.brush_engine.is_direct_replace_mode();
if is_direct_replace {
// Phase 5 Natural Paint / Color Mixing: seed LiveStroke with ActiveBase
// inside update_scissor, then project complete updated straight RGBA16F
// tiles with premultiplication + BlendState::REPLACE!
get_surface(&self.targets, SurfaceId::ActiveBase).copy_region_to(
- &mut encoder,
+ encoder,
get_surface(&self.targets, SurfaceId::LiveStroke),
update_scissor,
);
@@ -1863,21 +2500,24 @@ impl WgpuCompositor {
clear_surface(
&self.pipelines,
&self.targets,
- &mut encoder,
+ encoder,
SurfaceId::LiveStroke,
update_scissor,
);
}
// Project ONLY visible touched sparse GPU stroke tiles into LiveStroke surface
- let (stroke_atlas_view, stroke_tile_map) = overlay.brush_engine.active_stroke_atlas();
+ let (stroke_atlas_id, stroke_atlas_view, stroke_tile_map) =
+ overlay.brush_engine.active_stroke_atlas_with_id();
project_sparse_stroke_tiles_into_surface(
device,
queue,
&self.pipelines,
&mut self.arenas,
&self.targets,
- &mut encoder,
+ Some(&mut self.bg_cache),
+ encoder,
+ stroke_atlas_id,
stroke_atlas_view,
stroke_tile_map,
is_direct_replace,
@@ -1885,38 +2525,53 @@ impl WgpuCompositor {
update_scissor,
);
- // Render transient predicted head dabs directly inside the DX12 frame
- if !is_direct_replace && !overlay.predicted_dabs.is_empty() {
- overlay.brush_engine.render_predicted_dabs_into_viewport(
- device,
- queue,
- &mut encoder,
- &self.targets.live_stroke_surface.view,
- overlay.predicted_dabs,
- [view.viewport_w as f32, view.viewport_h as f32],
- [view.camera.pan_x, view.camera.pan_y],
- view.camera.zoom,
- view.rot_rad,
- view.flip,
- view.dpr,
- );
+ if !overlay.predicted_dabs.is_empty() && !update_scissor.is_empty() {
+ let pred_scissor = clamped_pred_scissor.unwrap_or(update_scissor);
+ if !pred_scissor.is_empty() {
+ overlay.brush_engine.render_predicted_dabs_into_viewport(
+ device,
+ queue,
+ encoder,
+ &get_surface(&self.targets, SurfaceId::LiveStroke).view,
+ overlay.predicted_dabs,
+ [view.viewport_w as f32, view.viewport_h as f32],
+ [view.camera.pan_x, view.camera.pan_y],
+ view.camera.zoom,
+ view.rot_rad,
+ view.flip,
+ view.dpr,
+ [
+ pred_scissor.x,
+ pred_scissor.y,
+ pred_scissor.width,
+ pred_scissor.height,
+ ],
+ );
+ }
}
let ab = overlay.brush_engine.active_brush();
let merge_params = LiveMergeParams {
- combine_mode: if is_direct_replace {
+ combine_mode: if is_mask_stroke {
+ 33
+ } else if is_direct_replace {
32
} else {
ab.brush_combine_mode.as_u32()
},
- is_eraser: !is_direct_replace && (ab.is_effective_eraser() || live_is_eraser),
- is_bg_eraser: !is_direct_replace && ab.is_bg_eraser,
+ is_eraser: !is_mask_stroke
+ && !is_direct_replace
+ && (ab.is_effective_eraser() || live_is_eraser),
+ is_bg_eraser: !is_mask_stroke && !is_direct_replace && ab.is_bg_eraser,
brush_opacity: if is_direct_replace {
1.0
} else {
ab.opacity.clamp(0.0, 1.0)
},
bg_color: ab.bg_color,
+ // Keep ActiveUnit un-attenuated when layer styles are active so Stroke
+ // coverage (alpha >= 0.5) never disappears at layer.meta.opacity <= 0.5!
+ unattenuated_layer_opacity: active_has_styles,
};
self.live_stroke.has_live_dabs = true;
self.live_stroke.is_eraser = merge_params.is_eraser;
@@ -1927,8 +2582,9 @@ impl WgpuCompositor {
&self.pipelines,
&mut self.arenas,
&self.targets,
+ Some(&mut self.bg_cache),
&self.doc_mask_cache,
- &mut encoder,
+ encoder,
active_layer,
merge_params,
overlay.selection_vp_mask,
@@ -1937,12 +2593,12 @@ impl WgpuCompositor {
);
// Phase 5 Live Impasto 3D Relief Lighting on ActiveUnit (zero cost on flat layers!)
- let engine_imp_overlay = overlay.brush_engine.active_impasto_overlay();
+ let engine_imp_overlay = overlay.brush_engine.active_impasto_overlay_with_id();
let live_imp_light = overlay
.live_impasto
.as_ref()
.map(|li| li.light)
- .or_else(|| engine_imp_overlay.map(|(_, _, l)| l))
+ .or_else(|| engine_imp_overlay.map(|(_, _, _, l)| l))
.or_else(|| {
if active_layer.grid.has_impasto() {
Some(active_layer.meta.impasto_light.unwrap_or_default())
@@ -1954,28 +2610,32 @@ impl WgpuCompositor {
if let Some(imp_light) = live_imp_light {
self.targets.ensure_impasto_surfaces(device);
- let live_height_pair = overlay
+ let live_height_triple = overlay
.live_impasto
.as_ref()
- .map(|li| (li.height_atlas_view, li.height_tile_map))
- .or_else(|| engine_imp_overlay.map(|(v, m, _)| (v, m)));
- // Project base layer impasto height tiles + live stroke impasto height tiles
+ .map(|li| (0u64, li.height_atlas_view, li.height_tile_map))
+ .or_else(|| engine_imp_overlay.map(|(id, v, m, _)| (id, v, m)));
+ // Scissored impasto height projection (expanded >= 22 px so 18 px raymarch samples valid heights!)
+ let height_scissor =
+ update_scissor.expand(22, view.viewport_w, view.viewport_h);
project_impasto_height_tiles(
device,
queue,
&self.pipelines,
&mut self.arenas,
&self.targets,
+ Some(&mut self.bg_cache),
tile_pool,
- &mut encoder,
+ encoder,
doc,
active_layer,
- live_height_pair,
+ live_height_triple,
&view,
+ height_scissor,
);
// Copy unlit ActiveUnit -> ImpastoColorScratch, then light back -> ActiveUnit
get_surface(&self.targets, SurfaceId::ActiveUnit).copy_region_to(
- &mut encoder,
+ encoder,
get_surface(&self.targets, SurfaceId::ImpastoColorScratch),
update_scissor,
);
@@ -1985,7 +2645,8 @@ impl WgpuCompositor {
&self.pipelines,
&mut self.arenas,
&self.targets,
- &mut encoder,
+ Some(&mut self.bg_cache),
+ encoder,
SurfaceId::ImpastoColorScratch,
SurfaceId::ActiveUnit,
imp_light,
@@ -2018,7 +2679,8 @@ impl WgpuCompositor {
&self.pipelines,
&mut self.arenas,
&self.targets,
- &mut encoder,
+ Some(&mut self.bg_cache),
+ encoder,
pending_dabs,
&view,
sc,
@@ -2034,6 +2696,7 @@ impl WgpuCompositor {
is_bg_eraser: false,
brush_opacity: 1.0,
bg_color: [1.0, 1.0, 1.0],
+ unattenuated_layer_opacity: active_has_styles,
};
merge_live_stroke_layer(
device,
@@ -2041,8 +2704,9 @@ impl WgpuCompositor {
&self.pipelines,
&mut self.arenas,
&self.targets,
+ Some(&mut self.bg_cache),
&self.doc_mask_cache,
- &mut encoder,
+ encoder,
active_layer,
merge_params,
None,
@@ -2059,12 +2723,24 @@ impl WgpuCompositor {
}
// Step 4: Composite the 3 slices into FinalScene strictly inside `composite_scissor`!
+ self.last_composite_scissor = Some(composite_scissor);
if !composite_scissor.is_empty() {
- get_surface(&self.targets, SurfaceId::BelowCache).copy_region_to(
- &mut encoder,
- get_surface(&self.targets, SurfaceId::FinalScene),
- composite_scissor,
- );
+ if has_below_content {
+ self.targets.ensure_below_cache(device);
+ get_surface(&self.targets, SurfaceId::BelowCache).copy_region_to(
+ encoder,
+ get_surface(&self.targets, SurfaceId::FinalScene),
+ composite_scissor,
+ );
+ } else {
+ clear_surface(
+ &self.pipelines,
+ &self.targets,
+ encoder,
+ SurfaceId::FinalScene,
+ composite_scissor,
+ );
+ }
{
let mut ctx = PassCtx {
@@ -2073,6 +2749,7 @@ impl WgpuCompositor {
pipelines: &self.pipelines,
arenas: &mut self.arenas,
targets: &mut self.targets,
+ bg_cache: Some(&mut self.bg_cache),
tile_pool,
lut_cache: &self.lut_cache,
doc_mask_cache: &self.doc_mask_cache,
@@ -2088,10 +2765,11 @@ impl WgpuCompositor {
if let Some(active_unit) = &partition.active_unit {
render_compositing_unit(
&mut ctx,
- &mut encoder,
+ encoder,
active_unit,
SurfaceId::FinalScene,
None,
+ false,
0,
0,
0,
@@ -2103,10 +2781,11 @@ impl WgpuCompositor {
for dyn_unit in &partition.above_dynamic_units {
render_compositing_unit(
&mut ctx,
- &mut encoder,
+ encoder,
dyn_unit,
SurfaceId::FinalScene,
None,
+ false,
0,
0,
0,
@@ -2123,13 +2802,14 @@ impl WgpuCompositor {
};
blit_surface_onto(
&mut ctx,
- &mut encoder,
+ encoder,
SurfaceId::AboveCache,
SurfaceId::FinalScene,
above_blend,
1.0,
None,
None,
+ false,
composite_scissor,
);
}
@@ -2141,12 +2821,40 @@ impl WgpuCompositor {
eval.above_signature,
!partition.above_cached_units.is_empty(),
);
+ if let Some(sig) = final_scene_sig {
+ self.last_final_scene_sig = Some(sig);
+ self.stack_tracker.stats.final_scene_rebuilds += 1;
+ } else {
+ self.last_final_scene_sig = None;
+ }
} else {
+ self.last_final_scene_sig = None;
+ self.last_composite_scissor = Some(full_scissor);
+ self.stack_tracker.stats.final_scene_rebuilds += 1;
+
+ prepare_document_gpu_resources(
+ device,
+ queue,
+ &self.pipelines,
+ &mut self.arenas,
+ Some(&mut self.bg_cache),
+ encoder,
+ tile_pool,
+ &mut self.lut_cache,
+ &mut self.doc_mask_cache,
+ doc,
+ scratch,
+ &display.cel_visibility_overrides,
+ &display.onion_skin_frames,
+ None,
+ &view,
+ );
+
// Direct single-pass render while camera is moving or stack caching disabled
clear_surface(
&self.pipelines,
&self.targets,
- &mut encoder,
+ encoder,
SurfaceId::FinalScene,
full_scissor,
);
@@ -2163,6 +2871,7 @@ impl WgpuCompositor {
pipelines: &self.pipelines,
arenas: &mut self.arenas,
targets: &mut self.targets,
+ bg_cache: Some(&mut self.bg_cache),
tile_pool,
lut_cache: &self.lut_cache,
doc_mask_cache: &self.doc_mask_cache,
@@ -2174,13 +2883,28 @@ impl WgpuCompositor {
allow_style_cache: !liquify_active,
liquify_engine,
};
+ let active_id_ref = doc.active_layer_id.as_deref();
+ let mut onion_drawn = display.onion_skin_frames.is_empty();
for unit in &units {
+ if !onion_drawn
+ && active_id_ref.is_some_and(|aid| unit.contained_layer_ids.contains(aid))
+ {
+ render_onion_skins(
+ &mut ctx,
+ encoder,
+ &display.onion_skin_frames,
+ SurfaceId::FinalScene,
+ full_scissor,
+ );
+ onion_drawn = true;
+ }
render_compositing_unit(
&mut ctx,
- &mut encoder,
+ encoder,
unit,
SurfaceId::FinalScene,
None,
+ false,
0,
0,
0,
@@ -2188,13 +2912,15 @@ impl WgpuCompositor {
full_scissor,
);
}
- render_onion_skins(
- &mut ctx,
- &mut encoder,
- &display.onion_skin_frames,
- SurfaceId::FinalScene,
- full_scissor,
- );
+ if !onion_drawn {
+ render_onion_skins(
+ &mut ctx,
+ encoder,
+ &display.onion_skin_frames,
+ SurfaceId::FinalScene,
+ full_scissor,
+ );
+ }
}
// Step 5: Present FinalScene -> swapchain view with matte, artboard chrome,
@@ -2205,7 +2931,8 @@ impl WgpuCompositor {
&self.pipelines,
&mut self.arenas,
&self.targets,
- &mut encoder,
+ Some(&mut self.bg_cache),
+ encoder,
output_view,
&view,
display.show_checkerboard,
@@ -2218,9 +2945,10 @@ impl WgpuCompositor {
false,
);
- self.arenas.finish_and_submit(queue, encoder);
+ self.arenas.upload_staging_buffers(queue);
+ tile_pool.unpin_all_pinned();
- // Prune deleted layer caches cleanly
+ // Prune deleted layer caches cleanly (fast-path returns early above!)
let valid_ids: HashSet<&str> = doc.layers.iter().map(|l| l.meta.id.as_str()).collect();
self.lut_cache.retain_layers(&valid_ids);
self.doc_mask_cache.retain_layers(&valid_ids);
@@ -2279,16 +3007,18 @@ impl WgpuCompositor {
(src_w, src_h)
};
- let scale = out_w as f32 / src_w as f32;
+ // Use min(scale_x, scale_y) centered on the source region so extreme aspect ratios
+ // (e.g. tall webtoons) never suffer X/Y scale aspect drift or edge clipping!
+ let scale = (out_w as f32 / src_w as f32).min(out_h as f32 / src_h as f32);
let max_style_doc_margin = doc
.layers
.iter()
.filter(|l| is_node_visible(l, &options.cel_visibility_overrides))
.map(|l| parse_layer_styles(l.meta.styles.as_ref()).max_margin_doc_px())
.fold(0.0f32, f32::max);
- let pad_px = (max_style_doc_margin * scale).ceil().min(256.0) as u32;
+ let pad_px = (((max_style_doc_margin * scale).ceil().min(256.0) as u32) + 3) & !3;
- let max_chunk_core = 2048u32.saturating_sub(pad_px * 2).max(256);
+ let max_chunk_core = (2048u32.saturating_sub(pad_px * 2) & !3).max(256);
let mut out_rgba = vec![0u8; (out_w as usize) * (out_h as usize) * 4];
let transparent_bg = !options.fill_white_background && !options.show_checkerboard;
@@ -2300,6 +3030,15 @@ impl WgpuCompositor {
1.0,
);
+ let src_center_x = src_x + src_w as f32 * 0.5;
+ let src_center_y = src_y + src_h as f32 * 0.5;
+ let active_id_ref = doc.active_layer_id.as_deref();
+
+ // Scope export GPU targets locally so ALL export VRAM is released immediately on return!
+ let mut local_export_targets: Option<CompositorTargets> = None;
+ let mut local_readback_surf: Option<SurfaceRgba8> = None;
+ let mut local_readback_staging: Option<(wgpu::Buffer, u64)> = None;
+
let mut cy = 0u32;
while cy < out_h {
let core_h = (out_h - cy).min(max_chunk_core);
@@ -2314,23 +3053,27 @@ impl WgpuCompositor {
let chunk_w = core_w + pad_l + pad_r;
let chunk_h = core_h + pad_t + pad_b;
- // Ensure dedicated export targets (leaves live viewport targets untouched!)
- let export_targets = self.export_targets.get_or_insert_with(|| {
- CompositorTargets::new(device, queue, chunk_w, chunk_h)
+ // Exact-sized lazy export targets (leaves live viewport targets untouched and allocates
+ // only final_scene + any surfaces actually required by this document!)
+ let export_targets = local_export_targets.get_or_insert_with(|| {
+ CompositorTargets::new_exact(device, queue, chunk_w, chunk_h)
});
export_targets.ensure_size(device, chunk_w, chunk_h);
- let readback_surf = self.export_readback_surface.get_or_insert_with(|| {
- SurfaceRgba16F::new(device, "ink-export-readback-16f", chunk_w, chunk_h)
+ // 4 B/px Rgba8Unorm target: GPU does Rgba16Float -> straight RGBA8 + 4x4 Bayer dithering
+ let readback_surf = local_readback_surf.get_or_insert_with(|| {
+ SurfaceRgba8::new(device, "ink-export-readback-rgba8", chunk_w, chunk_h)
});
- readback_surf.ensure_size(device, "ink-export-readback-16f", chunk_w, chunk_h);
+ readback_surf.ensure_size(device, "ink-export-readback-rgba8", chunk_w, chunk_h);
- // Exact orthographic camera mapping chunk doc origin onto pixel (0, 0)
- let doc_origin_x = src_x + (cx as f32 - pad_l as f32) / scale;
- let doc_origin_y = src_y + (cy as f32 - pad_t as f32) / scale;
+ // Centered aspect-preserving orthographic camera mapping source region onto (out_w, out_h)
let cam = CameraState {
- pan_x: (doc_w as f32 * 0.5 - doc_origin_x) * scale,
- pan_y: (doc_h as f32 * 0.5 - doc_origin_y) * scale,
+ pan_x: (out_w as f32 * 0.5)
+ - (cx as f32 - pad_l as f32)
+ - (src_center_x - doc_w as f32 * 0.5) * scale,
+ pan_y: (out_h as f32 * 0.5)
+ - (cy as f32 - pad_t as f32)
+ - (src_center_y - doc_h as f32 * 0.5) * scale,
zoom: scale,
rotation: 0.0,
flip_x: false,
@@ -2341,22 +3084,27 @@ impl WgpuCompositor {
let full_scissor = ScissorRect::full(chunk_w, chunk_h);
tile_pool.begin_frame();
+ tile_pool.unpin_all_pinned();
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-compositor-flatten-encoder"),
+ });
prepare_document_gpu_resources(
device,
queue,
+ &self.pipelines,
+ &mut self.arenas,
+ None,
+ &mut encoder,
tile_pool,
&mut self.lut_cache,
- &mut self.doc_mask_cache,
+ &mut self.export_doc_mask_cache,
doc,
scratch,
&options.cel_visibility_overrides,
&options.onion_skin_frames,
+ None,
&view,
);
-
- let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-compositor-flatten-encoder"),
- });
clear_surface(
&self.pipelines,
export_targets,
@@ -2371,9 +3119,10 @@ impl WgpuCompositor {
pipelines: &self.pipelines,
arenas: &mut self.arenas,
targets: export_targets,
+ bg_cache: None,
tile_pool,
lut_cache: &self.lut_cache,
- doc_mask_cache: &self.doc_mask_cache,
+ doc_mask_cache: &self.export_doc_mask_cache,
styled_cache: &mut self.styled_cache,
doc,
cel_overrides: &options.cel_visibility_overrides,
@@ -2382,20 +3131,29 @@ impl WgpuCompositor {
allow_style_cache: false,
liquify_engine: None,
};
- render_onion_skins(
- &mut ctx,
- &mut encoder,
- &options.onion_skin_frames,
- SurfaceId::FinalScene,
- full_scissor,
- );
+ // Render onion skins ABOVE background/paper layers (right before the active cel),
+ // matching the live viewport stacking order identically!
+ let mut onion_drawn = options.onion_skin_frames.is_empty();
for unit in &units {
+ if !onion_drawn
+ && active_id_ref.is_some_and(|aid| unit.contained_layer_ids.contains(aid))
+ {
+ render_onion_skins(
+ &mut ctx,
+ &mut encoder,
+ &options.onion_skin_frames,
+ SurfaceId::FinalScene,
+ full_scissor,
+ );
+ onion_drawn = true;
+ }
render_compositing_unit(
&mut ctx,
&mut encoder,
unit,
SurfaceId::FinalScene,
None,
+ false,
0,
0,
0,
@@ -2403,6 +3161,15 @@ impl WgpuCompositor {
full_scissor,
);
}
+ if !onion_drawn {
+ render_onion_skins(
+ &mut ctx,
+ &mut encoder,
+ &options.onion_skin_frames,
+ SurfaceId::FinalScene,
+ full_scissor,
+ );
+ }
}
let proof_cfg = if options.apply_soft_proof {
@@ -2416,6 +3183,7 @@ impl WgpuCompositor {
&self.pipelines,
&mut self.arenas,
export_targets,
+ None,
&mut encoder,
&readback_surf.view,
&view,
@@ -2428,28 +3196,72 @@ impl WgpuCompositor {
transparent_bg,
true,
);
+
+ // Copy ONLY the core region in the same command encoder (1 submit per chunk, 4 B/px!).
+ let raw_bpr = core_w * 4;
+ let aligned_bpr = raw_bpr.div_ceil(256) * 256;
+ let staging_size = (aligned_bpr as u64) * (core_h as u64);
+ let staging = ensure_readback_staging(
+ device,
+ &mut local_readback_staging,
+ staging_size,
+ );
+ encoder.copy_texture_to_buffer(
+ wgpu::TexelCopyTextureInfo {
+ texture: &readback_surf.texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d {
+ x: pad_l,
+ y: pad_t,
+ z: 0,
+ },
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::TexelCopyBufferInfo {
+ buffer: staging,
+ layout: wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(aligned_bpr),
+ rows_per_image: Some(core_h),
+ },
+ },
+ wgpu::Extent3d {
+ width: core_w,
+ height: core_h,
+ depth_or_array_layers: 1,
+ },
+ );
self.arenas.finish_and_submit(queue, encoder);
+ tile_pool.unpin_all_pinned();
- let chunk_f16 = readback_surface_rgba16f(device, queue, readback_surf)?;
- copy_chunk_rgba16f_to_rgba8(
- &chunk_f16,
- chunk_w,
- pad_l,
- pad_t,
+ map_and_copy_rgba8_rows(
+ device,
+ staging,
+ staging_size,
+ aligned_bpr,
+ raw_bpr,
core_w,
core_h,
&mut out_rgba,
out_w,
cx,
cy,
- transparent_bg,
- );
+ )?;
cx += core_w;
}
cy += core_h;
}
+ // Release any temporary export caches immediately so export VRAM never leaks
+ self.export_targets = None;
+ self.export_readback_rgba8 = None;
+ self.export_readback_staging = None;
+ self.export_doc_mask_cache.clear();
+ drop(local_export_targets);
+ drop(local_readback_surf);
+ drop(local_readback_staging);
+
Ok((out_w, out_h, out_rgba))
}
@@ -2482,7 +3294,7 @@ impl WgpuCompositor {
let w = ((doc_w as f64 * max_d as f64) / doc_h as f64).round().max(1.0) as u32;
(w, max_d)
};
- let scale = out_w as f32 / doc_w as f32;
+ let scale = (out_w as f32 / doc_w as f32).min(out_h as f32 / doc_h as f32);
let cam = CameraState {
pan_x: out_w as f32 * 0.5,
pan_y: out_h as f32 * 0.5,
@@ -2494,29 +3306,33 @@ impl WgpuCompositor {
let view = FrameRenderView::new(doc, cam, out_w, out_h, 1.0, false, false);
let full_scissor = ScissorRect::full(out_w, out_h);
- let export_targets = self
- .export_targets
- .get_or_insert_with(|| CompositorTargets::new(device, queue, out_w, out_h));
- export_targets.ensure_size(device, out_w, out_h);
+ // Minimal local exact-sized targets (only final_scene + 1 Rgba8 readback) dropped immediately on return!
+ let mut export_targets = CompositorTargets::new_exact(device, queue, out_w, out_h);
+ let readback_surf = SurfaceRgba8::new(device, "ink-thumb-readback-rgba8", out_w, out_h);
+ let mut thumb_staging: Option<(wgpu::Buffer, u64)> = None;
tile_pool.begin_frame();
+ tile_pool.unpin_all_pinned();
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-compositor-thumb-encoder"),
+ });
prepare_layer_gpu_resources(
device,
queue,
+ &self.pipelines,
+ &mut self.arenas,
+ None,
+ &mut encoder,
tile_pool,
- &mut self.doc_mask_cache,
+ &mut self.export_doc_mask_cache,
doc,
layer,
scratch,
&view,
);
-
- let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-compositor-thumb-encoder"),
- });
clear_surface(
&self.pipelines,
- export_targets,
+ &export_targets,
&mut encoder,
SurfaceId::FinalScene,
full_scissor,
@@ -2528,10 +3344,11 @@ impl WgpuCompositor {
queue,
pipelines: &self.pipelines,
arenas: &mut self.arenas,
- targets: export_targets,
+ targets: &mut export_targets,
+ bg_cache: None,
tile_pool,
lut_cache: &self.lut_cache,
- doc_mask_cache: &self.doc_mask_cache,
+ doc_mask_cache: &self.export_doc_mask_cache,
styled_cache: &mut self.styled_cache,
doc,
cel_overrides: &empty_overrides,
@@ -2549,38 +3366,317 @@ impl WgpuCompositor {
1.0,
None,
None,
+ false,
full_scissor,
);
}
+ present_scene_to_view(
+ device,
+ queue,
+ &self.pipelines,
+ &mut self.arenas,
+ &export_targets,
+ None,
+ &mut encoder,
+ &readback_surf.view,
+ &view,
+ false,
+ [0.0, 0.0, 0.0, 0.0],
+ &SoftProofConfig::default(),
+ false,
+ false,
+ true,
+ true,
+ true,
+ );
+
+ let raw_bpr = out_w * 4;
+ let aligned_bpr = raw_bpr.div_ceil(256) * 256;
+ let staging_size = (aligned_bpr as u64) * (out_h as u64);
+ let staging = ensure_readback_staging(
+ device,
+ &mut thumb_staging,
+ staging_size,
+ );
+ encoder.copy_texture_to_buffer(
+ wgpu::TexelCopyTextureInfo {
+ texture: &readback_surf.texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::TexelCopyBufferInfo {
+ buffer: staging,
+ layout: wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(aligned_bpr),
+ rows_per_image: Some(out_h),
+ },
+ },
+ wgpu::Extent3d {
+ width: out_w,
+ height: out_h,
+ depth_or_array_layers: 1,
+ },
+ );
self.arenas.finish_and_submit(queue, encoder);
+ tile_pool.unpin_all_pinned();
- let raw_f16 = readback_surface_rgba16f(device, queue, &export_targets.final_scene)?;
let mut out_rgba = vec![0u8; (out_w * out_h * 4) as usize];
- copy_chunk_rgba16f_to_rgba8(
- &raw_f16,
- out_w,
- 0,
- 0,
+ map_and_copy_rgba8_rows(
+ device,
+ staging,
+ staging_size,
+ aligned_bpr,
+ raw_bpr,
out_w,
out_h,
&mut out_rgba,
out_w,
0,
0,
- true,
- );
+ )?;
+ self.export_doc_mask_cache.clear();
Ok((out_w, out_h, out_rgba))
}
}
// ============================================================================
-// Resource Preparation (Frustum-Culled Tile Upload, LOD Mipmaps, Masks, LUTs)
+// Resource Preparation (Cache-Aware Frustum-Culled Tile Upload, LOD Mipmaps,
+// GPU Viewport-Resolution Mask Projection, LUTs)
// ============================================================================
+fn mark_tree_node_layers(node: &LayerTreeNode, out: &mut [bool]) {
+ if let Some(slot) = out.get_mut(node.layer_index) {
+ *slot = true;
+ }
+ for child in &node.children {
+ mark_tree_node_layers(child, out);
+ }
+}
+
+fn mark_unit_layers(unit: &CompositingUnit, out: &mut [bool]) {
+ mark_tree_node_layers(&unit.group.base_node, out);
+ for cn in &unit.group.clipped_nodes {
+ mark_tree_node_layers(cn, out);
+ }
+}
+
+fn compute_final_scene_sig(
+ eval: &super::stack_cache::StackCacheEvaluation,
+ doc: &Document,
+ display: &CompositorDisplayConfig,
+) -> u64 {
+ let mut h = Fnv1a64::new();
+ 0xF1A1_5CEEu32.hash(&mut h);
+ eval.below_signature.hash(&mut h);
+ eval.above_signature.hash(&mut h);
+ h.write_bool(!eval.partition.above_cached_units.is_empty());
+ doc.active_layer_id.hash(&mut h);
+ h.write_bool(eval.partition.active_unit.is_some());
+ if let Some(au) = &eval.partition.active_unit {
+ hash_compositing_unit(&mut h, au, &doc.layers, &display.cel_visibility_overrides);
+ }
+ eval.partition.above_dynamic_units.len().hash(&mut h);
+ for du in &eval.partition.above_dynamic_units {
+ hash_compositing_unit(&mut h, du, &doc.layers, &display.cel_visibility_overrides);
+ }
+ h.finish()
+}
+
+/// Uploads visible sparse `R8Unorm` mask tiles into `tile_pool.mask_atlas` and projects them
+/// directly on GPU into a razor-sharp viewport-resolution `R8Unorm` texture inside `doc_mask_cache`
+/// ONLY when `DocMaskSig` (keyed on `grid.mask_version`, NEVER `layer_version`!) changes.
+#[allow(clippy::too_many_arguments)]
+fn ensure_gpu_viewport_mask_projected(
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ pipelines: &CompositorPipelines,
+ arenas: &mut FrameArenas,
+ mut bg_cache: Option<&mut ViewportBindGroupCache>,
+ encoder: &mut wgpu::CommandEncoder,
+ tile_pool: &mut GpuTilePool,
+ doc_mask_cache: &mut DocMaskCache,
+ doc: &Document,
+ layer: &LayerNode,
+ scratch: Option<&dyn ScratchBackend>,
+ view: &FrameRenderView,
+) {
+ let sig = DocMaskSig::for_layer(
+ layer,
+ doc.dimensions.width,
+ doc.dimensions.height,
+ view.viewport_w,
+ view.viewport_h,
+ view.camera_sig,
+ view.force_nearest,
+ );
+ if !doc_mask_cache.needs_update(&layer.meta.id, sig) {
+ return;
+ }
+
+ let doc_key = tile_pool.intern_doc(&doc.id);
+ let layer_key = tile_pool.intern_layer(&layer.meta.id);
+ let mut insts: Vec<SparseTileInst> = Vec::new();
+
+ if !layer.grid.mask_tiles.is_empty() && !view.frustum.is_empty() {
+ let min_tx = view.frustum.min_x.div_euclid(TILE_SIZE as i32);
+ let max_tx = (view.frustum.max_x - 1).div_euclid(TILE_SIZE as i32);
+ let min_ty = view.frustum.min_y.div_euclid(TILE_SIZE as i32);
+ let max_ty = (view.frustum.max_y - 1).div_euclid(TILE_SIZE as i32);
+ insts.reserve(layer.grid.mask_tiles.len().min(64));
+
+ for (&coord, mask_tile) in &layer.grid.mask_tiles {
+ if coord.tx < min_tx || coord.tx > max_tx || coord.ty < min_ty || coord.ty > max_ty {
+ continue;
+ }
+ let mkey = GpuTileKey {
+ doc_id: doc_key,
+ layer_id: layer_key,
+ lod: 0,
+ coord,
+ };
+ if let Ok(mslot) =
+ tile_pool.ensure_mask_uploaded(device, queue, mkey, mask_tile, scratch)
+ {
+ tile_pool.pin_mask_slot(mslot);
+ insts.push(SparseTileInst {
+ tile_origin_doc: [
+ (coord.tx * TILE_SIZE as i32) as f32,
+ (coord.ty * TILE_SIZE as i32) as f32,
+ ],
+ slot_f: mslot as f32,
+ tile_span: TILE_SIZE as f32,
+ });
+ }
+ }
+ }
+
+ let target_view = doc_mask_cache.prepare_render_target(device, &layer.meta.id, sig);
+ let clear_val = layer.grid.mask_default_value as f64 / 255.0;
+
+ if insts.is_empty() {
+ // Uniform reveal-all or hide-all mask: pure hardware clear, zero draw calls!
+ let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("ink-comp-mask-clear-pass"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: target_view,
+ depth_slice: None,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color {
+ r: clear_val,
+ g: 0.0,
+ b: 0.0,
+ a: 1.0,
+ }),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ multiview_mask: None,
+ });
+ return;
+ }
+
+ let uniforms = LiveDabUniforms {
+ viewport_size_phys: [view.viewport_w as f32, view.viewport_h as f32],
+ doc_size: [view.dimensions.width as f32, view.dimensions.height as f32],
+ pan_css: [view.camera.pan_x, view.camera.pan_y],
+ zoom: view.camera.zoom,
+ rotation_rad: view.rot_rad,
+ flip: view.flip,
+ dpr: view.dpr,
+ _pad: if view.force_nearest { 1.0 } else { 0.0 },
+ };
+ arenas.ensure_capacity(
+ device,
+ queue,
+ encoder,
+ std::mem::size_of::<LiveDabUniforms>(),
+ std::mem::size_of_val(insts.as_slice()),
+ 0,
+ 0,
+ );
+ let u_off = arenas.push_uniform(device, queue, encoder, &uniforms);
+ let (i_start, i_end) = arenas.push_sparse_stroke_tiles(device, queue, encoder, &insts);
+
+ let atlas_id = tile_pool.atlas_id();
+ let mask_atlas_view = tile_pool.mask_atlas_view();
+ let make_bg = || {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-comp-sparse-mask-bg"),
+ layout: &pipelines.sparse_mask_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &arenas.uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(std::mem::size_of::<LiveDabUniforms>() as u64),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(mask_atlas_view),
+ },
+ ],
+ })
+ };
+
+ let owned_bg;
+ let bg: &wgpu::BindGroup = if let Some(cache) = bg_cache.as_deref_mut() {
+ let needs_new = cache
+ .sparse_mask_bg
+ .as_ref()
+ .map(|(id, _)| *id != atlas_id)
+ .unwrap_or(true);
+ if needs_new {
+ cache.sparse_mask_bg = Some((atlas_id, make_bg()));
+ }
+ &cache.sparse_mask_bg.as_ref().expect("sparse_mask_bg cached").1
+ } else {
+ owned_bg = make_bg();
+ &owned_bg
+ };
+
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("ink-comp-mask-project-pass"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: target_view,
+ depth_slice: None,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color {
+ r: clear_val,
+ g: 0.0,
+ b: 0.0,
+ a: 1.0,
+ }),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ multiview_mask: None,
+ });
+ pass.set_pipeline(&pipelines.sparse_mask_project);
+ pass.set_bind_group(0, bg, &[u_off]);
+ pass.set_vertex_buffer(0, arenas.tile_inst_buf.slice(i_start..i_end));
+ pass.draw(0..6, 0..insts.len() as u32);
+}
+
#[allow(clippy::too_many_arguments)]
fn prepare_document_gpu_resources(
device: &wgpu::Device,
queue: &wgpu::Queue,
+ pipelines: &CompositorPipelines,
+ arenas: &mut FrameArenas,
+ mut bg_cache: Option<&mut ViewportBindGroupCache>,
+ encoder: &mut wgpu::CommandEncoder,
tile_pool: &mut GpuTilePool,
lut_cache: &mut AdjustmentLutCache,
doc_mask_cache: &mut DocMaskCache,
@@ -2588,10 +3684,16 @@ fn prepare_document_gpu_resources(
scratch: Option<&dyn ScratchBackend>,
cel_overrides: &HashMap<String, bool>,
onion_frames: &[OnionSkinFrame],
+ needed_layers: Option<&[bool]>,
view: &FrameRenderView,
) {
let onion_ids: HashSet<&str> = onion_frames.iter().map(|f| f.layer_id.as_str()).collect();
- for layer in &doc.layers {
+ for (idx, layer) in doc.layers.iter().enumerate() {
+ if let Some(mask) = needed_layers {
+ if !mask.get(idx).copied().unwrap_or(false) {
+ continue;
+ }
+ }
let visible = is_node_visible(layer, cel_overrides)
|| (onion_ids.contains(layer.meta.id.as_str()) && layer.meta.visible);
if !visible {
@@ -2607,13 +3709,19 @@ fn prepare_document_gpu_resources(
}
}
if layer_has_active_mask(layer) {
- doc_mask_cache.get_or_update(
+ ensure_gpu_viewport_mask_projected(
device,
queue,
+ pipelines,
+ arenas,
+ bg_cache.as_deref_mut(),
+ encoder,
+ tile_pool,
+ doc_mask_cache,
+ doc,
layer,
- doc.dimensions.width,
- doc.dimensions.height,
scratch,
+ view,
);
}
continue;
@@ -2621,13 +3729,19 @@ fn prepare_document_gpu_resources(
if layer.meta.layer_type.is_folder_like() {
if layer_has_active_mask(layer) {
- doc_mask_cache.get_or_update(
+ ensure_gpu_viewport_mask_projected(
device,
queue,
+ pipelines,
+ arenas,
+ bg_cache.as_deref_mut(),
+ encoder,
+ tile_pool,
+ doc_mask_cache,
+ doc,
layer,
- doc.dimensions.width,
- doc.dimensions.height,
scratch,
+ view,
);
}
continue;
@@ -2636,6 +3750,10 @@ fn prepare_document_gpu_resources(
prepare_layer_gpu_resources(
device,
queue,
+ pipelines,
+ arenas,
+ bg_cache.as_deref_mut(),
+ encoder,
tile_pool,
doc_mask_cache,
doc,
@@ -2650,6 +3768,10 @@ fn prepare_document_gpu_resources(
fn prepare_layer_gpu_resources(
device: &wgpu::Device,
queue: &wgpu::Queue,
+ pipelines: &CompositorPipelines,
+ arenas: &mut FrameArenas,
+ bg_cache: Option<&mut ViewportBindGroupCache>,
+ encoder: &mut wgpu::CommandEncoder,
tile_pool: &mut GpuTilePool,
doc_mask_cache: &mut DocMaskCache,
doc: &Document,
@@ -2658,16 +3780,22 @@ fn prepare_layer_gpu_resources(
view: &FrameRenderView,
) {
let has_mask = layer_has_active_mask(layer);
- // Active layer during live stroke, OR masked layers at LOD > 0 need the compact doc-level mask
+ // Active layer during live stroke, OR masked layers at LOD > 0 need the viewport-resolution GPU mask
let is_active = doc.active_layer_id.as_deref() == Some(layer.meta.id.as_str());
if has_mask && (view.lod > 0 || is_active) {
- doc_mask_cache.get_or_update(
+ ensure_gpu_viewport_mask_projected(
device,
queue,
+ pipelines,
+ arenas,
+ bg_cache,
+ encoder,
+ tile_pool,
+ doc_mask_cache,
+ doc,
layer,
- doc.dimensions.width,
- doc.dimensions.height,
scratch,
+ view,
);
}
@@ -2675,6 +3803,9 @@ fn prepare_layer_gpu_resources(
return;
}
+ let doc_key = tile_pool.intern_doc(&doc.id);
+ let layer_key = tile_pool.intern_layer(&layer.meta.id);
+
let scale = 1i32 << view.lod;
let span = TILE_SIZE as i32 * scale;
let min_tx = view.frustum.min_x.div_euclid(span);
@@ -2682,28 +3813,42 @@ fn prepare_layer_gpu_resources(
let min_ty = view.frustum.min_y.div_euclid(span);
let max_ty = (view.frustum.max_y - 1).div_euclid(span);
+ let reserve = 12u32.min(tile_pool.capacity() / 2);
+
if view.lod == 0 {
for (&coord, tile) in &layer.grid.tiles {
if coord.tx < min_tx || coord.tx > max_tx || coord.ty < min_ty || coord.ty > max_ty {
continue;
}
let key = GpuTileKey {
- doc_id: doc.id.clone(),
- layer_id: layer.meta.id.clone(),
+ doc_id: doc_key,
+ layer_id: layer_key,
lod: 0,
coord,
};
- let _ = tile_pool.ensure_tile_uploaded(queue, key, tile, scratch);
+ if let Ok(slot) = tile_pool.ensure_tile_uploaded(queue, key, tile, scratch) {
+ let is_solid = tile.solid_rgba16f().is_some();
+ if is_solid
+ || tile_pool.is_slot_pinned(slot)
+ || tile_pool.unpinned_slot_count() > reserve
+ {
+ tile_pool.pin_slot(slot);
+ }
+ }
if has_mask {
if let Some(mask_tile) = layer.grid.mask_tiles.get(&coord) {
let mkey = GpuTileKey {
- doc_id: doc.id.clone(),
- layer_id: layer.meta.id.clone(),
+ doc_id: doc_key,
+ layer_id: layer_key,
lod: 0,
coord,
};
- let _ = tile_pool.ensure_mask_uploaded(queue, mkey, mask_tile, scratch);
+ if let Ok(mslot) =
+ tile_pool.ensure_mask_uploaded(device, queue, mkey, mask_tile, scratch)
+ {
+ tile_pool.pin_mask_slot(mslot);
+ }
}
}
}
@@ -2717,17 +3862,52 @@ fn prepare_layer_gpu_resources(
parent_coords.insert(TileCoord::new(ptx, pty));
}
}
+ // Pre-generate all missing LOD tiles for this layer in ONE batched compute submit
+ if (1..=3).contains(&view.lod) && !parent_coords.is_empty() {
+ let mut batch_lods: [Vec<TileCoord>; 3] = [Vec::new(), Vec::new(), Vec::new()];
+ batch_lods[(view.lod - 1) as usize] = parent_coords.iter().copied().collect();
+ regenerate_grid_lods_batched(
+ device,
+ queue,
+ tile_pool,
+ &doc.id,
+ &layer.meta.id,
+ &layer.grid,
+ doc.dimensions.width,
+ doc.dimensions.height,
+ &batch_lods,
+ false,
+ scratch,
+ );
+ }
for pcoord in parent_coords {
- let _ = ensure_lod_tile_recursive(
+ let is_uniform_solid = uniform_solid_color_for_lod_tile(
+ &layer.grid,
+ view.lod,
+ pcoord,
+ doc.dimensions.width,
+ doc.dimensions.height,
+ )
+ .is_some();
+ if let Some(slot) = ensure_lod_tile_recursive(
device,
queue,
tile_pool,
&doc.id,
layer,
+ doc.dimensions.width,
+ doc.dimensions.height,
view.lod,
pcoord,
scratch,
- );
+ ) {
+ if is_uniform_solid
+ || tile_pool.is_slot_pinned(slot)
+ || tile_pool.unpinned_slot_count() > reserve
+ {
+ tile_pool.pin_slot(slot);
+ }
+ }
}
}
@@ -2746,12 +3926,14 @@ fn prepare_layer_gpu_resources(
continue;
}
let key = GpuTileKey {
- doc_id: doc.id.clone(),
- layer_id: layer.meta.id.clone(),
+ doc_id: doc_key,
+ layer_id: layer_key,
lod: 0,
coord,
};
- let _ = tile_pool.ensure_impasto_uploaded(device, queue, key, imp_tile, scratch);
+ if let Ok(islot) = tile_pool.ensure_impasto_uploaded(device, queue, key, imp_tile, scratch) {
+ tile_pool.pin_impasto_slot(islot);
+ }
}
}
}
@@ -2763,76 +3945,25 @@ fn ensure_lod_tile_recursive(
tile_pool: &mut GpuTilePool,
doc_id: &str,
layer: &LayerNode,
+ doc_w: u32,
+ doc_h: u32,
lod: u8,
coord: TileCoord,
scratch: Option<&dyn ScratchBackend>,
) -> Option<u32> {
- let key = GpuTileKey {
- doc_id: doc_id.to_string(),
- layer_id: layer.meta.id.clone(),
- lod,
- coord,
- };
- if lod == 0 {
- let tile = layer.grid.tiles.get(&coord)?;
- return tile_pool.ensure_tile_uploaded(queue, key, tile, scratch).ok();
- }
- if let Some(slot) = tile_pool.get_slot_if_version(&key, layer.grid.layer_version) {
- return Some(slot);
- }
-
- let c00 = ensure_lod_tile_recursive(
- device,
- queue,
- tile_pool,
- doc_id,
- layer,
- lod - 1,
- TileCoord::new(coord.tx * 2, coord.ty * 2),
- scratch,
- );
- let c10 = ensure_lod_tile_recursive(
- device,
- queue,
- tile_pool,
- doc_id,
- layer,
- lod - 1,
- TileCoord::new(coord.tx * 2 + 1, coord.ty * 2),
- scratch,
- );
- let c01 = ensure_lod_tile_recursive(
- device,
- queue,
- tile_pool,
- doc_id,
- layer,
- lod - 1,
- TileCoord::new(coord.tx * 2, coord.ty * 2 + 1),
- scratch,
- );
- let c11 = ensure_lod_tile_recursive(
+ ensure_grid_lod_tile_recursive(
device,
queue,
tile_pool,
doc_id,
- layer,
- lod - 1,
- TileCoord::new(coord.tx * 2 + 1, coord.ty * 2 + 1),
+ &layer.meta.id,
+ &layer.grid,
+ doc_w,
+ doc_h,
+ lod,
+ coord,
scratch,
- );
-
- if c00.is_none() && c10.is_none() && c01.is_none() && c11.is_none() {
- return None;
- }
-
- Some(tile_pool.generate_mipmap_tile(
- device,
- queue,
- key,
- [c00, c10, c01, c11],
- layer.grid.layer_version,
- ))
+ )
}
// ============================================================================
@@ -2845,6 +3976,7 @@ struct PassCtx<'a> {
pipelines: &'a CompositorPipelines,
arenas: &'a mut FrameArenas,
targets: &'a mut CompositorTargets,
+ bg_cache: Option<&'a mut ViewportBindGroupCache>,
tile_pool: &'a mut GpuTilePool,
lut_cache: &'a AdjustmentLutCache,
doc_mask_cache: &'a DocMaskCache,
@@ -2868,8 +4000,10 @@ fn clear_surface(
return;
}
let surf = get_surface(targets, dst);
- let is_full =
- scissor.x == 0 && scissor.y == 0 && scissor.width >= surf.width && scissor.height >= surf.height;
+ let is_full = scissor.x == 0
+ && scissor.y == 0
+ && scissor.width >= targets.width
+ && scissor.height >= targets.height;
if is_full {
let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("ink-comp-clear-full"),
@@ -2904,6 +4038,7 @@ fn clear_surface(
occlusion_query_set: None,
multiview_mask: None,
});
+ pass.set_viewport(0.0, 0.0, targets.width as f32, targets.height as f32, 0.0, 1.0);
pass.set_scissor_rect(scissor.x, scissor.y, scissor.width, scissor.height);
pass.set_pipeline(&pipelines.clear_rect);
pass.draw(0..3, 0..1);
@@ -2936,6 +4071,7 @@ fn render_onion_skins(
onion.opacity,
Some((onion.tint, [1.0, 1.0, 1.0])),
None,
+ false,
scissor,
);
}
@@ -2948,6 +4084,7 @@ fn render_compositing_unit(
unit: &CompositingUnit,
dst: SurfaceId,
outer_clip: Option<SurfaceId>,
+ source_atop: bool,
folder_depth: usize,
clip_depth: usize,
frame_depth: usize,
@@ -2961,6 +4098,7 @@ fn render_compositing_unit(
unit.inherited_opacity,
dst,
outer_clip,
+ source_atop,
folder_depth,
clip_depth,
frame_depth,
@@ -2977,6 +4115,7 @@ fn render_group(
inherited_opacity: f32,
dst: SurfaceId,
outer_clip: Option<SurfaceId>,
+ source_atop: bool,
folder_depth: usize,
clip_depth: usize,
frame_depth: usize,
@@ -3010,6 +4149,7 @@ fn render_group(
inherited_opacity,
dst,
outer_clip,
+ source_atop,
folder_depth,
clip_depth,
frame_depth,
@@ -3019,9 +4159,9 @@ fn render_group(
return;
}
- // Clipping-mask chain:
- // 1. Render base node into `ClipMask(clip_depth)` with Normal blend & outer_clip
- // so `clip_surf` holds the exact continuous-alpha silhouette of the base layer!
+ // Isolated Clipping-Mask Group (`source-atop`):
+ // 1. Render base node into `ClipMask(clip_depth)` with Normal blend & `outer_clip`
+ // so `clip_surf` holds the exact continuous-alpha silhouette & color of the base layer.
ctx.targets.ensure_clip_depth(ctx.device, clip_depth);
let clip_surf = SurfaceId::ClipMask(clip_depth);
clear_surface(ctx.pipelines, ctx.targets, encoder, clip_surf, scissor);
@@ -3033,6 +4173,7 @@ fn render_group(
inherited_opacity,
clip_surf,
outer_clip,
+ false,
folder_depth,
clip_depth + 1,
frame_depth,
@@ -3040,7 +4181,27 @@ fn render_group(
scissor,
);
- // 2. Composite base silhouette onto `dst` with base's true blend mode
+ // 2. Composite every clipped sibling directly onto `clip_surf` using hardware `source-atop`
+ // blending (`Color: DstAlpha / OneMinusSrcAlpha`, `Alpha: Zero / One`) so `base.alpha` is
+ // preserved strictly with ZERO alpha bloat (`0.5 -> 0.5`) and ZERO color bleed!
+ for cn in visible_clipped {
+ render_tree_node(
+ ctx,
+ encoder,
+ cn,
+ inherited_opacity,
+ clip_surf,
+ None,
+ true,
+ folder_depth,
+ clip_depth + 1,
+ frame_depth,
+ false,
+ scissor,
+ );
+ }
+
+ // 3. Composite the finished clipped group onto `dst` ONCE using `base`'s true blend mode!
let base_blend = if override_root_blend_normal
|| (base_layer.meta.layer_type.is_folder_like()
&& base_layer.meta.blend_mode == BlendMode::PassThrough)
@@ -3058,25 +4219,9 @@ fn render_group(
1.0,
None,
None, // outer_clip already baked into clip_surf!
+ source_atop,
scissor,
);
-
- // 3. Render every clipped sibling node onto `dst` clipped strictly by `clip_surf`!
- for cn in visible_clipped {
- render_tree_node(
- ctx,
- encoder,
- cn,
- inherited_opacity,
- dst,
- Some(clip_surf),
- folder_depth,
- clip_depth + 1,
- frame_depth,
- false,
- scissor,
- );
- }
}
#[allow(clippy::too_many_arguments)]
@@ -3087,6 +4232,7 @@ fn render_tree_node(
inherited_opacity: f32,
dst: SurfaceId,
outer_clip: Option<SurfaceId>,
+ source_atop: bool,
folder_depth: usize,
clip_depth: usize,
frame_depth: usize,
@@ -3102,7 +4248,15 @@ fn render_tree_node(
match layer.meta.layer_type {
LayerType::Adjustment => {
- render_adjustment_layer(ctx, encoder, layer, inherited_opacity, dst, outer_clip, scissor);
+ render_adjustment_layer(
+ ctx,
+ encoder,
+ layer,
+ inherited_opacity,
+ dst,
+ outer_clip,
+ scissor,
+ );
}
LayerType::Folder => {
render_folder_node(
@@ -3113,6 +4267,7 @@ fn render_tree_node(
inherited_opacity,
dst,
outer_clip,
+ source_atop,
folder_depth,
clip_depth,
frame_depth,
@@ -3129,6 +4284,7 @@ fn render_tree_node(
inherited_opacity,
dst,
outer_clip,
+ source_atop,
folder_depth,
clip_depth,
frame_depth,
@@ -3157,6 +4313,7 @@ fn render_tree_node(
blend,
dst,
outer_clip,
+ source_atop,
is_live,
scissor,
);
@@ -3172,6 +4329,7 @@ fn render_tree_node(
inherited_opacity.clamp(0.0, 1.0),
None,
outer_clip,
+ source_atop,
scissor,
);
} else {
@@ -3184,6 +4342,7 @@ fn render_tree_node(
eff_opacity,
None,
outer_clip,
+ source_atop,
scissor,
);
}
@@ -3200,6 +4359,7 @@ fn render_folder_node(
inherited_opacity: f32,
dst: SurfaceId,
outer_clip: Option<SurfaceId>,
+ source_atop: bool,
folder_depth: usize,
clip_depth: usize,
frame_depth: usize,
@@ -3208,10 +4368,8 @@ fn render_folder_node(
) {
let has_mask = layer_has_active_mask(layer);
let styles = parse_layer_styles(layer.meta.styles.as_ref());
- let is_pass_through = layer.meta.blend_mode == BlendMode::PassThrough
- && !has_mask
- && !styles.has_active()
- && !override_blend_normal;
+ // Isolate PassThrough folders whenever masked, styled, opacity < 1.0, or root blend overridden!
+ let is_pass_through = folder_is_true_pass_through(layer) && !override_blend_normal && !source_atop;
// Children in `node.children` are top-to-bottom; reverse to bottom-to-top for compositing
let children_b2t: Vec<LayerTreeNode> = node.children.iter().rev().cloned().collect();
@@ -3227,6 +4385,7 @@ fn render_folder_node(
next_opacity,
dst,
outer_clip,
+ false,
folder_depth,
clip_depth,
frame_depth,
@@ -3250,6 +4409,7 @@ fn render_folder_node(
1.0,
folder_surf,
None,
+ false,
folder_depth + 1,
clip_depth,
frame_depth,
@@ -3281,6 +4441,7 @@ fn render_folder_node(
dst,
mask_id,
outer_clip,
+ source_atop,
scissor,
);
} else {
@@ -3293,6 +4454,7 @@ fn render_folder_node(
eff_opacity,
mask_id,
outer_clip,
+ source_atop,
scissor,
);
}
@@ -3307,6 +4469,7 @@ fn render_frame_folder_node(
inherited_opacity: f32,
dst: SurfaceId,
outer_clip: Option<SurfaceId>,
+ source_atop: bool,
folder_depth: usize,
clip_depth: usize,
frame_depth: usize,
@@ -3317,12 +4480,15 @@ fn render_frame_folder_node(
let has_mask = layer_has_active_mask(layer);
let styles = parse_layer_styles(layer.meta.styles.as_ref());
let eff_opacity = (layer.meta.opacity * inherited_opacity).clamp(0.0, 1.0);
+ // Isolate `Normal` FrameFolders (and any non-PassThrough blend mode, mask, style, <1 opacity, or outer clip)
+ // matching `Folder` isolation and `layer_tree::is_unit_normal_associative`!
let is_isolated = override_blend_normal
|| has_mask
|| styles.has_active()
- || (layer.meta.blend_mode != BlendMode::PassThrough && layer.meta.blend_mode != BlendMode::Normal)
+ || layer.meta.blend_mode != BlendMode::PassThrough
|| eff_opacity < 0.999
- || outer_clip.is_some();
+ || outer_clip.is_some()
+ || source_atop;
let render_target = if is_isolated {
ctx.targets.ensure_folder_depth(ctx.device, folder_depth);
@@ -3396,6 +4562,7 @@ fn render_frame_folder_node(
1.0,
render_target,
child_clip,
+ false,
folder_depth + usize::from(is_isolated),
clip_depth,
frame_depth + 1,
@@ -3453,6 +4620,7 @@ fn render_frame_folder_node(
dst,
mask_id,
outer_clip,
+ source_atop,
scissor,
);
} else {
@@ -3465,6 +4633,7 @@ fn render_frame_folder_node(
eff_opacity,
mask_id,
outer_clip,
+ source_atop,
scissor,
);
}
@@ -3493,21 +4662,49 @@ fn draw_frame_polygons(
_pad: 0.0,
color,
};
+ ctx.arenas.ensure_capacity(
+ ctx.device,
+ ctx.queue,
+ encoder,
+ std::mem::size_of::<FramePolyUniforms>(),
+ 0,
+ std::mem::size_of_val(verts),
+ 0,
+ );
let u_off = ctx.arenas.push_uniform(ctx.device, ctx.queue, encoder, &uniforms);
let (v_start, v_end) = ctx.arenas.push_poly_vertices(ctx.device, ctx.queue, encoder, verts);
- let bg = ctx.device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-comp-frame-poly-bg"),
- layout: &ctx.pipelines.frame_poly_bgl,
- entries: &[wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &ctx.arenas.uniform_buf,
- offset: 0,
- size: NonZeroU64::new(std::mem::size_of::<FramePolyUniforms>() as u64),
- }),
- }],
- });
+ let owned_bg;
+ let bg: &wgpu::BindGroup = if let Some(cache) = ctx.bg_cache.as_deref_mut() {
+ cache.frame_poly_bg.get_or_insert_with(|| {
+ ctx.device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-comp-frame-poly-bg"),
+ layout: &ctx.pipelines.frame_poly_bgl,
+ entries: &[wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &ctx.arenas.uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(std::mem::size_of::<FramePolyUniforms>() as u64),
+ }),
+ }],
+ })
+ })
+ } else {
+ owned_bg = ctx.device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-comp-frame-poly-bg"),
+ layout: &ctx.pipelines.frame_poly_bgl,
+ entries: &[wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &ctx.arenas.uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(std::mem::size_of::<FramePolyUniforms>() as u64),
+ }),
+ }],
+ });
+ &owned_bg
+ };
let dst_surf = get_surface(ctx.targets, dst);
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
@@ -3526,9 +4723,10 @@ fn draw_frame_polygons(
occlusion_query_set: None,
multiview_mask: None,
});
+ pass.set_viewport(0.0, 0.0, ctx.view.viewport_w as f32, ctx.view.viewport_h as f32, 0.0, 1.0);
pass.set_scissor_rect(scissor.x, scissor.y, scissor.width, scissor.height);
pass.set_pipeline(&ctx.pipelines.frame_poly);
- pass.set_bind_group(0, &bg, &[u_off]);
+ pass.set_bind_group(0, bg, &[u_off]);
pass.set_vertex_buffer(0, ctx.arenas.poly_vert_buf.slice(v_start..v_end));
pass.draw(0..verts.len() as u32, 0..1);
}
@@ -3553,7 +4751,8 @@ fn render_adjustment_layer(
return;
};
- // Snapshot backdrop strictly inside `scissor`!
+ // Lazily ensure backdrop scratch and snapshot backdrop strictly inside `scissor`!
+ ctx.targets.ensure_backdrop_scratch(ctx.device);
get_surface(ctx.targets, dst).copy_region_to(
encoder,
get_surface(ctx.targets, SurfaceId::BackdropScratch),
@@ -3578,18 +4777,18 @@ fn render_adjustment_layer(
};
let has_mask = layer_has_active_mask(layer);
- let mask_view = if has_mask {
+ let (mask_view, mask_view_id) = if has_mask {
ctx.doc_mask_cache
- .get_cached_view(&layer.meta.id)
- .unwrap_or(&ctx.targets.dummy_white_r8_view)
+ .get_cached_view_with_id(&layer.meta.id)
+ .unwrap_or((&ctx.targets.dummy_white_r8_view, 0))
} else {
- &ctx.targets.dummy_white_r8_view
+ (&ctx.targets.dummy_white_r8_view, 0)
};
- let lut_view = ctx
+ let (lut_view, lut_view_id) = ctx
.lut_cache
- .get_view(&layer.meta.id)
- .unwrap_or(&ctx.targets.dummy_lut_rgba8_view);
+ .get_view_with_id(&layer.meta.id)
+ .unwrap_or((&ctx.targets.dummy_lut_rgba8_view, 0));
let clip_view = outer_clip
.map(|id| &get_surface(ctx.targets, id).view)
@@ -3613,43 +4812,58 @@ fn render_adjustment_layer(
cb_shadows,
cb_midtones,
cb_highlights,
+ blend_flags: [blend_mode_to_code(layer.meta.blend_mode), 0, 0, 0],
};
let u_off = ctx.arenas.push_uniform(ctx.device, ctx.queue, encoder, &uniforms);
- let bg = ctx.device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-comp-adjustment-bg"),
- layout: &ctx.pipelines.adjustment_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &ctx.arenas.uniform_buf,
- offset: 0,
- size: NonZeroU64::new(std::mem::size_of::<AdjustmentUniforms>() as u64),
- }),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(&ctx.targets.backdrop_scratch.view),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::TextureView(lut_view),
- },
- wgpu::BindGroupEntry {
- binding: 3,
- resource: wgpu::BindingResource::TextureView(mask_view),
- },
- wgpu::BindGroupEntry {
- binding: 4,
- resource: wgpu::BindingResource::TextureView(clip_view),
- },
- wgpu::BindGroupEntry {
- binding: 5,
- resource: wgpu::BindingResource::Sampler(&ctx.pipelines.linear_sampler),
- },
- ],
- });
+ let backdrop_view = &get_surface(ctx.targets, SurfaceId::BackdropScratch).view;
+ let make_bg = || {
+ ctx.device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-comp-adjustment-bg"),
+ layout: &ctx.pipelines.adjustment_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &ctx.arenas.uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(std::mem::size_of::<AdjustmentUniforms>() as u64),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(backdrop_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(lut_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::TextureView(mask_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 4,
+ resource: wgpu::BindingResource::TextureView(clip_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 5,
+ resource: wgpu::BindingResource::Sampler(&ctx.pipelines.linear_sampler),
+ },
+ ],
+ })
+ };
+
+ let owned_bg;
+ let bg: &wgpu::BindGroup = if let Some(cache) = ctx.bg_cache.as_deref_mut() {
+ cache
+ .adjustment_bgs
+ .entry((lut_view_id, mask_view_id, outer_clip))
+ .or_insert_with(make_bg)
+ } else {
+ owned_bg = make_bg();
+ &owned_bg
+ };
let dst_surf = get_surface(ctx.targets, dst);
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
@@ -3668,9 +4882,10 @@ fn render_adjustment_layer(
occlusion_query_set: None,
multiview_mask: None,
});
+ pass.set_viewport(0.0, 0.0, ctx.view.viewport_w as f32, ctx.view.viewport_h as f32, 0.0, 1.0);
pass.set_scissor_rect(scissor.x, scissor.y, scissor.width, scissor.height);
pass.set_pipeline(&ctx.pipelines.adjustment);
- pass.set_bind_group(0, &bg, &[u_off]);
+ pass.set_bind_group(0, bg, &[u_off]);
pass.draw(0..3, 0..1);
}
@@ -3684,6 +4899,7 @@ fn render_styled_layer(
blend: BlendMode,
dst: SurfaceId,
outer_clip: Option<SurfaceId>,
+ source_atop: bool,
is_live: bool,
scissor: ScissorRect,
) {
@@ -3699,7 +4915,7 @@ fn render_styled_layer(
// Check LRU StyledLayerCache when full viewport & not actively streaming a live stroke
if ctx.allow_style_cache && !is_live && is_full {
let style_sig = compute_styled_layer_sig(layer, ctx.view);
- if let Some(cached) = ctx.styled_cache.get_hit(
+ if let Some((cached, cached_view_id)) = ctx.styled_cache.get_hit(
&layer.meta.id,
style_sig,
ctx.view.viewport_w,
@@ -3712,6 +4928,8 @@ fn render_styled_layer(
ctx.pipelines,
ctx.arenas,
ctx.targets,
+ ctx.bg_cache.as_deref_mut(),
+ Some(cached_view_id),
ctx.doc_mask_cache,
encoder,
cached_view,
@@ -3720,13 +4938,15 @@ fn render_styled_layer(
eff_opacity,
None,
outer_clip,
+ source_atop,
ctx.view,
scissor,
);
return;
}
- // Cache miss -> render raw styled layer at opacity 1.0 into StyleSrc, run blurs + styles into cached slot!
+ // Cache miss -> render raw styled layer at opacity 1.0 into StyleSrc, run blurs + stroke SDF into cached slot!
+ ctx.targets.ensure_style_src(ctx.device);
clear_surface(ctx.pipelines, ctx.targets, encoder, SurfaceId::StyleSrc, scissor);
render_raster_layer_tiles(
ctx,
@@ -3737,11 +4957,12 @@ fn render_styled_layer(
1.0,
None,
None,
+ false,
scissor,
);
- run_style_blurs(ctx, encoder, SurfaceId::StyleSrc, styles, scissor);
+ run_style_prepasses(ctx, encoder, SurfaceId::StyleSrc, styles, scissor);
- let slot_surf = ctx.styled_cache.allocate_slot(
+ let (slot_surf, slot_view_id) = ctx.styled_cache.allocate_slot(
ctx.device,
&layer.meta.id,
style_sig,
@@ -3754,8 +4975,9 @@ fn render_styled_layer(
ctx.pipelines,
ctx.arenas,
ctx.targets,
+ ctx.bg_cache.as_deref_mut(),
encoder,
- &ctx.targets.style_src.view,
+ SurfaceId::StyleSrc,
&slot_surf.view,
styles,
1.0,
@@ -3768,6 +4990,8 @@ fn render_styled_layer(
ctx.pipelines,
ctx.arenas,
ctx.targets,
+ ctx.bg_cache.as_deref_mut(),
+ Some(slot_view_id),
ctx.doc_mask_cache,
encoder,
&slot_surf.view,
@@ -3776,16 +5000,20 @@ fn render_styled_layer(
eff_opacity,
None,
outer_clip,
+ source_atop,
ctx.view,
scissor,
);
return;
}
- // Live stroke or partial-scissor styled path (bypass LRU cache)
+ // Live stroke or partial-scissor styled path (bypass LRU cache).
+ // Note: when `is_live`, ActiveUnit was intentionally merged with `unattenuated_layer_opacity = true`
+ // (`layer_opacity = 1.0`) so stroke coverage (alpha >= 0.5) never disappears when `layer.meta.opacity <= 0.5`!
let src_id = if is_live {
SurfaceId::ActiveUnit
} else {
+ ctx.targets.ensure_style_src(ctx.device);
clear_surface(ctx.pipelines, ctx.targets, encoder, SurfaceId::StyleSrc, scissor);
render_raster_layer_tiles(
ctx,
@@ -3796,26 +5024,22 @@ fn render_styled_layer(
1.0,
None,
None,
+ false,
scissor,
);
SurfaceId::StyleSrc
};
- let final_opacity = if is_live {
- // ActiveUnit already has layer.meta.opacity applied
- (eff_opacity / layer.meta.opacity.max(0.001)).clamp(0.0, 1.0)
- } else {
- eff_opacity
- };
apply_styles_to_surface_and_blit(
ctx,
encoder,
src_id,
styles,
- final_opacity,
+ eff_opacity,
blend,
dst,
None,
outer_clip,
+ source_atop,
scissor,
);
}
@@ -3831,19 +5055,22 @@ fn apply_styles_to_surface_and_blit(
dst: SurfaceId,
mask_layer_id: Option<&str>,
outer_clip: Option<SurfaceId>,
+ source_atop: bool,
scissor: ScissorRect,
) {
- run_style_blurs(ctx, encoder, src, styles, scissor);
- // Write styled result into StyleBlurTmp (safe: blur passes already finished into Shadow/Glow!)
+ run_style_prepasses(ctx, encoder, src, styles, scissor);
+ // Write styled result into dedicated `StyleCompositeOut` (never aliasing `StyleBlurTmp`!)
+ ctx.targets.ensure_style_composite_out(ctx.device);
run_layer_styles_composite(
ctx.device,
ctx.queue,
ctx.pipelines,
ctx.arenas,
ctx.targets,
+ ctx.bg_cache.as_deref_mut(),
encoder,
- &get_surface(ctx.targets, src).view,
- &ctx.targets.style_blur_tmp.view,
+ src,
+ &get_surface(ctx.targets, SurfaceId::StyleCompositeOut).view,
styles,
1.0,
ctx.view,
@@ -3852,17 +5079,21 @@ fn apply_styles_to_surface_and_blit(
blit_surface_onto(
ctx,
encoder,
- SurfaceId::StyleBlurTmp,
+ SurfaceId::StyleCompositeOut,
dst,
blend,
eff_opacity,
mask_layer_id,
outer_clip,
+ source_atop,
scissor,
);
}
-fn run_style_blurs(
+/// Runs all required separable blur (Drop Shadow / Outer Glow) and 2-pass exact Euclidean
+/// Stroke SDF prepasses for `styles`, expanding horizontal pass scissors vertically by
+/// `ceil(radius_px)` so vertical passes never sample stale pixels outside `scissor`.
+fn run_style_prepasses(
ctx: &mut PassCtx<'_>,
encoder: &mut wgpu::CommandEncoder,
src: SurfaceId,
@@ -3871,28 +5102,41 @@ fn run_style_blurs(
) {
let scale = ctx.view.camera.zoom * ctx.view.dpr;
if let Some(sh) = styles.drop_shadow {
- if sh.enabled && sh.opacity > 0.001 && sh.blur > 0.25 {
- let rad_px = (sh.blur * scale).min(128.0);
- run_separable_blur_pass(
+ let rad_px = (sh.blur * scale).min(128.0);
+ // Unified screen-space threshold (`> 0.25`) matching `run_layer_styles_composite` & WGSL!
+ if sh.enabled && sh.opacity > 0.001 && rad_px > 0.25 {
+ ctx.targets.ensure_style_blur_tmp(ctx.device);
+ ctx.targets.ensure_style_shadow_blur(ctx.device);
+ // Expand horizontal pass vertically by ceil(rad_px) so vertical pass never reads stale rows
+ let horiz_scissor = scissor.expand_y(
+ rad_px.ceil() as i32 + 1,
+ ctx.view.viewport_w,
+ ctx.view.viewport_h,
+ );
+ run_separable_filter_pass(
ctx.device,
ctx.queue,
ctx.pipelines,
+ &ctx.pipelines.separable_blur,
ctx.arenas,
ctx.targets,
+ ctx.bg_cache.as_deref_mut(),
encoder,
src,
SurfaceId::StyleBlurTmp,
[1.0, 0.0],
rad_px,
ctx.view,
- scissor,
+ horiz_scissor,
);
- run_separable_blur_pass(
+ run_separable_filter_pass(
ctx.device,
ctx.queue,
ctx.pipelines,
+ &ctx.pipelines.separable_blur,
ctx.arenas,
ctx.targets,
+ ctx.bg_cache.as_deref_mut(),
encoder,
SurfaceId::StyleBlurTmp,
SurfaceId::StyleShadowBlur,
@@ -3904,28 +5148,39 @@ fn run_style_blurs(
}
}
if let Some(gl) = styles.outer_glow {
- if gl.enabled && gl.opacity > 0.001 && gl.blur > 0.0 {
- let rad_px = (gl.blur * scale).min(128.0);
- run_separable_blur_pass(
+ let rad_px = (gl.blur * scale).min(128.0);
+ if gl.enabled && gl.opacity > 0.001 && rad_px > 0.0 {
+ ctx.targets.ensure_style_blur_tmp(ctx.device);
+ ctx.targets.ensure_style_glow_blur(ctx.device);
+ let horiz_scissor = scissor.expand_y(
+ rad_px.ceil() as i32 + 1,
+ ctx.view.viewport_w,
+ ctx.view.viewport_h,
+ );
+ run_separable_filter_pass(
ctx.device,
ctx.queue,
ctx.pipelines,
+ &ctx.pipelines.separable_blur,
ctx.arenas,
ctx.targets,
+ ctx.bg_cache.as_deref_mut(),
encoder,
src,
SurfaceId::StyleBlurTmp,
[1.0, 0.0],
rad_px,
ctx.view,
- scissor,
+ horiz_scissor,
);
- run_separable_blur_pass(
+ run_separable_filter_pass(
ctx.device,
ctx.queue,
ctx.pipelines,
+ &ctx.pipelines.separable_blur,
ctx.arenas,
ctx.targets,
+ ctx.bg_cache.as_deref_mut(),
encoder,
SurfaceId::StyleBlurTmp,
SurfaceId::StyleGlowBlur,
@@ -3936,15 +5191,65 @@ fn run_style_blurs(
);
}
}
+ if let Some(st) = styles.stroke {
+ if st.enabled && st.size > 0.0 && st.opacity > 0.001 {
+ let stroke_px = (st.size * scale).min(128.0);
+ let sdf_rad = if st.position == super::StrokePosition::Center {
+ (stroke_px * 0.5).max(0.5)
+ } else {
+ stroke_px.max(0.5)
+ };
+ ctx.targets.ensure_style_stroke_surfaces(ctx.device);
+ let horiz_scissor = scissor.expand_y(
+ sdf_rad.ceil() as i32 + 2,
+ ctx.view.viewport_w,
+ ctx.view.viewport_h,
+ );
+ run_separable_filter_pass(
+ ctx.device,
+ ctx.queue,
+ ctx.pipelines,
+ &ctx.pipelines.stroke_sdf_horiz,
+ ctx.arenas,
+ ctx.targets,
+ ctx.bg_cache.as_deref_mut(),
+ encoder,
+ src,
+ SurfaceId::StyleStrokeDilateTmp,
+ [1.0, 0.0],
+ sdf_rad,
+ ctx.view,
+ horiz_scissor,
+ );
+ run_separable_filter_pass(
+ ctx.device,
+ ctx.queue,
+ ctx.pipelines,
+ &ctx.pipelines.stroke_sdf_vert,
+ ctx.arenas,
+ ctx.targets,
+ ctx.bg_cache.as_deref_mut(),
+ encoder,
+ SurfaceId::StyleStrokeDilateTmp,
+ SurfaceId::StyleStrokeDilate,
+ [0.0, 1.0],
+ sdf_rad,
+ ctx.view,
+ scissor,
+ );
+ }
+ }
}
#[allow(clippy::too_many_arguments)]
-fn run_separable_blur_pass(
+fn run_separable_filter_pass(
device: &wgpu::Device,
queue: &wgpu::Queue,
pipelines: &CompositorPipelines,
+ pipeline: &wgpu::RenderPipeline,
arenas: &mut FrameArenas,
targets: &CompositorTargets,
+ bg_cache: Option<&mut ViewportBindGroupCache>,
encoder: &mut wgpu::CommandEncoder,
src: SurfaceId,
dst: SurfaceId,
@@ -3953,36 +5258,68 @@ fn run_separable_blur_pass(
view: &FrameRenderView,
scissor: ScissorRect,
) {
+ if scissor.is_empty() {
+ return;
+ }
let uniforms = BlurUniforms {
viewport_size_phys: [view.viewport_w as f32, view.viewport_h as f32],
direction,
radius_px,
_pad: [0.0; 3],
};
- let u_off = arenas.push_uniform(device, queue, encoder, &uniforms);
-
- let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-comp-blur-bg"),
- layout: &pipelines.blur_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &arenas.uniform_buf,
- offset: 0,
- size: NonZeroU64::new(std::mem::size_of::<BlurUniforms>() as u64),
- }),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(&get_surface(targets, src).view),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::Sampler(&pipelines.linear_sampler),
- },
- ],
- });
+ let u_off = arenas.push_uniform(device, queue, encoder, &uniforms);
+
+ let owned_bg;
+ let bg: &wgpu::BindGroup = if let Some(cache) = bg_cache {
+ cache.blur_bgs.entry(src).or_insert_with(|| {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-comp-blur-bg"),
+ layout: &pipelines.blur_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &arenas.uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(std::mem::size_of::<BlurUniforms>() as u64),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(&get_surface(targets, src).view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::Sampler(&pipelines.linear_sampler),
+ },
+ ],
+ })
+ })
+ } else {
+ owned_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-comp-blur-bg"),
+ layout: &pipelines.blur_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &arenas.uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(std::mem::size_of::<BlurUniforms>() as u64),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(&get_surface(targets, src).view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::Sampler(&pipelines.linear_sampler),
+ },
+ ],
+ });
+ &owned_bg
+ };
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("ink-comp-blur-pass"),
@@ -4000,9 +5337,10 @@ fn run_separable_blur_pass(
occlusion_query_set: None,
multiview_mask: None,
});
+ pass.set_viewport(0.0, 0.0, view.viewport_w as f32, view.viewport_h as f32, 0.0, 1.0);
pass.set_scissor_rect(scissor.x, scissor.y, scissor.width, scissor.height);
- pass.set_pipeline(&pipelines.separable_blur);
- pass.set_bind_group(0, &bg, &[u_off]);
+ pass.set_pipeline(pipeline);
+ pass.set_bind_group(0, bg, &[u_off]);
pass.draw(0..3, 0..1);
}
@@ -4013,8 +5351,9 @@ fn run_layer_styles_composite(
pipelines: &CompositorPipelines,
arenas: &mut FrameArenas,
targets: &CompositorTargets,
+ bg_cache: Option<&mut ViewportBindGroupCache>,
encoder: &mut wgpu::CommandEncoder,
- layer_view: &wgpu::TextureView,
+ src_id: SurfaceId,
dst_view: &wgpu::TextureView,
styles: &ParsedLayerStyles,
layer_opacity: f32,
@@ -4048,13 +5387,16 @@ fn run_layer_styles_composite(
let shadow_blur_px = shadow_active.map(|s| (s.blur * scale).min(128.0)).unwrap_or(0.0);
let glow_blur_px = glow_active.map(|g| (g.blur * scale).min(128.0)).unwrap_or(0.0);
+ let use_shadow_blur = shadow_active.is_some() && shadow_blur_px > 0.25;
+ let use_glow_blur = glow_active.is_some() && glow_blur_px > 0.0;
+ let use_stroke_sdf = stroke_active.is_some();
let uniforms = LayerStylesUniforms {
viewport_size_phys: [view.viewport_w as f32, view.viewport_h as f32],
shadow_offset_px,
params0: [
layer_opacity,
- stroke_active.map(|s| s.size * scale).unwrap_or(0.0),
+ stroke_active.map(|s| (s.size * scale).min(128.0)).unwrap_or(0.0),
glow_blur_px,
glow_active.map(|g| g.spread).unwrap_or(0.0),
],
@@ -4065,9 +5407,9 @@ fn run_layer_styles_composite(
0.0,
],
flags: [
- u32::from(stroke_active.is_some()),
+ u32::from(use_stroke_sdf),
stroke_active.map(|s| s.position as u32).unwrap_or(0),
- u32::from(glow_active.is_some()),
+ u32::from(use_glow_blur),
u32::from(shadow_active.is_some()),
],
stroke_color: stroke_active
@@ -4082,47 +5424,70 @@ fn run_layer_styles_composite(
};
let u_off = arenas.push_uniform(device, queue, encoder, &uniforms);
- let shadow_tex_view = if shadow_active.is_some() && shadow_blur_px > 0.25 {
- &targets.style_shadow_blur.view
+ let layer_view = &get_surface(targets, src_id).view;
+ let shadow_tex_view = if use_shadow_blur {
+ &get_surface(targets, SurfaceId::StyleShadowBlur).view
} else {
layer_view
};
- let glow_tex_view = if glow_active.is_some() {
- &targets.style_glow_blur.view
+ let glow_tex_view = if use_glow_blur {
+ &get_surface(targets, SurfaceId::StyleGlowBlur).view
+ } else {
+ &targets.dummy_transparent_rgba16f_view
+ };
+ let stroke_sdf_view = if use_stroke_sdf {
+ &get_surface(targets, SurfaceId::StyleStrokeDilate).view
} else {
&targets.dummy_transparent_rgba16f_view
};
- let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-comp-styles-bg"),
- layout: &pipelines.layer_styles_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &arenas.uniform_buf,
- offset: 0,
- size: NonZeroU64::new(std::mem::size_of::<LayerStylesUniforms>() as u64),
- }),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(layer_view),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::TextureView(shadow_tex_view),
- },
- wgpu::BindGroupEntry {
- binding: 3,
- resource: wgpu::BindingResource::TextureView(glow_tex_view),
- },
- wgpu::BindGroupEntry {
- binding: 4,
- resource: wgpu::BindingResource::Sampler(&pipelines.linear_sampler),
- },
- ],
- });
+ let make_bg = || {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-comp-styles-bg"),
+ layout: &pipelines.layer_styles_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &arenas.uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(std::mem::size_of::<LayerStylesUniforms>() as u64),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(layer_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(shadow_tex_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::TextureView(glow_tex_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 4,
+ resource: wgpu::BindingResource::Sampler(&pipelines.linear_sampler),
+ },
+ wgpu::BindGroupEntry {
+ binding: 5,
+ resource: wgpu::BindingResource::TextureView(stroke_sdf_view),
+ },
+ ],
+ })
+ };
+
+ let owned_bg;
+ let bg: &wgpu::BindGroup = if let Some(cache) = bg_cache {
+ cache
+ .layer_styles_bgs
+ .entry((src_id, use_shadow_blur, use_glow_blur, use_stroke_sdf))
+ .or_insert_with(make_bg)
+ } else {
+ owned_bg = make_bg();
+ &owned_bg
+ };
// Clear target region first since LAYER_STYLES_COMPOSITE_WGSL discards transparent pixels
let is_full = scissor.x == 0
@@ -4151,35 +5516,53 @@ fn run_layer_styles_composite(
occlusion_query_set: None,
multiview_mask: None,
});
+ pass.set_viewport(0.0, 0.0, view.viewport_w as f32, view.viewport_h as f32, 0.0, 1.0);
pass.set_scissor_rect(scissor.x, scissor.y, scissor.width, scissor.height);
if !is_full {
pass.set_pipeline(&pipelines.clear_rect);
pass.draw(0..3, 0..1);
}
pass.set_pipeline(&pipelines.layer_styles);
- pass.set_bind_group(0, &bg, &[u_off]);
+ pass.set_bind_group(0, bg, &[u_off]);
pass.draw(0..3, 0..1);
}
fn compute_styled_layer_sig(layer: &LayerNode, view: &FrameRenderView) -> u64 {
let mut h = Fnv1a64::new();
- layer.meta.id.hash(&mut h);
+ let m = &layer.meta;
+ m.id.hash(&mut h);
layer.grid.layer_version.hash(&mut h);
view.camera_sig.hash(&mut h);
h.write_bool(layer_has_active_mask(layer));
- layer.meta.mask_version.unwrap_or(0).hash(&mut h);
+ layer.grid.mask_version.hash(&mut h);
+ m.mask_version.unwrap_or(0).hash(&mut h);
layer.grid.mask_default_value.hash(&mut h);
layer.grid.mask_tiles.len().hash(&mut h);
- h.write_json_opt(layer.meta.styles.as_ref());
- h.write_bool(layer.meta.tone_enabled.unwrap_or(false));
- h.write_f32(layer.meta.tone_frequency.unwrap_or(60.0));
- h.write_f32(layer.meta.tone_angle.unwrap_or(45.0));
- h.write_f32(layer.meta.tone_density.unwrap_or(40.0));
- h.write_bool(layer.meta.layer_color_enabled.unwrap_or(false));
- layer.meta.layer_color.hash(&mut h);
- layer.meta.layer_sub_color.hash(&mut h);
- layer.meta.expression_color.map(|e| e as u8).unwrap_or(0).hash(&mut h);
- layer.meta.mono_threshold.unwrap_or(128).hash(&mut h);
+ h.write_json_opt(m.styles.as_ref());
+ h.write_bool(m.tone_enabled.unwrap_or(false));
+ h.write_f32(m.tone_frequency.unwrap_or(60.0));
+ h.write_f32(m.tone_angle.unwrap_or(45.0));
+ h.write_f32(m.tone_density.unwrap_or(40.0));
+ m.tone_dot_shape.map(|s| s as u8).unwrap_or(0).hash(&mut h);
+ m.tone_density_type.map(|d| d as u8).unwrap_or(0).hash(&mut h);
+ h.write_bool(m.is_tone_layer.unwrap_or(false));
+ h.write_bool(m.layer_color_enabled.unwrap_or(false));
+ m.layer_color.hash(&mut h);
+ m.layer_sub_color.hash(&mut h);
+ m.expression_color.map(|e| e as u8).unwrap_or(0).hash(&mut h);
+ m.mono_threshold.unwrap_or(128).hash(&mut h);
+ h.write_bool(m.mono_express_black.unwrap_or(true));
+ h.write_bool(m.mono_express_white.unwrap_or(true));
+ // Impasto lighting parameters (affect styled source appearance!)
+ h.write_bool(!layer.grid.impasto_tiles.is_empty());
+ if let Some(imp) = m.impasto_light {
+ h.write_bool(imp.enabled);
+ h.write_f32(imp.depth);
+ h.write_f32(imp.gloss);
+ h.write_f32(imp.relief_contrast);
+ h.write_f32(imp.light_azimuth);
+ h.write_f32(imp.light_elevation);
+ }
h.finish()
}
@@ -4225,6 +5608,7 @@ fn render_layer_raw_tiles(
ctx.pipelines,
ctx.arenas,
ctx.targets,
+ ctx.bg_cache.as_deref_mut(),
ctx.tile_pool,
encoder,
&uniforms,
@@ -4233,6 +5617,8 @@ fn render_layer_raw_tiles(
&ctx.targets.dummy_transparent_rgba16f_view,
&ctx.targets.dummy_white_rgba16f_view,
&ctx.targets.dummy_white_r8_view,
+ Some((false, None, 0)),
+ false,
scissor,
);
}
@@ -4247,6 +5633,7 @@ fn render_raster_layer_tiles(
eff_opacity: f32,
tint_override: Option<([f32; 3], [f32; 3])>,
outer_clip: Option<SurfaceId>,
+ source_atop: bool,
scissor: ScissorRect,
) {
if eff_opacity <= 0.001 || scissor.is_empty() || layer.grid.tiles.is_empty() {
@@ -4283,20 +5670,24 @@ fn render_raster_layer_tiles(
1.0,
None,
None,
+ false,
scissor,
);
+ let height_scissor = scissor.expand(22, ctx.view.viewport_w, ctx.view.viewport_h);
project_impasto_height_tiles(
ctx.device,
ctx.queue,
ctx.pipelines,
ctx.arenas,
ctx.targets,
+ ctx.bg_cache.as_deref_mut(),
ctx.tile_pool,
encoder,
ctx.doc,
layer,
None,
ctx.view,
+ height_scissor,
);
run_impasto_lighting_pass(
ctx.device,
@@ -4304,6 +5695,7 @@ fn render_raster_layer_tiles(
ctx.pipelines,
ctx.arenas,
ctx.targets,
+ ctx.bg_cache.as_deref_mut(),
encoder,
SurfaceId::ImpastoColorScratch,
SurfaceId::ImpastoLitScratch,
@@ -4320,6 +5712,7 @@ fn render_raster_layer_tiles(
eff_opacity,
None,
outer_clip,
+ source_atop,
scissor,
);
return;
@@ -4334,6 +5727,7 @@ fn render_raster_layer_tiles(
eff_opacity,
tint_override,
outer_clip,
+ source_atop,
scissor,
);
}
@@ -4348,6 +5742,7 @@ fn render_raster_layer_tiles_direct(
eff_opacity: f32,
tint_override: Option<([f32; 3], [f32; 3])>,
outer_clip: Option<SurfaceId>,
+ source_atop: bool,
scissor: ScissorRect,
) {
if eff_opacity <= 0.001 || scissor.is_empty() || layer.grid.tiles.is_empty() {
@@ -4376,6 +5771,7 @@ fn render_raster_layer_tiles_direct(
let needs_backdrop = blend_mode_needs_backdrop(blend);
if needs_backdrop {
+ ctx.targets.ensure_backdrop_scratch(ctx.device);
get_surface(ctx.targets, dst).copy_region_to(
encoder,
get_surface(ctx.targets, SurfaceId::BackdropScratch),
@@ -4425,6 +5821,12 @@ fn render_raster_layer_tiles_direct(
|| tone_enabled,
);
+ let clip_mode = if source_atop {
+ 2u32
+ } else {
+ u32::from(outer_clip.is_some())
+ };
+
let uniforms = LayerTileUniforms {
viewport_size_phys: [ctx.view.viewport_w as f32, ctx.view.viewport_h as f32],
doc_size: [ctx.view.dimensions.width as f32, ctx.view.dimensions.height as f32],
@@ -4437,7 +5839,7 @@ fn render_raster_layer_tiles_direct(
flags0: [
blend_mode_to_code(blend),
u32::from(needs_backdrop),
- u32::from(outer_clip.is_some()),
+ clip_mode,
mask_mode,
],
expr_flags: [
@@ -4463,21 +5865,23 @@ fn render_raster_layer_tiles_direct(
};
let backdrop_view = if needs_backdrop {
- &ctx.targets.backdrop_scratch.view
+ &get_surface(ctx.targets, SurfaceId::BackdropScratch).view
} else {
&ctx.targets.dummy_transparent_rgba16f_view
};
let clip_view = outer_clip
.map(|id| &get_surface(ctx.targets, id).view)
.unwrap_or(&ctx.targets.dummy_white_rgba16f_view);
- let doc_mask_view = if mask_mode == 2 {
+ let (doc_mask_view, doc_mask_view_id) = if mask_mode == 2 {
ctx.doc_mask_cache
- .get_cached_view(&layer.meta.id)
- .unwrap_or(&ctx.targets.dummy_white_r8_view)
+ .get_cached_view_with_id(&layer.meta.id)
+ .unwrap_or((&ctx.targets.dummy_white_r8_view, 0))
} else {
- &ctx.targets.dummy_white_r8_view
+ (&ctx.targets.dummy_white_r8_view, 0)
};
+ let tile_bg_cache_key = Some((needs_backdrop, outer_clip, doc_mask_view_id));
+
if let Some((warped_view, warped_map)) = liquify_override {
// Draw untouched base tiles from GpuTilePool (excluding tiles overridden by live Liquify)
let base_instances: Vec<TileInstanceGpu> = instances
@@ -4495,6 +5899,8 @@ fn render_raster_layer_tiles_direct(
ctx.pipelines,
ctx.arenas,
ctx.targets,
+ ctx.bg_cache.as_deref_mut(),
+ tile_bg_cache_key.map(|(nb, oc, mid)| (ctx.tile_pool.atlas_id(), nb, oc, mid)),
ctx.tile_pool.atlas_view(),
ctx.tile_pool.mask_atlas_view(),
encoder,
@@ -4504,20 +5910,23 @@ fn render_raster_layer_tiles_direct(
backdrop_view,
clip_view,
doc_mask_view,
+ source_atop,
scissor,
);
}
// Draw live warped RG16F-displaced tiles directly in-stack with full blend modes/masks/clipping!
let mask_default = layer.grid.mask_default_value as f32 / 255.0;
+ let doc_key = ctx.tile_pool.intern_doc(&ctx.doc.id);
+ let layer_key = ctx.tile_pool.intern_layer(&layer.meta.id);
let warped_instances: Vec<TileInstanceGpu> = warped_map
.iter()
.map(|(&coord, &slot)| {
let mask_slice = if use_sparse_mask {
ctx.tile_pool
.get_mask_slot(&GpuTileKey {
- doc_id: ctx.doc.id.clone(),
- layer_id: layer.meta.id.clone(),
+ doc_id: doc_key,
+ layer_id: layer_key,
lod: 0,
coord,
})
@@ -4546,6 +5955,8 @@ fn render_raster_layer_tiles_direct(
ctx.pipelines,
ctx.arenas,
ctx.targets,
+ None,
+ None,
warped_view,
ctx.tile_pool.mask_atlas_view(),
encoder,
@@ -4555,6 +5966,7 @@ fn render_raster_layer_tiles_direct(
backdrop_view,
clip_view,
doc_mask_view,
+ source_atop,
scissor,
);
}
@@ -4567,6 +5979,7 @@ fn render_raster_layer_tiles_direct(
ctx.pipelines,
ctx.arenas,
ctx.targets,
+ ctx.bg_cache.as_deref_mut(),
ctx.tile_pool,
encoder,
&uniforms,
@@ -4575,6 +5988,8 @@ fn render_raster_layer_tiles_direct(
backdrop_view,
clip_view,
doc_mask_view,
+ tile_bg_cache_key,
+ source_atop,
scissor,
);
}
@@ -4586,6 +6001,7 @@ fn draw_layer_tile_instances(
pipelines: &CompositorPipelines,
arenas: &mut FrameArenas,
targets: &CompositorTargets,
+ bg_cache: Option<&mut ViewportBindGroupCache>,
tile_pool: &GpuTilePool,
encoder: &mut wgpu::CommandEncoder,
uniforms: &LayerTileUniforms,
@@ -4594,6 +6010,8 @@ fn draw_layer_tile_instances(
backdrop_view: &wgpu::TextureView,
clip_view: &wgpu::TextureView,
doc_mask_view: &wgpu::TextureView,
+ cache_key: Option<(bool, Option<SurfaceId>, u64)>,
+ source_atop: bool,
scissor: ScissorRect,
) {
draw_layer_tile_instances_with_atlas(
@@ -4602,6 +6020,8 @@ fn draw_layer_tile_instances(
pipelines,
arenas,
targets,
+ bg_cache,
+ cache_key.map(|(nb, oc, mid)| (tile_pool.atlas_id(), nb, oc, mid)),
tile_pool.atlas_view(),
tile_pool.mask_atlas_view(),
encoder,
@@ -4611,6 +6031,7 @@ fn draw_layer_tile_instances(
backdrop_view,
clip_view,
doc_mask_view,
+ source_atop,
scissor,
);
}
@@ -4622,6 +6043,8 @@ fn draw_layer_tile_instances_with_atlas(
pipelines: &CompositorPipelines,
arenas: &mut FrameArenas,
targets: &CompositorTargets,
+ bg_cache: Option<&mut ViewportBindGroupCache>,
+ cache_key: Option<(u64, bool, Option<SurfaceId>, u64)>,
atlas_view: &wgpu::TextureView,
mask_atlas_view: &wgpu::TextureView,
encoder: &mut wgpu::CommandEncoder,
@@ -4631,49 +6054,77 @@ fn draw_layer_tile_instances_with_atlas(
backdrop_view: &wgpu::TextureView,
clip_view: &wgpu::TextureView,
doc_mask_view: &wgpu::TextureView,
+ source_atop: bool,
scissor: ScissorRect,
) {
+ arenas.ensure_capacity(
+ device,
+ queue,
+ encoder,
+ std::mem::size_of::<LayerTileUniforms>(),
+ std::mem::size_of_val(instances),
+ 0,
+ 0,
+ );
let u_off = arenas.push_uniform(device, queue, encoder, uniforms);
let (i_start, i_end) = arenas.push_tile_instances(device, queue, encoder, instances);
- let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-comp-layer-tile-bg"),
- layout: &pipelines.layer_tile_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &arenas.uniform_buf,
- offset: 0,
- size: NonZeroU64::new(std::mem::size_of::<LayerTileUniforms>() as u64),
- }),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(atlas_view),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::TextureView(mask_atlas_view),
- },
- wgpu::BindGroupEntry {
- binding: 3,
- resource: wgpu::BindingResource::TextureView(backdrop_view),
- },
- wgpu::BindGroupEntry {
- binding: 4,
- resource: wgpu::BindingResource::TextureView(clip_view),
- },
- wgpu::BindGroupEntry {
- binding: 5,
- resource: wgpu::BindingResource::TextureView(doc_mask_view),
- },
- wgpu::BindGroupEntry {
- binding: 6,
- resource: wgpu::BindingResource::Sampler(&pipelines.linear_sampler),
- },
- ],
- });
+ let make_bg = || {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-comp-layer-tile-bg"),
+ layout: &pipelines.layer_tile_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &arenas.uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(std::mem::size_of::<LayerTileUniforms>() as u64),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(atlas_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(mask_atlas_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::TextureView(backdrop_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 4,
+ resource: wgpu::BindingResource::TextureView(clip_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 5,
+ resource: wgpu::BindingResource::TextureView(doc_mask_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 6,
+ resource: wgpu::BindingResource::Sampler(&pipelines.linear_sampler),
+ },
+ ],
+ })
+ };
+
+ let owned_bg;
+ let bg: &wgpu::BindGroup =
+ if let (Some(cache), Some((atlas_id, nb, oc, mid))) = (bg_cache, cache_key) {
+ if cache.layer_tile_atlas_id != atlas_id {
+ cache.layer_tile_bgs.clear();
+ cache.layer_tile_atlas_id = atlas_id;
+ }
+ cache
+ .layer_tile_bgs
+ .entry((nb, oc, mid))
+ .or_insert_with(make_bg)
+ } else {
+ owned_bg = make_bg();
+ &owned_bg
+ };
let dst_surf = get_surface(targets, dst);
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
@@ -4692,9 +6143,21 @@ fn draw_layer_tile_instances_with_atlas(
occlusion_query_set: None,
multiview_mask: None,
});
+ pass.set_viewport(
+ 0.0,
+ 0.0,
+ uniforms.viewport_size_phys[0],
+ uniforms.viewport_size_phys[1],
+ 0.0,
+ 1.0,
+ );
pass.set_scissor_rect(scissor.x, scissor.y, scissor.width, scissor.height);
- pass.set_pipeline(&pipelines.layer_tile_blend);
- pass.set_bind_group(0, &bg, &[u_off]);
+ pass.set_pipeline(if source_atop {
+ &pipelines.layer_tile_atop
+ } else {
+ &pipelines.layer_tile_blend
+ });
+ pass.set_bind_group(0, bg, &[u_off]);
pass.set_vertex_buffer(0, arenas.tile_inst_buf.slice(i_start..i_end));
pass.draw(0..6, 0..instances.len() as u32);
}
@@ -4718,26 +6181,36 @@ fn collect_visible_tile_instances(
let max_ty = (view.frustum.max_y - 1).div_euclid(span);
let mut instances = Vec::new();
+ let doc_key = tile_pool.intern_doc(&doc.id);
+ let layer_key = tile_pool.intern_layer(&layer.meta.id);
if view.lod == 0 {
let mask_default = layer.grid.mask_default_value as f32 / 255.0;
- for &coord in layer.grid.tiles.keys() {
+ for (&coord, tile) in &layer.grid.tiles {
if coord.tx < min_tx || coord.tx > max_tx || coord.ty < min_ty || coord.ty > max_ty {
continue;
}
- let key = GpuTileKey {
- doc_id: doc.id.clone(),
- layer_id: layer.meta.id.clone(),
- lod: 0,
- coord,
- };
- let Some(atlas_slice) = tile_pool.get_slot(&key) else {
- continue;
+ let atlas_slice = if let Some(solid_16f) = tile.solid_rgba16f() {
+ let Some(s) = tile_pool.get_solid_color_slot(solid_16f) else {
+ continue;
+ };
+ s
+ } else {
+ let key = GpuTileKey {
+ doc_id: doc_key,
+ layer_id: layer_key,
+ lod: 0,
+ coord,
+ };
+ let Some(s) = tile_pool.get_slot(&key) else {
+ continue;
+ };
+ s
};
let mask_slice = if use_sparse_mask {
let mkey = GpuTileKey {
- doc_id: doc.id.clone(),
- layer_id: layer.meta.id.clone(),
+ doc_id: doc_key,
+ layer_id: layer_key,
lod: 0,
coord,
};
@@ -4774,14 +6247,28 @@ fn collect_visible_tile_instances(
}
}
for pcoord in parent_coords {
- let key = GpuTileKey {
- doc_id: doc.id.clone(),
- layer_id: layer.meta.id.clone(),
- lod: view.lod,
- coord: pcoord,
- };
- let Some(atlas_slice) = tile_pool.get_slot(&key) else {
- continue;
+ let atlas_slice = if let Some(solid_16f) = uniform_solid_color_for_lod_tile(
+ &layer.grid,
+ view.lod,
+ pcoord,
+ doc.dimensions.width,
+ doc.dimensions.height,
+ ) {
+ let Some(s) = tile_pool.get_solid_color_slot(solid_16f) else {
+ continue;
+ };
+ s
+ } else {
+ let key = GpuTileKey {
+ doc_id: doc_key,
+ layer_id: layer_key,
+ lod: view.lod,
+ coord: pcoord,
+ };
+ let Some(s) = tile_pool.get_slot(&key) else {
+ continue;
+ };
+ s
};
instances.push(TileInstanceGpu {
tile_origin_doc: [(pcoord.tx * span) as f32, (pcoord.ty * span) as f32],
@@ -4828,6 +6315,7 @@ fn blit_surface_onto(
opacity: f32,
mask_layer_id: Option<&str>,
outer_clip: Option<SurfaceId>,
+ source_atop: bool,
scissor: ScissorRect,
) {
if opacity <= 0.001 || scissor.is_empty() {
@@ -4835,6 +6323,7 @@ fn blit_surface_onto(
}
let needs_backdrop = blend_mode_needs_backdrop(blend);
if needs_backdrop {
+ ctx.targets.ensure_backdrop_scratch(ctx.device);
get_surface(ctx.targets, dst).copy_region_to(
encoder,
get_surface(ctx.targets, SurfaceId::BackdropScratch),
@@ -4848,6 +6337,9 @@ fn blit_surface_onto(
ctx.pipelines,
ctx.arenas,
ctx.targets,
+ ctx.bg_cache.as_deref_mut(),
+ Some(src),
+ None,
ctx.doc_mask_cache,
encoder,
src_view,
@@ -4857,6 +6349,7 @@ fn blit_surface_onto(
opacity,
mask_layer_id,
outer_clip,
+ source_atop,
ctx.view,
scissor,
);
@@ -4868,7 +6361,9 @@ fn blit_view_onto(
queue: &wgpu::Queue,
pipelines: &CompositorPipelines,
arenas: &mut FrameArenas,
- targets: &CompositorTargets,
+ targets: &mut CompositorTargets,
+ bg_cache: Option<&mut ViewportBindGroupCache>,
+ src_view_id: Option<u64>,
doc_mask_cache: &DocMaskCache,
encoder: &mut wgpu::CommandEncoder,
src_view: &wgpu::TextureView,
@@ -4877,6 +6372,7 @@ fn blit_view_onto(
opacity: f32,
mask_layer_id: Option<&str>,
outer_clip: Option<SurfaceId>,
+ source_atop: bool,
view: &FrameRenderView,
scissor: ScissorRect,
) {
@@ -4885,6 +6381,7 @@ fn blit_view_onto(
}
let needs_backdrop = blend_mode_needs_backdrop(blend);
if needs_backdrop {
+ targets.ensure_backdrop_scratch(device);
get_surface(targets, dst).copy_region_to(
encoder,
get_surface(targets, SurfaceId::BackdropScratch),
@@ -4897,6 +6394,9 @@ fn blit_view_onto(
pipelines,
arenas,
targets,
+ bg_cache,
+ None,
+ src_view_id,
doc_mask_cache,
encoder,
src_view,
@@ -4906,6 +6406,7 @@ fn blit_view_onto(
opacity,
mask_layer_id,
outer_clip,
+ source_atop,
view,
scissor,
);
@@ -4918,6 +6419,9 @@ fn blit_view_onto_inner(
pipelines: &CompositorPipelines,
arenas: &mut FrameArenas,
targets: &CompositorTargets,
+ bg_cache: Option<&mut ViewportBindGroupCache>,
+ src_surface_id: Option<SurfaceId>,
+ src_view_id: Option<u64>,
doc_mask_cache: &DocMaskCache,
encoder: &mut wgpu::CommandEncoder,
src_view: &wgpu::TextureView,
@@ -4927,15 +6431,16 @@ fn blit_view_onto_inner(
opacity: f32,
mask_layer_id: Option<&str>,
outer_clip: Option<SurfaceId>,
+ source_atop: bool,
view: &FrameRenderView,
scissor: ScissorRect,
) {
let has_mask = mask_layer_id.is_some();
- let doc_mask_view = mask_layer_id
- .and_then(|id| doc_mask_cache.get_cached_view(id))
- .unwrap_or(&targets.dummy_white_r8_view);
+ let (doc_mask_view, mask_view_id) = mask_layer_id
+ .and_then(|id| doc_mask_cache.get_cached_view_with_id(id))
+ .unwrap_or((&targets.dummy_white_r8_view, 0));
let backdrop_view = if needs_backdrop {
- &targets.backdrop_scratch.view
+ &get_surface(targets, SurfaceId::BackdropScratch).view
} else {
&targets.dummy_transparent_rgba16f_view
};
@@ -4943,6 +6448,12 @@ fn blit_view_onto_inner(
.map(|id| &get_surface(targets, id).view)
.unwrap_or(&targets.dummy_white_rgba16f_view);
+ let clip_mode = if source_atop {
+ 2u32
+ } else {
+ u32::from(outer_clip.is_some())
+ };
+
let uniforms = BlitUniforms {
viewport_size_phys: [view.viewport_w as f32, view.viewport_h as f32],
doc_size: [view.dimensions.width as f32, view.dimensions.height as f32],
@@ -4956,45 +6467,68 @@ fn blit_view_onto_inner(
blend_mode_to_code(blend),
u32::from(needs_backdrop),
u32::from(has_mask),
- u32::from(outer_clip.is_some()),
+ clip_mode,
],
};
let u_off = arenas.push_uniform(device, queue, encoder, &uniforms);
- let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-comp-blit-bg"),
- layout: &pipelines.blit_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &arenas.uniform_buf,
- offset: 0,
- size: NonZeroU64::new(std::mem::size_of::<BlitUniforms>() as u64),
- }),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(src_view),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::TextureView(backdrop_view),
- },
- wgpu::BindGroupEntry {
- binding: 3,
- resource: wgpu::BindingResource::TextureView(clip_view),
- },
- wgpu::BindGroupEntry {
- binding: 4,
- resource: wgpu::BindingResource::TextureView(doc_mask_view),
- },
- wgpu::BindGroupEntry {
- binding: 5,
- resource: wgpu::BindingResource::Sampler(&pipelines.linear_sampler),
- },
- ],
- });
+ let make_bg = || {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-comp-blit-bg"),
+ layout: &pipelines.blit_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &arenas.uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(std::mem::size_of::<BlitUniforms>() as u64),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(src_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(backdrop_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::TextureView(clip_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 4,
+ resource: wgpu::BindingResource::TextureView(doc_mask_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 5,
+ resource: wgpu::BindingResource::Sampler(&pipelines.linear_sampler),
+ },
+ ],
+ })
+ };
+
+ let owned_bg;
+ let bg: &wgpu::BindGroup = if let Some(cache) = bg_cache {
+ if let Some(src_id) = src_surface_id {
+ cache
+ .blit_bgs
+ .entry((src_id, needs_backdrop, outer_clip, mask_view_id))
+ .or_insert_with(make_bg)
+ } else if let Some(vid) = src_view_id {
+ cache
+ .blit_view_bgs
+ .entry((vid, needs_backdrop, outer_clip, mask_view_id))
+ .or_insert_with(make_bg)
+ } else {
+ owned_bg = make_bg();
+ &owned_bg
+ }
+ } else {
+ owned_bg = make_bg();
+ &owned_bg
+ };
let dst_surf = get_surface(targets, dst);
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
@@ -5013,9 +6547,14 @@ fn blit_view_onto_inner(
occlusion_query_set: None,
multiview_mask: None,
});
+ pass.set_viewport(0.0, 0.0, view.viewport_w as f32, view.viewport_h as f32, 0.0, 1.0);
pass.set_scissor_rect(scissor.x, scissor.y, scissor.width, scissor.height);
- pass.set_pipeline(&pipelines.blit_blend);
- pass.set_bind_group(0, &bg, &[u_off]);
+ pass.set_pipeline(if source_atop {
+ &pipelines.blit_atop
+ } else {
+ &pipelines.blit_blend
+ });
+ pass.set_bind_group(0, bg, &[u_off]);
pass.draw(0..3, 0..1);
}
@@ -5067,6 +6606,7 @@ struct LiveMergeParams {
is_bg_eraser: bool,
brush_opacity: f32,
bg_color: [f32; 3],
+ unattenuated_layer_opacity: bool,
}
fn gpu_dabs_dirty_scissor(
@@ -5115,7 +6655,9 @@ fn project_sparse_stroke_tiles_into_surface(
pipelines: &CompositorPipelines,
arenas: &mut FrameArenas,
targets: &CompositorTargets,
+ bg_cache: Option<&mut ViewportBindGroupCache>,
encoder: &mut wgpu::CommandEncoder,
+ stroke_atlas_id: (u8, u64),
stroke_atlas_view: &wgpu::TextureView,
tile_slots: &HashMap<TileCoord, u32>,
premultiply_straight: bool,
@@ -5158,37 +6700,63 @@ fn project_sparse_stroke_tiles_into_surface(
dpr: view.dpr,
_pad: if premultiply_straight { 1.0 } else { 0.0 },
};
+ arenas.ensure_capacity(
+ device,
+ queue,
+ encoder,
+ std::mem::size_of::<LiveDabUniforms>(),
+ std::mem::size_of_val(insts.as_slice()),
+ 0,
+ 0,
+ );
let u_off = arenas.push_uniform(device, queue, encoder, &uniforms);
let (v_start, v_end) = arenas.push_sparse_stroke_tiles(device, queue, encoder, &insts);
let sampler = &pipelines.linear_sampler;
- let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-comp-sparse-stroke-bg"),
- layout: &pipelines.sparse_stroke_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &arenas.uniform_buf,
- offset: 0,
- size: NonZeroU64::new(std::mem::size_of::<LiveDabUniforms>() as u64),
- }),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(stroke_atlas_view),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::Sampler(sampler),
- },
- ],
- });
+ let make_bg = || {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-comp-sparse-stroke-bg"),
+ layout: &pipelines.sparse_stroke_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &arenas.uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(std::mem::size_of::<LiveDabUniforms>() as u64),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(stroke_atlas_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::Sampler(sampler),
+ },
+ ],
+ })
+ };
+
+ let owned_bg;
+ let bg: &wgpu::BindGroup = if let Some(cache) = bg_cache {
+ let hit = cache
+ .sparse_stroke_bg
+ .as_ref()
+ .is_some_and(|(k, _)| *k == stroke_atlas_id);
+ if !hit {
+ cache.sparse_stroke_bg = Some((stroke_atlas_id, make_bg()));
+ }
+ &cache.sparse_stroke_bg.as_ref().unwrap().1
+ } else {
+ owned_bg = make_bg();
+ &owned_bg
+ };
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("ink-comp-sparse-stroke-project-pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
- view: &targets.live_stroke_surface.view,
+ view: &get_surface(targets, SurfaceId::LiveStroke).view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
@@ -5201,9 +6769,10 @@ fn project_sparse_stroke_tiles_into_surface(
occlusion_query_set: None,
multiview_mask: None,
});
+ pass.set_viewport(0.0, 0.0, view.viewport_w as f32, view.viewport_h as f32, 0.0, 1.0);
pass.set_scissor_rect(scissor.x, scissor.y, scissor.width, scissor.height);
pass.set_pipeline(&pipelines.sparse_stroke_project);
- pass.set_bind_group(0, &bg, &[u_off]);
+ pass.set_bind_group(0, bg, &[u_off]);
pass.set_vertex_buffer(0, arenas.tile_inst_buf.slice(v_start..v_end));
pass.draw(0..6, 0..insts.len() as u32);
}
@@ -5215,6 +6784,7 @@ fn stamp_live_dabs_into_surface(
pipelines: &CompositorPipelines,
arenas: &mut FrameArenas,
targets: &CompositorTargets,
+ bg_cache: Option<&mut ViewportBindGroupCache>,
encoder: &mut wgpu::CommandEncoder,
dabs: &[DabInstance],
view: &FrameRenderView,
@@ -5233,26 +6803,45 @@ fn stamp_live_dabs_into_surface(
dpr: view.dpr,
_pad: 0.0,
};
- let u_off = arenas.push_uniform(device, queue, encoder, &uniforms);
- let (d_start, d_end) = arenas.push_dab_instances(device, queue, encoder, dabs);
+ arenas.ensure_capacity(
+ device,
+ queue,
+ encoder,
+ std::mem::size_of::<LiveDabUniforms>(),
+ 0,
+ 0,
+ std::mem::size_of_val(dabs),
+ );
+ let u_off = arenas.push_uniform(device, queue, encoder, &uniforms);
+ let (d_start, d_end) = arenas.push_dab_instances(device, queue, encoder, dabs);
+
+ let make_bg = || {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-comp-live-dab-bg"),
+ layout: &pipelines.live_dab_bgl,
+ entries: &[wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &arenas.uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(std::mem::size_of::<LiveDabUniforms>() as u64),
+ }),
+ }],
+ })
+ };
- let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-comp-live-dab-bg"),
- layout: &pipelines.live_dab_bgl,
- entries: &[wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &arenas.uniform_buf,
- offset: 0,
- size: NonZeroU64::new(std::mem::size_of::<LiveDabUniforms>() as u64),
- }),
- }],
- });
+ let owned_bg;
+ let bg: &wgpu::BindGroup = if let Some(cache) = bg_cache {
+ cache.live_dab_bg.get_or_insert_with(make_bg)
+ } else {
+ owned_bg = make_bg();
+ &owned_bg
+ };
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("ink-comp-live-dab-pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
- view: &targets.live_stroke_surface.view,
+ view: &get_surface(targets, SurfaceId::LiveStroke).view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
@@ -5265,9 +6854,10 @@ fn stamp_live_dabs_into_surface(
occlusion_query_set: None,
multiview_mask: None,
});
+ pass.set_viewport(0.0, 0.0, view.viewport_w as f32, view.viewport_h as f32, 0.0, 1.0);
pass.set_scissor_rect(scissor.x, scissor.y, scissor.width, scissor.height);
pass.set_pipeline(&pipelines.live_dab_paint);
- pass.set_bind_group(0, &bg, &[u_off]);
+ pass.set_bind_group(0, bg, &[u_off]);
pass.set_vertex_buffer(0, arenas.dab_inst_buf.slice(d_start..d_end));
pass.draw(0..6, 0..dabs.len() as u32);
}
@@ -5279,6 +6869,7 @@ fn merge_live_stroke_layer(
pipelines: &CompositorPipelines,
arenas: &mut FrameArenas,
targets: &CompositorTargets,
+ bg_cache: Option<&mut ViewportBindGroupCache>,
doc_mask_cache: &DocMaskCache,
encoder: &mut wgpu::CommandEncoder,
layer: &LayerNode,
@@ -5291,12 +6882,12 @@ fn merge_live_stroke_layer(
return;
}
let has_mask = layer_has_active_mask(layer);
- let mask_view = if has_mask {
+ let (mask_view, mask_view_id) = if has_mask {
doc_mask_cache
- .get_cached_view(&layer.meta.id)
- .unwrap_or(&targets.dummy_white_r8_view)
+ .get_cached_view_with_id(&layer.meta.id)
+ .unwrap_or((&targets.dummy_white_r8_view, 0))
} else {
- &targets.dummy_white_r8_view
+ (&targets.dummy_white_r8_view, 0)
};
let (expr_mode, mono_thresh, mono_black, mono_white) =
@@ -5327,6 +6918,12 @@ fn merge_live_stroke_layer(
ToneDensityType::Image => 1u32,
};
+ let effective_layer_opacity = if merge.unattenuated_layer_opacity {
+ 1.0
+ } else {
+ layer.meta.opacity.clamp(0.0, 1.0)
+ };
+
let uniforms = LiveStrokeMergeUniforms {
viewport_size_phys: [view.viewport_w as f32, view.viewport_h as f32],
doc_size: [view.dimensions.width as f32, view.dimensions.height as f32],
@@ -5335,7 +6932,7 @@ fn merge_live_stroke_layer(
rotation_rad: view.rot_rad,
flip: view.flip,
dpr: view.dpr,
- layer_opacity: layer.meta.opacity.clamp(0.0, 1.0),
+ layer_opacity: effective_layer_opacity,
flags0: [
u32::from(merge.is_eraser),
u32::from(layer.meta.alpha_locked.unwrap_or(false)),
@@ -5377,46 +6974,68 @@ fn merge_live_stroke_layer(
let u_off = arenas.push_uniform(device, queue, encoder, &uniforms);
let sel_vp_view = selection_vp_mask.unwrap_or(&targets.dummy_white_r8_view);
+ let can_cache_default = !has_mask && selection_vp_mask.is_none();
+ let can_cache_masked = has_mask && selection_vp_mask.is_none();
- let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-comp-live-merge-bg"),
- layout: &pipelines.live_merge_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &arenas.uniform_buf,
- offset: 0,
- size: NonZeroU64::new(std::mem::size_of::<LiveStrokeMergeUniforms>() as u64),
- }),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(&targets.active_layer_base_surface.view),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::TextureView(&targets.live_stroke_surface.view),
- },
- wgpu::BindGroupEntry {
- binding: 3,
- resource: wgpu::BindingResource::TextureView(mask_view),
- },
- wgpu::BindGroupEntry {
- binding: 4,
- resource: wgpu::BindingResource::Sampler(&pipelines.linear_sampler),
- },
- wgpu::BindGroupEntry {
- binding: 5,
- resource: wgpu::BindingResource::TextureView(sel_vp_view),
- },
- ],
- });
+ let make_bg = || {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-comp-live-merge-bg"),
+ layout: &pipelines.live_merge_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &arenas.uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(std::mem::size_of::<LiveStrokeMergeUniforms>() as u64),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(&get_surface(targets, SurfaceId::ActiveBase).view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(&get_surface(targets, SurfaceId::LiveStroke).view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::TextureView(mask_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 4,
+ resource: wgpu::BindingResource::Sampler(&pipelines.linear_sampler),
+ },
+ wgpu::BindGroupEntry {
+ binding: 5,
+ resource: wgpu::BindingResource::TextureView(sel_vp_view),
+ },
+ ],
+ })
+ };
+
+ let owned_bg;
+ let bg: &wgpu::BindGroup = if let Some(cache) = bg_cache {
+ if can_cache_default {
+ cache.live_merge_default_bg.get_or_insert_with(make_bg)
+ } else if can_cache_masked {
+ cache
+ .live_merge_masked_bgs
+ .entry(mask_view_id)
+ .or_insert_with(make_bg)
+ } else {
+ owned_bg = make_bg();
+ &owned_bg
+ }
+ } else {
+ owned_bg = make_bg();
+ &owned_bg
+ };
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("ink-comp-live-merge-pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
- view: &targets.active_unit_surface.view,
+ view: &get_surface(targets, SurfaceId::ActiveUnit).view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
@@ -5429,9 +7048,10 @@ fn merge_live_stroke_layer(
occlusion_query_set: None,
multiview_mask: None,
});
+ pass.set_viewport(0.0, 0.0, view.viewport_w as f32, view.viewport_h as f32, 0.0, 1.0);
pass.set_scissor_rect(scissor.x, scissor.y, scissor.width, scissor.height);
pass.set_pipeline(&pipelines.live_stroke_merge);
- pass.set_bind_group(0, &bg, &[u_off]);
+ pass.set_bind_group(0, bg, &[u_off]);
pass.draw(0..3, 0..1);
}
@@ -5463,13 +7083,19 @@ fn project_impasto_height_tiles(
pipelines: &CompositorPipelines,
arenas: &mut FrameArenas,
targets: &CompositorTargets,
+ mut bg_cache: Option<&mut ViewportBindGroupCache>,
tile_pool: &mut GpuTilePool,
encoder: &mut wgpu::CommandEncoder,
doc: &Document,
layer: &LayerNode,
- live_height_overlay: Option<(&wgpu::TextureView, &HashMap<TileCoord, u32>)>,
+ live_height_overlay: Option<(u64, &wgpu::TextureView, &HashMap<TileCoord, u32>)>,
view: &FrameRenderView,
+ scissor: ScissorRect,
) {
+ let proj_scissor = scissor.clamp(view.viewport_w, view.viewport_h);
+ if proj_scissor.is_empty() {
+ return;
+ }
let Some(height_surf) = targets.impasto_height.as_ref() else {
return;
};
@@ -5479,79 +7105,118 @@ fn project_impasto_height_tiles(
let max_tx = view.frustum.max_x.div_euclid(TILE_SIZE as i32) + 1;
let max_ty = view.frustum.max_y.div_euclid(TILE_SIZE as i32) + 1;
- // Collect base layer impasto height tiles (skipping coords replaced by live stroke height tiles)
- let mut base_insts: Vec<SparseTileInst> = Vec::with_capacity(layer.grid.impasto_tiles.len());
+ // Build unified encoded slot map (+(slot+1) = base atlas, -(slot+1) = live atlas, 0 = empty)
+ // across a 1-tile expanded neighborhood so 256×256 tile edges sample seamlessly across neighbors!
+ let doc_key = tile_pool.intern_doc(&doc.id);
+ let layer_key = tile_pool.intern_layer(&layer.meta.id);
+ let mut encoded_map: HashMap<TileCoord, i32> = HashMap::with_capacity(
+ layer.grid.impasto_tiles.len()
+ + live_height_overlay.map(|(_, _, m)| m.len()).unwrap_or(0),
+ );
+
for &coord in layer.grid.impasto_tiles.keys() {
- if coord.tx < min_tx || coord.tx > max_tx || coord.ty < min_ty || coord.ty > max_ty {
+ if coord.tx < min_tx - 1
+ || coord.tx > max_tx + 1
+ || coord.ty < min_ty - 1
+ || coord.ty > max_ty + 1
+ {
continue;
}
- if let Some((_, live_map)) = live_height_overlay {
- if live_map.contains_key(&coord) {
- continue;
- }
- }
let key = GpuTileKey {
- doc_id: doc.id.clone(),
- layer_id: layer.meta.id.clone(),
+ doc_id: doc_key,
+ layer_id: layer_key,
lod: 0,
coord,
};
if let Some(slot) = tile_pool.get_impasto_slot(&key) {
- base_insts.push(SparseTileInst {
- tile_origin_doc: [
- (coord.tx * TILE_SIZE as i32) as f32,
- (coord.ty * TILE_SIZE as i32) as f32,
- ],
- slot_f: slot as f32,
- tile_span: TILE_SIZE as f32,
- });
+ encoded_map.insert(coord, (slot as i32) + 1);
}
}
- let mut live_insts: Vec<SparseTileInst> = Vec::new();
- if let Some((_, live_map)) = live_height_overlay {
+ if let Some((_, _, live_map)) = live_height_overlay {
for (&coord, &slot) in live_map {
- if coord.tx < min_tx || coord.tx > max_tx || coord.ty < min_ty || coord.ty > max_ty {
+ if coord.tx < min_tx - 1
+ || coord.tx > max_tx + 1
+ || coord.ty < min_ty - 1
+ || coord.ty > max_ty + 1
+ {
continue;
}
- live_insts.push(SparseTileInst {
- tile_origin_doc: [
- (coord.tx * TILE_SIZE as i32) as f32,
- (coord.ty * TILE_SIZE as i32) as f32,
- ],
- slot_f: slot as f32,
- tile_span: TILE_SIZE as f32,
- });
+ encoded_map.insert(coord, -((slot as i32) + 1));
}
}
- let uniforms = LiveDabUniforms {
- viewport_size_phys: [view.viewport_w as f32, view.viewport_h as f32],
- doc_size: [view.dimensions.width as f32, view.dimensions.height as f32],
- pan_css: [view.camera.pan_x, view.camera.pan_y],
- zoom: view.camera.zoom,
- rotation_rad: view.rot_rad,
- flip: view.flip,
- dpr: view.dpr,
- _pad: 0.0,
- };
- let u_off = arenas.push_uniform(device, queue, encoder, &uniforms);
+ let mut insts: Vec<ImpastoTileInst> = Vec::with_capacity(encoded_map.len());
+ for (&coord, &slot_c) in &encoded_map {
+ if coord.tx < min_tx || coord.tx > max_tx || coord.ty < min_ty || coord.ty > max_ty {
+ continue;
+ }
+ let lookup = |dx: i32, dy: i32| -> i32 {
+ encoded_map
+ .get(&TileCoord::new(coord.tx + dx, coord.ty + dy))
+ .copied()
+ .unwrap_or(0)
+ };
+ insts.push(ImpastoTileInst {
+ tile_origin_doc: [
+ (coord.tx * TILE_SIZE as i32) as f32,
+ (coord.ty * TILE_SIZE as i32) as f32,
+ ],
+ tile_span: TILE_SIZE as f32,
+ slot_center: slot_c,
+ neighbors_cardinal: [
+ lookup(-1, 0), // L
+ lookup(1, 0), // R
+ lookup(0, -1), // T
+ lookup(0, 1), // B
+ ],
+ neighbors_diag: [
+ lookup(-1, -1), // TL
+ lookup(1, -1), // TR
+ lookup(-1, 1), // BL
+ lookup(1, 1), // BR
+ ],
+ });
+ }
- let base_range = if !base_insts.is_empty() {
- Some(arenas.push_sparse_stroke_tiles(device, queue, encoder, &base_insts))
+ let draw_payload = if !insts.is_empty() {
+ let uniforms = LiveDabUniforms {
+ viewport_size_phys: [view.viewport_w as f32, view.viewport_h as f32],
+ doc_size: [view.dimensions.width as f32, view.dimensions.height as f32],
+ pan_css: [view.camera.pan_x, view.camera.pan_y],
+ zoom: view.camera.zoom,
+ rotation_rad: view.rot_rad,
+ flip: view.flip,
+ dpr: view.dpr,
+ _pad: 0.0,
+ };
+ arenas.ensure_capacity(
+ device,
+ queue,
+ encoder,
+ std::mem::size_of::<LiveDabUniforms>(),
+ std::mem::size_of_val(insts.as_slice()),
+ 0,
+ 0,
+ );
+ let u_off = arenas.push_uniform(device, queue, encoder, &uniforms);
+ let range = arenas.push_impasto_tiles(device, queue, encoder, &insts);
+ Some((u_off, range))
} else {
None
};
- let live_range = if !live_insts.is_empty() {
- Some(arenas.push_sparse_stroke_tiles(device, queue, encoder, &live_insts))
- } else {
- None
+
+ let base_atlas_id = tile_pool.impasto_atlas_id();
+ let base_view = tile_pool.impasto_atlas_view();
+ let (live_atlas_id, live_view, can_cache) = match live_height_overlay {
+ Some((id, v, _)) => (id, v, id != 0),
+ None => (0, base_view, true),
};
- let base_bg = base_range.map(|_| {
+ let make_bg = || {
device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-comp-impasto-proj-base-bg"),
- layout: &pipelines.sparse_stroke_bgl,
+ label: Some("ink-comp-impasto-proj-bg"),
+ layout: &pipelines.impasto_proj_bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
@@ -5563,43 +7228,43 @@ fn project_impasto_height_tiles(
},
wgpu::BindGroupEntry {
binding: 1,
- resource: wgpu::BindingResource::TextureView(tile_pool.impasto_atlas_view()),
+ resource: wgpu::BindingResource::TextureView(base_view),
},
wgpu::BindGroupEntry {
binding: 2,
- resource: wgpu::BindingResource::Sampler(&pipelines.linear_sampler),
+ resource: wgpu::BindingResource::TextureView(live_view),
},
],
})
- });
+ };
- let live_bg = live_range.and_then(|_| {
- live_height_overlay.map(|(view_ref, _)| {
- device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-comp-impasto-proj-live-bg"),
- layout: &pipelines.sparse_stroke_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &arenas.uniform_buf,
- offset: 0,
- size: NonZeroU64::new(std::mem::size_of::<LiveDabUniforms>() as u64),
- }),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(view_ref),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::Sampler(&pipelines.linear_sampler),
- },
- ],
- })
- })
- });
+ let owned_bg;
+ let bg_opt: Option<&wgpu::BindGroup> = if draw_payload.is_some() {
+ if can_cache {
+ if let Some(cache) = bg_cache.as_deref_mut() {
+ let key = (base_atlas_id, live_atlas_id);
+ let needs_new = cache
+ .impasto_proj_bg
+ .as_ref()
+ .map(|(k, _)| *k != key)
+ .unwrap_or(true);
+ if needs_new {
+ cache.impasto_proj_bg = Some((key, make_bg()));
+ }
+ Some(&cache.impasto_proj_bg.as_ref().expect("impasto_proj_bg cached").1)
+ } else {
+ owned_bg = make_bg();
+ Some(&owned_bg)
+ }
+ } else {
+ owned_bg = make_bg();
+ Some(&owned_bg)
+ }
+ } else {
+ None
+ };
+ // Scissored LoadOp::Load + clear_rect_r16f + scissored tile projection (ZERO full-viewport clear!)
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("ink-comp-impasto-height-project-pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
@@ -5607,7 +7272,7 @@ fn project_impasto_height_tiles(
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
- load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
+ load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})],
@@ -5616,16 +7281,21 @@ fn project_impasto_height_tiles(
occlusion_query_set: None,
multiview_mask: None,
});
- pass.set_pipeline(&pipelines.impasto_height_project);
- if let (Some((start, end)), Some(ref bg)) = (base_range, base_bg) {
- pass.set_bind_group(0, bg, &[u_off]);
- pass.set_vertex_buffer(0, arenas.tile_inst_buf.slice(start..end));
- pass.draw(0..6, 0..base_insts.len() as u32);
- }
- if let (Some((start, end)), Some(ref bg)) = (live_range, live_bg) {
+ pass.set_viewport(0.0, 0.0, view.viewport_w as f32, view.viewport_h as f32, 0.0, 1.0);
+ pass.set_scissor_rect(
+ proj_scissor.x,
+ proj_scissor.y,
+ proj_scissor.width,
+ proj_scissor.height,
+ );
+ pass.set_pipeline(&pipelines.clear_rect_r16f);
+ pass.draw(0..3, 0..1);
+
+ if let (Some((u_off, (start, end))), Some(bg)) = (draw_payload, bg_opt) {
+ pass.set_pipeline(&pipelines.impasto_height_project);
pass.set_bind_group(0, bg, &[u_off]);
pass.set_vertex_buffer(0, arenas.tile_inst_buf.slice(start..end));
- pass.draw(0..6, 0..live_insts.len() as u32);
+ pass.draw(0..6, 0..insts.len() as u32);
}
}
@@ -5636,6 +7306,7 @@ fn run_impasto_lighting_pass(
pipelines: &CompositorPipelines,
arenas: &mut FrameArenas,
targets: &CompositorTargets,
+ bg_cache: Option<&mut ViewportBindGroupCache>,
encoder: &mut wgpu::CommandEncoder,
color_src: SurfaceId,
color_dst: SurfaceId,
@@ -5673,32 +7344,42 @@ fn run_impasto_lighting_pass(
};
let u_off = arenas.push_uniform(device, queue, encoder, &uniforms);
- let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-comp-impasto-light-bg"),
- layout: &pipelines.impasto_light_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &arenas.uniform_buf,
- offset: 0,
- size: NonZeroU64::new(std::mem::size_of::<ImpastoLightUniforms>() as u64),
- }),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(&get_surface(targets, color_src).view),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::TextureView(&height_surf.view),
- },
- wgpu::BindGroupEntry {
- binding: 3,
- resource: wgpu::BindingResource::Sampler(&pipelines.linear_sampler),
- },
- ],
- });
+ let make_bg = || {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-comp-impasto-light-bg"),
+ layout: &pipelines.impasto_light_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &arenas.uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(std::mem::size_of::<ImpastoLightUniforms>() as u64),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(&get_surface(targets, color_src).view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(&height_surf.view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::Sampler(&pipelines.linear_sampler),
+ },
+ ],
+ })
+ };
+
+ let owned_bg;
+ let bg: &wgpu::BindGroup = if let Some(cache) = bg_cache {
+ cache.impasto_light_bgs.entry(color_src).or_insert_with(make_bg)
+ } else {
+ owned_bg = make_bg();
+ &owned_bg
+ };
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("ink-comp-impasto-lighting-pass"),
@@ -5716,9 +7397,10 @@ fn run_impasto_lighting_pass(
occlusion_query_set: None,
multiview_mask: None,
});
+ pass.set_viewport(0.0, 0.0, view.viewport_w as f32, view.viewport_h as f32, 0.0, 1.0);
pass.set_scissor_rect(scissor.x, scissor.y, scissor.width, scissor.height);
pass.set_pipeline(&pipelines.impasto_lighting);
- pass.set_bind_group(0, &bg, &[u_off]);
+ pass.set_bind_group(0, bg, &[u_off]);
pass.draw(0..3, 0..1);
}
@@ -5733,6 +7415,7 @@ fn present_scene_to_view(
pipelines: &CompositorPipelines,
arenas: &mut FrameArenas,
targets: &CompositorTargets,
+ bg_cache: Option<&mut ViewportBindGroupCache>,
encoder: &mut wgpu::CommandEncoder,
output_view: &wgpu::TextureView,
view: &FrameRenderView,
@@ -5743,7 +7426,7 @@ fn present_scene_to_view(
show_pixel_grid: bool,
hide_artboard_chrome: bool,
transparent_bg: bool,
- target_is_rgba16f: bool,
+ target_is_export_rgba8: bool,
) {
let gw_rgb = hex_to_rgb_f32(&soft_proof.gamut_warning_color, [0.5, 0.5, 0.5]);
let uniforms = ViewportPresentUniforms {
@@ -5772,27 +7455,37 @@ fn present_scene_to_view(
};
let u_off = arenas.push_uniform(device, queue, encoder, &uniforms);
- let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-comp-present-bg"),
- layout: &pipelines.present_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &arenas.uniform_buf,
- offset: 0,
- size: NonZeroU64::new(std::mem::size_of::<ViewportPresentUniforms>() as u64),
- }),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(&targets.final_scene.view),
- },
- ],
- });
+ let make_bg = || {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-comp-present-bg"),
+ layout: &pipelines.present_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &arenas.uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(std::mem::size_of::<ViewportPresentUniforms>() as u64),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(&targets.final_scene.view),
+ },
+ ],
+ })
+ };
- let pipeline = if target_is_rgba16f {
- &pipelines.present_rgba16f
+ let owned_bg;
+ let bg: &wgpu::BindGroup = if let Some(cache) = bg_cache {
+ cache.present_bg.get_or_insert_with(make_bg)
+ } else {
+ owned_bg = make_bg();
+ &owned_bg
+ };
+
+ let pipeline = if target_is_export_rgba8 {
+ &pipelines.present_rgba8
} else {
&pipelines.present_surface
};
@@ -5814,53 +7507,47 @@ fn present_scene_to_view(
multiview_mask: None,
});
pass.set_pipeline(pipeline);
- pass.set_bind_group(0, &bg, &[u_off]);
+ pass.set_bind_group(0, bg, &[u_off]);
pass.draw(0..3, 0..1);
}
-fn readback_surface_rgba16f(
+/// Ensures a persistent reusable `MAP_READ` staging buffer of at least `required_bytes`.
+fn ensure_readback_staging<'a>(
device: &wgpu::Device,
- queue: &wgpu::Queue,
- surf: &SurfaceRgba16F,
-) -> Result<Vec<u8>, String> {
- let raw_bpr = surf.width * 8; // 8 bytes per Rgba16Float pixel
- let aligned_bpr = raw_bpr.div_ceil(256) * 256;
- let staging_size = (aligned_bpr as u64) * (surf.height as u64);
-
- let staging = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("ink-comp-readback-staging"),
- size: staging_size,
- usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
- mapped_at_creation: false,
- });
-
- let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-comp-readback-encoder"),
- });
- encoder.copy_texture_to_buffer(
- wgpu::TexelCopyTextureInfo {
- texture: &surf.texture,
- mip_level: 0,
- origin: wgpu::Origin3d::ZERO,
- aspect: wgpu::TextureAspect::All,
- },
- wgpu::TexelCopyBufferInfo {
- buffer: &staging,
- layout: wgpu::TexelCopyBufferLayout {
- offset: 0,
- bytes_per_row: Some(aligned_bpr),
- rows_per_image: Some(surf.height),
- },
- },
- wgpu::Extent3d {
- width: surf.width,
- height: surf.height,
- depth_or_array_layers: 1,
- },
- );
- queue.submit(Some(encoder.finish()));
+ slot: &'a mut Option<(wgpu::Buffer, u64)>,
+ required_bytes: u64,
+) -> &'a wgpu::Buffer {
+ let min_size = required_bytes.max(256);
+ let needs_alloc = slot.as_ref().is_none_or(|(_, cap)| *cap < min_size);
+ if needs_alloc {
+ let buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-comp-readback-staging-rgba8"),
+ size: min_size,
+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
+ mapped_at_creation: false,
+ });
+ *slot = Some((buf, min_size));
+ }
+ &slot.as_ref().expect("staging buffer ensured").0
+}
- let slice = staging.slice(..);
+/// Maps the reused GPU RGBA8 staging buffer and copies straight `RGBA8` rows into `out_rgba`
+/// (zero CPU f16 decoding or unpremultiplication!).
+#[allow(clippy::too_many_arguments)]
+fn map_and_copy_rgba8_rows(
+ device: &wgpu::Device,
+ staging: &wgpu::Buffer,
+ staging_size: u64,
+ aligned_bpr: u32,
+ raw_bpr: u32,
+ core_w: u32,
+ core_h: u32,
+ out_rgba: &mut [u8],
+ out_w: u32,
+ dst_x: u32,
+ dst_y: u32,
+) -> Result<(), String> {
+ let slice = staging.slice(0..staging_size);
let (tx, rx) = std::sync::mpsc::channel();
slice.map_async(wgpu::MapMode::Read, move |res| {
let _ = tx.send(res);
@@ -5874,83 +7561,23 @@ fn readback_surface_rgba16f(
.get_mapped_range()
.map_err(|e| format!("Compositor readback get_mapped_range failed: {e}"))?;
- let mut tight = vec![0u8; (raw_bpr * surf.height) as usize];
- for y in 0..surf.height as usize {
- let src_off = y * aligned_bpr as usize;
- let dst_off = y * raw_bpr as usize;
- tight[dst_off..dst_off + raw_bpr as usize]
- .copy_from_slice(&mapped[src_off..src_off + raw_bpr as usize]);
+ let row_bytes = raw_bpr as usize;
+ let src_stride = aligned_bpr as usize;
+ if dst_x == 0 && core_w == out_w && src_stride == row_bytes {
+ let dst_start = (dst_y as usize) * row_bytes;
+ let total_bytes = (core_h as usize) * row_bytes;
+ out_rgba[dst_start..dst_start + total_bytes].copy_from_slice(&mapped[..total_bytes]);
+ } else {
+ let out_stride = (out_w as usize) * 4;
+ let dst_x_bytes = (dst_x as usize) * 4;
+ for y in 0..core_h as usize {
+ let src_off = y * src_stride;
+ let dst_off = ((dst_y as usize) + y) * out_stride + dst_x_bytes;
+ out_rgba[dst_off..dst_off + row_bytes]
+ .copy_from_slice(&mapped[src_off..src_off + row_bytes]);
+ }
}
drop(mapped);
staging.unmap();
- Ok(tight)
-}
-
-const BAYER_4X4: [[f32; 4]; 4] = [
- [0.0 / 16.0, 8.0 / 16.0, 2.0 / 16.0, 10.0 / 16.0],
- [12.0 / 16.0, 4.0 / 16.0, 14.0 / 16.0, 6.0 / 16.0],
- [3.0 / 16.0, 11.0 / 16.0, 1.0 / 16.0, 9.0 / 16.0],
- [15.0 / 16.0, 7.0 / 16.0, 13.0 / 16.0, 5.0 / 16.0],
-];
-
-#[allow(clippy::too_many_arguments)]
-fn copy_chunk_rgba16f_to_rgba8(
- chunk_f16: &[u8],
- chunk_w: u32,
- pad_l: u32,
- pad_t: u32,
- core_w: u32,
- core_h: u32,
- out_rgba: &mut [u8],
- out_w: u32,
- dst_x: u32,
- dst_y: u32,
- unpremultiply: bool,
-) {
- let read_f16 = |off: usize| -> f32 {
- half::f16::from_bits(u16::from_le_bytes([chunk_f16[off], chunk_f16[off + 1]])).to_f32()
- };
-
- for y in 0..core_h {
- let sy = y + pad_t;
- let dy = dst_y + y;
- let bayer_row = &BAYER_4X4[(dy & 3) as usize];
- for x in 0..core_w {
- let sx = x + pad_l;
- let dx = dst_x + x;
- let src_off = ((sy * chunk_w + sx) * 8) as usize;
- let dst_off = ((dy * out_w + dx) * 4) as usize;
-
- let mut r = read_f16(src_off);
- let mut g = read_f16(src_off + 2);
- let mut b = read_f16(src_off + 4);
- let a = read_f16(src_off + 6).clamp(0.0, 1.0);
-
- if unpremultiply {
- if a <= 1e-4 {
- out_rgba[dst_off] = 0;
- out_rgba[dst_off + 1] = 0;
- out_rgba[dst_off + 2] = 0;
- out_rgba[dst_off + 3] = 0;
- continue;
- }
- r /= a;
- g /= a;
- b /= a;
- }
-
- // Subtle ordered Bayer dithering breaks 16F -> 8-bit gradient banding cleanly
- let dither = (bayer_row[(dx & 3) as usize] - 0.5) * 0.5;
- out_rgba[dst_off] = (r.clamp(0.0, 1.0) * 255.0 + dither).round().clamp(0.0, 255.0) as u8;
- out_rgba[dst_off + 1] =
- (g.clamp(0.0, 1.0) * 255.0 + dither).round().clamp(0.0, 255.0) as u8;
- out_rgba[dst_off + 2] =
- (b.clamp(0.0, 1.0) * 255.0 + dither).round().clamp(0.0, 255.0) as u8;
- out_rgba[dst_off + 3] = if unpremultiply {
- (a * 255.0).round().clamp(0.0, 255.0) as u8
- } else {
- 255
- };
- }
- }
+ Ok(())
}
diff --git a/crates/ink-engine/src/compositor/shaders/adjustment.rs b/crates/ink-engine/src/compositor/shaders/adjustment.rs
index d9a8cee..9bfb186 100644
--- a/crates/ink-engine/src/compositor/shaders/adjustment.rs
+++ b/crates/ink-engine/src/compositor/shaders/adjustment.rs
@@ -3,9 +3,14 @@
//! - Mode 0 (`curves`, `levels`): per-channel 256×1 RGBA8 LUT lookup
//! - Mode 1 (`gradient-map`): BT.601 luminance 256×1 RGBA8 LUT lookup
//! - Mode 2 (`color-balance`): exact analytic shadows/midtones/highlights shifts + `preserveLuminosity`
+//! - Honors all 28 `layer.meta.blend_mode`s on adjustment output.
-pub const ADJUSTMENT_SHADER_WGSL: &str = r#"
-struct AdjustmentUniforms {
+use super::blend_modes::BLEND_MODES_WGSL;
+
+pub fn build_adjustment_shader_wgsl() -> String {
+ format!(
+ r#"
+struct AdjustmentUniforms {{
viewport_size_phys: vec2<f32>,
doc_size: vec2<f32>,
pan_css: vec2<f32>,
@@ -20,7 +25,9 @@ struct AdjustmentUniforms {
cb_shadows: vec4<f32>,
cb_midtones: vec4<f32>,
cb_highlights: vec4<f32>,
-};
+ // blend_flags = [blend_mode, 0, 0, 0]
+ blend_flags: vec4<u32>,
+}};
@group(0) @binding(0) var<uniform> u: AdjustmentUniforms;
@group(0) @binding(1) var backdrop_tex: texture_2d<f32>;
@@ -29,22 +36,24 @@ struct AdjustmentUniforms {
@group(0) @binding(4) var clip_mask_tex: texture_2d<f32>;
@group(0) @binding(5) var linear_sampler: sampler;
-struct VsOut {
+struct VsOut {{
@builtin(position) pos: vec4<f32>,
@location(0) uv: vec2<f32>,
-};
+}};
@vertex
-fn vs_main(@builtin(vertex_index) vid: u32) -> VsOut {
+fn vs_main(@builtin(vertex_index) vid: u32) -> VsOut {{
let x = f32((vid << 1u) & 2u);
let y = f32(vid & 2u);
var out: VsOut;
out.uv = vec2<f32>(x, y);
out.pos = vec4<f32>(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0);
return out;
-}
+}}
-fn phys_to_doc(phys: vec2<f32>) -> vec2<f32> {
+{BLEND_MODES_WGSL}
+
+fn phys_to_doc(phys: vec2<f32>) -> vec2<f32> {{
let safe_dpr = max(0.05, u.dpr);
let safe_zoom = max(0.0001, u.zoom);
let css = phys / safe_dpr;
@@ -56,13 +65,13 @@ fn phys_to_doc(phys: vec2<f32>) -> vec2<f32> {
-rel.x * s + rel.y * c,
);
return unrot * u.flip + u.doc_size * 0.5;
-}
+}}
-fn sample_lut_u(val: f32) -> f32 {
+fn sample_lut_u(val: f32) -> f32 {{
return (clamp(val, 0.0, 1.0) * 255.0 + 0.5) / 256.0;
-}
+}}
-fn evaluate_color_balance(rgb: vec3<f32>) -> vec3<f32> {
+fn evaluate_color_balance(rgb: vec3<f32>) -> vec3<f32> {{
let lum = dot(rgb, vec3<f32>(0.299, 0.587, 0.114));
let w_shad = pow(max(0.0, 1.0 - lum * 2.0), 2.0);
let w_high = pow(max(0.0, lum * 2.0 - 1.0), 2.0);
@@ -72,26 +81,26 @@ fn evaluate_color_balance(rgb: vec3<f32>) -> vec3<f32> {
* (1.28 / 255.0);
var out_rgb = clamp(rgb + delta, vec3<f32>(0.0), vec3<f32>(1.0));
- if (u.flags.w != 0u) {
+ if (u.flags.w != 0u) {{
let new_lum = dot(out_rgb, vec3<f32>(0.299, 0.587, 0.114));
- if (new_lum > 0.0001) {
+ if (new_lum > 0.0001) {{
out_rgb = clamp(out_rgb * (lum / new_lum), vec3<f32>(0.0), vec3<f32>(1.0));
- }
- }
+ }}
+ }}
return out_rgb;
-}
+}}
@fragment
-fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
+fn fs_main(in: VsOut) -> @location(0) vec4<f32> {{
let px_coord = clamp(
vec2<i32>(in.pos.xy),
vec2<i32>(0),
max(vec2<i32>(0), vec2<i32>(u.viewport_size_phys) - vec2<i32>(1)),
);
let base_color = textureLoad(backdrop_tex, px_coord, 0);
- if (base_color.a < 0.0005) {
+ if (base_color.a < 0.0005) {{
return base_color;
- }
+ }}
let doc_coord = phys_to_doc(in.pos.xy);
if (
@@ -99,40 +108,47 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
doc_coord.y < 0.0 ||
doc_coord.x > u.doc_size.x ||
doc_coord.y > u.doc_size.y
- ) {
+ ) {{
return base_color;
- }
+ }}
let unpremult = clamp(base_color.rgb / max(0.0005, base_color.a), vec3<f32>(0.0), vec3<f32>(1.0));
var adjusted: vec3<f32>;
- if (u.flags.x == 1u) {
+ if (u.flags.x == 1u) {{
// Gradient map: map BT.601 luminance to 256x1 RGBA LUT
let lum = dot(unpremult, vec3<f32>(0.299, 0.587, 0.114));
adjusted = textureSampleLevel(lut_tex, linear_sampler, vec2<f32>(sample_lut_u(lum), 0.5), 0.0).rgb;
- } else if (u.flags.x == 2u) {
+ }} else if (u.flags.x == 2u) {{
// Analytic Color Balance (shadows/midtones/highlights + optional preserveLuminosity)
adjusted = evaluate_color_balance(unpremult);
- } else {
+ }} else {{
// Curves / Levels: per-channel LUT lookup
let r = textureSampleLevel(lut_tex, linear_sampler, vec2<f32>(sample_lut_u(unpremult.r), 0.5), 0.0).r;
let g = textureSampleLevel(lut_tex, linear_sampler, vec2<f32>(sample_lut_u(unpremult.g), 0.5), 0.0).g;
let b = textureSampleLevel(lut_tex, linear_sampler, vec2<f32>(sample_lut_u(unpremult.b), 0.5), 0.0).b;
adjusted = vec3<f32>(r, g, b);
- }
+ }}
+
+ let blend_mode = u.blend_flags.x;
+ if (blend_mode != 0u && blend_mode != 12u) {{
+ adjusted = evaluate_blend_mode(unpremult, adjusted, blend_mode);
+ }}
var mask_factor = clamp(u.opacity, 0.0, 1.0);
- if (u.flags.y != 0u) {
- let mask_uv = clamp(doc_coord / max(vec2<f32>(1.0), u.doc_size), vec2<f32>(0.0), vec2<f32>(1.0));
+ if (u.flags.y != 0u) {{
+ let mask_uv = clamp(in.pos.xy / max(vec2<f32>(1.0), u.viewport_size_phys), vec2<f32>(0.0), vec2<f32>(1.0));
let mask_val = textureSampleLevel(doc_mask_tex, linear_sampler, mask_uv, 0.0).r;
mask_factor *= mask_val;
- }
- if (u.flags.z != 0u) {
+ }}
+ if (u.flags.z != 0u) {{
let clip_a = textureLoad(clip_mask_tex, px_coord, 0).a;
mask_factor *= clamp(clip_a, 0.0, 1.0);
- }
+ }}
let final_rgb = mix(unpremult, adjusted, mask_factor);
return vec4<f32>(final_rgb * base_color.a, base_color.a);
+}}
+"#
+ )
}
-"#;
diff --git a/crates/ink-engine/src/compositor/shaders/blend_modes.rs b/crates/ink-engine/src/compositor/shaders/blend_modes.rs
index b24a00e..ade532d 100644
--- a/crates/ink-engine/src/compositor/shaders/blend_modes.rs
+++ b/crates/ink-engine/src/compositor/shaders/blend_modes.rs
@@ -55,6 +55,35 @@ pub const fn blend_mode_needs_backdrop(mode: BlendMode) -> bool {
!matches!(mode, BlendMode::Normal | BlendMode::PassThrough)
}
+/// CPU reference implementation matching `clip_color` in `BLEND_MODES_WGSL` (W3C/Photoshop spec).
+pub fn clip_color_cpu(c_in: [f32; 3]) -> [f32; 3] {
+ let mut c = c_in;
+ let l = (0.3 * c[0] + 0.59 * c[1] + 0.11 * c[2]).clamp(0.0, 1.0);
+ let n = c[0].min(c[1]).min(c[2]);
+ if n < 0.0 {
+ let denom = (l - n).max(0.0001);
+ c = [
+ l + ((c[0] - l) * l) / denom,
+ l + ((c[1] - l) * l) / denom,
+ l + ((c[2] - l) * l) / denom,
+ ];
+ }
+ let x = c[0].max(c[1]).max(c[2]);
+ if x > 1.0 {
+ let denom = (x - l).max(0.0001);
+ c = [
+ l + ((c[0] - l) * (1.0 - l)) / denom,
+ l + ((c[1] - l) * (1.0 - l)) / denom,
+ l + ((c[2] - l) * (1.0 - l)) / denom,
+ ];
+ }
+ [
+ c[0].clamp(0.0, 1.0),
+ c[1].clamp(0.0, 1.0),
+ c[2].clamp(0.0, 1.0),
+ ]
+}
+
/// Shared WGSL routines for all 28 blend modes (`blend_lum`, `clip_color`, `set_lum`,
/// `blend_sat`, `set_sat`, `blend_channel`, `evaluate_blend_mode`).
pub const BLEND_MODES_WGSL: &str = r#"
@@ -66,10 +95,10 @@ fn clip_color(c_in: vec3<f32>) -> vec3<f32> {
var c = c_in;
let l = clamp(blend_lum(c), 0.0, 1.0);
let n = min(min(c.r, c.g), c.b);
- let x = max(max(c.r, c.g), c.b);
if (n < 0.0) {
c = vec3<f32>(l) + ((c - vec3<f32>(l)) * l) / max(0.0001, l - n);
}
+ let x = max(max(c.r, c.g), c.b);
if (x > 1.0) {
c = vec3<f32>(l) + ((c - vec3<f32>(l)) * (1.0 - l)) / max(0.0001, x - l);
}
diff --git a/crates/ink-engine/src/compositor/shaders/blit.rs b/crates/ink-engine/src/compositor/shaders/blit.rs
index 393e6b1..ed42c6c 100644
--- a/crates/ink-engine/src/compositor/shaders/blit.rs
+++ b/crates/ink-engine/src/compositor/shaders/blit.rs
@@ -76,7 +76,7 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {{
discard;
}}
- // Optional folder/layer full-doc R8Unorm mask
+ // Optional folder/layer viewport-resolution R8Unorm mask
if (u.flags.z != 0u) {{
let doc_coord = phys_to_doc(in.pos.xy);
if (
@@ -87,7 +87,7 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {{
) {{
discard;
}}
- let mask_uv = clamp(doc_coord / max(vec2<f32>(1.0), u.doc_size), vec2<f32>(0.0), vec2<f32>(1.0));
+ let mask_uv = clamp(in.pos.xy / max(vec2<f32>(1.0), u.viewport_size_phys), vec2<f32>(0.0), vec2<f32>(1.0));
let mask_val = textureSampleLevel(doc_mask_tex, linear_sampler, mask_uv, 0.0).r;
src_a *= mask_val;
if (src_a < 0.0005) {{
@@ -95,8 +95,9 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {{
}}
}}
- // Optional continuous-alpha clip mask (clipping chain OR comic frame polygon mask)
- if (u.flags.w != 0u) {{
+ // Optional continuous-alpha clip mask (flags.w == 1u: comic frame mask; 2u: hardware source-atop)
+ let clip_mode = u.flags.w;
+ if (clip_mode == 1u) {{
let clip_a = textureLoad(clip_mask_tex, px_coord, 0).a;
src_a *= clamp(clip_a, 0.0, 1.0);
if (src_a < 0.0005) {{
@@ -118,8 +119,13 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {{
cb = clamp(dst_premul.rgb / dst_premul.a, vec3<f32>(0.0), vec3<f32>(1.0));
}}
let blended = evaluate_blend_mode(cb, cs, blend_mode);
- let dst_a = clamp(dst_premul.a, 0.0, 1.0);
- cs = mix(cs, blended, dst_a);
+ if (clip_mode == 2u) {{
+ // Hardware source-atop multiplies output RGB by dst_a, so no src-outside-dst mix!
+ cs = blended;
+ }} else {{
+ let dst_a = clamp(dst_premul.a, 0.0, 1.0);
+ cs = mix(cs, blended, dst_a);
+ }}
}}
return vec4<f32>(cs * src_a, src_a);
diff --git a/crates/ink-engine/src/compositor/shaders/impasto_lighting.rs b/crates/ink-engine/src/compositor/shaders/impasto_lighting.rs
index cbd1e94..830ef1d 100644
--- a/crates/ink-engine/src/compositor/shaders/impasto_lighting.rs
+++ b/crates/ink-engine/src/compositor/shaders/impasto_lighting.rs
@@ -8,7 +8,9 @@
//! trough deepening, and 2-lobe Blinn-Phong gloss specular over the layer's `Rgba16Float`
//! color surface.
-/// Projects sparse `256×256` `R16Float` height tiles into a viewport `R16Float` surface.
+/// Projects sparse `256×256` `R16Float` height tiles (from both base layer atlas and optional live
+/// stroke atlas) into a viewport `R16Float` surface with seamless cross-tile 3×3 neighbor bilinear
+/// sampling (zero 256×256 tile-edge Sobel seams) and strict document-bounds clipping.
pub const IMPASTO_HEIGHT_PROJECT_WGSL: &str = r#"
struct ImpastoProjUniforms {
viewport_size_phys: vec2<f32>,
@@ -22,19 +24,28 @@ struct ImpastoProjUniforms {
};
@group(0) @binding(0) var<uniform> u: ImpastoProjUniforms;
-@group(0) @binding(1) var height_atlas: texture_2d_array<f32>;
-@group(0) @binding(2) var lin_sampler: sampler;
+@group(0) @binding(1) var base_height_atlas: texture_2d_array<f32>;
+@group(0) @binding(2) var live_height_atlas: texture_2d_array<f32>;
-struct TileInst {
+// Encoded slot convention:
+// 0 => empty/unallocated tile (height = 0.0)
+// >0 => base_height_atlas slice (val - 1)
+// <0 => live_height_atlas slice ((-val) - 1)
+struct ImpastoTileInst {
@location(0) doc_origin: vec2<f32>,
- @location(1) slot_f: f32,
- @location(2) tile_span: f32,
+ @location(1) tile_span: f32,
+ @location(2) slot_center: i32,
+ @location(3) neighbors_cardinal: vec4<i32>, // (L, R, T, B)
+ @location(4) neighbors_diag: vec4<i32>, // (TL, TR, BL, BR)
};
struct VsOut {
@builtin(position) clip_pos: vec4<f32>,
@location(0) uv: vec2<f32>,
- @location(1) @interpolate(flat) slot_idx: i32,
+ @location(1) doc_coord: vec2<f32>,
+ @location(2) @interpolate(flat) slot_center: i32,
+ @location(3) @interpolate(flat) neighbors_cardinal: vec4<i32>,
+ @location(4) @interpolate(flat) neighbors_diag: vec4<i32>,
};
fn doc_to_ndc(doc_px: vec2<f32>) -> vec2<f32> {
@@ -52,7 +63,7 @@ fn doc_to_ndc(doc_px: vec2<f32>) -> vec2<f32> {
}
@vertex
-fn vs_main(@builtin(vertex_index) vid: u32, inst: TileInst) -> VsOut {
+fn vs_main(@builtin(vertex_index) vid: u32, inst: ImpastoTileInst) -> VsOut {
var corners = array<vec2<f32>, 6>(
vec2<f32>(0.0, 0.0),
vec2<f32>(1.0, 0.0),
@@ -66,13 +77,88 @@ fn vs_main(@builtin(vertex_index) vid: u32, inst: TileInst) -> VsOut {
var out: VsOut;
out.clip_pos = vec4<f32>(doc_to_ndc(doc_px), 0.0, 1.0);
out.uv = uv;
- out.slot_idx = i32(inst.slot_f + 0.5);
+ out.doc_coord = doc_px;
+ out.slot_center = inst.slot_center;
+ out.neighbors_cardinal = inst.neighbors_cardinal;
+ out.neighbors_diag = inst.neighbors_diag;
return out;
}
+fn load_encoded_slot(enc: i32, local_px: vec2<i32>) -> f32 {
+ if (enc == 0) {
+ return 0.0;
+ }
+ if (enc > 0) {
+ return max(textureLoad(base_height_atlas, local_px, enc - 1, 0).r, 0.0);
+ }
+ return max(textureLoad(live_height_atlas, local_px, (-enc) - 1, 0).r, 0.0);
+}
+
+fn sample_local_with_neighbors(
+ lx: i32,
+ ly: i32,
+ slot_c: i32,
+ card: vec4<i32>,
+ diag: vec4<i32>,
+) -> f32 {
+ var enc = slot_c;
+ var px = lx;
+ var py = ly;
+ if (lx < 0) {
+ px = lx + 256;
+ if (ly < 0) {
+ py = ly + 256;
+ enc = diag.x; // TL
+ } else if (ly >= 256) {
+ py = ly - 256;
+ enc = diag.z; // BL
+ } else {
+ enc = card.x; // L
+ }
+ } else if (lx >= 256) {
+ px = lx - 256;
+ if (ly < 0) {
+ py = ly + 256;
+ enc = diag.y; // TR
+ } else if (ly >= 256) {
+ py = ly - 256;
+ enc = diag.w; // BR
+ } else {
+ enc = card.y; // R
+ }
+ } else if (ly < 0) {
+ py = ly + 256;
+ enc = card.z; // T
+ } else if (ly >= 256) {
+ py = ly - 256;
+ enc = card.w; // B
+ }
+ return load_encoded_slot(enc, clamp(vec2<i32>(px, py), vec2<i32>(0), vec2<i32>(255)));
+}
+
@fragment
fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
- let h = textureSampleLevel(height_atlas, lin_sampler, in.uv, in.slot_idx, 0.0).r;
+ if (
+ in.doc_coord.x < 0.0 ||
+ in.doc_coord.y < 0.0 ||
+ in.doc_coord.x >= u.doc_size.x ||
+ in.doc_coord.y >= u.doc_size.y
+ ) {
+ discard;
+ }
+
+ let p = in.uv * 256.0 - vec2<f32>(0.5);
+ let p_floor = floor(p);
+ let i0 = vec2<i32>(p_floor);
+ let i1 = i0 + vec2<i32>(1, 1);
+ let f = clamp(p - p_floor, vec2<f32>(0.0), vec2<f32>(1.0));
+
+ let h00 = sample_local_with_neighbors(i0.x, i0.y, in.slot_center, in.neighbors_cardinal, in.neighbors_diag);
+ let h10 = sample_local_with_neighbors(i1.x, i0.y, in.slot_center, in.neighbors_cardinal, in.neighbors_diag);
+ let h01 = sample_local_with_neighbors(i0.x, i1.y, in.slot_center, in.neighbors_cardinal, in.neighbors_diag);
+ let h11 = sample_local_with_neighbors(i1.x, i1.y, in.slot_center, in.neighbors_cardinal, in.neighbors_diag);
+
+ let h = mix(mix(h00, h10, f.x), mix(h01, h11, f.x), f.y);
return vec4<f32>(max(h, 0.0), 0.0, 0.0, 1.0);
}
"#;
@@ -114,8 +200,8 @@ fn vs_main(@builtin(vertex_index) vid: u32) -> VsOut {
return out;
}
-fn sample_height(uv: vec2<f32>) -> f32 {
- return max(textureSampleLevel(height_tex, lin_sampler, clamp(uv, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0).r, 0.0);
+fn sample_height(uv: vec2<f32>, min_uv: vec2<f32>, max_uv: vec2<f32>) -> f32 {
+ return max(textureSampleLevel(height_tex, lin_sampler, clamp(uv, min_uv, max_uv), 0.0).r, 0.0);
}
@fragment
@@ -126,24 +212,29 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
return base;
}
+ let tex_dims = max(vec2<f32>(1.0), vec2<f32>(textureDimensions(height_tex)));
+ let inv_tex = vec2<f32>(1.0) / tex_dims;
+ let min_uv = vec2<f32>(0.5) * inv_tex;
+ let max_uv = max(min_uv, (u.viewport_size_phys - vec2<f32>(0.5)) * inv_tex);
+
let depth = max(u.params0.x, 0.0);
let gloss = clamp(u.params0.y, 0.0, 1.5);
let contrast = clamp(u.params0.z, 0.0, 3.0);
let step_px = clamp(u.params1.z, 1.0, 2.5);
- let dx = u.inv_viewport_size.x * step_px;
- let dy = u.inv_viewport_size.y * step_px;
+ let dx = inv_tex.x * step_px;
+ let dy = inv_tex.y * step_px;
- let uv = in.uv;
+ let uv = in.clip_pos.xy * inv_tex;
// 3x3 height neighborhood for Sobel normal & concavity micro-AO
- let h00 = sample_height(uv + vec2<f32>(-dx, -dy));
- let h10 = sample_height(uv + vec2<f32>(0.0, -dy));
- let h20 = sample_height(uv + vec2<f32>( dx, -dy));
- let h01 = sample_height(uv + vec2<f32>(-dx, 0.0));
- let h11 = sample_height(uv);
- let h21 = sample_height(uv + vec2<f32>( dx, 0.0));
- let h02 = sample_height(uv + vec2<f32>(-dx, dy));
- let h12 = sample_height(uv + vec2<f32>(0.0, dy));
- let h22 = sample_height(uv + vec2<f32>( dx, dy));
+ let h00 = sample_height(uv + vec2<f32>(-dx, -dy), min_uv, max_uv);
+ let h10 = sample_height(uv + vec2<f32>(0.0, -dy), min_uv, max_uv);
+ let h20 = sample_height(uv + vec2<f32>( dx, -dy), min_uv, max_uv);
+ let h01 = sample_height(uv + vec2<f32>(-dx, 0.0), min_uv, max_uv);
+ let h11 = sample_height(uv, min_uv, max_uv);
+ let h21 = sample_height(uv + vec2<f32>( dx, 0.0), min_uv, max_uv);
+ let h02 = sample_height(uv + vec2<f32>(-dx, dy), min_uv, max_uv);
+ let h12 = sample_height(uv + vec2<f32>(0.0, dy), min_uv, max_uv);
+ let h22 = sample_height(uv + vec2<f32>( dx, dy), min_uv, max_uv);
let gx = (h20 + 2.0 * h21 + h22) - (h00 + 2.0 * h01 + h02);
let gy = (h02 + 2.0 * h12 + h22) - (h00 + 2.0 * h10 + h20);
@@ -169,12 +260,12 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
// 5-tap directional cast shadow march toward light source
let l_xy_len = max(length(l.xy), 1e-4);
- let march_dir = (l.xy / l_xy_len) * u.inv_viewport_size * (1.8 * step_px);
+ let march_dir = (l.xy / l_xy_len) * inv_tex * (1.8 * step_px);
let slope_rise = max(l.z / l_xy_len, 0.25) * (0.28 / max(depth, 0.15));
var shadow_occ = 0.0;
for (var s: i32 = 1; s <= 5; s = s + 1) {
let sf = f32(s);
- let h_tap = sample_height(uv + march_dir * sf);
+ let h_tap = sample_height(uv + march_dir * sf, min_uv, max_uv);
let excess = h_tap - (h_smooth + slope_rise * sf * 0.22);
shadow_occ = max(shadow_occ, clamp(excess * 1.65, 0.0, 1.0));
}
diff --git a/crates/ink-engine/src/compositor/shaders/layer_styles.rs b/crates/ink-engine/src/compositor/shaders/layer_styles.rs
index 346586f..a7b3b2f 100644
--- a/crates/ink-engine/src/compositor/shaders/layer_styles.rs
+++ b/crates/ink-engine/src/compositor/shaders/layer_styles.rs
@@ -1,7 +1,9 @@
//! Non-destructive GPU Layer Styles WGSL shaders:
//! 1. `SEPARABLE_ALPHA_BLUR_WGSL`: Two-pass separable Gaussian blur (Horizontal + Vertical)
//! for smooth, artifact-free Drop Shadow and Outer Glow alpha halos.
-//! 2. `LAYER_STYLES_COMPOSITE_WGSL`: Evaluates `stroke` (`outside` / `inside` / `center`),
+//! 2. `STROKE_SDF_HORIZ_WGSL` & `STROKE_SDF_VERT_WGSL`: Fast 2-pass separable exact Euclidean
+//! distance transform (SDF) for artifact-free circular `stroke` outlines (replaces 144-tap radial loop).
+//! 3. `LAYER_STYLES_COMPOSITE_WGSL`: Evaluates `stroke` (`outside` / `inside` / `center`),
//! `dropShadow`, and `outerGlow` in exact Photoshop/InkStudio stacking order.
pub const SEPARABLE_ALPHA_BLUR_WGSL: &str = r#"
@@ -32,10 +34,15 @@ fn vs_main(@builtin(vertex_index) vid: u32) -> VsOut {
@fragment
fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
- let texel = vec2<f32>(1.0) / max(vec2<f32>(1.0), u.viewport_size_phys);
+ let tex_dims = vec2<f32>(textureDimensions(src_tex));
+ let texel = vec2<f32>(1.0) / max(vec2<f32>(1.0), tex_dims);
+ let base_uv = in.pos.xy * texel;
+ let min_uv = vec2<f32>(0.5) * texel;
+ let max_uv = max(min_uv, (u.viewport_size_phys - vec2<f32>(0.5)) * texel);
+
let radius = max(0.0, u.params.x);
if (radius <= 0.25) {
- let a = textureSampleLevel(src_tex, linear_sampler, in.uv, 0.0).a;
+ let a = textureSampleLevel(src_tex, linear_sampler, clamp(base_uv, min_uv, max_uv), 0.0).a;
return vec4<f32>(0.0, 0.0, 0.0, a);
}
@@ -46,7 +53,7 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
let step_px = max(1.0, radius / f32(max_taps));
let dir_uv = u.direction * texel;
- var sum_a = textureSampleLevel(src_tex, linear_sampler, in.uv, 0.0).a;
+ var sum_a = textureSampleLevel(src_tex, linear_sampler, clamp(base_uv, min_uv, max_uv), 0.0).a;
var sum_w = 1.0;
for (var i: i32 = 1; i <= max_taps; i = i + 1) {
@@ -56,8 +63,18 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
}
let w = exp(-(dist * dist) * inv_two_sigma2);
let off = dir_uv * dist;
- let a_pos = textureSampleLevel(src_tex, linear_sampler, in.uv + off, 0.0).a;
- let a_neg = textureSampleLevel(src_tex, linear_sampler, in.uv - off, 0.0).a;
+ let uv_pos = base_uv + off;
+ let uv_neg = base_uv - off;
+ let a_pos = select(
+ 0.0,
+ textureSampleLevel(src_tex, linear_sampler, uv_pos, 0.0).a,
+ uv_pos.x >= 0.0 && uv_pos.y >= 0.0 && uv_pos.x <= max_uv.x + texel.x * 0.5 && uv_pos.y <= max_uv.y + texel.y * 0.5,
+ );
+ let a_neg = select(
+ 0.0,
+ textureSampleLevel(src_tex, linear_sampler, uv_neg, 0.0).a,
+ uv_neg.x >= 0.0 && uv_neg.y >= 0.0 && uv_neg.x <= max_uv.x + texel.x * 0.5 && uv_neg.y <= max_uv.y + texel.y * 0.5,
+ );
sum_a += (a_pos + a_neg) * w;
sum_w += 2.0 * w;
}
@@ -67,6 +84,155 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
}
"#;
+/// Pass 1 of separable 2-pass exact Euclidean Distance Transform (Horizontal 1D distance scan).
+/// Outputs `rg = (dx_to_inside, dx_to_outside)` in physical pixels.
+pub const STROKE_SDF_HORIZ_WGSL: &str = r#"
+struct BlurUniforms {
+ viewport_size_phys: vec2<f32>,
+ direction: vec2<f32>,
+ params: vec4<f32>, // x = radius_px
+};
+
+@group(0) @binding(0) var<uniform> u: BlurUniforms;
+@group(0) @binding(1) var src_tex: texture_2d<f32>;
+@group(0) @binding(2) var linear_sampler: sampler;
+
+struct VsOut {
+ @builtin(position) pos: vec4<f32>,
+ @location(0) uv: vec2<f32>,
+};
+
+@vertex
+fn vs_main(@builtin(vertex_index) vid: u32) -> VsOut {
+ let x = f32((vid << 1u) & 2u);
+ let y = f32(vid & 2u);
+ var out: VsOut;
+ out.uv = vec2<f32>(x, y);
+ out.pos = vec4<f32>(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0);
+ return out;
+}
+
+@fragment
+fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
+ let vp_w = max(1, i32(u.viewport_size_phys.x));
+ let vp_h = max(1, i32(u.viewport_size_phys.y));
+ let px = clamp(vec2<i32>(in.pos.xy), vec2<i32>(0), vec2<i32>(vp_w - 1, vp_h - 1));
+ let center_in = textureLoad(src_tex, px, 0).a >= 0.5;
+
+ let radius = clamp(u.params.x, 0.5, 128.0);
+ let max_steps = 48;
+ let step_px = max(1.0, ceil(radius) / f32(max_steps));
+ let steps = min(max_steps, i32(ceil(radius / step_px)) + 1);
+
+ let inf_d = 1024.0;
+ if (center_in) {
+ var dx_out = inf_d;
+ for (var i: i32 = 1; i <= steps; i = i + 1) {
+ let d = f32(i) * step_px;
+ let di = i32(round(d));
+ let xr = px.x + di;
+ let xl = px.x - di;
+ let out_r = xr >= vp_w || textureLoad(src_tex, vec2<i32>(xr, px.y), 0).a < 0.5;
+ let out_l = xl < 0 || textureLoad(src_tex, vec2<i32>(xl, px.y), 0).a < 0.5;
+ if (out_r || out_l) {
+ dx_out = d;
+ break;
+ }
+ }
+ return vec4<f32>(0.0, dx_out, 0.0, 1.0);
+ } else {
+ var dx_in = inf_d;
+ for (var i: i32 = 1; i <= steps; i = i + 1) {
+ let d = f32(i) * step_px;
+ let di = i32(round(d));
+ let xr = px.x + di;
+ let xl = px.x - di;
+ let in_r = xr < vp_w && textureLoad(src_tex, vec2<i32>(xr, px.y), 0).a >= 0.5;
+ let in_l = xl >= 0 && textureLoad(src_tex, vec2<i32>(xl, px.y), 0).a >= 0.5;
+ if (in_r || in_l) {
+ dx_in = d;
+ break;
+ }
+ }
+ return vec4<f32>(dx_in, 0.0, 0.0, 1.0);
+ }
+}
+"#;
+
+/// Pass 2 of separable 2-pass exact Euclidean Distance Transform (Vertical parabolic minimization).
+/// Outputs `rg = (euclid_dist_to_inside, euclid_dist_to_outside)` in physical pixels.
+pub const STROKE_SDF_VERT_WGSL: &str = r#"
+struct BlurUniforms {
+ viewport_size_phys: vec2<f32>,
+ direction: vec2<f32>,
+ params: vec4<f32>, // x = radius_px
+};
+
+@group(0) @binding(0) var<uniform> u: BlurUniforms;
+@group(0) @binding(1) var src_tex: texture_2d<f32>;
+@group(0) @binding(2) var linear_sampler: sampler;
+
+struct VsOut {
+ @builtin(position) pos: vec4<f32>,
+ @location(0) uv: vec2<f32>,
+};
+
+@vertex
+fn vs_main(@builtin(vertex_index) vid: u32) -> VsOut {
+ let x = f32((vid << 1u) & 2u);
+ let y = f32(vid & 2u);
+ var out: VsOut;
+ out.uv = vec2<f32>(x, y);
+ out.pos = vec4<f32>(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0);
+ return out;
+}
+
+@fragment
+fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
+ let vp_w = max(1, i32(u.viewport_size_phys.x));
+ let vp_h = max(1, i32(u.viewport_size_phys.y));
+ let px = clamp(vec2<i32>(in.pos.xy), vec2<i32>(0), vec2<i32>(vp_w - 1, vp_h - 1));
+
+ let radius = clamp(u.params.x, 0.5, 128.0);
+ let max_steps = 48;
+ let step_px = max(1.0, ceil(radius) / f32(max_steps));
+ let steps = min(max_steps, i32(ceil(radius / step_px)) + 1);
+
+ let c = textureLoad(src_tex, px, 0).rg;
+ var min_in_sq = c.x * c.x;
+ var min_out_sq = c.y * c.y;
+
+ for (var i: i32 = 1; i <= steps; i = i + 1) {
+ let dy = f32(i) * step_px;
+ let dy2 = dy * dy;
+ if (dy2 >= min_in_sq && dy2 >= min_out_sq) {
+ break;
+ }
+ let dyi = i32(round(dy));
+
+ let yp = px.y + dyi;
+ if (yp < vp_h) {
+ let hp = textureLoad(src_tex, vec2<i32>(px.x, yp), 0).rg;
+ min_in_sq = min(min_in_sq, hp.x * hp.x + dy2);
+ min_out_sq = min(min_out_sq, hp.y * hp.y + dy2);
+ } else {
+ min_out_sq = min(min_out_sq, dy2);
+ }
+
+ let yn = px.y - dyi;
+ if (yn >= 0) {
+ let hn = textureLoad(src_tex, vec2<i32>(px.x, yn), 0).rg;
+ min_in_sq = min(min_in_sq, hn.x * hn.x + dy2);
+ min_out_sq = min(min_out_sq, hn.y * hn.y + dy2);
+ } else {
+ min_out_sq = min(min_out_sq, dy2);
+ }
+ }
+
+ return vec4<f32>(sqrt(min_in_sq), sqrt(min_out_sq), 0.0, 1.0);
+}
+"#;
+
pub const LAYER_STYLES_COMPOSITE_WGSL: &str = r#"
struct LayerStylesUniforms {
viewport_size_phys: vec2<f32>,
@@ -87,6 +253,7 @@ struct LayerStylesUniforms {
@group(0) @binding(2) var shadow_blur_tex: texture_2d<f32>;
@group(0) @binding(3) var glow_blur_tex: texture_2d<f32>;
@group(0) @binding(4) var linear_sampler: sampler;
+@group(0) @binding(5) var stroke_sdf_tex: texture_2d<f32>;
struct VsOut {
@builtin(position) pos: vec4<f32>,
@@ -104,39 +271,23 @@ fn vs_main(@builtin(vertex_index) vid: u32) -> VsOut {
}
fn compute_stroke_coverage(
- uv: vec2<f32>,
+ px_coord: vec2<i32>,
center_alpha: f32,
radius_px: f32,
position: u32,
- texel: vec2<f32>,
) -> f32 {
if (radius_px <= 0.0) {
return 0.0;
}
- // 24 angular directions * 6 radial steps gives smooth circular outlines with clean AA
- let angle_step = 0.26179939; // 2*PI / 24
+ let sdf = textureLoad(stroke_sdf_tex, px_coord, 0).rg;
// Outside stroke (0)
if (position == 0u) {
if (center_alpha >= 0.99) {
return 0.0;
}
- var min_inside_dist = radius_px + 1.0;
- for (var i: i32 = 0; i < 24; i = i + 1) {
- let ang = f32(i) * angle_step;
- let dir = vec2<f32>(cos(ang), sin(ang));
- for (var j: i32 = 1; j <= 6; j = j + 1) {
- let dist = radius_px * (f32(j) / 6.0);
- let s_uv = uv + dir * (dist * texel);
- if (textureSampleLevel(layer_tex, linear_sampler, s_uv, 0.0).a > 0.5) {
- if (dist < min_inside_dist) {
- min_inside_dist = dist;
- }
- break;
- }
- }
- }
+ let min_inside_dist = sdf.r;
if (min_inside_dist <= radius_px) {
return clamp(radius_px - min_inside_dist + 1.0, 0.0, 1.0) * (1.0 - center_alpha);
}
@@ -148,21 +299,7 @@ fn compute_stroke_coverage(
if (center_alpha < 0.01) {
return 0.0;
}
- var min_outside_dist = radius_px + 1.0;
- for (var i: i32 = 0; i < 24; i = i + 1) {
- let ang = f32(i) * angle_step;
- let dir = vec2<f32>(cos(ang), sin(ang));
- for (var j: i32 = 1; j <= 6; j = j + 1) {
- let dist = radius_px * (f32(j) / 6.0);
- let s_uv = uv + dir * (dist * texel);
- if (textureSampleLevel(layer_tex, linear_sampler, s_uv, 0.0).a < 0.5) {
- if (dist < min_outside_dist) {
- min_outside_dist = dist;
- }
- break;
- }
- }
- }
+ let min_outside_dist = sdf.g;
if (min_outside_dist <= radius_px) {
return clamp(radius_px - min_outside_dist + 1.0, 0.0, 1.0) * center_alpha;
}
@@ -171,52 +308,15 @@ fn compute_stroke_coverage(
// Center stroke (2): half outside, half inside
let half_r = max(0.5, radius_px * 0.5);
- if (center_alpha < 0.5) {
- var min_inside_dist = half_r + 1.0;
- for (var i: i32 = 0; i < 24; i = i + 1) {
- let ang = f32(i) * angle_step;
- let dir = vec2<f32>(cos(ang), sin(ang));
- for (var j: i32 = 1; j <= 6; j = j + 1) {
- let dist = half_r * (f32(j) / 6.0);
- let s_uv = uv + dir * (dist * texel);
- if (textureSampleLevel(layer_tex, linear_sampler, s_uv, 0.0).a >= 0.5) {
- if (dist < min_inside_dist) {
- min_inside_dist = dist;
- }
- break;
- }
- }
- }
- if (min_inside_dist <= half_r) {
- return clamp(half_r - min_inside_dist + 1.0, 0.0, 1.0);
- }
- return 0.0;
- } else {
- var min_outside_dist = half_r + 1.0;
- for (var i: i32 = 0; i < 24; i = i + 1) {
- let ang = f32(i) * angle_step;
- let dir = vec2<f32>(cos(ang), sin(ang));
- for (var j: i32 = 1; j <= 6; j = j + 1) {
- let dist = half_r * (f32(j) / 6.0);
- let s_uv = uv + dir * (dist * texel);
- if (textureSampleLevel(layer_tex, linear_sampler, s_uv, 0.0).a < 0.5) {
- if (dist < min_outside_dist) {
- min_outside_dist = dist;
- }
- break;
- }
- }
- }
- if (min_outside_dist <= half_r) {
- return clamp(half_r - min_outside_dist + 1.0, 0.0, 1.0);
- }
- return 0.0;
+ let dist = select(sdf.g, sdf.r, center_alpha < 0.5);
+ if (dist <= half_r) {
+ return clamp(half_r - dist + 1.0, 0.0, 1.0);
}
+ return 0.0;
}
@fragment
fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
- let texel = vec2<f32>(1.0) / max(vec2<f32>(1.0), u.viewport_size_phys);
let px_coord = clamp(
vec2<i32>(in.pos.xy),
vec2<i32>(0),
@@ -228,16 +328,20 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
// 1. Drop Shadow (sampled from separable Gaussian blur pass shifted by shadow_offset_px)
var shadow_alpha = 0.0;
if (u.flags.w != 0u) {
- let shadow_uv = in.uv - u.shadow_offset_px * texel;
+ let shadow_pos = in.pos.xy - u.shadow_offset_px;
if (
- shadow_uv.x >= 0.0 && shadow_uv.x <= 1.0 &&
- shadow_uv.y >= 0.0 && shadow_uv.y <= 1.0
+ shadow_pos.x >= 0.0 && shadow_pos.x <= u.viewport_size_phys.x &&
+ shadow_pos.y >= 0.0 && shadow_pos.y <= u.viewport_size_phys.y
) {
var raw_a: f32;
- if (u.params1.x <= 0.5) {
- raw_a = textureSampleLevel(layer_tex, linear_sampler, shadow_uv, 0.0).a;
+ if (u.params1.x <= 0.25) {
+ let l_dims = max(vec2<f32>(1.0), vec2<f32>(textureDimensions(layer_tex)));
+ let l_uv = clamp(shadow_pos / l_dims, vec2<f32>(0.5) / l_dims, (u.viewport_size_phys - vec2<f32>(0.5)) / l_dims);
+ raw_a = textureSampleLevel(layer_tex, linear_sampler, l_uv, 0.0).a;
} else {
- raw_a = textureSampleLevel(shadow_blur_tex, linear_sampler, shadow_uv, 0.0).a;
+ let s_dims = max(vec2<f32>(1.0), vec2<f32>(textureDimensions(shadow_blur_tex)));
+ let s_uv = clamp(shadow_pos / s_dims, vec2<f32>(0.5) / s_dims, (u.viewport_size_phys - vec2<f32>(0.5)) / s_dims);
+ raw_a = textureSampleLevel(shadow_blur_tex, linear_sampler, s_uv, 0.0).a;
}
let spread_factor = max(0.01, 1.0 - u.params1.y * 0.95);
shadow_alpha = clamp(raw_a / spread_factor, 0.0, 1.0) * u.shadow_color.a;
@@ -247,16 +351,18 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
// 2. Outer Glow (sampled from separable Gaussian blur pass)
var glow_alpha = 0.0;
if (u.flags.z != 0u && center_alpha < 0.99) {
- let raw_g = textureSampleLevel(glow_blur_tex, linear_sampler, in.uv, 0.0).a;
+ let g_dims = max(vec2<f32>(1.0), vec2<f32>(textureDimensions(glow_blur_tex)));
+ let g_uv = clamp(in.pos.xy / g_dims, vec2<f32>(0.5) / g_dims, (u.viewport_size_phys - vec2<f32>(0.5)) / g_dims);
+ let raw_g = textureSampleLevel(glow_blur_tex, linear_sampler, g_uv, 0.0).a;
let spread_factor = max(0.01, 1.0 - u.params0.w * 0.95);
let glow_val = clamp(raw_g / spread_factor, 0.0, 1.0);
glow_alpha = glow_val * (1.0 - center_alpha) * u.glow_color.a;
}
- // 3. Stroke
+ // 3. Stroke (O(1) lookup from 2-pass separable exact Euclidean SDF)
var stroke_cov = 0.0;
if (u.flags.x != 0u) {
- stroke_cov = compute_stroke_coverage(in.uv, center_alpha, u.params0.y, u.flags.y, texel);
+ stroke_cov = compute_stroke_coverage(px_coord, center_alpha, u.params0.y, u.flags.y);
}
// Standard Photoshop / InkStudio stacking order:
diff --git a/crates/ink-engine/src/compositor/shaders/layer_tile.rs b/crates/ink-engine/src/compositor/shaders/layer_tile.rs
index 4ce0253..a61f9c6 100644
--- a/crates/ink-engine/src/compositor/shaders/layer_tile.rs
+++ b/crates/ink-engine/src/compositor/shaders/layer_tile.rs
@@ -182,7 +182,7 @@ fn evaluate_mask_alpha(in: VsOut, use_nearest: bool) -> f32 {{
if (mask_mode == 1u) {{
return sample_sparse_mask(in.tex_uv, in.mask_slice, in.mask_default, use_nearest);
}} else if (mask_mode == 2u) {{
- let mask_uv = clamp(in.doc_coord / max(vec2<f32>(1.0), u.doc_size), vec2<f32>(0.0), vec2<f32>(1.0));
+ let mask_uv = clamp(in.pos.xy / max(vec2<f32>(1.0), u.viewport_size_phys), vec2<f32>(0.0), vec2<f32>(1.0));
return textureSampleLevel(doc_mask_tex, linear_sampler, mask_uv, 0.0).r;
}}
return 1.0;
@@ -263,8 +263,9 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {{
final_color.a *= mask_alpha * u.layer_opacity;
}}
- // Continuous-alpha clipping mask against base layer silhouette (when clipped == true)
- if (u.flags0.z != 0u) {{
+ // Continuous-alpha clip mask (flags0.z == 1u: comic frame mask; 2u: hardware source-atop)
+ let clip_mode = u.flags0.z;
+ if (clip_mode == 1u) {{
let px_coord = clamp(
vec2<i32>(in.pos.xy),
vec2<i32>(0),
@@ -293,8 +294,13 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {{
}}
let cs = clamp(final_color.rgb, vec3<f32>(0.0), vec3<f32>(1.0));
let blended = evaluate_blend_mode(cb, cs, blend_mode);
- let dst_a = clamp(dst_premul.a, 0.0, 1.0);
- final_color = vec4<f32>(mix(cs, blended, dst_a), final_color.a);
+ if (clip_mode == 2u) {{
+ // Hardware source-atop multiplies output RGB by dst_a, so no src-outside-dst mix!
+ final_color = vec4<f32>(blended, final_color.a);
+ }} else {{
+ let dst_a = clamp(dst_premul.a, 0.0, 1.0);
+ final_color = vec4<f32>(mix(cs, blended, dst_a), final_color.a);
+ }}
}}
return vec4<f32>(final_color.rgb * final_color.a, final_color.a);
diff --git a/crates/ink-engine/src/compositor/shaders/live_dab.rs b/crates/ink-engine/src/compositor/shaders/live_dab.rs
index 7386031..5f252a0 100644
--- a/crates/ink-engine/src/compositor/shaders/live_dab.rs
+++ b/crates/ink-engine/src/compositor/shaders/live_dab.rs
@@ -14,6 +14,103 @@
use super::blend_modes::BLEND_MODES_WGSL;
use super::screentone::SCREENTONE_WGSL;
+/// Instanced projector drawing sparse `256×256` `R8Unorm` layer mask tiles from
+/// `GpuTilePool::mask_atlas` directly into a viewport-resolution `R8Unorm` mask target.
+///
+/// Uses `textureLoad` bilinear (or nearest when `u._pad > 0.5`) matching `sample_sparse_mask`
+/// in `layer_tile.rs` identically so 4K–8K masks stay razor-sharp with zero pen-down snap!
+pub const SPARSE_MASK_PROJECT_WGSL: &str = r#"
+struct SparseMaskProjectUniforms {
+ viewport_size_phys: vec2<f32>,
+ doc_size: vec2<f32>,
+ pan_css: vec2<f32>,
+ zoom: f32,
+ rotation_rad: f32,
+ flip: vec2<f32>,
+ dpr: f32,
+ use_nearest: f32,
+};
+
+@group(0) @binding(0) var<uniform> u: SparseMaskProjectUniforms;
+@group(0) @binding(1) var mask_atlas: texture_2d_array<f32>;
+
+struct SparseTileInst {
+ @location(0) tile_origin_doc: vec2<f32>,
+ @location(1) slot_f: f32,
+ @location(2) _pad: f32,
+};
+
+struct VsOut {
+ @builtin(position) pos: vec4<f32>,
+ @location(0) uv: vec2<f32>,
+ @location(1) doc_coord: vec2<f32>,
+ @location(2) @interpolate(flat) slot_i: i32,
+};
+
+@vertex
+fn vs_main(@builtin(vertex_index) vid: u32, inst: SparseTileInst) -> VsOut {
+ var uv: vec2<f32>;
+ switch (vid) {
+ case 0u: { uv = vec2<f32>(0.0, 0.0); }
+ case 1u: { uv = vec2<f32>(1.0, 0.0); }
+ case 2u: { uv = vec2<f32>(0.0, 1.0); }
+ case 3u: { uv = vec2<f32>(0.0, 1.0); }
+ case 4u: { uv = vec2<f32>(1.0, 0.0); }
+ default: { uv = vec2<f32>(1.0, 1.0); }
+ }
+
+ let doc_pos = inst.tile_origin_doc + uv * 256.0;
+ let centered = (doc_pos - u.doc_size * 0.5) * u.flip;
+ let cos_r = cos(u.rotation_rad);
+ let sin_r = sin(u.rotation_rad);
+ let rotated = vec2<f32>(
+ centered.x * cos_r - centered.y * sin_r,
+ centered.x * sin_r + centered.y * cos_r,
+ );
+ let screen_phys = (u.pan_css + rotated * u.zoom) * u.dpr;
+ let ndc = vec2<f32>(
+ (2.0 * screen_phys.x / max(1.0, u.viewport_size_phys.x)) - 1.0,
+ 1.0 - (2.0 * screen_phys.y / max(1.0, u.viewport_size_phys.y)),
+ );
+
+ var out: VsOut;
+ out.pos = vec4<f32>(ndc, 0.0, 1.0);
+ out.uv = uv;
+ out.doc_coord = doc_pos;
+ out.slot_i = i32(round(inst.slot_f));
+ return out;
+}
+
+@fragment
+fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
+ if (
+ in.doc_coord.x < 0.0 ||
+ in.doc_coord.y < 0.0 ||
+ in.doc_coord.x >= u.doc_size.x ||
+ in.doc_coord.y >= u.doc_size.y
+ ) {
+ discard;
+ }
+ var m: f32;
+ if (u.use_nearest > 0.5) {
+ let coord = clamp(vec2<i32>(floor(in.uv * 256.0)), vec2<i32>(0), vec2<i32>(255));
+ m = textureLoad(mask_atlas, coord, in.slot_i, 0).r;
+ } else {
+ let p = in.uv * 256.0 - vec2<f32>(0.5);
+ let p_floor = floor(p);
+ let i0 = clamp(vec2<i32>(p_floor), vec2<i32>(0), vec2<i32>(255));
+ let i1 = clamp(i0 + vec2<i32>(1), vec2<i32>(0), vec2<i32>(255));
+ let f = clamp(p - p_floor, vec2<f32>(0.0), vec2<f32>(1.0));
+ let m00 = textureLoad(mask_atlas, i0, in.slot_i, 0).r;
+ let m10 = textureLoad(mask_atlas, vec2<i32>(i1.x, i0.y), in.slot_i, 0).r;
+ let m01 = textureLoad(mask_atlas, vec2<i32>(i0.x, i1.y), in.slot_i, 0).r;
+ let m11 = textureLoad(mask_atlas, i1, in.slot_i, 0).r;
+ m = mix(mix(m00, m10, f.x), mix(m01, m11, f.x), f.y);
+ }
+ return vec4<f32>(m, 0.0, 0.0, 1.0);
+}
+"#;
+
/// Instanced projector drawing active `256×256` `Rgba16Float` (premultiplied) sparse GPU
/// stroke tiles into the viewport `live_stroke_surface` with exact camera transform.
pub const SPARSE_STROKE_PROJECT_WGSL: &str = r#"
@@ -89,14 +186,37 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
) {
discard;
}
- let sample_uv = clamp(in.uv, vec2<f32>(0.5 / 256.0), vec2<f32>(255.5 / 256.0));
- let px = textureSampleLevel(stroke_atlas, stroke_sampler, sample_uv, in.slot_i, 0.0);
- // When u._pad > 0.5, tiles carry straight RGBA16F complete layer replacements (Phase 5 Natural Paint):
- // premultiply and overwrite cleanly without discarding transparent margin pixels!
+ // When u._pad > 0.5, tiles carry straight RGBA16F complete layer replacements (Phase 5 Natural Paint / Color Mixing):
+ // Use halo-free premultiplied 2x2 bilinear interpolation (matching layer_tile.rs) instead of
+ // hardware bilinear sampling straight-alpha tiles before premultiplying (which creates dark edge halos).
if (u._pad > 0.5) {
- let a = clamp(px.a, 0.0, 1.0);
- return vec4<f32>(clamp(px.rgb, vec3<f32>(0.0), vec3<f32>(1.0)) * a, a);
+ let p = in.uv * 256.0 - vec2<f32>(0.5);
+ let p_floor = floor(p);
+ let i0 = clamp(vec2<i32>(p_floor), vec2<i32>(0), vec2<i32>(255));
+ let i1 = clamp(i0 + vec2<i32>(1), vec2<i32>(0), vec2<i32>(255));
+ let f = clamp(p - p_floor, vec2<f32>(0.0), vec2<f32>(1.0));
+
+ let c00 = textureLoad(stroke_atlas, i0, in.slot_i, 0);
+ let c10 = textureLoad(stroke_atlas, vec2<i32>(i1.x, i0.y), in.slot_i, 0);
+ let c01 = textureLoad(stroke_atlas, vec2<i32>(i0.x, i1.y), in.slot_i, 0);
+ let c11 = textureLoad(stroke_atlas, i1, in.slot_i, 0);
+
+ let a00 = clamp(c00.a, 0.0, 1.0);
+ let a10 = clamp(c10.a, 0.0, 1.0);
+ let a01 = clamp(c01.a, 0.0, 1.0);
+ let a11 = clamp(c11.a, 0.0, 1.0);
+
+ let p00 = vec4<f32>(clamp(c00.rgb, vec3<f32>(0.0), vec3<f32>(1.0)) * a00, a00);
+ let p10 = vec4<f32>(clamp(c10.rgb, vec3<f32>(0.0), vec3<f32>(1.0)) * a10, a10);
+ let p01 = vec4<f32>(clamp(c01.rgb, vec3<f32>(0.0), vec3<f32>(1.0)) * a01, a01);
+ let p11 = vec4<f32>(clamp(c11.rgb, vec3<f32>(0.0), vec3<f32>(1.0)) * a11, a11);
+
+ let top = mix(p00, p10, f.x);
+ let bot = mix(p01, p11, f.x);
+ return mix(top, bot, f.y);
}
+ let sample_uv = clamp(in.uv, vec2<f32>(0.5 / 256.0), vec2<f32>(255.5 / 256.0));
+ let px = textureSampleLevel(stroke_atlas, stroke_sampler, sample_uv, in.slot_i, 0.0);
if (px.a <= 0.0005) {
discard;
}
@@ -295,7 +415,10 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {{
let alpha_locked = u.flags0.y != 0u;
let is_bg_eraser = u.tone_flags.w != 0u;
- if (combine_mode == 32u) {{
+ if (combine_mode == 33u) {{
+ // Live Layer Mask editing mode: keep layer RGB artwork intact and modulate mask alpha below!
+ merged_premul = base_premul;
+ }} else if (combine_mode == 32u) {{
// Phase 5 Direct Layer Replacement mode (Natural Paint & Color Mixing):
// `stroke_tex` already holds Base + Mixed Stroke in premultiplied Rgba16Float!
merged_premul = stroke_raw;
@@ -407,9 +530,17 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {{
var mask_a = 1.0;
if (u.flags0.z != 0u) {{
- let mask_uv = clamp(in.doc_coord / max(vec2<f32>(1.0), u.doc_size), vec2<f32>(0.0), vec2<f32>(1.0));
+ let mask_uv = clamp(in.pos.xy / max(vec2<f32>(1.0), u.viewport_size_phys), vec2<f32>(0.0), vec2<f32>(1.0));
mask_a = textureSampleLevel(doc_mask_tex, linear_sampler, mask_uv, 0.0).r;
}}
+ if (combine_mode == 33u && stroke_a > 0.0005) {{
+ let stroke_lum = select(
+ 0.0,
+ clamp(stroke_raw.r / max(1e-5, stroke_raw.a), 0.0, 1.0),
+ stroke_raw.a > 0.0005,
+ );
+ mask_a = mix(mask_a, stroke_lum, stroke_a);
+ }}
if (u.tone_flags.x != 0u) {{
final_color.a *= mask_a * u.layer_opacity;
diff --git a/crates/ink-engine/src/compositor/shaders/mod.rs b/crates/ink-engine/src/compositor/shaders/mod.rs
index 2d6e11d..1a3c368 100644
--- a/crates/ink-engine/src/compositor/shaders/mod.rs
+++ b/crates/ink-engine/src/compositor/shaders/mod.rs
@@ -11,15 +11,21 @@ pub mod live_dab;
pub mod screentone;
pub mod viewport_present;
-pub use adjustment::ADJUSTMENT_SHADER_WGSL;
-pub use blend_modes::{blend_mode_needs_backdrop, blend_mode_to_code, BLEND_MODES_WGSL};
+pub use adjustment::build_adjustment_shader_wgsl;
+pub use blend_modes::{
+ blend_mode_needs_backdrop, blend_mode_to_code, clip_color_cpu, BLEND_MODES_WGSL,
+};
pub use blit::build_blit_shader_wgsl;
pub use frame_poly::FRAME_POLY_SHADER_WGSL;
pub use impasto_lighting::{IMPASTO_HEIGHT_PROJECT_WGSL, IMPASTO_LIGHTING_WGSL};
-pub use layer_styles::{LAYER_STYLES_COMPOSITE_WGSL, SEPARABLE_ALPHA_BLUR_WGSL};
+pub use layer_styles::{
+ LAYER_STYLES_COMPOSITE_WGSL, SEPARABLE_ALPHA_BLUR_WGSL, STROKE_SDF_HORIZ_WGSL,
+ STROKE_SDF_VERT_WGSL,
+};
pub use layer_tile::build_layer_tile_shader_wgsl;
pub use live_dab::{
- build_live_stroke_merge_wgsl, LIVE_DAB_VIEWPORT_WGSL, SPARSE_STROKE_PROJECT_WGSL,
+ build_live_stroke_merge_wgsl, LIVE_DAB_VIEWPORT_WGSL, SPARSE_MASK_PROJECT_WGSL,
+ SPARSE_STROKE_PROJECT_WGSL,
};
pub use screentone::SCREENTONE_WGSL;
pub use viewport_present::VIEWPORT_PRESENT_WGSL;
diff --git a/crates/ink-engine/src/compositor/shaders/viewport_present.rs b/crates/ink-engine/src/compositor/shaders/viewport_present.rs
index a1338e5..352b2a6 100644
--- a/crates/ink-engine/src/compositor/shaders/viewport_present.rs
+++ b/crates/ink-engine/src/compositor/shaders/viewport_present.rs
@@ -290,4 +290,79 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
return vec4<f32>(out_rgb, 1.0);
}
+
+fn bayer_4x4(px: vec2<i32>) -> f32 {
+ let x = u32(px.x) & 3u;
+ let y = u32(px.y) & 3u;
+ let idx = (y << 2u) | x;
+ switch idx {
+ case 0u: { return 0.0 / 16.0; }
+ case 1u: { return 8.0 / 16.0; }
+ case 2u: { return 2.0 / 16.0; }
+ case 3u: { return 10.0 / 16.0; }
+ case 4u: { return 12.0 / 16.0; }
+ case 5u: { return 4.0 / 16.0; }
+ case 6u: { return 14.0 / 16.0; }
+ case 7u: { return 6.0 / 16.0; }
+ case 8u: { return 3.0 / 16.0; }
+ case 9u: { return 11.0 / 16.0; }
+ case 10u: { return 1.0 / 16.0; }
+ case 11u: { return 9.0 / 16.0; }
+ case 12u: { return 15.0 / 16.0; }
+ case 13u: { return 7.0 / 16.0; }
+ case 14u: { return 13.0 / 16.0; }
+ default: { return 5.0 / 16.0; }
+ }
+}
+
+/// GPU Rgba16Float -> straight RGBA8 export/readback fragment entry point.
+/// Performs unpremultiplication, display color passes, and 4x4 ordered Bayer dithering
+/// directly on the GPU so readback transfers 4 B/px (`Rgba8Unorm`) instead of 8 B/px!
+@fragment
+fn fs_export_rgba8(in: VsOut) -> @location(0) vec4<f32> {
+ let px_coord = clamp(
+ vec2<i32>(in.pos.xy),
+ vec2<i32>(0),
+ max(vec2<i32>(0), vec2<i32>(u.viewport_size_phys) - vec2<i32>(1)),
+ );
+ let scene_premul = textureLoad(scene_tex, px_coord, 0);
+ let dither = (bayer_4x4(px_coord) - 0.5) * (0.5 / 255.0);
+
+ // Transparent straight-alpha export (PNG with transparency, brush previews, layer thumbnails)
+ if (u.flags1.w != 0u) {
+ let a = clamp(scene_premul.a, 0.0, 1.0);
+ if (a <= 0.0001) {
+ return vec4<f32>(0.0, 0.0, 0.0, 0.0);
+ }
+ let rgb = clamp(scene_premul.rgb / a, vec3<f32>(0.0), vec3<f32>(1.0));
+ let out_rgb = apply_display_color_passes(rgb);
+ return vec4<f32>(
+ clamp(out_rgb + vec3<f32>(dither), vec3<f32>(0.0), vec3<f32>(1.0)),
+ a,
+ );
+ }
+
+ // Opaque artboard background (white paper or 16px checkerboard)
+ let doc_coord = phys_to_doc(in.pos.xy);
+ var bg_rgb: vec3<f32>;
+ if (u.flags0.x != 0u) {
+ let check_coord = floor(doc_coord / 16.0);
+ let check = abs((check_coord.x + check_coord.y) - 2.0 * floor((check_coord.x + check_coord.y) * 0.5));
+ if (check > 0.5) {
+ bg_rgb = vec3<f32>(0.157, 0.157, 0.157);
+ } else {
+ bg_rgb = vec3<f32>(0.125, 0.125, 0.125);
+ }
+ } else {
+ bg_rgb = vec3<f32>(1.0, 1.0, 1.0);
+ }
+
+ let art_a = clamp(scene_premul.a, 0.0, 1.0);
+ let art_rgb = clamp(scene_premul.rgb + bg_rgb * (1.0 - art_a), vec3<f32>(0.0), vec3<f32>(1.0));
+ let out_rgb = apply_display_color_passes(art_rgb);
+ return vec4<f32>(
+ clamp(out_rgb + vec3<f32>(dither), vec3<f32>(0.0), vec3<f32>(1.0)),
+ 1.0,
+ );
+}
"#;
diff --git a/crates/ink-engine/src/compositor/stack_cache.rs b/crates/ink-engine/src/compositor/stack_cache.rs
index bb95555..f5087b2 100644
--- a/crates/ink-engine/src/compositor/stack_cache.rs
+++ b/crates/ink-engine/src/compositor/stack_cache.rs
@@ -99,6 +99,52 @@ impl ScissorRect {
height: y1.saturating_sub(y0),
}
}
+
+ /// Expands vertically by `pad_y` physical pixels (clamped to `[0..viewport_h]`).
+ /// Used by horizontal separable blur/SDF passes so the subsequent vertical pass
+ /// never reads stale pixels outside the dirty scissor rect.
+ #[inline]
+ pub fn expand_y(self, pad_y: i32, viewport_w: u32, viewport_h: u32) -> Self {
+ if self.is_empty() {
+ return self;
+ }
+ let pad = pad_y.max(0) as u32;
+ let y0 = self.y.saturating_sub(pad);
+ let y1 = self.y.saturating_add(self.height).saturating_add(pad).min(viewport_h);
+ let x0 = self.x.min(viewport_w);
+ let x1 = self.x.saturating_add(self.width).min(viewport_w);
+ Self {
+ x: x0,
+ y: y0,
+ width: x1.saturating_sub(x0),
+ height: y1.saturating_sub(y0),
+ }
+ }
+
+ #[inline]
+ pub fn expand(self, pad: u32, viewport_w: u32, viewport_h: u32) -> Self {
+ if self.is_empty() {
+ return self;
+ }
+ let x0 = self.x.saturating_sub(pad).min(viewport_w);
+ let y0 = self.y.saturating_sub(pad).min(viewport_h);
+ let x1 = self
+ .x
+ .saturating_add(self.width)
+ .saturating_add(pad)
+ .min(viewport_w);
+ let y1 = self
+ .y
+ .saturating_add(self.height)
+ .saturating_add(pad)
+ .min(viewport_h);
+ Self {
+ x: x0,
+ y: y0,
+ width: x1.saturating_sub(x0),
+ height: y1.saturating_sub(y0),
+ }
+ }
}
/// Selects mipmap LOD (`0..=3`) automatically from effective zoom.
@@ -378,6 +424,7 @@ pub(crate) fn hash_layer_node(
if has_mask {
layer.grid.mask_default_value.hash(h);
layer.grid.mask_tiles.len().hash(h);
+ layer.grid.mask_version.hash(h);
m.mask_version.unwrap_or(0).hash(h);
}
@@ -473,12 +520,36 @@ fn hash_onion_skins(
for f in onion_frames {
if let Some(target) = layers.iter().find(|l| l.meta.id == f.layer_id) {
if target.meta.visible {
+ let m = &target.meta;
f.layer_id.hash(h);
h.write_f32(f.tint[0]);
h.write_f32(f.tint[1]);
h.write_f32(f.tint[2]);
h.write_f32(f.opacity);
target.grid.layer_version.hash(h);
+ // Mask properties
+ let has_mask = layer_has_active_mask(target);
+ h.write_bool(has_mask);
+ if has_mask {
+ target.grid.mask_version.hash(h);
+ target.grid.mask_default_value.hash(h);
+ target.grid.mask_tiles.len().hash(h);
+ }
+ // Expression color & screentone properties
+ m.expression_color.map(|e| e as u8).unwrap_or(0).hash(h);
+ m.mono_threshold.unwrap_or(128).hash(h);
+ h.write_bool(m.mono_express_black.unwrap_or(true));
+ h.write_bool(m.mono_express_white.unwrap_or(true));
+ let tone = m.tone_enabled.unwrap_or(false);
+ h.write_bool(tone);
+ if tone {
+ h.write_f32(m.tone_frequency.unwrap_or(60.0));
+ h.write_f32(m.tone_angle.unwrap_or(45.0));
+ h.write_f32(m.tone_density.unwrap_or(40.0));
+ m.tone_dot_shape.map(|s| s as u8).unwrap_or(0).hash(h);
+ m.tone_density_type.map(|d| d as u8).unwrap_or(0).hash(h);
+ h.write_bool(m.is_tone_layer.unwrap_or(false));
+ }
}
}
}
@@ -494,12 +565,15 @@ pub struct StackCacheEvaluation {
pub above_dirty: bool,
}
-/// Telemetry counters for 3-slice cache hits vs rebuilds.
+/// Telemetry counters for 3-slice cache hits vs rebuilds and hover/ants fast-path skips.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct StackCacheStats {
pub below_rebuilds: u64,
pub above_rebuilds: u64,
pub cache_hits: u64,
+ pub final_scene_hits: u64,
+ pub final_scene_rebuilds: u64,
+ pub live_stroke_zero_skips: u64,
}
/// Pure invalidation tracker for the 3-slice GPU cache (`below_active_cache` + `above_active_cache`).
diff --git a/crates/ink-engine/src/compositor/targets.rs b/crates/ink-engine/src/compositor/targets.rs
index 21d7ca9..603d9b1 100644
--- a/crates/ink-engine/src/compositor/targets.rs
+++ b/crates/ink-engine/src/compositor/targets.rs
@@ -3,8 +3,6 @@
use super::stack_cache::ScissorRect;
use crate::document::LayerNode;
-use crate::memory::ScratchBackend;
-use crate::tiles::TILE_SIZE;
use std::collections::{HashMap, HashSet};
/// Single `Rgba16Float` offscreen GPU render target.
@@ -109,6 +107,62 @@ impl SurfaceRgba16F {
}
}
+/// Single `Rgba8Unorm` offscreen GPU render target for 4 B/px export/thumbnail readback.
+pub struct SurfaceRgba8 {
+ pub texture: wgpu::Texture,
+ pub view: wgpu::TextureView,
+ pub width: u32,
+ pub height: u32,
+}
+
+impl SurfaceRgba8 {
+ pub fn new(device: &wgpu::Device, label: &str, width: u32, height: u32) -> Self {
+ let w = width.max(1);
+ let h = height.max(1);
+ let texture = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some(label),
+ size: wgpu::Extent3d {
+ width: w,
+ height: h,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT
+ | wgpu::TextureUsages::TEXTURE_BINDING
+ | wgpu::TextureUsages::COPY_SRC
+ | wgpu::TextureUsages::COPY_DST,
+ view_formats: &[],
+ });
+ let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
+ Self {
+ texture,
+ view,
+ width: w,
+ height: h,
+ }
+ }
+
+ /// Resizes the texture only when dimensions actually differ. Returns `true` if recreated.
+ pub fn ensure_size(
+ &mut self,
+ device: &wgpu::Device,
+ label: &str,
+ width: u32,
+ height: u32,
+ ) -> bool {
+ let w = width.max(1);
+ let h = height.max(1);
+ if self.width == w && self.height == h {
+ return false;
+ }
+ *self = Self::new(device, label, w, h);
+ true
+ }
+}
+
/// Single `R16Float` offscreen GPU render target for live impasto 3D heightfield projection.
pub struct SurfaceR16F {
pub texture: wgpu::Texture,
@@ -164,26 +218,60 @@ impl SurfaceR16F {
}
}
-/// Compact document-level `R8Unorm` mask texture cache (max 1024px along longest edge).
+/// Viewport-resolution GPU-projected `R8Unorm` mask texture cache (zero CPU pixel loops,
+/// razor-sharp at 4K–8K!).
///
-/// Used when sampling a layer's non-destructive 8-bit mask in fullscreen passes:
+/// Keyed strictly on `grid.mask_version` (NEVER `grid.layer_version`) so raster strokes on a
+/// masked layer trigger ZERO mask rebuilds. Used by:
/// - Masked folders & frame-folders (`blit.rs`)
/// - Masked adjustment layers (`adjustment.rs`)
/// - Masked active layer during live stroke merge (`live_dab.rs`)
/// - Masked raster layers at zoomed-out LOD 1..3 (`layer_tile.rs`)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-struct DocMaskSig {
- doc_w: u32,
- doc_h: u32,
- mask_version: u64,
- layer_version: u64,
- mask_default: u8,
- mask_tile_count: usize,
+pub struct DocMaskSig {
+ pub doc_w: u32,
+ pub doc_h: u32,
+ pub vp_w: u32,
+ pub vp_h: u32,
+ pub camera_sig: u64,
+ pub mask_version: u64,
+ pub mask_default: u8,
+ pub mask_tile_count: usize,
+ pub force_nearest: bool,
+}
+
+impl DocMaskSig {
+ #[inline]
+ #[allow(clippy::too_many_arguments)]
+ pub fn for_layer(
+ layer: &LayerNode,
+ doc_w: u32,
+ doc_h: u32,
+ vp_w: u32,
+ vp_h: u32,
+ camera_sig: u64,
+ force_nearest: bool,
+ ) -> Self {
+ Self {
+ doc_w,
+ doc_h,
+ vp_w: vp_w.max(1),
+ vp_h: vp_h.max(1),
+ camera_sig,
+ mask_version: layer.grid.mask_version,
+ mask_default: layer.grid.mask_default_value,
+ mask_tile_count: layer.grid.mask_tiles.len(),
+ force_nearest,
+ }
+ }
}
+static NEXT_VIEW_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
+
struct CachedDocMask {
- texture: wgpu::Texture,
+ _texture: wgpu::Texture,
view: wgpu::TextureView,
+ view_id: u64,
width: u32,
height: u32,
sig: DocMaskSig,
@@ -192,6 +280,7 @@ struct CachedDocMask {
#[derive(Default)]
pub struct DocMaskCache {
entries: HashMap<String, CachedDocMask>,
+ pub rebuilds: u64,
}
impl DocMaskCache {
@@ -199,143 +288,74 @@ impl DocMaskCache {
Self::default()
}
- pub fn get_or_update(
+ #[inline]
+ pub fn needs_update(&self, layer_id: &str, sig: DocMaskSig) -> bool {
+ self.entries
+ .get(layer_id)
+ .map(|e| e.sig != sig || e.width != sig.vp_w || e.height != sig.vp_h)
+ .unwrap_or(true)
+ }
+
+ /// Allocates or resizes the viewport-resolution `R8Unorm` render target for `layer_id`,
+ /// records `sig`, increments `self.rebuilds`, and returns its `TextureView` ready for
+ /// GPU sparse-tile projection.
+ pub fn prepare_render_target(
&mut self,
device: &wgpu::Device,
- queue: &wgpu::Queue,
- layer: &LayerNode,
- doc_w: u32,
- doc_h: u32,
- scratch: Option<&dyn ScratchBackend>,
+ layer_id: &str,
+ sig: DocMaskSig,
) -> &wgpu::TextureView {
- let sig = DocMaskSig {
- doc_w,
- doc_h,
- mask_version: layer.meta.mask_version.unwrap_or(0),
- layer_version: layer.grid.layer_version,
- mask_default: layer.grid.mask_default_value,
- mask_tile_count: layer.grid.mask_tiles.len(),
- };
-
- let needs_update = self
+ let tex_w = sig.vp_w.max(1);
+ let tex_h = sig.vp_h.max(1);
+ let recreate = self
.entries
- .get(&layer.meta.id)
- .map(|e| e.sig != sig)
+ .get(layer_id)
+ .map(|e| e.width != tex_w || e.height != tex_h)
.unwrap_or(true);
- if needs_update {
- let max_dim = 1024u32;
- let dw = doc_w.max(1);
- let dh = doc_h.max(1);
- let (tex_w, tex_h) = if dw <= max_dim && dh <= max_dim {
- (dw, dh)
- } else if dw >= dh {
- let h = ((dh as f64 * max_dim as f64) / dw as f64).round().max(1.0) as u32;
- (max_dim, h)
- } else {
- let w = ((dw as f64 * max_dim as f64) / dh as f64).round().max(1.0) as u32;
- (w, max_dim)
- };
-
- let bytes_per_row = tex_w.div_ceil(256) * 256;
- let mut buf = vec![layer.grid.mask_default_value; (bytes_per_row * tex_h) as usize];
-
- if !layer.grid.mask_tiles.is_empty() {
- // Sample sparse 8-bit mask tiles into the compact doc-level texture
- let scale_x = dw as f64 / tex_w as f64;
- let scale_y = dh as f64 / tex_h as f64;
-
- // Materialize resident/compressed mask tiles once
- let mut materialized: HashMap<(i32, i32), Vec<u8>> =
- HashMap::with_capacity(layer.grid.mask_tiles.len());
- for (&coord, tile) in &layer.grid.mask_tiles {
- if let Ok(raw) = tile.materialize_raw(scratch) {
- materialized.insert((coord.tx, coord.ty), raw);
- }
- }
-
- for y in 0..tex_h {
- let doc_y = ((y as f64 + 0.5) * scale_y).floor().clamp(0.0, (dh - 1) as f64) as i32;
- let ty = doc_y.div_euclid(TILE_SIZE as i32);
- let ly = doc_y.rem_euclid(TILE_SIZE as i32) as usize;
- let row_off = (y * bytes_per_row) as usize;
-
- for x in 0..tex_w {
- let doc_x =
- ((x as f64 + 0.5) * scale_x).floor().clamp(0.0, (dw - 1) as f64) as i32;
- let tx = doc_x.div_euclid(TILE_SIZE as i32);
- let lx = doc_x.rem_euclid(TILE_SIZE as i32) as usize;
- if let Some(tile_bytes) = materialized.get(&(tx, ty)) {
- buf[row_off + x as usize] = tile_bytes[ly * TILE_SIZE + lx];
- }
- }
- }
- }
-
- let recreate = self
- .entries
- .get(&layer.meta.id)
- .map(|e| e.width != tex_w || e.height != tex_h)
- .unwrap_or(true);
-
- if recreate {
- let texture = device.create_texture(&wgpu::TextureDescriptor {
- label: Some("ink-doc-mask-r8"),
- size: wgpu::Extent3d {
- width: tex_w,
- height: tex_h,
- depth_or_array_layers: 1,
- },
- mip_level_count: 1,
- sample_count: 1,
- dimension: wgpu::TextureDimension::D2,
- format: wgpu::TextureFormat::R8Unorm,
- usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
- view_formats: &[],
- });
- let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
- self.entries.insert(
- layer.meta.id.clone(),
- CachedDocMask {
- texture,
- view,
- width: tex_w,
- height: tex_h,
- sig,
- },
- );
- }
-
- let entry = self.entries.get_mut(&layer.meta.id).expect("mask inserted");
- queue.write_texture(
- wgpu::TexelCopyTextureInfo {
- texture: &entry.texture,
- mip_level: 0,
- origin: wgpu::Origin3d::ZERO,
- aspect: wgpu::TextureAspect::All,
- },
- &buf,
- wgpu::TexelCopyBufferLayout {
- offset: 0,
- bytes_per_row: Some(bytes_per_row),
- rows_per_image: Some(tex_h),
- },
- wgpu::Extent3d {
+ if recreate {
+ let texture = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("ink-vp-doc-mask-r8"),
+ size: wgpu::Extent3d {
width: tex_w,
height: tex_h,
depth_or_array_layers: 1,
},
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::R8Unorm,
+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT
+ | wgpu::TextureUsages::TEXTURE_BINDING,
+ view_formats: &[],
+ });
+ let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
+ self.entries.insert(
+ layer_id.to_string(),
+ CachedDocMask {
+ _texture: texture,
+ view,
+ view_id: NEXT_VIEW_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
+ width: tex_w,
+ height: tex_h,
+ sig,
+ },
);
+ } else if let Some(entry) = self.entries.get_mut(layer_id) {
entry.sig = sig;
}
-
- &self.entries.get(&layer.meta.id).expect("mask cached").view
+ self.rebuilds = self.rebuilds.saturating_add(1);
+ &self.entries.get(layer_id).expect("mask target prepared").view
}
pub fn get_cached_view(&self, layer_id: &str) -> Option<&wgpu::TextureView> {
self.entries.get(layer_id).map(|e| &e.view)
}
+ pub fn get_cached_view_with_id(&self, layer_id: &str) -> Option<(&wgpu::TextureView, u64)> {
+ self.entries.get(layer_id).map(|e| (&e.view, e.view_id))
+ }
+
pub fn retain_layers(&mut self, valid_ids: &HashSet<&str>) {
self.entries.retain(|k, _| valid_ids.contains(k.as_str()));
}
@@ -348,6 +368,7 @@ impl DocMaskCache {
/// Per-layer cached GPU styled output (`stroke`, `dropShadow`, `outerGlow`) with LRU eviction.
pub struct StyledLayerEntry {
pub surface: SurfaceRgba16F,
+ pub view_id: u64,
pub sig: u64,
pub last_used_frame: u64,
}
@@ -382,12 +403,18 @@ impl StyledLayerCache {
}
/// Checks whether a cached styled texture exists with exact matching signature and dimensions.
- pub fn get_hit(&mut self, layer_id: &str, sig: u64, w: u32, h: u32) -> Option<&SurfaceRgba16F> {
+ pub fn get_hit(
+ &mut self,
+ layer_id: &str,
+ sig: u64,
+ w: u32,
+ h: u32,
+ ) -> Option<(&SurfaceRgba16F, u64)> {
let entry = self.entries.get_mut(layer_id)?;
if entry.sig == sig && entry.surface.width == w && entry.surface.height == h {
entry.last_used_frame = self.frame;
self.hits = self.hits.saturating_add(1);
- Some(&entry.surface)
+ Some((&entry.surface, entry.view_id))
} else {
None
}
@@ -401,7 +428,7 @@ impl StyledLayerCache {
sig: u64,
w: u32,
h: u32,
- ) -> &SurfaceRgba16F {
+ ) -> (&SurfaceRgba16F, u64) {
if !self.entries.contains_key(layer_id) && self.entries.len() >= self.max_entries {
if let Some(lru_key) = self
.entries
@@ -420,15 +447,19 @@ impl StyledLayerCache {
.entry(layer_id.to_string())
.or_insert_with(|| StyledLayerEntry {
surface: SurfaceRgba16F::new(device, "ink-styled-layer-cache", w, h),
+ view_id: NEXT_VIEW_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
sig,
last_used_frame: frame,
});
- entry
+ if entry
.surface
- .ensure_size(device, "ink-styled-layer-cache", w, h);
+ .ensure_size(device, "ink-styled-layer-cache", w, h)
+ {
+ entry.view_id = NEXT_VIEW_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ }
entry.sig = sig;
entry.last_used_frame = frame;
- &entry.surface
+ (&entry.surface, entry.view_id)
}
pub fn clear(&mut self) {
@@ -440,34 +471,57 @@ impl StyledLayerCache {
}
}
+/// Step granularity (in physical pixels) used to cushion drag-resize viewport target allocations
+/// so dragging a window edge does not destroy/recreate full-viewport textures on every pixel.
+const RESIZE_SLACK_STEP: u32 = 128;
+
+#[inline]
+fn round_up_slack(dim: u32, max_dim: u32) -> u32 {
+ let clamped = dim.max(1).min(max_dim);
+ let rounded = clamped.div_ceil(RESIZE_SLACK_STEP) * RESIZE_SLACK_STEP;
+ rounded.min(max_dim)
+}
+
/// Complete pool of viewport-sized `Rgba16Float` targets and 1×1 fallback dummy textures.
+///
+/// Only `final_scene` and the 1×1 dummy textures are allocated eagerly; all optional scratch,
+/// 3-slice cache, live-stroke, folder/clip/frame stack, layer-style, and impasto surfaces are
+/// allocated strictly on first use so a 1-layer blank canvas uses minimal VRAM.
pub struct CompositorTargets {
+ /// Logical viewport dimensions (in physical pixels).
pub width: u32,
pub height: u32,
+ /// Backing GPU texture dimensions (`>= width, height` when `use_slack` is true).
+ pub alloc_width: u32,
+ pub alloc_height: u32,
+ use_slack: bool,
- // Final composited scene (read by viewport_present) & reusable backdrop copy
+ // Final composited scene (read by viewport_present) & lazily-allocated reusable backdrop copy
pub final_scene: SurfaceRgba16F,
- pub backdrop_scratch: SurfaceRgba16F,
+ pub backdrop_scratch: Option<SurfaceRgba16F>,
- // 3-Slice Baked Layer Stack Cache targets
- pub below_active_cache: SurfaceRgba16F,
- pub above_active_cache: SurfaceRgba16F,
- pub active_unit_surface: SurfaceRgba16F,
+ // Lazily-allocated 3-Slice Baked Layer Stack Cache targets
+ pub below_active_cache: Option<SurfaceRgba16F>,
+ pub above_active_cache: Option<SurfaceRgba16F>,
+ pub active_unit_surface: Option<SurfaceRgba16F>,
- // Live WYSIWYG Stroke targets
- pub active_layer_base_surface: SurfaceRgba16F,
- pub live_stroke_surface: SurfaceRgba16F,
+ // Lazily-allocated Live WYSIWYG Stroke targets
+ pub active_layer_base_surface: Option<SurfaceRgba16F>,
+ pub live_stroke_surface: Option<SurfaceRgba16F>,
- // Nested stack targets (grown on demand by folder/clipping nesting depth)
+ // Nested stack targets (start empty, grown on demand by folder/clipping/frame nesting depth)
pub folder_stack: Vec<SurfaceRgba16F>,
pub clip_mask_stack: Vec<SurfaceRgba16F>,
pub frame_mask_stack: Vec<SurfaceRgba16F>,
- // Reusable Layer Styles intermediate passes
- pub style_src: SurfaceRgba16F,
- pub style_blur_tmp: SurfaceRgba16F,
- pub style_shadow_blur: SurfaceRgba16F,
- pub style_glow_blur: SurfaceRgba16F,
+ // Lazily-allocated Layer Styles intermediate passes
+ pub style_src: Option<SurfaceRgba16F>,
+ pub style_blur_tmp: Option<SurfaceRgba16F>,
+ pub style_shadow_blur: Option<SurfaceRgba16F>,
+ pub style_glow_blur: Option<SurfaceRgba16F>,
+ pub style_stroke_dilate_tmp: Option<SurfaceRgba16F>,
+ pub style_stroke_dilate: Option<SurfaceRgba16F>,
+ pub style_composite_out: Option<SurfaceRgba16F>,
// Lazily-allocated Impasto Relief Lighting passes (0 VRAM cost on non-impasto documents!)
pub impasto_height: Option<SurfaceR16F>,
@@ -486,9 +540,31 @@ pub struct CompositorTargets {
}
impl CompositorTargets {
+ /// Creates a viewport target pool with 128 px resize slack to prevent drag-resize reallocation storms.
pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, width: u32, height: u32) -> Self {
- let w = width.max(1);
- let h = height.max(1);
+ Self::new_with_slack(device, queue, width, height, true)
+ }
+
+ /// Creates an exact-sized target pool (used for temporary export/thumbnail chunks).
+ pub fn new_exact(device: &wgpu::Device, queue: &wgpu::Queue, width: u32, height: u32) -> Self {
+ Self::new_with_slack(device, queue, width, height, false)
+ }
+
+ fn new_with_slack(
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ width: u32,
+ height: u32,
+ use_slack: bool,
+ ) -> Self {
+ let max_dim = device.limits().max_texture_dimension_2d.min(16384).max(1);
+ let w = width.clamp(1, max_dim);
+ let h = height.clamp(1, max_dim);
+ let (alloc_w, alloc_h) = if use_slack {
+ (round_up_slack(w, max_dim), round_up_slack(h, max_dim))
+ } else {
+ (w, h)
+ };
let (dummy_transparent_rgba16f, dummy_transparent_rgba16f_view) =
create_1x1_rgba16f(device, queue, "ink-dummy-transparent-16f", [0.0, 0.0, 0.0, 0.0]);
@@ -502,20 +578,26 @@ impl CompositorTargets {
Self {
width: w,
height: h,
- final_scene: SurfaceRgba16F::new(device, "ink-comp-final-scene", w, h),
- backdrop_scratch: SurfaceRgba16F::new(device, "ink-comp-backdrop-scratch", w, h),
- below_active_cache: SurfaceRgba16F::new(device, "ink-comp-below-cache", w, h),
- above_active_cache: SurfaceRgba16F::new(device, "ink-comp-above-cache", w, h),
- active_unit_surface: SurfaceRgba16F::new(device, "ink-comp-active-unit", w, h),
- active_layer_base_surface: SurfaceRgba16F::new(device, "ink-comp-active-base", w, h),
- live_stroke_surface: SurfaceRgba16F::new(device, "ink-comp-live-stroke", w, h),
- folder_stack: vec![SurfaceRgba16F::new(device, "ink-comp-folder-0", w, h)],
- clip_mask_stack: vec![SurfaceRgba16F::new(device, "ink-comp-clip-0", w, h)],
- frame_mask_stack: vec![SurfaceRgba16F::new(device, "ink-comp-frame-0", w, h)],
- style_src: SurfaceRgba16F::new(device, "ink-comp-style-src", w, h),
- style_blur_tmp: SurfaceRgba16F::new(device, "ink-comp-style-blur-tmp", w, h),
- style_shadow_blur: SurfaceRgba16F::new(device, "ink-comp-style-shadow-blur", w, h),
- style_glow_blur: SurfaceRgba16F::new(device, "ink-comp-style-glow-blur", w, h),
+ alloc_width: alloc_w,
+ alloc_height: alloc_h,
+ use_slack,
+ final_scene: SurfaceRgba16F::new(device, "ink-comp-final-scene", alloc_w, alloc_h),
+ backdrop_scratch: None,
+ below_active_cache: None,
+ above_active_cache: None,
+ active_unit_surface: None,
+ active_layer_base_surface: None,
+ live_stroke_surface: None,
+ folder_stack: Vec::new(),
+ clip_mask_stack: Vec::new(),
+ frame_mask_stack: Vec::new(),
+ style_src: None,
+ style_blur_tmp: None,
+ style_shadow_blur: None,
+ style_glow_blur: None,
+ style_stroke_dilate_tmp: None,
+ style_stroke_dilate: None,
+ style_composite_out: None,
impasto_height: None,
impasto_color_scratch: None,
impasto_lit_scratch: None,
@@ -530,60 +612,214 @@ impl CompositorTargets {
}
}
- /// Resizes all viewport-sized compositor targets. Returns `true` if resized.
+ /// Updates logical viewport size and grows backing GPU textures with 128 px slack when needed.
+ /// Returns `(logical_changed, textures_reallocated)`.
+ pub fn ensure_size_detailed(
+ &mut self,
+ device: &wgpu::Device,
+ width: u32,
+ height: u32,
+ ) -> (bool, bool) {
+ let max_dim = device.limits().max_texture_dimension_2d.min(16384).max(1);
+ let w = width.clamp(1, max_dim);
+ let h = height.clamp(1, max_dim);
+ let logical_changed = self.width != w || self.height != h;
+ self.width = w;
+ self.height = h;
+
+ let (need_realloc, next_aw, next_ah) = if self.use_slack {
+ if w > self.alloc_width || h > self.alloc_height {
+ (
+ true,
+ round_up_slack(w, max_dim).max(self.alloc_width),
+ round_up_slack(h, max_dim).max(self.alloc_height),
+ )
+ } else {
+ (false, self.alloc_width, self.alloc_height)
+ }
+ } else if self.alloc_width != w || self.alloc_height != h {
+ (true, w, h)
+ } else {
+ (false, self.alloc_width, self.alloc_height)
+ };
+
+ if !need_realloc {
+ return (logical_changed, false);
+ }
+
+ self.reallocate_all(device, next_aw, next_ah);
+ (logical_changed, true)
+ }
+
+ /// Resizes viewport targets. Returns `true` if either logical dimensions or backing textures changed.
pub fn ensure_size(&mut self, device: &wgpu::Device, width: u32, height: u32) -> bool {
- let w = width.max(1);
- let h = height.max(1);
- if self.width == w && self.height == h {
+ let (logical_changed, reallocated) = self.ensure_size_detailed(device, width, height);
+ logical_changed || reallocated
+ }
+
+ /// Shrinks oversized slack-allocated textures down to `round_up_slack(width, height)` after idle.
+ /// Returns `true` if backing textures were reallocated.
+ pub fn trim_to_logical_size(&mut self, device: &wgpu::Device) -> bool {
+ if !self.use_slack {
return false;
}
- self.width = w;
- self.height = h;
- self.final_scene.ensure_size(device, "ink-comp-final-scene", w, h);
- self.backdrop_scratch
- .ensure_size(device, "ink-comp-backdrop-scratch", w, h);
- self.below_active_cache
- .ensure_size(device, "ink-comp-below-cache", w, h);
- self.above_active_cache
- .ensure_size(device, "ink-comp-above-cache", w, h);
- self.active_unit_surface
- .ensure_size(device, "ink-comp-active-unit", w, h);
- self.active_layer_base_surface
- .ensure_size(device, "ink-comp-active-base", w, h);
- self.live_stroke_surface
- .ensure_size(device, "ink-comp-live-stroke", w, h);
+ let max_dim = device.limits().max_texture_dimension_2d.min(16384).max(1);
+ let target_w = round_up_slack(self.width, max_dim);
+ let target_h = round_up_slack(self.height, max_dim);
+ if self.alloc_width > target_w + RESIZE_SLACK_STEP
+ || self.alloc_height > target_h + RESIZE_SLACK_STEP
+ {
+ self.reallocate_all(device, target_w, target_h);
+ return true;
+ }
+ false
+ }
+
+ fn reallocate_all(&mut self, device: &wgpu::Device, aw: u32, ah: u32) {
+ self.alloc_width = aw;
+ self.alloc_height = ah;
+ self.final_scene
+ .ensure_size(device, "ink-comp-final-scene", aw, ah);
+ if let Some(ref mut surf) = self.backdrop_scratch {
+ surf.ensure_size(device, "ink-comp-backdrop-scratch", aw, ah);
+ }
+ if let Some(ref mut surf) = self.below_active_cache {
+ surf.ensure_size(device, "ink-comp-below-cache", aw, ah);
+ }
+ if let Some(ref mut surf) = self.above_active_cache {
+ surf.ensure_size(device, "ink-comp-above-cache", aw, ah);
+ }
+ if let Some(ref mut surf) = self.active_unit_surface {
+ surf.ensure_size(device, "ink-comp-active-unit", aw, ah);
+ }
+ if let Some(ref mut surf) = self.active_layer_base_surface {
+ surf.ensure_size(device, "ink-comp-active-base", aw, ah);
+ }
+ if let Some(ref mut surf) = self.live_stroke_surface {
+ surf.ensure_size(device, "ink-comp-live-stroke", aw, ah);
+ }
for (i, surf) in self.folder_stack.iter_mut().enumerate() {
- surf.ensure_size(device, &format!("ink-comp-folder-{i}"), w, h);
+ surf.ensure_size(device, &format!("ink-comp-folder-{i}"), aw, ah);
}
for (i, surf) in self.clip_mask_stack.iter_mut().enumerate() {
- surf.ensure_size(device, &format!("ink-comp-clip-{i}"), w, h);
+ surf.ensure_size(device, &format!("ink-comp-clip-{i}"), aw, ah);
}
for (i, surf) in self.frame_mask_stack.iter_mut().enumerate() {
- surf.ensure_size(device, &format!("ink-comp-frame-{i}"), w, h);
+ surf.ensure_size(device, &format!("ink-comp-frame-{i}"), aw, ah);
+ }
+ if let Some(ref mut surf) = self.style_src {
+ surf.ensure_size(device, "ink-comp-style-src", aw, ah);
+ }
+ if let Some(ref mut surf) = self.style_blur_tmp {
+ surf.ensure_size(device, "ink-comp-style-blur-tmp", aw, ah);
+ }
+ if let Some(ref mut surf) = self.style_shadow_blur {
+ surf.ensure_size(device, "ink-comp-style-shadow-blur", aw, ah);
+ }
+ if let Some(ref mut surf) = self.style_glow_blur {
+ surf.ensure_size(device, "ink-comp-style-glow-blur", aw, ah);
+ }
+ if let Some(ref mut surf) = self.style_stroke_dilate_tmp {
+ surf.ensure_size(device, "ink-comp-style-stroke-dilate-tmp", aw, ah);
+ }
+ if let Some(ref mut surf) = self.style_stroke_dilate {
+ surf.ensure_size(device, "ink-comp-style-stroke-dilate", aw, ah);
+ }
+ if let Some(ref mut surf) = self.style_composite_out {
+ surf.ensure_size(device, "ink-comp-style-composite-out", aw, ah);
}
- self.style_src.ensure_size(device, "ink-comp-style-src", w, h);
- self.style_blur_tmp
- .ensure_size(device, "ink-comp-style-blur-tmp", w, h);
- self.style_shadow_blur
- .ensure_size(device, "ink-comp-style-shadow-blur", w, h);
- self.style_glow_blur
- .ensure_size(device, "ink-comp-style-glow-blur", w, h);
if let Some(ref mut surf) = self.impasto_height {
- surf.ensure_size(device, "ink-comp-impasto-height", w, h);
+ surf.ensure_size(device, "ink-comp-impasto-height", aw, ah);
}
if let Some(ref mut surf) = self.impasto_color_scratch {
- surf.ensure_size(device, "ink-comp-impasto-color-scratch", w, h);
+ surf.ensure_size(device, "ink-comp-impasto-color-scratch", aw, ah);
}
if let Some(ref mut surf) = self.impasto_lit_scratch {
- surf.ensure_size(device, "ink-comp-impasto-lit-scratch", w, h);
+ surf.ensure_size(device, "ink-comp-impasto-lit-scratch", aw, ah);
}
- true
+ }
+
+ pub fn ensure_backdrop_scratch(&mut self, device: &wgpu::Device) -> &SurfaceRgba16F {
+ let (w, h) = (self.alloc_width, self.alloc_height);
+ self.backdrop_scratch
+ .get_or_insert_with(|| SurfaceRgba16F::new(device, "ink-comp-backdrop-scratch", w, h))
+ }
+
+ pub fn ensure_below_cache(&mut self, device: &wgpu::Device) -> &SurfaceRgba16F {
+ let (w, h) = (self.alloc_width, self.alloc_height);
+ self.below_active_cache
+ .get_or_insert_with(|| SurfaceRgba16F::new(device, "ink-comp-below-cache", w, h))
+ }
+
+ pub fn ensure_above_cache(&mut self, device: &wgpu::Device) -> &SurfaceRgba16F {
+ let (w, h) = (self.alloc_width, self.alloc_height);
+ self.above_active_cache
+ .get_or_insert_with(|| SurfaceRgba16F::new(device, "ink-comp-above-cache", w, h))
+ }
+
+ pub fn ensure_active_unit(&mut self, device: &wgpu::Device) -> &SurfaceRgba16F {
+ let (w, h) = (self.alloc_width, self.alloc_height);
+ self.active_unit_surface
+ .get_or_insert_with(|| SurfaceRgba16F::new(device, "ink-comp-active-unit", w, h))
+ }
+
+ pub fn ensure_active_base(&mut self, device: &wgpu::Device) -> &SurfaceRgba16F {
+ let (w, h) = (self.alloc_width, self.alloc_height);
+ self.active_layer_base_surface
+ .get_or_insert_with(|| SurfaceRgba16F::new(device, "ink-comp-active-base", w, h))
+ }
+
+ pub fn ensure_live_stroke(&mut self, device: &wgpu::Device) -> &SurfaceRgba16F {
+ let (w, h) = (self.alloc_width, self.alloc_height);
+ self.live_stroke_surface
+ .get_or_insert_with(|| SurfaceRgba16F::new(device, "ink-comp-live-stroke", w, h))
+ }
+
+ pub fn ensure_style_src(&mut self, device: &wgpu::Device) -> &SurfaceRgba16F {
+ let (w, h) = (self.alloc_width, self.alloc_height);
+ self.style_src
+ .get_or_insert_with(|| SurfaceRgba16F::new(device, "ink-comp-style-src", w, h))
+ }
+
+ pub fn ensure_style_blur_tmp(&mut self, device: &wgpu::Device) -> &SurfaceRgba16F {
+ let (w, h) = (self.alloc_width, self.alloc_height);
+ self.style_blur_tmp
+ .get_or_insert_with(|| SurfaceRgba16F::new(device, "ink-comp-style-blur-tmp", w, h))
+ }
+
+ pub fn ensure_style_shadow_blur(&mut self, device: &wgpu::Device) -> &SurfaceRgba16F {
+ let (w, h) = (self.alloc_width, self.alloc_height);
+ self.style_shadow_blur
+ .get_or_insert_with(|| SurfaceRgba16F::new(device, "ink-comp-style-shadow-blur", w, h))
+ }
+
+ pub fn ensure_style_glow_blur(&mut self, device: &wgpu::Device) -> &SurfaceRgba16F {
+ let (w, h) = (self.alloc_width, self.alloc_height);
+ self.style_glow_blur
+ .get_or_insert_with(|| SurfaceRgba16F::new(device, "ink-comp-style-glow-blur", w, h))
+ }
+
+ pub fn ensure_style_stroke_surfaces(&mut self, device: &wgpu::Device) {
+ let (w, h) = (self.alloc_width, self.alloc_height);
+ self.style_stroke_dilate_tmp.get_or_insert_with(|| {
+ SurfaceRgba16F::new(device, "ink-comp-style-stroke-dilate-tmp", w, h)
+ });
+ self.style_stroke_dilate.get_or_insert_with(|| {
+ SurfaceRgba16F::new(device, "ink-comp-style-stroke-dilate", w, h)
+ });
+ }
+
+ pub fn ensure_style_composite_out(&mut self, device: &wgpu::Device) -> &SurfaceRgba16F {
+ let (w, h) = (self.alloc_width, self.alloc_height);
+ self.style_composite_out.get_or_insert_with(|| {
+ SurfaceRgba16F::new(device, "ink-comp-style-composite-out", w, h)
+ })
}
/// Lazily allocates the viewport `R16Float` heightfield and `Rgba16Float` relief scratch surfaces.
pub fn ensure_impasto_surfaces(&mut self, device: &wgpu::Device) {
- let w = self.width;
- let h = self.height;
+ let w = self.alloc_width;
+ let h = self.alloc_height;
self.impasto_height
.get_or_insert_with(|| SurfaceR16F::new(device, "ink-comp-impasto-height", w, h));
self.impasto_color_scratch.get_or_insert_with(|| {
@@ -600,8 +836,8 @@ impl CompositorTargets {
self.folder_stack.push(SurfaceRgba16F::new(
device,
&format!("ink-comp-folder-{i}"),
- self.width,
- self.height,
+ self.alloc_width,
+ self.alloc_height,
));
}
}
@@ -612,8 +848,8 @@ impl CompositorTargets {
self.clip_mask_stack.push(SurfaceRgba16F::new(
device,
&format!("ink-comp-clip-{i}"),
- self.width,
- self.height,
+ self.alloc_width,
+ self.alloc_height,
));
}
}
@@ -624,11 +860,150 @@ impl CompositorTargets {
self.frame_mask_stack.push(SurfaceRgba16F::new(
device,
&format!("ink-comp-frame-{i}"),
- self.width,
- self.height,
+ self.alloc_width,
+ self.alloc_height,
));
}
}
+
+ /// Trims unused nested folder/clip/frame stack surfaces and optional transient surfaces.
+ /// Returns `true` if any GPU texture was dropped (caller should clear `bg_cache`).
+ pub fn trim_unused_stacks(
+ &mut self,
+ keep_folder: usize,
+ keep_clip: usize,
+ keep_frame: usize,
+ release_live_stroke: bool,
+ release_styles: bool,
+ release_impasto: bool,
+ ) -> bool {
+ let mut dropped = false;
+ if self.folder_stack.len() > keep_folder {
+ self.folder_stack.truncate(keep_folder);
+ self.folder_stack.shrink_to_fit();
+ dropped = true;
+ }
+ if self.clip_mask_stack.len() > keep_clip {
+ self.clip_mask_stack.truncate(keep_clip);
+ self.clip_mask_stack.shrink_to_fit();
+ dropped = true;
+ }
+ if self.frame_mask_stack.len() > keep_frame {
+ self.frame_mask_stack.truncate(keep_frame);
+ self.frame_mask_stack.shrink_to_fit();
+ dropped = true;
+ }
+ if release_live_stroke {
+ if self.active_layer_base_surface.take().is_some() {
+ dropped = true;
+ }
+ if self.live_stroke_surface.take().is_some() {
+ dropped = true;
+ }
+ if self.active_unit_surface.take().is_some() {
+ dropped = true;
+ }
+ }
+ if release_styles {
+ for slot in [
+ &mut self.style_src,
+ &mut self.style_blur_tmp,
+ &mut self.style_shadow_blur,
+ &mut self.style_glow_blur,
+ &mut self.style_stroke_dilate_tmp,
+ &mut self.style_stroke_dilate,
+ &mut self.style_composite_out,
+ ] {
+ if slot.take().is_some() {
+ dropped = true;
+ }
+ }
+ }
+ if release_impasto {
+ if self.impasto_height.take().is_some() {
+ dropped = true;
+ }
+ if self.impasto_color_scratch.take().is_some() {
+ dropped = true;
+ }
+ if self.impasto_lit_scratch.take().is_some() {
+ dropped = true;
+ }
+ }
+ dropped
+ }
+
+ /// Number of currently allocated full-viewport GPU textures (excluding 1×1 dummies).
+ pub fn allocated_surface_count(&self) -> usize {
+ let mut n = 1usize; // final_scene
+ for opt in [
+ &self.backdrop_scratch,
+ &self.below_active_cache,
+ &self.above_active_cache,
+ &self.active_unit_surface,
+ &self.active_layer_base_surface,
+ &self.live_stroke_surface,
+ &self.style_src,
+ &self.style_blur_tmp,
+ &self.style_shadow_blur,
+ &self.style_glow_blur,
+ &self.style_stroke_dilate_tmp,
+ &self.style_stroke_dilate,
+ &self.style_composite_out,
+ &self.impasto_color_scratch,
+ &self.impasto_lit_scratch,
+ ] {
+ if opt.is_some() {
+ n += 1;
+ }
+ }
+ if self.impasto_height.is_some() {
+ n += 1;
+ }
+ n + self.folder_stack.len() + self.clip_mask_stack.len() + self.frame_mask_stack.len()
+ }
+
+ /// Estimated VRAM bytes currently occupied by all allocated viewport surfaces.
+ pub fn allocated_vram_bytes(&self) -> u64 {
+ let mut bytes = (self.final_scene.width as u64) * (self.final_scene.height as u64) * 8;
+ let mut add_rgba16f = |s: &SurfaceRgba16F| {
+ bytes += (s.width as u64) * (s.height as u64) * 8;
+ };
+ for opt in [
+ &self.backdrop_scratch,
+ &self.below_active_cache,
+ &self.above_active_cache,
+ &self.active_unit_surface,
+ &self.active_layer_base_surface,
+ &self.live_stroke_surface,
+ &self.style_src,
+ &self.style_blur_tmp,
+ &self.style_shadow_blur,
+ &self.style_glow_blur,
+ &self.style_stroke_dilate_tmp,
+ &self.style_stroke_dilate,
+ &self.style_composite_out,
+ &self.impasto_color_scratch,
+ &self.impasto_lit_scratch,
+ ] {
+ if let Some(s) = opt {
+ add_rgba16f(s);
+ }
+ }
+ for s in &self.folder_stack {
+ add_rgba16f(s);
+ }
+ for s in &self.clip_mask_stack {
+ add_rgba16f(s);
+ }
+ for s in &self.frame_mask_stack {
+ add_rgba16f(s);
+ }
+ if let Some(ref s) = self.impasto_height {
+ bytes += (s.width as u64) * (s.height as u64) * 2;
+ }
+ bytes
+ }
}
fn create_1x1_rgba16f(
diff --git a/crates/ink-engine/src/compositor_tests.rs b/crates/ink-engine/src/compositor_tests.rs
index 2edc359..ac69d73 100644
--- a/crates/ink-engine/src/compositor_tests.rs
+++ b/crates/ink-engine/src/compositor_tests.rs
@@ -320,14 +320,13 @@ fn test_layer_tree_clipping_chains_folders_and_above_strategies() {
// Stack (top-to-bottom):
// top-normal (Normal)
// mid-mul (Multiply)
- // pt-folder (PassThrough, opacity 0.5)
+ // pt-folder (PassThrough, opacity 1.0 -> true pass-through, flattens children!)
// clip-child (clipped -> active-base)
// active-base (Normal)
// iso-folder (Multiply)
// iso-child
// bg (Normal)
- let mut pt_folder = make_layer("pt-folder", LayerType::Folder, BlendMode::PassThrough, false, None);
- pt_folder.meta.opacity = 0.5;
+ let pt_folder = make_layer("pt-folder", LayerType::Folder, BlendMode::PassThrough, false, None);
let layers = vec![
make_layer("top-normal", LayerType::Raster, BlendMode::Normal, false, None),
make_layer("mid-mul", LayerType::Raster, BlendMode::Multiply, false, None),
@@ -346,7 +345,33 @@ fn test_layer_tree_clipping_chains_folders_and_above_strategies() {
assert_eq!(units.len(), 5);
assert_eq!(layers[units[2].group.base_node.layer_index].meta.id, "active-base");
assert_eq!(units[2].group.clipped_nodes.len(), 1);
- assert!((units[2].inherited_opacity - 0.5).abs() < 1e-5);
+ assert!((units[2].inherited_opacity - 1.0).abs() < 1e-5);
+
+ // Translucent PassThrough folder (opacity < 1.0) MUST isolate as a single unit so overlapping
+ // children do not bleed through each other, and it remains associative for AboveCache!
+ let mut translucent_pt = make_layer(
+ "pt-translucent",
+ LayerType::Folder,
+ BlendMode::PassThrough,
+ false,
+ None,
+ );
+ translucent_pt.meta.opacity = 0.5;
+ let pt_iso_layers = vec![
+ translucent_pt,
+ make_layer("pt-child-a", LayerType::Raster, BlendMode::Normal, false, Some("pt-translucent")),
+ make_layer("pt-child-b", LayerType::Raster, BlendMode::Multiply, false, Some("pt-translucent")),
+ make_layer("below", LayerType::Raster, BlendMode::Normal, false, None),
+ ];
+ let pt_iso_tree = build_layer_tree(&pt_iso_layers);
+ let pt_iso_units = flatten_layer_tree_to_units(&pt_iso_tree, &pt_iso_layers, &overrides, 1.0);
+ assert_eq!(pt_iso_units.len(), 2);
+ assert_eq!(
+ pt_iso_layers[pt_iso_units[1].group.base_node.layer_index].meta.id,
+ "pt-translucent"
+ );
+ let pt_part = partition_layer_stack(&pt_iso_layers, &overrides, Some("below"));
+ assert_eq!(pt_part.above_strategy, AboveSliceStrategy::BakedNormal);
// Partition around active-base -> above has [mid-mul (non-assoc), top-normal (assoc)] => Mixed!
let part = partition_layer_stack(&layers, &overrides, Some("active-base"));
@@ -374,6 +399,18 @@ fn test_layer_tree_clipping_chains_folders_and_above_strategies() {
let part4 = partition_layer_stack(&single_mul, &overrides, Some("base"));
assert_eq!(part4.above_strategy, AboveSliceStrategy::BakedSingleBlend);
assert_eq!(part4.above_cache_blend_mode, BlendMode::Multiply);
+
+ // Multiply folder WITH a clipped sibling must NOT use BakedSingleBlend (clipped child needs separate mask)!
+ let clipped_mul_folder = vec![
+ make_layer("clip-over-folder", LayerType::Raster, BlendMode::Normal, true, None),
+ make_layer("mul-folder", LayerType::Folder, BlendMode::Multiply, false, None),
+ make_layer("mf-child", LayerType::Raster, BlendMode::Normal, false, Some("mul-folder")),
+ make_layer("base", LayerType::Raster, BlendMode::Normal, false, None),
+ ];
+ let part5 = partition_layer_stack(&clipped_mul_folder, &overrides, Some("base"));
+ assert_eq!(part5.above_strategy, AboveSliceStrategy::Mixed);
+ assert_eq!(part5.above_dynamic_units.len(), 1);
+ assert!(part5.above_cached_units.is_empty());
}
#[test]
@@ -552,6 +589,7 @@ fn test_frame_geometry_and_frustum_scissor_math() {
#[test]
fn test_gpu_all_28_blend_modes_pixel_accurate() {
+ let _dx12_guard = crate::lock_dx12_test();
let Some(mut renderer) = try_headless_renderer(64, 64) else {
return;
};
@@ -645,6 +683,7 @@ fn test_gpu_all_28_blend_modes_pixel_accurate() {
#[test]
fn test_gpu_clipping_chain_and_layer_masks() {
+ let _dx12_guard = crate::lock_dx12_test();
let Some(mut renderer) = try_headless_renderer(128, 128) else {
return;
};
@@ -709,6 +748,7 @@ fn test_gpu_clipping_chain_and_layer_masks() {
#[test]
fn test_gpu_passthrough_vs_isolated_folders() {
+ let _dx12_guard = crate::lock_dx12_test();
let Some(mut renderer) = try_headless_renderer(64, 64) else {
return;
};
@@ -763,6 +803,7 @@ fn test_gpu_passthrough_vs_isolated_folders() {
#[test]
fn test_gpu_comic_frame_folder_clipping_fill_and_border() {
+ let _dx12_guard = crate::lock_dx12_test();
let Some(mut renderer) = try_headless_renderer(160, 160) else {
return;
};
@@ -822,6 +863,7 @@ fn test_gpu_comic_frame_folder_clipping_fill_and_border() {
#[test]
fn test_gpu_expression_color_tint_and_screentones() {
+ let _dx12_guard = crate::lock_dx12_test();
let Some(mut renderer) = try_headless_renderer(128, 128) else {
return;
};
@@ -925,6 +967,7 @@ fn test_gpu_expression_color_tint_and_screentones() {
#[test]
fn test_gpu_adjustment_layers_all_4_types() {
+ let _dx12_guard = crate::lock_dx12_test();
let Some(mut renderer) = try_headless_renderer(64, 64) else {
return;
};
@@ -1010,6 +1053,7 @@ fn test_gpu_adjustment_layers_all_4_types() {
#[test]
fn test_gpu_layer_styles_and_lru_cache_hits() {
+ let _dx12_guard = crate::lock_dx12_test();
let Some(mut renderer) = try_headless_renderer(256, 256) else {
return;
};
@@ -1054,6 +1098,7 @@ fn test_gpu_layer_styles_and_lru_cache_hits() {
#[test]
fn test_gpu_3slice_cache_live_stroke_display_passes_and_chunked_flatten() {
+ let _dx12_guard = crate::lock_dx12_test();
let Some(mut renderer) = try_headless_renderer(256, 256) else {
return;
};
@@ -1206,3 +1251,548 @@ fn test_gpu_3slice_cache_live_stroke_display_passes_and_chunked_flatten() {
assert_eq!(pixel_at(&wide_rgba, ww, 2048, 64), [42, 180, 99, 255]);
assert_eq!(pixel_at(&wide_rgba, ww, 2399, 64), [42, 180, 99, 255]);
}
+
+// ============================================================================
+// Targeted Audit Regression Tests (Clipping Atop, FrameArenas Flush, CoW RAM,
+// clip_color Dual Bounds, Lazy CompositorTargets & Export Cleanup)
+// ============================================================================
+
+/// Regression Test 1: Clipped opaque blue over 50%-alpha red base MUST produce pure blue
+/// at strictly 50% alpha (NO alpha bloat to 75%, NO purple bleed from red showing through!).
+#[test]
+fn test_dx12_clipping_mask_source_atop_no_alpha_bloat_or_color_bleed() {
+ let _dx12_guard = crate::lock_dx12_test();
+ let Some(mut renderer) = try_headless_renderer(128, 128) else {
+ return;
+ };
+
+ let mut doc = make_empty_doc("doc-clip-atop", 128, 128);
+ let mut clip_blue = LayerNodeMeta::new_raster("clip-blue", "Clip Blue");
+ clip_blue.clipped = Some(true);
+ clip_blue.blend_mode = BlendMode::Normal;
+ let base_red = LayerNodeMeta::new_raster("base-red", "Base Red");
+
+ doc.layers.push(LayerNode {
+ meta: clip_blue,
+ grid: SparseLayerGrid::new(TileFormat::Color32Bit),
+ });
+ doc.layers.push(LayerNode {
+ meta: base_red,
+ grid: SparseLayerGrid::new(TileFormat::Color32Bit),
+ });
+
+ // Base = 50% alpha pure red; Clipped child = 100% opaque pure blue
+ fill_layer_rect(&mut doc, "base-red", RectI32::new(16, 16, 96, 96), [255, 0, 0, 128]);
+ fill_layer_rect(&mut doc, "clip-blue", RectI32::new(0, 0, 128, 128), [0, 0, 255, 255]);
+
+ let _ = renderer.sync_document(&mut doc, None);
+ let (_, _, rgba) = renderer
+ .render_document_flattened(
+ &doc,
+ None,
+ &FlattenOptions {
+ fill_white_background: false,
+ ..Default::default()
+ },
+ )
+ .expect("flatten clipped source-atop");
+
+ // Outside base: strictly transparent
+ let outside = pixel_at(&rgba, 128, 4, 4);
+ assert_eq!(outside, [0, 0, 0, 0], "Clipped child must not leak outside base");
+
+ // Inside base: pure blue [0, 0, 255] at strictly 50% alpha (~128), NO alpha bloat (~191), NO purple bleed!
+ let inside = pixel_at(&rgba, 128, 64, 64);
+ assert!(
+ inside[0] <= 2 && inside[1] <= 2 && inside[2] >= 253,
+ "Clipped opaque blue over 50% red must be pure blue with zero purple bleed, got {inside:?}"
+ );
+ assert!(
+ (inside[3] as i32 - 128).abs() <= 2,
+ "Clipped layer must preserve base alpha (~128) with zero alpha bloat to 191, got {inside:?}"
+ );
+
+ // Stack a SECOND clipped opaque green layer on top — alpha must STILL remain strictly 128 (never 223)!
+ let mut clip_green = LayerNodeMeta::new_raster("clip-green", "Clip Green");
+ clip_green.clipped = Some(true);
+ clip_green.blend_mode = BlendMode::Normal;
+ doc.layers.insert(
+ 0,
+ LayerNode {
+ meta: clip_green,
+ grid: SparseLayerGrid::new(TileFormat::Color32Bit),
+ },
+ );
+ fill_layer_rect(&mut doc, "clip-green", RectI32::new(0, 0, 128, 128), [0, 255, 0, 255]);
+ let _ = renderer.sync_document(&mut doc, None);
+ let (_, _, rgba2) = renderer
+ .render_document_flattened(
+ &doc,
+ None,
+ &FlattenOptions {
+ fill_white_background: false,
+ ..Default::default()
+ },
+ )
+ .expect("flatten double clipped source-atop");
+ let inside2 = pixel_at(&rgba2, 128, 64, 64);
+ assert!(
+ inside2[0] <= 2 && inside2[1] >= 253 && inside2[2] <= 2,
+ "Second clipped opaque green must be pure green, got {inside2:?}"
+ );
+ assert!(
+ (inside2[3] as i32 - 128).abs() <= 2,
+ "Double clipped stack must STILL preserve base alpha (~128), got {inside2:?}"
+ );
+}
+
+/// Regression Test 2: `FrameArenas::ensure_capacity` flushes atomically BEFORE pushing a draw's
+/// uniform + geometry so mid-frame flushes NEVER corrupt uniform offsets for subsequent draws.
+#[test]
+fn test_dx12_frame_arenas_mid_frame_flush_preserves_uniform_offsets() {
+ use crate::compositor::renderer::{FrameArenas, TileInstanceGpu};
+
+ let _dx12_guard = crate::lock_dx12_test();
+ let Some(renderer) = try_headless_renderer(64, 64) else {
+ return;
+ };
+ let device = renderer.device();
+ let queue = renderer.queue();
+
+ let inst_bytes = std::mem::size_of::<TileInstanceGpu>();
+ // Tiny tile instance arena that holds exactly 1 instance so Draw 2 MUST trigger a flush!
+ let mut arenas = FrameArenas::new_with_capacities(device, 256 * 8, inst_bytes, 64, 64);
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("test-frame-arenas-flush"),
+ });
+
+ let inst = TileInstanceGpu {
+ tile_origin_doc: [0.0, 0.0],
+ tile_size_doc: [256.0, 256.0],
+ atlas_slice: 0,
+ mask_slice: -1,
+ mask_default: 1.0,
+ _pad: 0.0,
+ };
+
+ // Draw 1: fits cleanly in initial capacity (0 flushes)
+ let u_draw1: [u32; 4] = [0x1111_1111, 0x2222_2222, 0x3333_3333, 0x4444_4444];
+ arenas.ensure_capacity(device, queue, &mut encoder, std::mem::size_of_val(&u_draw1), inst_bytes, 0, 0);
+ let u0 = arenas.push_uniform(device, queue, &mut encoder, &u_draw1);
+ let (s0, e0) = arenas.push_tile_instances(device, queue, &mut encoder, &[inst]);
+ assert_eq!(arenas.flush_count(), 0);
+ assert_eq!(u0, 0);
+ assert_eq!((s0, e0), (0, inst_bytes as u64));
+
+ // Draw 2: tile instance arena is full! ensure_capacity MUST flush BEFORE pushing u_draw2,
+ // so u_draw2 lands cleanly at offset 0 of the post-flush staging buffer and push_tile_instances
+ // does NOT trigger a second mid-draw flush that wipes u_draw2!
+ let u_draw2: [u32; 4] = [0xDEAD_BEEF, 0xCAFE_BABE, 0xA1B2_C3D4, 0x55AA_66BB];
+ arenas.ensure_capacity(
+ device,
+ queue,
+ &mut encoder,
+ std::mem::size_of_val(&u_draw2),
+ inst_bytes * 2,
+ 0,
+ 0,
+ );
+ assert_eq!(arenas.flush_count(), 1, "ensure_capacity must flush before Draw 2");
+ let u1 = arenas.push_uniform(device, queue, &mut encoder, &u_draw2);
+ let (s1, e1) = arenas.push_tile_instances(device, queue, &mut encoder, &[inst, inst]);
+ assert_eq!(
+ arenas.flush_count(),
+ 1,
+ "push_uniform + push_tile_instances must NOT split across a flush after ensure_capacity"
+ );
+ assert_eq!(u1, 0);
+ assert_eq!((s1, e1), (0, (inst_bytes * 2) as u64));
+
+ let staging = arenas.uniform_staging_slice();
+ assert!(
+ staging.len() >= std::mem::size_of_val(&u_draw2),
+ "Post-flush uniform staging must retain Draw 2's uniform bytes"
+ );
+ assert_eq!(
+ &staging[u1 as usize..u1 as usize + std::mem::size_of_val(&u_draw2)],
+ bytemuck::bytes_of(&u_draw2),
+ "Draw 2 uniform bytes at u_off must remain intact after geometry push"
+ );
+ queue.submit(Some(encoder.finish()));
+}
+
+/// Regression Test 3: `TieredMemoryManager::enforce_budget` MUST never clone CoW-shared tiles
+/// (increasing RAM!) and `DocumentManager::enforce_memory_budget` MUST LZ4-compress / page cold
+/// `doc.history` undo tiles while keeping Undo/Redo pixel-exact.
+#[test]
+fn test_tiered_memory_cow_shared_never_increases_ram_and_compresses_history() {
+ use crate::document::DocumentManager;
+ use crate::memory::tiered::{EvictionContext, ManagedTileSlot};
+ use crate::memory::{
+ InMemoryScratchBackend, MemoryBudgetConfig, TieredMemoryManager, ViewportFrustum,
+ };
+ use crate::tiles::{CowTileDelta, TileCoord, TileData, TileKind, TileStorage, BYTES_32BIT};
+ use std::sync::Arc;
+
+ // Part A: Externally shared Arc<TileData> (strong_count > 1 outside managed slots) must NOT be
+ // CoW-cloned by TieredMemoryManager::enforce_budget!
+ let make_noisy_tile = |seed: u32| -> Arc<TileData> {
+ let mut raw = vec![0u8; BYTES_32BIT];
+ let mut x = seed ^ 0x9E37_79B9;
+ for b in &mut raw {
+ x ^= x << 13;
+ x ^= x >> 17;
+ x ^= x << 5;
+ *b = (x & 0xFF) as u8;
+ }
+ Arc::new(TileData::from_raw_auto_compact(
+ TileFormat::Color32Bit,
+ TileKind::Raster,
+ raw,
+ ))
+ };
+
+ let scratch = Arc::new(InMemoryScratchBackend::new());
+ let mgr_tiered = TieredMemoryManager::new(
+ MemoryBudgetConfig {
+ ram_budget_bytes: 1024, // tiny budget to force aggressive demotion
+ vram_budget_bytes: 1024,
+ max_history_steps: 50,
+ offload_inactive_tabs: true,
+ },
+ Arc::clone(&scratch) as Arc<dyn crate::memory::ScratchBackend>,
+ );
+
+ let mut tile = make_noisy_tile(42);
+ let external_owner = Arc::clone(&tile);
+ assert_eq!(Arc::strong_count(&tile), 2);
+ let before_ram = tile.ram_bytes();
+ assert!(before_ram >= BYTES_32BIT);
+
+ let (compressed, paged, bytes_freed) = mgr_tiered
+ .enforce_budget(
+ vec![ManagedTileSlot {
+ doc_id: "d",
+ layer_id: "l",
+ kind: TileKind::Raster,
+ coord: TileCoord::new(0, 0),
+ is_history: false,
+ tile: &mut tile,
+ }],
+ &EvictionContext::default(),
+ )
+ .expect("enforce_budget");
+
+ assert_eq!(
+ compressed, 0,
+ "Externally shared CoW tile must not be cloned/compressed"
+ );
+ assert_eq!(
+ paged, 0,
+ "Externally shared CoW tile must not be cloned/evicted"
+ );
+ assert_eq!(bytes_freed, 0);
+ assert!(
+ Arc::ptr_eq(&tile, &external_owner),
+ "CoW-shared Arc must NOT be forked into a second RAM buffer!"
+ );
+
+ // Part B: DocumentManager::enforce_memory_budget includes doc.history tiles, deduplicates
+ // shared Arcs, compresses/pages cold undo tiles, and NEVER increases RAM!
+ let doc_scratch = Arc::new(InMemoryScratchBackend::new());
+ let mut doc_mgr = DocumentManager::new(
+ MemoryBudgetConfig {
+ ram_budget_bytes: 300 * 1024, // tightly fits ~1 raw tile so history MUST demote
+ vram_budget_bytes: 64 * 1024 * 1024,
+ max_history_steps: 50,
+ offload_inactive_tabs: true,
+ },
+ Arc::clone(&doc_scratch) as Arc<dyn crate::memory::ScratchBackend>,
+ );
+ doc_mgr.create_document(
+ "doc-hist-mem",
+ "HistMem",
+ CanvasDimensions {
+ width: 512,
+ height: 512,
+ dpi: 300,
+ },
+ CanvasColorMode::Color,
+ "#ffffff",
+ 60.0,
+ );
+ doc_mgr.set_viewport_frustum(Some(ViewportFrustum {
+ min_x: 0,
+ min_y: 0,
+ max_x: 256,
+ max_y: 256,
+ }));
+
+ let lid = doc_mgr
+ .active_document()
+ .unwrap()
+ .active_layer_id
+ .clone()
+ .unwrap();
+
+ // Record 4 sequential noisy strokes on tile (0,0) -> creates 4 history entries holding raw 256 KB tiles
+ let mut expected_snapshots: Vec<Vec<u8>> = Vec::new();
+ for step in 0..4u32 {
+ let mut raw = vec![0u8; BYTES_32BIT];
+ for (idx, chunk) in raw.chunks_exact_mut(4).enumerate() {
+ // Compressible but non-solid structured pattern (high LZ4 ratio)
+ let v = ((idx / 16) as u8).wrapping_add((step * 37) as u8);
+ chunk.copy_from_slice(&[v, v.wrapping_mul(3), step as u8 * 50, 255]);
+ }
+ expected_snapshots.push(raw.clone());
+ let new_tile = Arc::new(TileData::from_raw_auto_compact(
+ TileFormat::Color32Bit,
+ TileKind::Raster,
+ raw,
+ ));
+ let doc = doc_mgr.active_document_mut().unwrap();
+ let before = doc.layer(&lid).unwrap().grid.tiles.get(&TileCoord::new(0, 0)).cloned();
+ doc.layer_mut(&lid)
+ .unwrap()
+ .grid
+ .set_tile(TileCoord::new(0, 0), Arc::clone(&new_tile));
+ doc.record_stroke_deltas(
+ &lid,
+ "brush",
+ &format!("Stroke {step}"),
+ vec![CowTileDelta {
+ layer_id: lid.clone(),
+ kind: TileKind::Raster,
+ coord: TileCoord::new(0, 0),
+ before,
+ after: Some(new_tile),
+ remote_epoch: 0,
+ }],
+ Some("local".to_string()),
+ Some(format!("s-{step}")),
+ );
+ }
+
+ let ram_before = doc_mgr.memory_stats().ram_total_bytes;
+ let (compressed_b, paged_b, bytes_freed_b) =
+ doc_mgr.enforce_memory_budget().expect("doc enforce_memory_budget");
+ let ram_after = doc_mgr.memory_stats().ram_total_bytes;
+ assert!(
+ ram_after <= ram_before,
+ "enforce_memory_budget must NEVER increase RAM: before={ram_before} after={ram_after}"
+ );
+ assert!(
+ (compressed_b > 0 || paged_b > 0) && bytes_freed_b > 0,
+ "Cold history tiles must actually be LZ4-compressed or paged to disk: compressed={compressed_b}, paged={paged_b}, freed={bytes_freed_b}"
+ );
+ // Verify at least one history tile actually transitioned out of Raw storage
+ let any_demoted_in_history = {
+ let doc = doc_mgr.active_document().unwrap();
+ doc.history.entries().iter().any(|e| {
+ e.tile_deltas.iter().any(|d| {
+ d.before
+ .as_ref()
+ .is_some_and(|t| !matches!(t.storage, TileStorage::Raw(_)))
+ || d.after
+ .as_ref()
+ .is_some_and(|t| !matches!(t.storage, TileStorage::Raw(_)))
+ })
+ })
+ };
+ assert!(
+ any_demoted_in_history,
+ "doc.history entries must hold compressed/disk-paged tiles after budget enforcement"
+ );
+
+ // Undo all the way back to step 0 and verify exact pixel integrity from compressed/paged history!
+ let scratch_ref = Arc::clone(doc_mgr.scratch_backend());
+ for target_step in (0..3usize).rev() {
+ let doc = doc_mgr.active_document_mut().unwrap();
+ let _ = doc.undo();
+ let tile = doc
+ .layer(&lid)
+ .unwrap()
+ .grid
+ .tiles
+ .get(&TileCoord::new(0, 0))
+ .expect("tile present after undo");
+ let restored = tile
+ .to_rgba8(Some(scratch_ref.as_ref()), false)
+ .expect("materialize demoted history tile");
+ assert_eq!(
+ restored, expected_snapshots[target_step],
+ "Undo to step {target_step} must restore exact pixels from compressed/paged history"
+ );
+ }
+}
+
+/// Regression Test 4: `clip_color` MUST recompute `max(c)` after the `n < 0` clamp so
+/// out-of-gamut colors with both `n < 0` and `x > 1` stay strictly in `[0..1]` without distortion.
+#[test]
+fn test_clip_color_dual_out_of_bounds_cpu_and_dx12() {
+ use crate::compositor::shaders::blend_modes::clip_color_cpu;
+
+ // Case 1: Both n < 0 AND x > 1 initially, AND after clamping n < 0, c.b is STILL > 1.0!
+ // c = [-0.1, 0.9, 1.5], l = 0.3*(-0.1) + 0.59*0.9 + 0.11*1.5 = 0.666
+ // After n < 0: c1 = [0.0, 0.869..., 1.391...] -> fresh max = 1.391..., NOT stale 1.5!
+ let c1 = clip_color_cpu([-0.1, 0.9, 1.5]);
+ for ch in c1 {
+ assert!(
+ ch.is_finite() && (0.0..=1.0 + 1e-5).contains(&ch),
+ "clip_color_cpu must stay in [0..1], got {c1:?}"
+ );
+ }
+ assert!(
+ (c1[2] - 1.0).abs() < 1e-4,
+ "Max channel after recomputing x must reach 1.0 (stale x would undershoot to ~0.958), got {c1:?}"
+ );
+
+ // Case 2: Both n < 0 AND x > 1 initially, but clamping n < 0 pulls ALL channels below 1.0!
+ // c = [-0.8, 0.2, 1.2], l = 0.3*(-0.8) + 0.59*0.2 + 0.11*1.2 = 0.01
+ // After n < 0: c = l + (c - l) * l / (l - n) = [0.0, 0.01234..., 0.02469...] -> max is 0.0247 < 1.0!
+ // Stale x = 1.2 would erroneously trigger the x > 1 branch and blow up channels!
+ let c2 = clip_color_cpu([-0.8, 0.2, 1.2]);
+ let l2 = 0.3 * (-0.8f32) + 0.59 * 0.2 + 0.11 * 1.2;
+ let expected_b2 = l2 + ((1.2 - l2) * l2) / (l2 - (-0.8));
+ assert!(
+ (c2[2] - expected_b2).abs() < 1e-4,
+ "clip_color_cpu must NOT run x>1 branch once n<0 pulled max<=1: got {c2:?}, expected b={expected_b2}"
+ );
+ for ch in c2 {
+ assert!(
+ ch.is_finite() && (0.0..=1.0).contains(&ch),
+ "clip_color_cpu must stay in [0..1], got {c2:?}"
+ );
+ }
+
+ // DX12 GPU verification: BlendMode::Color with pure saturated blue over mid-bright yellow
+ // exercises set_lum -> clip_color with both n < 0 and x > 1 in WGSL!
+ let _dx12_guard = crate::lock_dx12_test();
+ let Some(mut renderer) = try_headless_renderer(64, 64) else {
+ return;
+ };
+ let mut doc = make_empty_doc("doc-clip-color-gpu", 64, 64);
+ let mut top = LayerNodeMeta::new_raster("top", "Top Color");
+ top.blend_mode = BlendMode::Color;
+ let base = LayerNodeMeta::new_raster("base", "Base");
+ doc.layers.push(LayerNode {
+ meta: top,
+ grid: SparseLayerGrid::new(TileFormat::Color32Bit),
+ });
+ doc.layers.push(LayerNode {
+ meta: base,
+ grid: SparseLayerGrid::new(TileFormat::Color32Bit),
+ });
+ fill_layer_rect(&mut doc, "base", RectI32::new(0, 0, 64, 64), [240, 240, 180, 255]);
+ fill_layer_rect(&mut doc, "top", RectI32::new(0, 0, 64, 64), [0, 0, 255, 255]);
+ let _ = renderer.sync_document(&mut doc, None);
+ let (_, _, rgba) = renderer
+ .render_document_flattened(&doc, None, &FlattenOptions::default())
+ .expect("flatten BlendMode::Color");
+ let px = pixel_at(&rgba, 64, 32, 32);
+ // Expected: set_lum([0,0,1], lum([240/255, 240/255, 180/255])) -> blue reaches 255 cleanly!
+ let base_l = 0.3 * (240.0 / 255.0) + 0.59 * (240.0 / 255.0) + 0.11 * (180.0 / 255.0);
+ let d = base_l - 0.11;
+ let exp = clip_color_cpu([d, d, 1.0 + d]);
+ let exp_u8 = [
+ (exp[0] * 255.0).round() as i32,
+ (exp[1] * 255.0).round() as i32,
+ (exp[2] * 255.0).round() as i32,
+ ];
+ assert!(
+ (px[0] as i32 - exp_u8[0]).abs() <= 2
+ && (px[1] as i32 - exp_u8[1]).abs() <= 2
+ && (px[2] as i32 - exp_u8[2]).abs() <= 2
+ && px[3] == 255,
+ "GPU BlendMode::Color must match clip_color_cpu: got {px:?}, expected {exp_u8:?}"
+ );
+}
+
+/// Regression Test 5: `CompositorTargets` lazy allocation allocates only 1 surface (`final_scene`)
+/// on a 1-layer blank canvas (instead of 14 eager full-viewport Rgba16Float targets), and
+/// `export_targets` is immediately freed after `render_document_flattened` & `render_layer_thumbnail_gpu`.
+#[test]
+fn test_dx12_compositor_targets_lazy_allocation_and_export_cleanup() {
+ let _dx12_guard = crate::lock_dx12_test();
+ let Some(mut renderer) = try_headless_renderer(1024, 1024) else {
+ return;
+ };
+
+ // Immediately after startup: ONLY `final_scene` is allocated (1 surface, not 14!)
+ assert_eq!(
+ renderer.compositor().targets_allocated_surface_count(),
+ 1,
+ "Fresh WgpuCompositor must lazily allocate ONLY final_scene (1 surface)"
+ );
+ let startup_vram = renderer.compositor().targets_allocated_vram_bytes();
+ // 1024×1024 Rgba16Float = 8 MB (14 eager surfaces would be 112+ MB!)
+ assert!(
+ startup_vram <= 16 * 1024 * 1024,
+ "Startup compositor VRAM at 1024x1024 must be minimal (~8 MB), got {startup_vram} bytes"
+ );
+
+ // Render a 1-layer blank canvas frame: must STILL allocate only 1 surface!
+ let doc = make_empty_doc("doc-blank-lazy", 1024, 1024);
+ let vp = ViewportRect {
+ x_px: 0,
+ y_px: 0,
+ width_px: 1024,
+ height_px: 1024,
+ dpr: 1.0,
+ };
+ let cam = CameraState {
+ pan_x: 512.0,
+ pan_y: 512.0,
+ zoom: 1.0,
+ ..CameraState::default()
+ };
+ let _ = renderer.render_document_frame(
+ &doc,
+ None,
+ &CompositorDisplayConfig::default(),
+ &vp,
+ &cam,
+ &[],
+ false,
+ false,
+ &CursorConfig::default(),
+ None,
+ true,
+ );
+ assert_eq!(
+ renderer.compositor().targets_allocated_surface_count(),
+ 1,
+ "1-layer blank canvas must NOT trigger allocation of optional compositor targets"
+ );
+ assert!(
+ !renderer.compositor().has_export_targets(),
+ "export_targets must be None before export"
+ );
+
+ // Run flattened export -> export_targets MUST be dropped after completion (zero permanent leak!)
+ let (ew, eh, _) = renderer
+ .render_document_flattened(&doc, None, &FlattenOptions::default())
+ .expect("flatten blank doc");
+ assert_eq!((ew, eh), (1024, 1024));
+ assert!(
+ !renderer.compositor().has_export_targets(),
+ "export_targets MUST be freed immediately after render_document_flattened!"
+ );
+
+ // Run layer thumbnail export -> export_targets MUST also be dropped after completion!
+ let mut thumb_doc = make_empty_doc("doc-thumb-lazy", 512, 512);
+ thumb_doc.layers.push(LayerNode {
+ meta: LayerNodeMeta::new_raster("l1", "Layer 1"),
+ grid: SparseLayerGrid::new(TileFormat::Color32Bit),
+ });
+ fill_layer_rect(&mut thumb_doc, "l1", RectI32::new(0, 0, 256, 256), [200, 100, 50, 255]);
+ let _ = renderer.sync_document(&mut thumb_doc, None);
+ let (tw, th, _) = renderer
+ .render_layer_thumbnail_gpu(&thumb_doc, "l1", None, 64)
+ .expect("render layer thumbnail");
+ assert_eq!((tw, th), (64, 64));
+ assert!(
+ !renderer.compositor().has_export_targets(),
+ "export_targets MUST be freed immediately after render_layer_thumbnail_gpu!"
+ );
+}
diff --git a/crates/ink-engine/src/document/doc.rs b/crates/ink-engine/src/document/doc.rs
index 9650b18..f570088 100644
--- a/crates/ink-engine/src/document/doc.rs
+++ b/crates/ink-engine/src/document/doc.rs
@@ -259,6 +259,21 @@ impl Document {
alpha
}
+ /// Sets the active layer ID if valid (or clears it when `None`), marking the compositor dirty.
+ pub fn set_active_layer(&mut self, layer_id: Option<LayerId>) -> bool {
+ let next = match layer_id {
+ Some(ref id) if self.layer(id).is_some() => Some(id.clone()),
+ None => None,
+ _ => return false,
+ };
+ if self.active_layer_id == next {
+ return false;
+ }
+ self.active_layer_id = next;
+ self.dirty_for_render = true;
+ true
+ }
+
/// Builds a compact metadata snapshot for React (ZERO full-res pixel buffers!).
pub fn snapshot_meta(&self) -> DocumentMetaSnapshot {
DocumentMetaSnapshot {
@@ -266,6 +281,7 @@ impl Document {
name: self.name.clone(),
dimensions: self.dimensions,
color_mode: self.color_mode,
+ default_tone_frequency: self.default_tone_frequency,
layers: self.layers.iter().map(|l| l.meta.clone()).collect(),
active_layer_id: self.active_layer_id.clone(),
history: self.history.snapshot(),
@@ -279,7 +295,7 @@ impl Document {
}
#[allow(clippy::too_many_arguments)]
- fn record_tree_history(
+ pub fn record_tree_history(
&mut self,
action_type: &str,
label: impl Into<String>,
@@ -496,7 +512,7 @@ impl Document {
return Err(format!("Layer not found: {layer_id}"));
};
- let mut tile_deltas = Vec::new();
+ let tile_deltas = Vec::new();
let mut visual_changed = false;
if let Some(name) = patch.name {
@@ -624,17 +640,17 @@ impl Document {
node.meta.impasto_light = Some(light);
visual_changed = true;
}
+ let mut before_grids = Vec::new();
+ let mut after_grids = Vec::new();
if let Some(expr) = patch.expression_color {
node.meta.expression_color = Some(expr);
let target_fmt = expr.to_tile_format();
if node.grid.format != target_fmt && node.meta.layer_type.has_tiles() {
- let before_snap = node.grid.snapshot_all_cow(TileKind::Raster);
+ before_grids.push((layer_id.to_string(), node.grid.clone_cow()));
let threshold = node.meta.mono_threshold.unwrap_or(128);
node.grid
.convert_format(target_fmt, threshold, true, scratch)?;
- tile_deltas =
- node.grid
- .diff_from_full_snapshot(layer_id, TileKind::Raster, &before_snap);
+ after_grids.push((layer_id.to_string(), node.grid.clone_cow()));
}
visual_changed = true;
}
@@ -654,8 +670,8 @@ impl Document {
Some(layer_id.to_string()),
before_layers,
before_active,
- Vec::new(),
- Vec::new(),
+ before_grids,
+ after_grids,
tile_deltas,
patch.coalesce_key,
);
@@ -760,6 +776,9 @@ impl Document {
let Some(node) = self.layer_mut(layer_id) else {
return Err(format!("Layer not found: {layer_id}"));
};
+ if node.meta.locked {
+ return Err("Target layer is locked".to_string());
+ }
let before_snap = node.grid.snapshot_all_cow(TileKind::Raster);
let before_impasto_snap = node.grid.snapshot_all_cow(TileKind::ImpastoHeight);
if is_bg {
@@ -817,11 +836,13 @@ impl Document {
let Some(node) = self.layer_mut(layer_id) else {
return Err(format!("Layer not found: {layer_id}"));
};
+ let before_grid = (layer_id.to_string(), node.grid.clone_cow());
node.grid.init_mask(default_value);
node.meta.has_mask = true;
node.meta.mask_enabled = Some(true);
node.meta.mask_linked = Some(true);
- node.meta.mask_version = Some(node.grid.layer_version);
+ node.meta.mask_version = Some(node.grid.mask_version);
+ let after_grid = (layer_id.to_string(), node.grid.clone_cow());
let updated = node.meta.clone();
self.dirty_for_render = true;
@@ -832,8 +853,8 @@ impl Document {
Some(layer_id.to_string()),
before_layers,
before_active,
- Vec::new(),
- Vec::new(),
+ vec![before_grid],
+ vec![after_grid],
Vec::new(),
None,
);
@@ -1001,7 +1022,10 @@ impl Document {
let Some(folder_idx) = self.layer_index(folder_id) else {
return Err(format!("Folder not found: {folder_id}"));
};
- if self.layers[folder_idx].meta.layer_type != LayerType::Folder {
+ if !matches!(
+ self.layers[folder_idx].meta.layer_type,
+ LayerType::Folder | LayerType::FrameFolder
+ ) {
return Err(format!("Layer {folder_id} is not a folder"));
}
@@ -1032,7 +1056,7 @@ impl Document {
let h = self.dimensions.height;
let rect = RectI32::new(0, 0, w, h);
- // Composite visible descendant raster layers bottom-to-top
+ // Composite visible descendant raster layers bottom-to-top (honoring nested subfolder visibility & opacity)
let mut merged_rgba = vec![0u8; (w as usize) * (h as usize) * 4];
for layer in self.layers.iter().rev() {
if !to_remove.contains(&layer.meta.id)
@@ -1042,8 +1066,27 @@ impl Document {
{
continue;
}
- let op = layer.meta.opacity.clamp(0.0, 1.0);
- if op <= 0.001 || layer.grid.tiles.is_empty() {
+ let mut sub_visible = true;
+ let mut sub_opacity = layer.meta.opacity.clamp(0.0, 1.0);
+ let mut cur_parent = layer.meta.parent_id.as_deref();
+ let mut depth = 0usize;
+ while let Some(pid) = cur_parent {
+ if pid == folder_id || depth > 64 {
+ break;
+ }
+ depth += 1;
+ if let Some(pnode) = self.layer(pid) {
+ if !pnode.meta.visible {
+ sub_visible = false;
+ break;
+ }
+ sub_opacity *= pnode.meta.opacity.clamp(0.0, 1.0);
+ cur_parent = pnode.meta.parent_id.as_deref();
+ } else {
+ break;
+ }
+ }
+ if !sub_visible || sub_opacity <= 0.001 || layer.grid.tiles.is_empty() {
continue;
}
let mut src_rgba = layer.grid.read_rgba8_rect(rect, false, scratch)?;
@@ -1053,7 +1096,7 @@ impl Document {
px[3] = ((u32::from(px[3]) * u32::from(m) + 127) / 255) as u8;
}
}
- compositor_cpu::blend_rgba8_over(&mut merged_rgba, &src_rgba, op, layer.meta.blend_mode);
+ compositor_cpu::blend_rgba8_over(&mut merged_rgba, &src_rgba, sub_opacity, layer.meta.blend_mode);
}
// Preserve folder mask if present
@@ -1063,13 +1106,18 @@ impl Document {
new_grid.has_mask = true;
new_grid.mask_default_value = self.layers[folder_idx].grid.mask_default_value;
new_grid.mask_tiles = self.layers[folder_idx].grid.mask_tiles.clone();
+ new_grid.mask_version = self.layers[folder_idx].grid.mask_version;
}
let new_id = new_layer_id.into();
let mut new_meta = LayerNodeMeta::new_raster(new_id.clone(), folder_meta.name.clone());
new_meta.visible = folder_meta.visible;
new_meta.opacity = folder_meta.opacity;
- new_meta.blend_mode = folder_meta.blend_mode;
+ new_meta.blend_mode = if folder_meta.blend_mode == BlendMode::PassThrough {
+ BlendMode::Normal
+ } else {
+ folder_meta.blend_mode
+ };
new_meta.clipped = folder_meta.clipped;
new_meta.parent_id = folder_meta.parent_id.clone();
new_meta.has_mask = folder_meta.has_mask;
@@ -1164,7 +1212,7 @@ impl Document {
if is_mask {
node.meta.has_mask = true;
- node.meta.mask_version = Some(node.grid.layer_version);
+ node.meta.mask_version = Some(node.grid.mask_version);
}
// Bump remote_epoch on tiles mutated by remote collaboration peers
@@ -1562,7 +1610,7 @@ impl Document {
}
node.grid.apply_delta(delta, is_undo);
if delta.kind == TileKind::Mask {
- node.meta.mask_version = Some(node.grid.layer_version);
+ node.meta.mask_version = Some(node.grid.mask_version);
}
changed_layer_ids.insert(delta.layer_id.clone());
}
@@ -1663,6 +1711,51 @@ impl Document {
Ok((w, h, png))
}
+ /// Zero-copy Copy-on-Write snapshot of document metadata and `Arc<TileData>` grids for
+ /// lock-free background I/O (recovery checkpoints, `.ink` ZIP serialization, GPU/CPU flatten).
+ /// Runs in microseconds under a brief `docs.read()` guard so the guard can be dropped
+ /// immediately before any DEFLATE/ZIP/PNG/GPU readback work begins.
+ pub fn clone_cow_snapshot(&self) -> Self {
+ let layers = self
+ .layers
+ .iter()
+ .map(|l| LayerNode {
+ meta: l.meta.clone(),
+ grid: SparseLayerGrid {
+ format: l.grid.format,
+ tiles: l.grid.tiles.clone(),
+ has_mask: l.grid.has_mask,
+ mask_default_value: l.grid.mask_default_value,
+ mask_tiles: l.grid.mask_tiles.clone(),
+ impasto_tiles: l.grid.impasto_tiles.clone(),
+ dirty_lods: [HashSet::new(), HashSet::new(), HashSet::new()],
+ layer_version: l.grid.layer_version,
+ mask_version: l.grid.mask_version,
+ remote_epochs: HashMap::new(),
+ },
+ })
+ .collect();
+ Self {
+ id: self.id.clone(),
+ name: self.name.clone(),
+ dimensions: self.dimensions,
+ color_mode: self.color_mode,
+ default_tone_frequency: self.default_tone_frequency,
+ layers,
+ active_layer_id: self.active_layer_id.clone(),
+ history: HistoryStack::new(0),
+ perspective_ruler: self.perspective_ruler.clone(),
+ straight_ruler: self.straight_ruler.clone(),
+ animation_timeline: self.animation_timeline.clone(),
+ timelapse: self.timelapse.clone(),
+ work_time_ms: self.work_time_ms,
+ preview_data_url: None,
+ selection: None,
+ dirty_for_render: false,
+ last_accessed_ms: self.last_accessed_ms,
+ }
+ }
+
/// Collects all `Arc<TileData>` references in this document (layers + history).
pub fn collect_all_tile_refs<'a>(&'a self, out: &mut Vec<&'a Arc<TileData>>) {
for l in &self.layers {
diff --git a/crates/ink-engine/src/document/manager.rs b/crates/ink-engine/src/document/manager.rs
index e62cf9f..de2bb6c 100644
--- a/crates/ink-engine/src/document/manager.rs
+++ b/crates/ink-engine/src/document/manager.rs
@@ -15,6 +15,154 @@ use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
+fn collect_doc_managed_slots<'a>(
+ doc_id: &'a str,
+ doc: &'a mut Document,
+ slots: &mut Vec<ManagedTileSlot<'a>>,
+) {
+ for layer in &mut doc.layers {
+ let lid = layer.meta.id.as_str();
+ for (&coord, tile) in &mut layer.grid.tiles {
+ slots.push(ManagedTileSlot {
+ doc_id,
+ layer_id: lid,
+ kind: TileKind::Raster,
+ coord,
+ tile,
+ is_history: false,
+ });
+ }
+ for (&coord, tile) in &mut layer.grid.mask_tiles {
+ slots.push(ManagedTileSlot {
+ doc_id,
+ layer_id: lid,
+ kind: TileKind::Mask,
+ coord,
+ tile,
+ is_history: false,
+ });
+ }
+ for (&coord, tile) in &mut layer.grid.impasto_tiles {
+ slots.push(ManagedTileSlot {
+ doc_id,
+ layer_id: lid,
+ kind: TileKind::ImpastoHeight,
+ coord,
+ tile,
+ is_history: false,
+ });
+ }
+ }
+
+ // Include CoW undo/redo history tiles so shared Arcs are deduplicated accurately
+ // and cold undo steps are LZ4-compressed and paged to scratch disk under budget pressure.
+ for entry in doc.history.entries_mut() {
+ for delta in &mut entry.tile_deltas {
+ let lid = delta.layer_id.as_str();
+ let kind = delta.kind;
+ let coord = delta.coord;
+ if let Some(ref mut before) = delta.before {
+ slots.push(ManagedTileSlot {
+ doc_id,
+ layer_id: lid,
+ kind,
+ coord,
+ tile: before,
+ is_history: true,
+ });
+ }
+ if let Some(ref mut after) = delta.after {
+ slots.push(ManagedTileSlot {
+ doc_id,
+ layer_id: lid,
+ kind,
+ coord,
+ tile: after,
+ is_history: true,
+ });
+ }
+ }
+ if let Some(ref mut lt) = entry.layer_tree_delta {
+ for (lid, grid) in lt
+ .before_grids
+ .iter_mut()
+ .chain(lt.after_grids.iter_mut())
+ {
+ let lid = lid.as_str();
+ for (&coord, tile) in &mut grid.tiles {
+ slots.push(ManagedTileSlot {
+ doc_id,
+ layer_id: lid,
+ kind: TileKind::Raster,
+ coord,
+ tile,
+ is_history: true,
+ });
+ }
+ for (&coord, tile) in &mut grid.mask_tiles {
+ slots.push(ManagedTileSlot {
+ doc_id,
+ layer_id: lid,
+ kind: TileKind::Mask,
+ coord,
+ tile,
+ is_history: true,
+ });
+ }
+ for (&coord, tile) in &mut grid.impasto_tiles {
+ slots.push(ManagedTileSlot {
+ doc_id,
+ layer_id: lid,
+ kind: TileKind::ImpastoHeight,
+ coord,
+ tile,
+ is_history: true,
+ });
+ }
+ }
+ }
+ if let Some(ref mut cr) = entry.canvas_resize_delta {
+ for (lid, grid) in cr
+ .before_grids
+ .iter_mut()
+ .chain(cr.after_grids.iter_mut())
+ {
+ let lid = lid.as_str();
+ for (&coord, tile) in &mut grid.tiles {
+ slots.push(ManagedTileSlot {
+ doc_id,
+ layer_id: lid,
+ kind: TileKind::Raster,
+ coord,
+ tile,
+ is_history: true,
+ });
+ }
+ for (&coord, tile) in &mut grid.mask_tiles {
+ slots.push(ManagedTileSlot {
+ doc_id,
+ layer_id: lid,
+ kind: TileKind::Mask,
+ coord,
+ tile,
+ is_history: true,
+ });
+ }
+ for (&coord, tile) in &mut grid.impasto_tiles {
+ slots.push(ManagedTileSlot {
+ doc_id,
+ layer_id: lid,
+ kind: TileKind::ImpastoHeight,
+ coord,
+ tile,
+ is_history: true,
+ });
+ }
+ }
+ }
+ }
+}
+
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MemoryPurgeOutcome {
@@ -163,39 +311,10 @@ impl DocumentManager {
let prev_id = self.active_doc_id.clone();
if let Some(ref pid) = prev_id {
if Some(pid.as_str()) != next_id && self.memory.config.offload_inactive_tabs {
- // Compress previous tab's raw tiles into L2 LZ4 RAM in-process (instant, zero disk stall)
+ // Compress previous tab's raw tiles (including history) into L2 LZ4 RAM in-process
if let Some(prev_doc) = self.documents.get_mut(pid) {
let mut slots = Vec::new();
- for layer in &mut prev_doc.layers {
- let lid = layer.meta.id.as_str();
- for (&coord, tile) in &mut layer.grid.tiles {
- slots.push(ManagedTileSlot {
- doc_id: pid.as_str(),
- layer_id: lid,
- kind: TileKind::Raster,
- coord,
- tile,
- });
- }
- for (&coord, tile) in &mut layer.grid.mask_tiles {
- slots.push(ManagedTileSlot {
- doc_id: pid.as_str(),
- layer_id: lid,
- kind: TileKind::Mask,
- coord,
- tile,
- });
- }
- for (&coord, tile) in &mut layer.grid.impasto_tiles {
- slots.push(ManagedTileSlot {
- doc_id: pid.as_str(),
- layer_id: lid,
- kind: TileKind::ImpastoHeight,
- coord,
- tile,
- });
- }
- }
+ collect_doc_managed_slots(pid.as_str(), prev_doc, &mut slots);
let _ = self.memory.compress_all_to_lz4(slots);
}
}
@@ -245,42 +364,12 @@ impl DocumentManager {
}
}
- /// Enforces the shared CPU RAM budget across all open documents (L2 LZ4 -> L3 Scratch Disk).
+ /// Enforces the shared CPU RAM budget across all open documents (live layers + undo history).
pub fn enforce_memory_budget(&mut self) -> Result<(usize, usize, u64), String> {
let ctx = self.build_eviction_context();
let mut slots = Vec::new();
for (doc_id, doc) in &mut self.documents {
- let did = doc_id.as_str();
- for layer in &mut doc.layers {
- let lid = layer.meta.id.as_str();
- for (&coord, tile) in &mut layer.grid.tiles {
- slots.push(ManagedTileSlot {
- doc_id: did,
- layer_id: lid,
- kind: TileKind::Raster,
- coord,
- tile,
- });
- }
- for (&coord, tile) in &mut layer.grid.mask_tiles {
- slots.push(ManagedTileSlot {
- doc_id: did,
- layer_id: lid,
- kind: TileKind::Mask,
- coord,
- tile,
- });
- }
- for (&coord, tile) in &mut layer.grid.impasto_tiles {
- slots.push(ManagedTileSlot {
- doc_id: did,
- layer_id: lid,
- kind: TileKind::ImpastoHeight,
- coord,
- tile,
- });
- }
- }
+ collect_doc_managed_slots(doc_id.as_str(), doc, &mut slots);
}
self.memory.enforce_budget(slots, &ctx)
}
@@ -295,38 +384,8 @@ impl DocumentManager {
for (doc_id, doc) in &mut self.documents {
let is_active = active_id.as_deref() == Some(doc_id.as_str());
- let did = doc_id.as_str();
let mut slots = Vec::new();
- for layer in &mut doc.layers {
- let lid = layer.meta.id.as_str();
- for (&coord, tile) in &mut layer.grid.tiles {
- slots.push(ManagedTileSlot {
- doc_id: did,
- layer_id: lid,
- kind: TileKind::Raster,
- coord,
- tile,
- });
- }
- for (&coord, tile) in &mut layer.grid.mask_tiles {
- slots.push(ManagedTileSlot {
- doc_id: did,
- layer_id: lid,
- kind: TileKind::Mask,
- coord,
- tile,
- });
- }
- for (&coord, tile) in &mut layer.grid.impasto_tiles {
- slots.push(ManagedTileSlot {
- doc_id: did,
- layer_id: lid,
- kind: TileKind::ImpastoHeight,
- coord,
- tile,
- });
- }
- }
+ collect_doc_managed_slots(doc_id.as_str(), doc, &mut slots);
if !is_active || include_active_to_disk {
let (d_cnt, d_freed) = self.memory.evict_all_to_disk(slots)?;
disk_count += d_cnt;
diff --git a/crates/ink-engine/src/document/types.rs b/crates/ink-engine/src/document/types.rs
index da251a4..2b2cd07 100644
--- a/crates/ink-engine/src/document/types.rs
+++ b/crates/ink-engine/src/document/types.rs
@@ -482,6 +482,18 @@ impl LayerNodeMeta {
}
}
+fn deserialize_double_option<'de, T, D>(deserializer: D) -> Result<Option<Option<T>>, D::Error>
+where
+ T: Deserialize<'de>,
+ D: serde::Deserializer<'de>,
+{
+ Deserialize::deserialize(deserializer).map(Some)
+}
+
+fn default_doc_tone_frequency() -> f32 {
+ 60.0
+}
+
/// Partial property update sent from React layer panel / sliders to Rust.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -494,6 +506,7 @@ pub struct LayerPropsPatch {
pub alpha_locked: Option<bool>,
pub clipped: Option<bool>,
pub collapsed: Option<bool>,
+ #[serde(default, deserialize_with = "deserialize_double_option")]
pub parent_id: Option<Option<LayerId>>,
pub is_reference: Option<bool>,
pub color_label: Option<LayerColorLabel>,
@@ -536,6 +549,8 @@ pub struct DocumentMetaSnapshot {
pub name: String,
pub dimensions: CanvasDimensions,
pub color_mode: CanvasColorMode,
+ #[serde(default = "default_doc_tone_frequency")]
+ pub default_tone_frequency: f32,
pub layers: Vec<LayerNodeMeta>,
pub active_layer_id: Option<LayerId>,
pub history: HistoryStateSnapshot,
diff --git a/crates/ink-engine/src/engine.rs b/crates/ink-engine/src/engine.rs
index 6868e95..6eebc82 100644
--- a/crates/ink-engine/src/engine.rs
+++ b/crates/ink-engine/src/engine.rs
@@ -5,14 +5,18 @@
use crate::brush::{GpuBrushDab, NativeBrushConfig, RibbonRepeatMode, StrokeDabEmitter};
use crate::camera::{clamp_zoom, viewport_css_to_doc, NativeCameraNavigator};
use crate::clock;
-use crate::compositor::{CompositorDisplayConfig, DocBounds, FlattenOptions};
+use crate::compositor::{
+ calculate_visible_doc_bounds, CompositorDisplayConfig, DocBounds, FlattenOptions,
+};
use crate::document::{DocumentManager, ExpressionColor};
use crate::gpu::{GpuRenderer, RenderOutcome};
use crate::hit_test::SharedHitTest;
use crate::memory::{
- GpuPoolStats, InMemoryScratchBackend, MemoryBudgetConfig, ScratchBackend,
+ GpuPoolStats, InMemoryScratchBackend, MemoryBudgetConfig, ScratchBackend, ViewportFrustum,
+};
+use crate::natural_paint::{
+ BristleRibbonSimulator, GpuBristleCapsule, RibbonMeshBuilder, RibbonVertex,
};
-use crate::natural_paint::{BristleRibbonSimulator, RibbonMeshBuilder, RibbonVertex};
use crate::ring::{create_input_rings, InputConsumers, InputProducers, WakeSignal};
use crate::stroke::{
polyline_to_bezier_segments, CommittedStrokePoint, CompiledCurveLut, CubicBezierSegment,
@@ -27,8 +31,8 @@ use crate::types::{
};
use crossbeam_channel::{Receiver, Sender};
use parking_lot::RwLock;
-use std::collections::HashMap;
-use std::sync::atomic::{AtomicBool, Ordering};
+use std::collections::{HashMap, VecDeque};
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::thread::JoinHandle;
use std::time::Duration;
@@ -56,6 +60,25 @@ impl Default for EngineConfig {
}
}
+/// Lock-free performance & regression telemetry counters exposed on [`EngineHandle`].
+#[derive(Debug, Default)]
+pub struct EnginePerfCounters {
+ /// Total batched GPU brush stamp dispatches (`stamp_gpu_stroke_dabs`, ribbon, natural paint, color mixing).
+ pub stamp_dispatches: AtomicU64,
+ /// Number of synchronous CPU PNG thumbnails encoded on the DX12 render thread during pen-up (target: 0).
+ pub sync_render_thread_thumbnails: AtomicU64,
+ /// Number of asynchronous thumbnails finished by the background thumbnail worker thread.
+ pub async_thumbnails_completed: AtomicU64,
+}
+
+/// Snapshot of [`EnginePerfCounters`] for diagnostics and headless regression benchmarks.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct EnginePerfSnapshot {
+ pub stamp_dispatches: u64,
+ pub sync_render_thread_thumbnails: u64,
+ pub async_thumbnails_completed: u64,
+}
+
/// Thread-safe handle to a running `ink-engine` instance.
///
/// The host sends control commands via [`send_command`], shares [`hit_test`] directly with
@@ -70,6 +93,8 @@ pub struct EngineHandle {
retouch_session: Arc<Mutex<crate::tools::RetouchSession>>,
gpu_pool_stats: Arc<RwLock<GpuPoolStats>>,
diagnostics: Arc<Mutex<EngineDiagnostics>>,
+ perf_counters: Arc<EnginePerfCounters>,
+ stroke_active: Arc<AtomicBool>,
running: Arc<AtomicBool>,
thread: Mutex<Option<JoinHandle<()>>>,
}
@@ -83,7 +108,7 @@ impl EngineHandle {
let wake = WakeSignal::new();
let (producers, consumers) = create_input_rings(&wake);
let (cmd_tx, cmd_rx) = crossbeam_channel::unbounded::<EngineCommand>();
- let (event_tx, event_rx) = crossbeam_channel::bounded::<EngineEvent>(128);
+ let (event_tx, event_rx) = crossbeam_channel::bounded::<EngineEvent>(512);
let hit_test = SharedHitTest::new();
let scratch: Arc<dyn ScratchBackend> = config
.scratch_backend
@@ -101,6 +126,8 @@ impl EngineHandle {
gpu_vram_budget_bytes: vram_budget,
..Default::default()
}));
+ let perf_counters = Arc::new(EnginePerfCounters::default());
+ let stroke_active = Arc::new(AtomicBool::new(false));
let running = Arc::new(AtomicBool::new(true));
let (init_tx, init_rx) = crossbeam_channel::bounded::<Result<EngineDiagnostics, String>>(1);
@@ -110,6 +137,8 @@ impl EngineHandle {
let docs_thread = Arc::clone(&documents);
let pool_stats_thread = Arc::clone(&gpu_pool_stats);
let diag_thread = Arc::clone(&diagnostics);
+ let perf_thread = Arc::clone(&perf_counters);
+ let stroke_active_thread = Arc::clone(&stroke_active);
let running_thread = Arc::clone(&running);
let handle = std::thread::Builder::new()
@@ -166,6 +195,8 @@ impl EngineHandle {
docs_thread,
pool_stats_thread,
diag_thread,
+ perf_thread,
+ stroke_active_thread,
running_thread,
);
state.run_loop();
@@ -183,6 +214,8 @@ impl EngineHandle {
retouch_session: Arc::new(Mutex::new(crate::tools::RetouchSession::default())),
gpu_pool_stats,
diagnostics,
+ perf_counters,
+ stroke_active,
running,
thread: Mutex::new(Some(handle)),
},
@@ -201,14 +234,27 @@ impl EngineHandle {
}
/// Sends a typed command to the engine thread and immediately wakes it.
+ /// Single source of truth for synchronous `SharedHitTest` updates (zero duplicate locks!).
pub fn send_command(&self, cmd: EngineCommand) {
- match &cmd {
- EngineCommand::SetViewport(vp) => self.hit_test.set_viewport(*vp),
- EngineCommand::SetOccludedRects(rects) => self.hit_test.set_occluded_rects(rects.clone()),
- EngineCommand::SetVisible(vis) => self.hit_test.set_visible(*vis),
- EngineCommand::SetInteractionPolicy(policy) => self.hit_test.set_policy(*policy),
- _ => {}
- }
+ let cmd = match cmd {
+ EngineCommand::SetViewport(vp) => {
+ self.hit_test.set_viewport(vp);
+ EngineCommand::SetViewport(vp)
+ }
+ EngineCommand::SetOccludedRects(rects) => {
+ self.hit_test.set_occluded_rects(rects);
+ EngineCommand::SetOccludedRects(Vec::new())
+ }
+ EngineCommand::SetVisible(vis) => {
+ self.hit_test.set_visible(vis);
+ EngineCommand::SetVisible(vis)
+ }
+ EngineCommand::SetInteractionPolicy(policy) => {
+ self.hit_test.set_policy(policy);
+ EngineCommand::SetInteractionPolicy(policy)
+ }
+ other => other,
+ };
let _ = self.cmd_tx.send(cmd);
self.wake.wake();
}
@@ -217,6 +263,17 @@ impl EngineHandle {
self.hit_test.clone()
}
+ /// Lock-free check indicating whether a native GPU stroke is currently active or committing.
+ #[inline]
+ pub fn is_stroke_active(&self) -> bool {
+ self.stroke_active.load(Ordering::Acquire)
+ }
+
+ /// Returns the shared lock-free `stroke_active` atomic flag for background tasks.
+ pub fn stroke_active_flag(&self) -> Arc<AtomicBool> {
+ Arc::clone(&self.stroke_active)
+ }
+
/// Returns a shared thread-safe handle to the multi-tab Rust [`DocumentManager`].
pub fn documents(&self) -> Arc<RwLock<DocumentManager>> {
Arc::clone(&self.documents)
@@ -322,6 +379,21 @@ impl EngineHandle {
.unwrap_or_default()
}
+ /// Returns a lock-free snapshot of GPU stamp batching & async thumbnail counters.
+ pub fn perf_snapshot(&self) -> EnginePerfSnapshot {
+ EnginePerfSnapshot {
+ stamp_dispatches: self.perf_counters.stamp_dispatches.load(Ordering::Relaxed),
+ sync_render_thread_thumbnails: self
+ .perf_counters
+ .sync_render_thread_thumbnails
+ .load(Ordering::Relaxed),
+ async_thumbnails_completed: self
+ .perf_counters
+ .async_thumbnails_completed
+ .load(Ordering::Relaxed),
+ }
+ }
+
pub fn is_running(&self) -> bool {
self.running.load(Ordering::Relaxed)
}
@@ -441,8 +513,169 @@ struct ActiveGpuStroke {
before_mask_tiles: HashMap<TileCoord, Option<Arc<TileData>>>,
}
+struct ThumbnailJob {
+ doc_id: String,
+ layer_id: String,
+ doc_w: u32,
+ doc_h: u32,
+ layer_version: u64,
+ is_mask: bool,
+ tiles: HashMap<TileCoord, Arc<TileData>>,
+ mask_default_value: u8,
+ tint: Option<([u8; 4], [u8; 4])>,
+ scratch: Arc<dyn ScratchBackend>,
+}
+
+fn spawn_thumbnail_worker(
+ documents: Arc<RwLock<DocumentManager>>,
+ event_tx: Sender<EngineEvent>,
+ perf_counters: Arc<EnginePerfCounters>,
+) -> (Option<Sender<ThumbnailJob>>, Option<JoinHandle<()>>) {
+ let (tx, rx) = crossbeam_channel::unbounded::<ThumbnailJob>();
+ let worker = std::thread::Builder::new()
+ .name("inkstudio-thumbnail-worker".to_string())
+ .spawn(move || {
+ while let Ok(first) = rx.recv() {
+ // Coalesce/debounce rapid consecutive pen-ups for the same (doc, layer, is_mask)
+ let mut latest: HashMap<(String, String, bool), ThumbnailJob> = HashMap::new();
+ latest.insert(
+ (first.doc_id.clone(), first.layer_id.clone(), first.is_mask),
+ first,
+ );
+ while let Ok(next) = rx.try_recv() {
+ latest.insert(
+ (next.doc_id.clone(), next.layer_id.clone(), next.is_mask),
+ next,
+ );
+ }
+
+ for (_, job) in latest {
+ let encoded = if job.is_mask {
+ crate::io::compositor_cpu::render_mask_thumbnail_rgba_from_tiles(
+ &job.tiles,
+ job.mask_default_value,
+ job.doc_w,
+ job.doc_h,
+ 64,
+ 64,
+ Some(job.scratch.as_ref()),
+ )
+ .and_then(|(tw, th, rgba)| {
+ crate::io::png_codec::encode_rgba8_to_png(tw, th, &rgba)
+ })
+ .map(|png| crate::io::png_codec::png_bytes_to_data_url(&png))
+ .ok()
+ } else {
+ crate::io::compositor_cpu::render_layer_thumbnail_rgba_from_tiles(
+ &job.tiles,
+ job.tint,
+ job.doc_w,
+ job.doc_h,
+ 64,
+ 64,
+ Some(job.scratch.as_ref()),
+ )
+ .and_then(|(tw, th, rgba)| {
+ crate::io::png_codec::encode_rgba8_to_png(tw, th, &rgba)
+ })
+ .map(|png| crate::io::png_codec::png_bytes_to_data_url(&png))
+ .ok()
+ };
+
+ let Some(url) = encoded else {
+ continue;
+ };
+
+ // Brief write lock ONLY to store finished URL if layer version hasn't moved on
+ {
+ let mut mgr = documents.write();
+ if let Some(doc) = mgr.get_document_mut(&job.doc_id) {
+ if let Some(l) = doc.layer_mut(&job.layer_id) {
+ if l.grid.layer_version == job.layer_version {
+ if job.is_mask {
+ l.meta.mask_thumbnail_url = Some(url.clone());
+ } else {
+ l.meta.thumbnail_url = Some(url.clone());
+ }
+ }
+ }
+ }
+ }
+
+ perf_counters
+ .async_thumbnails_completed
+ .fetch_add(1, Ordering::Relaxed);
+
+ let update = if job.is_mask {
+ ThumbnailUpdate {
+ layer_id: job.layer_id,
+ thumbnail_url: None,
+ mask_thumbnail_url: Some(url),
+ }
+ } else {
+ ThumbnailUpdate {
+ layer_id: job.layer_id,
+ thumbnail_url: Some(url),
+ mask_thumbnail_url: None,
+ }
+ };
+ let _ = event_tx.try_send(EngineEvent::ThumbnailsUpdated {
+ doc_id: job.doc_id,
+ updates: vec![update],
+ });
+ }
+ }
+ })
+ .ok();
+ match worker {
+ Some(handle) => (Some(tx), Some(handle)),
+ None => (None, None),
+ }
+}
+
+/// Maximum gap between two consecutive rendered frames to count as an active continuous
+/// frame interval (gaps >= 150 ms are on-demand idle pauses and must never drag FPS down).
+const ACTIVE_FRAME_GAP_THRESHOLD_MS: f64 = 150.0;
+/// Time since the last rendered frame after which the HUD enters explicit Idle state.
+const IDLE_DISPLAY_TIMEOUT_MS: f64 = 350.0;
+/// Upper cap for reported active display FPS.
+const MAX_DISPLAY_FPS: f32 = 240.0;
+
+/// Owns the live `GpuRenderer` while allowing device-lost recovery to drop the old DX12 device,
+/// swapchain, atlases, and compositor targets BEFORE constructing the replacement (preventing 2× VRAM spikes).
+struct RendererSlot(Option<GpuRenderer>);
+
+impl RendererSlot {
+ #[inline]
+ fn is_present(&self) -> bool {
+ self.0.is_some()
+ }
+}
+
+impl std::ops::Deref for RendererSlot {
+ type Target = GpuRenderer;
+
+ #[inline]
+ fn deref(&self) -> &Self::Target {
+ self.0
+ .as_ref()
+ .expect("GpuRenderer must be present during active engine loop")
+ }
+}
+
+impl std::ops::DerefMut for RendererSlot {
+ #[inline]
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ self.0
+ .as_mut()
+ .expect("GpuRenderer must be present during active engine loop")
+ }
+}
+
struct EngineThreadState {
- renderer: GpuRenderer,
+ renderer: RendererSlot,
+ pending_recovery: Option<(u32, u32, u64, SurfaceTarget)>,
+ viewport_commit_pending: bool,
consumers: InputConsumers,
cmd_rx: Receiver<EngineCommand>,
event_tx: Sender<EngineEvent>,
@@ -451,7 +684,13 @@ struct EngineThreadState {
documents: Arc<RwLock<DocumentManager>>,
shared_pool_stats: Arc<RwLock<GpuPoolStats>>,
shared_diag: Arc<Mutex<EngineDiagnostics>>,
+ perf_counters: Arc<EnginePerfCounters>,
+ stroke_active: Arc<AtomicBool>,
running: Arc<AtomicBool>,
+ thumb_tx: Option<Sender<ThumbnailJob>>,
+ thumb_worker: Option<JoinHandle<()>>,
+ collab_points_enabled: bool,
+ deferred_readback_cmds: VecDeque<EngineCommand>,
viewport: ViewportRect,
visible: bool,
@@ -479,20 +718,35 @@ struct EngineThreadState {
last_stroke_end_point: Option<StrokePoint>,
stroke_id_counter: u64,
+ // Per-frame stroke batching scratch buffers (flushed ONCE right before render_and_present,
+ // or immediately before pen-up / stroke-cancel so 200-300 Hz packets = 1 GPU submit/frame!)
+ pending_stamp_primary_dabs: Vec<GpuBrushDab>,
+ pending_stamp_secondary_dabs: Vec<GpuBrushDab>,
+ pending_cmix_dabs: Vec<GpuBrushDab>,
+ pending_cmix_secondary_dabs: Vec<GpuBrushDab>,
+ pending_np_pts: Vec<StrokePoint>,
+ pending_np_capsules: Vec<GpuBristleCapsule>,
+ pending_ribbon_pts: Vec<StrokePoint>,
+
// Legacy fallback for document-less Phase 1 PoC harness only
legacy_stroke_gen: StrokeDabGenerator,
legacy_pending_dabs: Vec<DabInstance>,
merged_samples: Vec<NativeInputSample>,
+ stashed_nav_events: VecDeque<NativeNavEvent>,
cursor_local_phys: Option<(f32, f32)>,
cursor_over_occluded: bool,
last_tablet_sample_ms: f64,
+ last_wintab_sample_ms: f64,
+ /// Owning input backend for the currently active stroke: 0=none, 1=wintab, 2=windows-ink, 3=mouse.
+ active_stroke_backend: u8,
// Throttling & telemetry
dirty: bool,
pending_doc_sync: bool,
pending_camera_emit: bool,
pending_camera_commit: bool,
+ pending_wheel_commit_deadline_ms: Option<f64>,
last_camera_emit_ms: f64,
last_diag_emit_ms: f64,
last_pointer_stat_ms: f64,
@@ -503,9 +757,11 @@ struct EngineThreadState {
newest_input_timestamp_ms: f64,
ema_frame_time_ms: f32,
ema_input_latency_ms: f32,
- fps_window_start_ms: f64,
- fps_window_frames: u32,
+ last_present_ms: f64,
+ ema_active_frame_interval_ms: f32,
+ active_interval_count: u32,
measured_fps: f32,
+ was_idle_diag: bool,
total_frames: u64,
active_stroke_dabs: u64,
device_lost_recoveries: u32,
@@ -524,13 +780,22 @@ impl EngineThreadState {
documents: Arc<RwLock<DocumentManager>>,
shared_pool_stats: Arc<RwLock<GpuPoolStats>>,
shared_diag: Arc<Mutex<EngineDiagnostics>>,
+ perf_counters: Arc<EnginePerfCounters>,
+ stroke_active: Arc<AtomicBool>,
running: Arc<AtomicBool>,
) -> Self {
let now = clock::now_ms();
let default_params = BrushParams::default();
let full_brush = NativeBrushConfig::from_basic_params(&default_params);
+ let (thumb_tx, thumb_worker) = spawn_thumbnail_worker(
+ Arc::clone(&documents),
+ event_tx.clone(),
+ Arc::clone(&perf_counters),
+ );
Self {
- renderer,
+ renderer: RendererSlot(Some(renderer)),
+ pending_recovery: None,
+ viewport_commit_pending: false,
consumers,
cmd_rx,
event_tx,
@@ -539,7 +804,13 @@ impl EngineThreadState {
documents,
shared_pool_stats,
shared_diag,
+ perf_counters,
+ stroke_active,
running,
+ thumb_tx,
+ thumb_worker,
+ collab_points_enabled: false,
+ deferred_readback_cmds: VecDeque::new(),
viewport: ViewportRect::default(),
visible: false,
show_checkerboard: config.show_checkerboard,
@@ -566,16 +837,27 @@ impl EngineThreadState {
frame_dirty_doc_bounds: None,
last_stroke_end_point: None,
stroke_id_counter: 1,
+ pending_stamp_primary_dabs: Vec::with_capacity(256),
+ pending_stamp_secondary_dabs: Vec::with_capacity(128),
+ pending_cmix_dabs: Vec::with_capacity(128),
+ pending_cmix_secondary_dabs: Vec::with_capacity(128),
+ pending_np_pts: Vec::with_capacity(64),
+ pending_np_capsules: Vec::with_capacity(512),
+ pending_ribbon_pts: Vec::with_capacity(64),
legacy_stroke_gen: StrokeDabGenerator::default(),
legacy_pending_dabs: Vec::with_capacity(256),
merged_samples: Vec::with_capacity(128),
+ stashed_nav_events: VecDeque::with_capacity(16),
cursor_local_phys: None,
cursor_over_occluded: false,
- last_tablet_sample_ms: 0.0,
+ last_tablet_sample_ms: f64::NEG_INFINITY,
+ last_wintab_sample_ms: f64::NEG_INFINITY,
+ active_stroke_backend: 0,
dirty: false,
pending_doc_sync: false,
pending_camera_emit: false,
pending_camera_commit: false,
+ pending_wheel_commit_deadline_ms: None,
last_camera_emit_ms: 0.0,
last_diag_emit_ms: now,
last_pointer_stat_ms: 0.0,
@@ -585,9 +867,11 @@ impl EngineThreadState {
newest_input_timestamp_ms: 0.0,
ema_frame_time_ms: 0.0,
ema_input_latency_ms: 0.0,
- fps_window_start_ms: now,
- fps_window_frames: 0,
+ last_present_ms: 0.0,
+ ema_active_frame_interval_ms: 0.0,
+ active_interval_count: 0,
measured_fps: 0.0,
+ was_idle_diag: true,
total_frames: 0,
active_stroke_dabs: 0,
device_lost_recoveries: 0,
@@ -599,27 +883,87 @@ impl EngineThreadState {
self.active_gpu_stroke.is_some() || self.legacy_stroke_gen.is_active()
}
+ #[inline]
+ fn sync_stroke_active_flag(&self) {
+ self.stroke_active
+ .store(self.is_any_stroke_active(), Ordering::Release);
+ }
+
+ fn clear_pending_stroke_batch(&mut self) {
+ self.pending_stamp_primary_dabs.clear();
+ self.pending_stamp_secondary_dabs.clear();
+ self.pending_cmix_dabs.clear();
+ self.pending_cmix_secondary_dabs.clear();
+ self.pending_np_pts.clear();
+ self.pending_np_capsules.clear();
+ self.pending_ribbon_pts.clear();
+ }
+
fn cancel_active_stroke(&mut self) {
self.active_gpu_stroke = None;
+ self.active_stroke_backend = 0;
+ self.clear_pending_stroke_batch();
self.stroke_pipeline.reset();
self.legacy_stroke_gen.reset();
self.legacy_pending_dabs.clear();
self.frame_dirty_doc_bounds = None;
self.renderer.clear_live_stroke();
+ self.stroke_active.store(false, Ordering::Release);
self.dirty = true;
}
+ /// Sends high-frequency telemetry events ONLY while queue headroom remains so critical
+ /// state-sync events (`StrokeCommitted`, `HistoryChanged`, `ThumbnailsUpdated`,
+ /// `SelectionChanged`, `ViewportInvalidated`) can never be starved or dropped.
+ #[inline]
+ fn send_throttled_event(&self, evt: EngineEvent) {
+ if self.event_tx.len() < 448 {
+ let _ = self.event_tx.try_send(evt);
+ }
+ }
+
+ fn sync_viewport_frustum_locked(&self, mgr: &mut DocumentManager) {
+ let Some(doc) = mgr.active_document() else {
+ mgr.set_viewport_frustum(None);
+ return;
+ };
+ let css_w = self.viewport.css_width();
+ let css_h = self.viewport.css_height();
+ if css_w <= 0.0 || css_h <= 0.0 {
+ mgr.set_viewport_frustum(None);
+ return;
+ }
+ let bounds = calculate_visible_doc_bounds(
+ css_w,
+ css_h,
+ &self.camera,
+ doc.dimensions.width,
+ doc.dimensions.height,
+ );
+ mgr.set_viewport_frustum(Some(ViewportFrustum {
+ min_x: bounds.min_x,
+ min_y: bounds.min_y,
+ max_x: bounds.max_x,
+ max_y: bounds.max_y,
+ }));
+ }
+
+ fn sync_viewport_frustum(&self) {
+ let mut mgr = self.documents.write();
+ self.sync_viewport_frustum_locked(&mut mgr);
+ }
+
fn sync_active_document_if_needed(&mut self) {
if !self.pending_doc_sync {
return;
}
self.pending_doc_sync = false;
- let mut mgr = self.documents.write();
- let scratch = Arc::clone(mgr.scratch_backend());
- if let Some(doc) = mgr.active_document_mut() {
- if let Err(err) = self.renderer.sync_document(doc, Some(scratch.as_ref())) {
- eprintln!("[ink-engine] sync_document failed: {err}");
- }
+ // Read-only lock + O(resident_slots) stale-key invalidation: NEVER hold documents.write()
+ // or upload offscreen tiles across all layers; frustum-culled prepare_document_gpu_resources
+ // uploads visible tiles lazily on demand!
+ let mgr = self.documents.read();
+ if let Some(doc) = mgr.active_document() {
+ self.renderer.sync_document_lazy(doc);
*self.shared_pool_stats.write() = self.renderer.gpu_pool_stats();
self.dirty = true;
}
@@ -705,9 +1049,35 @@ impl EngineThreadState {
}
}
- fn expand_frame_dirty_bounds(&mut self, dabs: &[GpuBrushDab]) {
- for d in dabs {
- self.expand_frame_dirty_doc_aabb(d.doc_bounds());
+ /// Coarse curvature-preserving Bezier sampling for `BristleRibbonSimulator` (which already
+ /// performs physical substepping), eliminating redundant double-subdivision!
+ fn sample_segments_for_natural_paint(
+ segs: &[CubicBezierSegment],
+ brush_size: f32,
+ out: &mut Vec<StrokePoint>,
+ ) {
+ let target_step = (brush_size as f64 * 0.22).clamp(5.0, 18.0);
+ for seg in segs {
+ let chord = (seg.p3.x - seg.p0.x).hypot(seg.p3.y - seg.p0.y);
+ let steps = ((chord / target_step).ceil() as usize).clamp(1, 8);
+ for s in 1..=steps {
+ let t = s as f64 / steps as f64;
+ let (x, y, _, _) = seg.eval_pos_tangent(t);
+ let tf = t as f32;
+ out.push(StrokePoint {
+ x,
+ y,
+ pressure: seg.p0.pressure + (seg.p3.pressure - seg.p0.pressure) * tf,
+ width: seg.p0.width + (seg.p3.width - seg.p0.width) * tf,
+ tilt_x: seg.p0.tilt_x + (seg.p3.tilt_x - seg.p0.tilt_x) * tf,
+ tilt_y: seg.p0.tilt_y + (seg.p3.tilt_y - seg.p0.tilt_y) * tf,
+ twist: seg.p0.twist + (seg.p3.twist - seg.p0.twist) * tf,
+ velocity: seg.p0.velocity + (seg.p3.velocity - seg.p0.velocity) * t,
+ timestamp_ms: seg.p0.timestamp_ms
+ + (seg.p3.timestamp_ms - seg.p0.timestamp_ms) * t,
+ is_corner: s == steps && seg.p3.is_corner,
+ });
+ }
}
}
@@ -738,6 +1108,7 @@ impl EngineThreadState {
&mut self.legacy_pending_dabs,
);
self.active_stroke_dabs = (self.legacy_pending_dabs.len() - before) as u64;
+ self.sync_stroke_active_flag();
self.dirty = true;
return;
};
@@ -861,6 +1232,8 @@ impl EngineThreadState {
doc_h,
stroke_brush.clone(),
);
+ self.renderer
+ .set_natural_paint_stroke_rand_offset(grain_offset);
ActiveStrokeKind::ColorMixingStamp
} else if stroke_brush.is_ribbon_brush() {
self.renderer.begin_gpu_stroke(
@@ -965,16 +1338,19 @@ impl EngineThreadState {
before_mask_tiles: HashMap::with_capacity(16),
};
+ self.clear_pending_stroke_batch();
self.active_stroke_dabs = 0;
self.frame_dirty_doc_bounds = None;
- self.dispatch_stroke_step(&mut active, step.initial_point, &step.sealed_segments);
+ self.accumulate_stroke_step(&mut active, step.initial_point, &step.sealed_segments);
self.active_gpu_stroke = Some(active);
+ self.sync_stroke_active_flag();
self.dirty = true;
}
- /// Dispatches stabilized points/segments to the active Phase 4 or Phase 5 GPU brush backend.
- fn dispatch_stroke_step(
+ /// Accumulates stabilized points/segments into per-frame scratch buffers WITHOUT submitting
+ /// to the GPU, so 200-300 Hz input packets collapse into ONE batched GPU dispatch per frame!
+ fn accumulate_stroke_step(
&mut self,
active: &mut ActiveGpuStroke,
initial_point: Option<StrokePoint>,
@@ -982,25 +1358,118 @@ impl EngineThreadState {
) {
match &mut active.kind {
ActiveStrokeKind::Stamp => {
- let mut p_dabs = Vec::with_capacity(64);
- let mut s_dabs = Vec::with_capacity(64);
if let Some(ref pt) = initial_point {
- active.primary_emitter.emit_initial_point(pt, None, 0.0, &mut p_dabs);
+ active.primary_emitter.emit_initial_point(
+ pt,
+ None,
+ 0.0,
+ &mut self.pending_stamp_primary_dabs,
+ );
if let Some(ref mut se) = active.secondary_emitter {
- se.emit_initial_point(pt, None, 0.0, &mut s_dabs);
+ se.emit_initial_point(
+ pt,
+ None,
+ 0.0,
+ &mut self.pending_stamp_secondary_dabs,
+ );
}
}
for seg in sealed_segments {
- active.primary_emitter.emit_segment(seg, None, 0.0, &mut p_dabs);
+ active.primary_emitter.emit_segment(
+ seg,
+ None,
+ 0.0,
+ &mut self.pending_stamp_primary_dabs,
+ );
if let Some(ref mut se) = active.secondary_emitter {
- se.emit_segment(seg, None, 0.0, &mut s_dabs);
+ se.emit_segment(seg, None, 0.0, &mut self.pending_stamp_secondary_dabs);
}
}
- if !p_dabs.is_empty() || !s_dabs.is_empty() {
- self.active_stroke_dabs += p_dabs.len() as u64;
- let newly_touched = self.renderer.stamp_gpu_stroke_dabs(&p_dabs, &s_dabs);
- self.capture_cow_before_tiles(active, &newly_touched);
- self.expand_frame_dirty_bounds(&p_dabs);
+ }
+ ActiveStrokeKind::Ribbon { .. } => {
+ if let Some(pt) = initial_point {
+ self.pending_ribbon_pts.push(pt);
+ }
+ Self::sample_segments_to_points(sealed_segments, &mut self.pending_ribbon_pts);
+ }
+ ActiveStrokeKind::NaturalPaint { .. } => {
+ if let Some(pt) = initial_point {
+ self.pending_np_pts.push(pt);
+ }
+ Self::sample_segments_for_natural_paint(
+ sealed_segments,
+ active.brush.size,
+ &mut self.pending_np_pts,
+ );
+ }
+ ActiveStrokeKind::ColorMixingStamp => {
+ if let Some(ref pt) = initial_point {
+ active.primary_emitter.emit_initial_point(
+ pt,
+ None,
+ 0.0,
+ &mut self.pending_cmix_dabs,
+ );
+ if let Some(ref mut se) = active.secondary_emitter {
+ se.emit_initial_point(
+ pt,
+ None,
+ 0.0,
+ &mut self.pending_cmix_secondary_dabs,
+ );
+ }
+ }
+ for seg in sealed_segments {
+ active.primary_emitter.emit_segment(
+ seg,
+ None,
+ 0.0,
+ &mut self.pending_cmix_dabs,
+ );
+ if let Some(ref mut se) = active.secondary_emitter {
+ se.emit_segment(seg, None, 0.0, &mut self.pending_cmix_secondary_dabs);
+ }
+ }
+ }
+ }
+ }
+
+ /// Flushes all accumulated per-frame stroke geometry/dabs/capsules for `active` in ONE
+ /// batched GPU dispatch! Called once per frame right before `render_and_present()`, or
+ /// right before pen-up commit (`finish_ribbon = true`).
+ fn flush_pending_stroke_batch_for(
+ &mut self,
+ active: &mut ActiveGpuStroke,
+ finish_ribbon: bool,
+ ) {
+ match &mut active.kind {
+ ActiveStrokeKind::Stamp => {
+ if self.pending_stamp_primary_dabs.is_empty()
+ && self.pending_stamp_secondary_dabs.is_empty()
+ {
+ return;
+ }
+ self.active_stroke_dabs += self.pending_stamp_primary_dabs.len() as u64;
+ let mut union_bounds: Option<(f32, f32, f32, f32)> = None;
+ for d in &self.pending_stamp_primary_dabs {
+ let b = d.doc_bounds();
+ union_bounds = Some(match union_bounds {
+ Some(p) => (p.0.min(b.0), p.1.min(b.1), p.2.max(b.2), p.3.max(b.3)),
+ None => b,
+ });
+ }
+ let newly_touched = self.renderer.stamp_gpu_stroke_dabs(
+ &self.pending_stamp_primary_dabs,
+ &self.pending_stamp_secondary_dabs,
+ );
+ self.perf_counters
+ .stamp_dispatches
+ .fetch_add(1, Ordering::Relaxed);
+ self.pending_stamp_primary_dabs.clear();
+ self.pending_stamp_secondary_dabs.clear();
+ self.capture_cow_before_tiles(active, &newly_touched);
+ if let Some(b) = union_bounds {
+ self.expand_frame_dirty_doc_aabb(b);
}
}
ActiveStrokeKind::Ribbon {
@@ -1010,12 +1479,7 @@ impl EngineThreadState {
primary_verts,
secondary_verts,
} => {
- let mut pts = Vec::with_capacity(16);
- if let Some(pt) = initial_point {
- pts.push(pt);
- }
- Self::sample_segments_to_points(sealed_segments, &mut pts);
- if pts.is_empty() {
+ if self.pending_ribbon_pts.is_empty() && !finish_ribbon {
return;
}
let is_once = active.brush.ribbon_repeat_mode == RibbonRepeatMode::Once;
@@ -1023,9 +1487,30 @@ impl EngineThreadState {
primary_verts.clear();
secondary_verts.clear();
}
- let bounds = primary.push_points(&pts, &active.brush, primary_verts);
- if let (Some(sec), Some(scfg)) = (secondary.as_mut(), secondary_cfg.as_ref()) {
- let _ = sec.push_points(&pts, scfg, secondary_verts);
+ let mut bounds: Option<(f32, f32, f32, f32)> = None;
+ if !self.pending_ribbon_pts.is_empty() {
+ bounds =
+ primary.push_points(&self.pending_ribbon_pts, &active.brush, primary_verts);
+ if let (Some(sec), Some(scfg)) = (secondary.as_mut(), secondary_cfg.as_ref()) {
+ let _ = sec.push_points(&self.pending_ribbon_pts, scfg, secondary_verts);
+ }
+ self.pending_ribbon_pts.clear();
+ }
+ if finish_ribbon {
+ if let Some(fb) = primary.finish(&active.brush, primary_verts) {
+ bounds = Some(match bounds {
+ Some(p) => (
+ p.0.min(fb.0),
+ p.1.min(fb.1),
+ p.2.max(fb.2),
+ p.3.max(fb.3),
+ ),
+ None => fb,
+ });
+ }
+ if let (Some(sec), Some(scfg)) = (secondary.as_mut(), secondary_cfg.as_ref()) {
+ let _ = sec.finish(scfg, secondary_verts);
+ }
}
if !primary_verts.is_empty() || !secondary_verts.is_empty() {
self.active_stroke_dabs += (primary_verts.len() / 6) as u64;
@@ -1034,6 +1519,9 @@ impl EngineThreadState {
secondary_verts,
is_once,
);
+ self.perf_counters
+ .stamp_dispatches
+ .fetch_add(1, Ordering::Relaxed);
self.capture_cow_before_tiles(active, &newly_touched);
if let Some(b) = bounds {
self.expand_frame_dirty_doc_aabb(b);
@@ -1041,20 +1529,20 @@ impl EngineThreadState {
}
}
ActiveStrokeKind::NaturalPaint { simulator, .. } => {
- let mut pts = Vec::with_capacity(16);
- if let Some(pt) = initial_point {
- pts.push(pt);
- }
- Self::sample_segments_to_points(sealed_segments, &mut pts);
- if pts.is_empty() {
+ if self.pending_np_pts.is_empty() {
return;
}
- let mut caps = Vec::with_capacity(pts.len() * simulator.bristle_count());
- simulator.step_points(&pts, &active.brush, &mut caps);
- if caps.is_empty() {
+ self.pending_np_capsules.clear();
+ simulator.step_points(
+ &self.pending_np_pts,
+ &active.brush,
+ &mut self.pending_np_capsules,
+ );
+ self.pending_np_pts.clear();
+ if self.pending_np_capsules.is_empty() {
return;
}
- self.active_stroke_dabs += caps.len() as u64;
+ self.active_stroke_dabs += self.pending_np_capsules.len() as u64;
let (newly_touched, bounds) = {
let mgr = self.documents.read();
let scratch = Arc::clone(mgr.scratch_backend());
@@ -1063,7 +1551,7 @@ impl EngineThreadState {
self.renderer.dispatch_natural_paint_capsules(
doc,
layer,
- &caps,
+ &self.pending_np_capsules,
Some(scratch.as_ref()),
)
} else {
@@ -1073,32 +1561,30 @@ impl EngineThreadState {
(Vec::new(), None)
}
};
+ self.perf_counters
+ .stamp_dispatches
+ .fetch_add(1, Ordering::Relaxed);
+ self.pending_np_capsules.clear();
self.capture_cow_before_tiles(active, &newly_touched);
if let Some(b) = bounds {
self.expand_frame_dirty_doc_aabb(b);
}
}
ActiveStrokeKind::ColorMixingStamp => {
- let mut p_dabs = Vec::with_capacity(64);
- if let Some(ref pt) = initial_point {
- active.primary_emitter.emit_initial_point(pt, None, 0.0, &mut p_dabs);
- }
- for seg in sealed_segments {
- active.primary_emitter.emit_segment(seg, None, 0.0, &mut p_dabs);
- }
- if p_dabs.is_empty() {
+ if self.pending_cmix_dabs.is_empty() && self.pending_cmix_secondary_dabs.is_empty() {
return;
}
- self.active_stroke_dabs += p_dabs.len() as u64;
+ self.active_stroke_dabs += self.pending_cmix_dabs.len() as u64;
let (newly_touched, bounds) = {
let mgr = self.documents.read();
let scratch = Arc::clone(mgr.scratch_backend());
if let Some(doc) = mgr.get_document(&active.doc_id) {
if let Some(layer) = doc.layer(&active.layer_id) {
- self.renderer.dispatch_color_mixing_dabs(
+ self.renderer.dispatch_color_mixing_dabs_with_secondary(
doc,
layer,
- &p_dabs,
+ &self.pending_cmix_dabs,
+ &self.pending_cmix_secondary_dabs,
Some(scratch.as_ref()),
)
} else {
@@ -1108,6 +1594,11 @@ impl EngineThreadState {
(Vec::new(), None)
}
};
+ self.perf_counters
+ .stamp_dispatches
+ .fetch_add(1, Ordering::Relaxed);
+ self.pending_cmix_dabs.clear();
+ self.pending_cmix_secondary_dabs.clear();
self.capture_cow_before_tiles(active, &newly_touched);
if let Some(b) = bounds {
self.expand_frame_dirty_doc_aabb(b);
@@ -1116,6 +1607,13 @@ impl EngineThreadState {
}
}
+ fn flush_pending_stroke_batch(&mut self) {
+ if let Some(mut active) = self.active_gpu_stroke.take() {
+ self.flush_pending_stroke_batch_for(&mut active, false);
+ self.active_gpu_stroke = Some(active);
+ }
+ }
+
fn push_native_gpu_stroke_move(
&mut self,
doc_x: f64,
@@ -1156,7 +1654,7 @@ impl EngineThreadState {
}
if let Some(mut active) = self.active_gpu_stroke.take() {
- self.dispatch_stroke_step(&mut active, None, &step.sealed_segments);
+ self.accumulate_stroke_step(&mut active, None, &step.sealed_segments);
self.active_gpu_stroke = Some(active);
}
self.dirty = true;
@@ -1165,6 +1663,12 @@ impl EngineThreadState {
/// Pen-up finalization & sub-millisecond GPU-to-GPU tile commit into `GpuTilePool`
/// + `SparseLayerGrid` + CoW Undo/Redo (raster + impasto `R16F` + mask) + `StrokeCommitted`!
fn finish_and_commit_gpu_stroke(&mut self, lift_timestamp_ms: f64) {
+ self.finish_and_commit_gpu_stroke_inner(lift_timestamp_ms);
+ self.sync_stroke_active_flag();
+ }
+
+ fn finish_and_commit_gpu_stroke_inner(&mut self, lift_timestamp_ms: f64) {
+ self.active_stroke_backend = 0;
let Some(mut active) = self.active_gpu_stroke.take() else {
if self.legacy_stroke_gen.is_active() {
self.legacy_stroke_gen.end();
@@ -1188,11 +1692,13 @@ impl EngineThreadState {
ActiveStrokeKind::NaturalPaint { .. } | ActiveStrokeKind::ColorMixingStamp
);
- if !is_natural_or_cmix
- && matches!(active.kind, ActiveStrokeKind::Stamp)
- && active.brush.requires_finalize_reraster()
+ if matches!(
+ active.kind,
+ ActiveStrokeKind::Stamp | ActiveStrokeKind::ColorMixingStamp
+ ) && active.brush.requires_finalize_reraster()
&& finalized_points.len() >= 2
{
+ self.clear_pending_stroke_batch();
let segs = polyline_to_bezier_segments(&finalized_points, 0.0);
let total_len: f64 = finalized_points
.windows(2)
@@ -1215,15 +1721,6 @@ impl EngineThreadState {
)
});
- let (doc_w, doc_h) = self.renderer.doc_size();
- self.renderer.begin_gpu_stroke(
- doc_w,
- doc_h,
- active.mono_layer,
- active.brush.clone(),
- p_emitter.stroke_grain_offset,
- );
-
let mut p_dabs = Vec::with_capacity(256);
let mut s_dabs = Vec::with_capacity(256);
for seg in &segs {
@@ -1232,41 +1729,67 @@ impl EngineThreadState {
se.emit_segment(seg, Some(total_len), exit_vel, &mut s_dabs);
}
}
- if !p_dabs.is_empty() || !s_dabs.is_empty() {
- let newly_touched = self.renderer.stamp_gpu_stroke_dabs(&p_dabs, &s_dabs);
- self.capture_cow_before_tiles(&mut active, &newly_touched);
- }
- } else {
- if !step.sealed_segments.is_empty() {
- self.dispatch_stroke_step(&mut active, None, &step.sealed_segments);
- }
- // Flush final ribbon lookahead segment (or full `Once` stretch)
- if let ActiveStrokeKind::Ribbon {
- ref mut primary,
- ref mut secondary,
- ref secondary_cfg,
- ref mut primary_verts,
- ref mut secondary_verts,
- } = active.kind
- {
- let is_once = active.brush.ribbon_repeat_mode == RibbonRepeatMode::Once;
- if !is_once {
- primary_verts.clear();
- secondary_verts.clear();
- }
- let _ = primary.finish(&active.brush, primary_verts);
- if let (Some(sec), Some(scfg)) = (secondary.as_mut(), secondary_cfg.as_ref()) {
- let _ = sec.finish(scfg, secondary_verts);
+
+ let (doc_w, doc_h) = self.renderer.doc_size();
+ if matches!(active.kind, ActiveStrokeKind::ColorMixingStamp) {
+ self.renderer.begin_natural_paint_stroke(
+ &active.doc_id,
+ &active.layer_id,
+ doc_w,
+ doc_h,
+ active.brush.clone(),
+ );
+ self.renderer
+ .set_natural_paint_stroke_rand_offset(p_emitter.stroke_grain_offset);
+ if !p_dabs.is_empty() || !s_dabs.is_empty() {
+ let newly_touched = {
+ let mgr = self.documents.read();
+ let scratch = Arc::clone(mgr.scratch_backend());
+ if let Some(doc) = mgr.get_document(&active.doc_id) {
+ if let Some(layer) = doc.layer(&active.layer_id) {
+ self.renderer
+ .dispatch_color_mixing_dabs_with_secondary(
+ doc,
+ layer,
+ &p_dabs,
+ &s_dabs,
+ Some(scratch.as_ref()),
+ )
+ .0
+ } else {
+ Vec::new()
+ }
+ } else {
+ Vec::new()
+ }
+ };
+ self.perf_counters
+ .stamp_dispatches
+ .fetch_add(1, Ordering::Relaxed);
+ self.capture_cow_before_tiles(&mut active, &newly_touched);
}
- if !primary_verts.is_empty() || !secondary_verts.is_empty() {
- let newly_touched = self.renderer.stamp_gpu_ribbon_vertices(
- primary_verts,
- secondary_verts,
- is_once,
- );
+ } else {
+ self.renderer.begin_gpu_stroke(
+ doc_w,
+ doc_h,
+ active.mono_layer,
+ active.brush.clone(),
+ p_emitter.stroke_grain_offset,
+ );
+ if !p_dabs.is_empty() || !s_dabs.is_empty() {
+ let newly_touched = self.renderer.stamp_gpu_stroke_dabs(&p_dabs, &s_dabs);
+ self.perf_counters
+ .stamp_dispatches
+ .fetch_add(1, Ordering::Relaxed);
self.capture_cow_before_tiles(&mut active, &newly_touched);
}
}
+ } else {
+ if !step.sealed_segments.is_empty() {
+ self.accumulate_stroke_step(&mut active, None, &step.sealed_segments);
+ }
+ // Flush all accumulated move dabs + trailing segments (+ ribbon finish) in ONE dispatch
+ self.flush_pending_stroke_batch_for(&mut active, true);
}
// Handle Select Pen / Select Eraser strokes directly onto Document::selection!
@@ -1321,94 +1844,136 @@ impl EngineThreadState {
return;
}
- // Sub-millisecond GPU-to-GPU commit directly into GpuTilePool + SparseLayerGrid + CoW Undo
- let committed_info = {
- let mut mgr = self.documents.write();
+ // Step A: Snapshot minimal read-only metadata / touched base Arc<TileData> refs under a
+ // microsecond read lock, then release ALL document locks BEFORE GPU commit + poll!
+ enum PreCommitInput {
+ NaturalPaint {
+ scratch: Arc<dyn ScratchBackend>,
+ mono_thresh: u8,
+ doc_rect: RectI32,
+ },
+ Mask {
+ scratch: Arc<dyn ScratchBackend>,
+ mask_tiles: HashMap<TileCoord, Arc<TileData>>,
+ touched_coords: Vec<TileCoord>,
+ mask_default_value: u8,
+ },
+ Raster {
+ scratch: Arc<dyn ScratchBackend>,
+ alpha_locked: bool,
+ mono_thresh: u8,
+ doc_selection: Option<crate::selection::SparseSelectionMask>,
+ base_subset: SparseLayerGrid,
+ },
+ }
+
+ let pre_input = {
+ let mgr = self.documents.read();
let scratch = Arc::clone(mgr.scratch_backend());
- let Some(doc) = mgr.get_document_mut(&active.doc_id) else {
+ let Some(doc) = mgr.get_document(&active.doc_id) else {
self.renderer.clear_live_stroke();
return;
};
- let (is_editable, alpha_locked, mono_thresh) = match doc.layer(&active.layer_id) {
- Some(l) => (
- (active.is_mask_stroke || l.meta.layer_type.has_tiles()) && !l.meta.locked,
- l.meta.alpha_locked.unwrap_or(false),
- l.meta.mono_threshold.unwrap_or(128),
- ),
- None => {
- self.renderer.clear_live_stroke();
- return;
- }
+ let Some(layer) = doc.layer(&active.layer_id) else {
+ self.renderer.clear_live_stroke();
+ return;
};
+ let is_editable =
+ (active.is_mask_stroke || layer.meta.layer_type.has_tiles()) && !layer.meta.locked;
if !is_editable {
self.renderer.clear_live_stroke();
self.dirty = true;
return;
}
-
+ let alpha_locked = layer.meta.alpha_locked.unwrap_or(false);
+ let mono_thresh = layer.meta.mono_threshold.unwrap_or(128);
let doc_rect = RectI32::new(0, 0, doc.dimensions.width, doc.dimensions.height);
- let doc_selection_ref = doc.selection.clone();
- let Some(layer) = doc.layer_mut(&active.layer_id) else {
- self.renderer.clear_live_stroke();
- return;
- };
- let (deltas, dirty_rect, mask_changed) = if is_natural_or_cmix {
- let batch = match self.renderer.commit_natural_paint_to_layer() {
- Ok(b) => b,
- Err(err) => {
- eprintln!("[ink-engine] GPU natural paint commit failed: {err}");
- self.renderer.clear_live_stroke();
- return;
- }
- };
- let mut drect = RectI32::empty();
- for &(c, _, _) in &batch.color_tiles {
- drect = drect.union(RectI32::new(
- c.tx * TILE_SIZE as i32,
- c.ty * TILE_SIZE as i32,
- TILE_SIZE as u32,
- TILE_SIZE as u32,
- ));
- }
- let (mut all_deltas, cleared_coords) = layer.grid.apply_gpu_committed_tiles(
- &active.layer_id,
- batch.color_tiles,
- &active.before_tiles,
+ if is_natural_or_cmix {
+ PreCommitInput::NaturalPaint {
+ scratch,
mono_thresh,
- );
- if !batch.impasto_tiles.is_empty() {
- let before_imp = match &active.kind {
- ActiveStrokeKind::NaturalPaint {
- before_impasto_tiles,
- ..
- } => before_impasto_tiles,
- _ => &active.before_tiles,
- };
- let (imp_deltas, _) = layer.grid.apply_gpu_committed_impasto_tiles(
- &active.layer_id,
- batch.impasto_tiles,
- before_imp,
- );
- all_deltas.extend(imp_deltas);
- if let Some(light) = active.brush.impasto_layer_light() {
- layer.meta.impasto_light = Some(light);
- }
+ doc_rect,
}
- self.renderer.regenerate_layer_mipmaps(
- &active.doc_id,
- &active.layer_id,
- &mut layer.grid,
- &cleared_coords,
- );
- self.renderer.clear_live_stroke();
- (all_deltas, drect.intersect(doc_rect), false)
} else if active.is_mask_stroke {
- // Build a temporary RGBA base grid from existing 8-bit mask tiles so standard GPU commit
- // blends mask stroke cleanly onto existing mask alpha!
+ // O(touched) snapshot of ONLY mask tiles touched by this stroke (never clone/unpack entire mask grid!)
+ let touched_coords = self.renderer.touched_stroke_coords();
+ let mut mask_tiles = HashMap::with_capacity(touched_coords.len());
+ for &coord in &touched_coords {
+ if let Some(tile_arc) = layer.grid.mask_tiles.get(&coord) {
+ mask_tiles.insert(coord, Arc::clone(tile_arc));
+ }
+ }
+ PreCommitInput::Mask {
+ scratch,
+ mask_tiles,
+ touched_coords,
+ mask_default_value: layer.grid.mask_default_value,
+ }
+ } else {
+ // O(touched) Arc::clone of ONLY base tiles touched by this stroke (zero pixel copies!)
+ let mut base_subset = SparseLayerGrid::new(layer.grid.format);
+ for coord in self.renderer.touched_stroke_coords() {
+ if let Some(tile_arc) = layer.grid.tiles.get(&coord) {
+ base_subset.tiles.insert(coord, Arc::clone(tile_arc));
+ }
+ }
+ PreCommitInput::Raster {
+ scratch,
+ alpha_locked,
+ mono_thresh,
+ doc_selection: doc.selection.clone(),
+ base_subset,
+ }
+ }
+ };
+
+ // Execute GPU commit + staging readback completely OUTSIDE documents.write()!
+ enum GpuCommitResult {
+ NaturalPaint {
+ batch: crate::natural_paint::CommittedNaturalPaintBatch,
+ scratch: Arc<dyn ScratchBackend>,
+ mono_thresh: u8,
+ doc_rect: RectI32,
+ },
+ Mask {
+ batch: crate::brush::CommittedTileBatch,
+ scratch: Arc<dyn ScratchBackend>,
+ },
+ Raster {
+ batch: crate::brush::CommittedTileBatch,
+ scratch: Arc<dyn ScratchBackend>,
+ mono_thresh: u8,
+ },
+ }
+
+ let gpu_commit = match pre_input {
+ PreCommitInput::NaturalPaint {
+ scratch,
+ mono_thresh,
+ doc_rect,
+ } => match self.renderer.commit_natural_paint_to_layer() {
+ Ok(batch) => GpuCommitResult::NaturalPaint {
+ batch,
+ scratch,
+ mono_thresh,
+ doc_rect,
+ },
+ Err(err) => {
+ eprintln!("[ink-engine] GPU natural paint commit failed: {err}");
+ self.renderer.clear_live_stroke();
+ return;
+ }
+ },
+ PreCommitInput::Mask {
+ scratch,
+ mask_tiles,
+ touched_coords,
+ mask_default_value,
+ } => {
+ // Build temporary RGBA base grid ONLY for mask tiles touched by this stroke off the doc lock
let mut mask_base = SparseLayerGrid::new(TileFormat::Color32Bit);
- let def_v = layer.grid.mask_default_value;
- for (&c, t) in &layer.grid.mask_tiles {
+ for (&c, t) in &mask_tiles {
if let Ok(rgba) = t.to_rgba8(Some(scratch.as_ref()), false) {
mask_base.set_tile(
c,
@@ -1420,190 +1985,323 @@ impl EngineThreadState {
);
}
}
- // Fill unallocated touched tiles with solid mask_default_value so stroke blends cleanly
- for &c in active.before_mask_tiles.keys() {
+ for &c in touched_coords
+ .iter()
+ .chain(active.before_mask_tiles.keys())
+ {
mask_base.tiles.entry(c).or_insert_with(|| {
Arc::new(TileData::new_solid(
TileFormat::Color32Bit,
TileKind::Raster,
- [def_v, def_v, def_v, 255],
+ [mask_default_value, mask_default_value, mask_default_value, 255],
))
});
}
let mask_tmp_id = format!("{}__mask_tmp", active.layer_id);
- let batch = match self.renderer.commit_gpu_stroke_to_layer(
+ let commit_res = self.renderer.commit_gpu_stroke_to_layer(
&active.doc_id,
&mask_tmp_id,
&mask_base,
Some(scratch.as_ref()),
false,
false,
- ) {
- Ok(b) => b,
- Err(err) => {
- eprintln!("[ink-engine] GPU mask stroke commit failed: {err}");
- self.renderer.clear_live_stroke();
- return;
- }
- };
- let (mask_deltas, _) = layer.grid.apply_gpu_committed_mask_tiles(
- &active.layer_id,
- batch.tiles,
- &active.before_mask_tiles,
);
- layer.meta.mask_version = Some(layer.grid.layer_version);
- self.renderer.invalidate_compositor_cache();
- self.renderer.clear_live_stroke();
- self.pending_doc_sync = true;
- (mask_deltas, batch.dirty_rect, true)
- } else {
- let batch = match self.renderer.commit_gpu_stroke_to_layer_with_selection(
- &active.doc_id,
- &active.layer_id,
- &layer.grid,
- doc_selection_ref.as_ref(),
- Some(scratch.as_ref()),
- alpha_locked,
- active.mono_layer,
- ) {
- Ok(b) => b,
+ // Always evict temporary `__mask_tmp` VRAM slots immediately after commit so VRAM never leaks!
+ self.renderer
+ .invalidate_layer_tiles(&active.doc_id, &mask_tmp_id);
+ match commit_res {
+ Ok(batch) => GpuCommitResult::Mask { batch, scratch },
Err(err) => {
- eprintln!("[ink-engine] GPU stroke commit failed: {err}");
+ eprintln!("[ink-engine] GPU mask stroke commit failed: {err}");
self.renderer.clear_live_stroke();
return;
}
- };
- let dirty_rect = batch.dirty_rect;
- let (deltas, cleared_coords) = layer.grid.apply_gpu_committed_tiles(
- &active.layer_id,
- batch.tiles,
- &active.before_tiles,
+ }
+ }
+ PreCommitInput::Raster {
+ scratch,
+ alpha_locked,
+ mono_thresh,
+ doc_selection,
+ base_subset,
+ } => match self.renderer.commit_gpu_stroke_to_layer_with_selection(
+ &active.doc_id,
+ &active.layer_id,
+ &base_subset,
+ doc_selection.as_ref(),
+ Some(scratch.as_ref()),
+ alpha_locked,
+ active.mono_layer,
+ ) {
+ Ok(batch) => GpuCommitResult::Raster {
+ batch,
+ scratch,
mono_thresh,
- );
- self.renderer.regenerate_layer_mipmaps(
- &active.doc_id,
- &active.layer_id,
- &mut layer.grid,
- &cleared_coords,
- );
+ },
+ Err(err) => {
+ eprintln!("[ink-engine] GPU stroke commit failed: {err}");
+ self.renderer.clear_live_stroke();
+ return;
+ }
+ },
+ };
+
+ // Step B: Tight, microsecond documents.write() lock ONLY for applying committed tiles,
+ // recording CoW history deltas, draining dirty LOD coords, and taking a zero-copy
+ // Arc<TileData> snapshot for off-thread PNG thumbnail encoding!
+ struct PostCommitWork {
+ doc_id: String,
+ layer_id: String,
+ entry_id: Option<String>,
+ dirty_rect: RectI32,
+ history: crate::history::HistoryStateSnapshot,
+ mask_changed: bool,
+ dirty_lods: [Vec<TileCoord>; 3],
+ cleared_coords: Vec<TileCoord>,
+ scratch: Arc<dyn ScratchBackend>,
+ thumb_job: ThumbnailJob,
+ }
+
+ let post_work: Option<PostCommitWork> = {
+ let mut mgr = self.documents.write();
+ let Some(doc) = mgr.get_document_mut(&active.doc_id) else {
self.renderer.clear_live_stroke();
- (deltas, dirty_rect, false)
+ return;
};
-
- if deltas.is_empty() {
- self.dirty = true;
+ let doc_w = doc.dimensions.width;
+ let doc_h = doc.dimensions.height;
+ let Some(layer) = doc.layer_mut(&active.layer_id) else {
+ self.renderer.clear_live_stroke();
return;
- }
-
- let is_eraser = active.brush.is_effective_eraser();
- let (action_type, label) = if mask_changed {
- ("mask", "Mask Stroke")
- } else if is_eraser {
- ("erase", "Erase")
- } else {
- ("brush", "Brush Stroke")
};
- let entry_id = doc.record_stroke_deltas(
- &active.layer_id,
- action_type,
- label,
- deltas,
- Some("local".to_string()),
- Some(format!("stroke-{}", active.stroke_seed)),
- );
- let thumb = if mask_changed {
+ let (deltas, dirty_rect, mask_changed, cleared_coords, dirty_lods, scratch) =
+ match gpu_commit {
+ GpuCommitResult::NaturalPaint {
+ batch,
+ scratch,
+ mono_thresh,
+ doc_rect,
+ } => {
+ let mut drect = RectI32::empty();
+ for &(c, _, _) in &batch.color_tiles {
+ drect = drect.union(RectI32::new(
+ c.tx * TILE_SIZE as i32,
+ c.ty * TILE_SIZE as i32,
+ TILE_SIZE as u32,
+ TILE_SIZE as u32,
+ ));
+ }
+ let (mut all_deltas, cleared) = layer.grid.apply_gpu_committed_tiles(
+ &active.layer_id,
+ batch.color_tiles,
+ &active.before_tiles,
+ mono_thresh,
+ );
+ if !batch.impasto_tiles.is_empty() {
+ let before_imp = match &active.kind {
+ ActiveStrokeKind::NaturalPaint {
+ before_impasto_tiles,
+ ..
+ } => before_impasto_tiles,
+ _ => &active.before_tiles,
+ };
+ let (imp_deltas, _) = layer.grid.apply_gpu_committed_impasto_tiles(
+ &active.layer_id,
+ batch.impasto_tiles,
+ before_imp,
+ );
+ all_deltas.extend(imp_deltas);
+ if let Some(light) = active.brush.impasto_layer_light() {
+ layer.meta.impasto_light = Some(light);
+ }
+ }
+ let dlods = [
+ layer.grid.dirty_lods[0].drain().collect(),
+ layer.grid.dirty_lods[1].drain().collect(),
+ layer.grid.dirty_lods[2].drain().collect(),
+ ];
+ (
+ all_deltas,
+ drect.intersect(doc_rect),
+ false,
+ cleared,
+ dlods,
+ scratch,
+ )
+ }
+ GpuCommitResult::Mask { batch, scratch } => {
+ let (mask_deltas, _) = layer.grid.apply_gpu_committed_mask_tiles(
+ &active.layer_id,
+ batch.tiles,
+ &active.before_mask_tiles,
+ );
+ layer.meta.mask_version = Some(layer.grid.mask_version);
+ (
+ mask_deltas,
+ batch.dirty_rect,
+ true,
+ Vec::new(),
+ [Vec::new(), Vec::new(), Vec::new()],
+ scratch,
+ )
+ }
+ GpuCommitResult::Raster {
+ batch,
+ scratch,
+ mono_thresh,
+ } => {
+ let drect = batch.dirty_rect;
+ let (deltas, cleared) = layer.grid.apply_gpu_committed_tiles(
+ &active.layer_id,
+ batch.tiles,
+ &active.before_tiles,
+ mono_thresh,
+ );
+ let dlods = [
+ layer.grid.dirty_lods[0].drain().collect(),
+ layer.grid.dirty_lods[1].drain().collect(),
+ layer.grid.dirty_lods[2].drain().collect(),
+ ];
+ (deltas, drect, false, cleared, dlods, scratch)
+ }
+ };
+
+ if deltas.is_empty() {
None
} else {
- doc.generate_layer_thumbnail_data_url(
- &active.layer_id,
- 64,
- 64,
- Some(scratch.as_ref()),
- )
- .ok()
- };
- let mask_thumb = if mask_changed {
- doc.generate_mask_thumbnail_data_url(
+ // Zero-copy O(N) Arc<TileData> snapshot for background thumbnail worker!
+ let thumb_job = ThumbnailJob {
+ doc_id: active.doc_id.clone(),
+ layer_id: active.layer_id.clone(),
+ doc_w,
+ doc_h,
+ layer_version: layer.grid.layer_version,
+ is_mask: mask_changed,
+ tiles: if mask_changed {
+ layer.grid.mask_tiles.clone()
+ } else {
+ layer.grid.tiles.clone()
+ },
+ mask_default_value: layer.grid.mask_default_value,
+ tint: if mask_changed {
+ None
+ } else {
+ crate::io::compositor_cpu::extract_layer_tint(layer)
+ },
+ scratch: Arc::clone(&scratch),
+ };
+
+ let is_eraser = active.brush.is_effective_eraser();
+ let (action_type, label) = if mask_changed {
+ ("mask", "Mask Stroke")
+ } else if is_eraser {
+ ("erase", "Erase")
+ } else {
+ ("brush", "Brush Stroke")
+ };
+ let entry_id = doc.record_stroke_deltas(
&active.layer_id,
- 64,
- 64,
- Some(scratch.as_ref()),
- )
- .ok()
- .flatten()
- } else {
- None
- };
- if let Some(ref url) = thumb {
- if let Some(l) = doc.layer_mut(&active.layer_id) {
- l.meta.thumbnail_url = Some(url.clone());
- }
+ action_type,
+ label,
+ deltas,
+ Some("local".to_string()),
+ Some(format!("stroke-{}", active.stroke_seed)),
+ );
+ let history = doc.history.snapshot();
+ self.sync_viewport_frustum_locked(&mut mgr);
+ let _ = mgr.enforce_memory_budget();
+
+ Some(PostCommitWork {
+ doc_id: active.doc_id,
+ layer_id: active.layer_id,
+ entry_id,
+ dirty_rect,
+ history,
+ mask_changed,
+ dirty_lods,
+ cleared_coords,
+ scratch,
+ thumb_job,
+ })
}
- if let Some(ref murl) = mask_thumb {
- if let Some(l) = doc.layer_mut(&active.layer_id) {
- l.meta.mask_thumbnail_url = Some(murl.clone());
+ };
+
+ // Step C: Outside documents.write() — batch mipmaps (1 submit!), clear live stroke,
+ // dispatch off-thread thumbnail job (ZERO render-thread PNG encoding!), and emit events!
+ self.frame_dirty_doc_bounds = None;
+
+ if let Some(work) = post_work {
+ if work.mask_changed {
+ self.renderer.invalidate_compositor_cache();
+ self.pending_doc_sync = true;
+ } else {
+ let mgr = self.documents.read();
+ if let Some(doc) = mgr.get_document(&work.doc_id) {
+ if let Some(layer) = doc.layer(&work.layer_id) {
+ self.renderer.regenerate_layer_mipmaps_from_dirty(
+ &work.doc_id,
+ &work.layer_id,
+ &layer.grid,
+ &work.dirty_lods,
+ &work.cleared_coords,
+ Some(work.scratch.as_ref()),
+ );
+ }
}
}
-
- let hist_snap = doc.history.snapshot();
+ self.renderer.clear_live_stroke();
*self.shared_pool_stats.write() = self.renderer.gpu_pool_stats();
self.dirty = true;
- let _ = mgr.enforce_memory_budget();
-
- Some((
- active.doc_id,
- active.layer_id,
- entry_id,
- dirty_rect,
- hist_snap,
- thumb,
- mask_thumb,
- ))
- };
- self.frame_dirty_doc_bounds = None;
+ // Offload PNG thumbnail generation to dedicated background worker thread
+ if let Some(ref tx) = self.thumb_tx {
+ let _ = tx.send(work.thumb_job);
+ }
- if let Some((doc_id, layer_id, entry_id, dirty_rect, history, thumb, mask_thumb)) =
- committed_info
- {
- let committed_pts: Vec<CommittedStrokePoint> = finalized_points
- .into_iter()
- .map(CommittedStrokePoint::from)
- .collect();
- if let Some(eid) = entry_id {
+ let committed_pts: Vec<CommittedStrokePoint> = if self.collab_points_enabled {
+ finalized_points
+ .into_iter()
+ .map(CommittedStrokePoint::from)
+ .collect()
+ } else {
+ Vec::new()
+ };
+ if let Some(eid) = work.entry_id {
let _ = self.event_tx.try_send(EngineEvent::StrokeCommitted {
- doc_id: doc_id.clone(),
- layer_id: layer_id.clone(),
+ doc_id: work.doc_id,
+ layer_id: work.layer_id,
entry_id: eid,
- dirty_rect,
- history: history.clone(),
+ dirty_rect: work.dirty_rect,
+ history: work.history,
points: committed_pts,
});
- }
- let _ = self.event_tx.try_send(EngineEvent::HistoryChanged {
- doc_id: doc_id.clone(),
- history,
- });
- if thumb.is_some() || mask_thumb.is_some() {
- let _ = self.event_tx.try_send(EngineEvent::ThumbnailsUpdated {
- doc_id,
- updates: vec![ThumbnailUpdate {
- layer_id,
- thumbnail_url: thumb,
- mask_thumbnail_url: mask_thumb,
- }],
+ } else {
+ let _ = self.event_tx.try_send(EngineEvent::HistoryChanged {
+ doc_id: work.doc_id,
+ history: work.history,
});
}
+ } else {
+ self.renderer.clear_live_stroke();
+ self.dirty = true;
}
}
- /// Generates ephemeral predicted-head dabs WITHOUT mutating active stroke state or PRNG.
+ /// Generates ephemeral predicted-head dabs for ALL brush types (`Stamp`, `ColorMixingStamp`,
+ /// `NaturalPaint`, and `Ribbon`) WITHOUT mutating active stroke state or PRNG.
fn build_ephemeral_predicted_dabs(&self) -> Vec<GpuBrushDab> {
let Some(ref active) = self.active_gpu_stroke else {
return Vec::new();
};
- if !matches!(active.kind, ActiveStrokeKind::Stamp) {
+ let is_direct_replace = matches!(
+ active.kind,
+ ActiveStrokeKind::NaturalPaint { .. } | ActiveStrokeKind::ColorMixingStamp
+ );
+ // Pure smear brushes pick up canvas pigment rather than depositing fg_color; skip fg preview
+ if is_direct_replace
+ && active.brush.mixing_mode == crate::brush::NaturalMixingMode::Smear
+ {
return Vec::new();
}
let pred_segs = self.stroke_pipeline.build_predicted_head();
@@ -1614,18 +2312,43 @@ impl EngineThreadState {
let mut out = Vec::with_capacity(32);
for seg in &pred_segs {
temp_emitter.emit_segment(seg, None, 0.0, &mut out);
+ if out.len() >= 48 {
+ out.truncate(48);
+ break;
+ }
+ }
+ // Keep predicted head lightweight and visually matched on NaturalPaint / ColorMixingStamp
+ if is_direct_replace {
+ let paint_scale = (active.brush.opacity.clamp(0.05, 1.0)
+ * active.brush.density_of_paint.clamp(0.15, 1.0)
+ * (0.35 + 0.65 * active.brush.amount_of_paint.clamp(0.0, 1.0)))
+ .clamp(0.08, 0.92);
+ for dab in &mut out {
+ dab.color_rgba[3] = (dab.color_rgba[3] * paint_scale).clamp(0.02, 0.92);
+ }
}
out
}
fn run_loop(&mut self) {
while self.running.load(Ordering::Relaxed) {
+ if !self.renderer.is_present() {
+ self.recover_from_device_lost();
+ continue;
+ }
if !self.drain_commands() {
break;
}
self.sync_active_document_if_needed();
- self.drain_tablet_rings();
- self.drain_nav_ring();
+ // Drain nav gestures BEFORE tablet rings so Space+Drag / Middle-Button nav
+ // activates and commits any prior stroke before concurrent stylus packets in the same frame.
+ if !self.drain_nav_ring() {
+ break;
+ }
+ if !self.drain_tablet_rings() {
+ break;
+ }
+ self.flush_pending_stroke_batch();
self.sync_active_document_if_needed();
let now = clock::now_ms();
@@ -1641,24 +2364,135 @@ impl EngineThreadState {
self.dirty = true;
}
- if self.dirty && self.visible && self.viewport.width_px > 0 && self.viewport.height_px > 0
- {
+ let can_render =
+ self.visible && self.viewport.width_px > 0 && self.viewport.height_px > 0;
+ if self.dirty && can_render {
self.render_and_present(now);
- } else if !self.legacy_pending_dabs.is_empty() {
- self.legacy_pending_dabs.clear();
+ } else {
+ if !self.legacy_pending_dabs.is_empty() {
+ self.legacy_pending_dabs.clear();
+ }
+ if !self.dirty || !can_render {
+ // Prevent stale non-rendering hover/out-of-viewport timestamps from polluting
+ // the next active stroke frame's input-to-present latency (I2P).
+ self.newest_input_timestamp_ms = 0.0;
+ }
}
self.flush_throttled_events(clock::now_ms());
- if has_active_sel && !self.dirty {
+ // Drain at most ONE deferred offscreen readback (Brush Preview / Navigator / Timelapse)
+ // only when no live stroke is in progress so live drawing is never stalled.
+ if !self.is_any_stroke_active() {
+ if let Some(deferred) = self.deferred_readback_cmds.pop_front() {
+ self.execute_readback_command(deferred);
+ }
+ }
+
+ let pending_render = self.dirty && can_render;
+ let has_stashed_inputs =
+ !self.merged_samples.is_empty() || !self.stashed_nav_events.is_empty();
+ let has_deferred_readback =
+ !self.deferred_readback_cmds.is_empty() && !self.is_any_stroke_active();
+ if has_deferred_readback || has_stashed_inputs {
+ // Immediately continue next iteration without sleeping
+ } else if has_active_sel && !pending_render {
self.wake.wait_timeout(Duration::from_millis(33));
- } else if !self.dirty && !self.pending_camera_emit && !self.pending_camera_commit {
+ } else if !pending_render
+ && !self.pending_camera_emit
+ && !self.pending_camera_commit
+ && self.pending_wheel_commit_deadline_ms.is_none()
+ {
self.wake.wait_timeout(Duration::from_millis(50));
- } else if !self.dirty {
+ } else if !pending_render && self.pending_wheel_commit_deadline_ms.is_some() {
+ self.wake.wait_timeout(Duration::from_millis(16));
+ } else if !pending_render {
self.wake.wait_timeout(Duration::from_millis(8));
}
}
+ self.stroke_active.store(false, Ordering::SeqCst);
self.running.store(false, Ordering::SeqCst);
+ self.deferred_readback_cmds.clear();
+ // Gracefully drain & stop the background thumbnail worker thread on engine shutdown
+ self.thumb_tx.take();
+ if let Some(worker) = self.thumb_worker.take() {
+ let _ = worker.join();
+ }
+ }
+
+ fn execute_readback_command(&mut self, cmd: EngineCommand) {
+ match cmd {
+ EngineCommand::RenderDocumentFlattened {
+ doc_id,
+ options,
+ reply,
+ } => {
+ // Take a microsecond zero-copy Arc<TileData> snapshot under docs.read() and
+ // drop the read guard BEFORE GPU flattening & readback!
+ let snap_res = {
+ let mgr = self.documents.read();
+ let scratch = Arc::clone(mgr.scratch_backend());
+ let doc_opt = match doc_id.as_deref() {
+ Some(id) => mgr.get_document(id),
+ None => mgr.active_document(),
+ };
+ match doc_opt {
+ Some(doc) => Ok((doc.clone_cow_snapshot(), scratch)),
+ None => Err("No active document available for GPU flatten".to_string()),
+ }
+ };
+ let res = match snap_res {
+ Ok((snapshot, scratch)) => self.renderer.render_document_flattened(
+ &snapshot,
+ Some(scratch.as_ref()),
+ &options,
+ ),
+ Err(e) => Err(e),
+ };
+ let _ = reply.send(res);
+ }
+ EngineCommand::RenderLayerThumbnail {
+ doc_id,
+ layer_id,
+ max_dim,
+ reply,
+ } => {
+ let snap_res = {
+ let mgr = self.documents.read();
+ let scratch = Arc::clone(mgr.scratch_backend());
+ let doc_opt = match doc_id.as_deref() {
+ Some(id) => mgr.get_document(id),
+ None => mgr.active_document(),
+ };
+ match doc_opt {
+ Some(doc) => Ok((doc.clone_cow_snapshot(), scratch)),
+ None => Err("No active document available for GPU thumbnail".to_string()),
+ }
+ };
+ let res = match snap_res {
+ Ok((snapshot, scratch)) => self.renderer.render_layer_thumbnail_gpu(
+ &snapshot,
+ &layer_id,
+ Some(scratch.as_ref()),
+ max_dim,
+ ),
+ Err(e) => Err(e),
+ };
+ let _ = reply.send(res);
+ }
+ EngineCommand::RenderBrushPreview {
+ brush,
+ width,
+ height,
+ reply,
+ } => {
+ let res = self
+ .renderer
+ .render_brush_preview_rgba8(&brush, width, height);
+ let _ = reply.send(res);
+ }
+ _ => {}
+ }
}
fn drain_commands(&mut self) -> bool {
@@ -1667,6 +2501,8 @@ impl EngineThreadState {
EngineCommand::SetViewport(vp) => {
if self.viewport != vp {
self.viewport = vp;
+ self.viewport_commit_pending = true;
+ self.sync_viewport_frustum();
self.dirty = true;
}
}
@@ -1725,53 +2561,13 @@ impl EngineThreadState {
self.renderer.invalidate_compositor_cache();
self.dirty = true;
}
- EngineCommand::RenderDocumentFlattened {
- doc_id,
- options,
- reply,
- } => {
- let res = {
- let mgr = self.documents.read();
- let scratch = Arc::clone(mgr.scratch_backend());
- let doc_opt = match doc_id.as_deref() {
- Some(id) => mgr.get_document(id),
- None => mgr.active_document(),
- };
- match doc_opt {
- Some(doc) => self.renderer.render_document_flattened(
- doc,
- Some(scratch.as_ref()),
- &options,
- ),
- None => Err("No active document available for GPU flatten".to_string()),
- }
- };
- let _ = reply.send(res);
- }
- EngineCommand::RenderLayerThumbnail {
- doc_id,
- layer_id,
- max_dim,
- reply,
- } => {
- let res = {
- let mgr = self.documents.read();
- let scratch = Arc::clone(mgr.scratch_backend());
- let doc_opt = match doc_id.as_deref() {
- Some(id) => mgr.get_document(id),
- None => mgr.active_document(),
- };
- match doc_opt {
- Some(doc) => self.renderer.render_layer_thumbnail_gpu(
- doc,
- &layer_id,
- Some(scratch.as_ref()),
- max_dim,
- ),
- None => Err("No active document available for GPU thumbnail".to_string()),
- }
- };
- let _ = reply.send(res);
+ cmd @ EngineCommand::RenderDocumentFlattened { .. }
+ | cmd @ EngineCommand::RenderLayerThumbnail { .. } => {
+ if self.is_any_stroke_active() {
+ self.deferred_readback_cmds.push_back(cmd);
+ } else {
+ self.execute_readback_command(cmd);
+ }
}
EngineCommand::SetCamera(cam) => {
let sanitized = CameraState {
@@ -1780,6 +2576,7 @@ impl EngineThreadState {
};
if self.camera != sanitized {
self.camera = sanitized;
+ self.sync_viewport_frustum();
self.dirty = true;
}
}
@@ -1808,16 +2605,12 @@ impl EngineThreadState {
EngineCommand::SetMaskMode(enabled) => {
self.mask_mode = enabled;
}
- EngineCommand::RenderBrushPreview {
- brush,
- width,
- height,
- reply,
- } => {
- let res = self
- .renderer
- .render_brush_preview_rgba8(&brush, width, height);
- let _ = reply.send(res);
+ cmd @ EngineCommand::RenderBrushPreview { .. } => {
+ if self.is_any_stroke_active() {
+ self.deferred_readback_cmds.push_back(cmd);
+ } else {
+ self.execute_readback_command(cmd);
+ }
}
EngineCommand::SetGlobalPressureCurve(curve) => {
self.global_pressure_lut = curve.compile_lut();
@@ -1868,7 +2661,9 @@ impl EngineThreadState {
}
self.navigator.cancel();
self.cursor_local_phys = None;
+ self.newest_input_timestamp_ms = 0.0;
} else {
+ self.viewport_commit_pending = true;
self.dirty = true;
}
}
@@ -1876,19 +2671,23 @@ impl EngineThreadState {
EngineCommand::ClearCanvas => {
self.cancel_active_stroke();
self.active_stroke_dabs = 0;
- let cleared_doc = {
+ let cleared_info: Option<(String, crate::history::HistoryStateSnapshot)> = {
let mut mgr = self.documents.write();
if let Some(doc) = mgr.active_document_mut() {
if let Some(aid) = doc.active_layer_id.clone() {
let _ = doc.clear_layer(&aid, true);
}
- true
+ Some((doc.id.clone(), doc.history.snapshot()))
} else {
- false
+ None
}
};
- if cleared_doc {
+ if let Some((doc_id, history)) = cleared_info {
self.pending_doc_sync = true;
+ let _ = self.event_tx.try_send(EngineEvent::HistoryChanged {
+ doc_id,
+ history,
+ });
} else {
self.renderer.clear_canvas();
}
@@ -1908,8 +2707,12 @@ impl EngineThreadState {
*self.shared_pool_stats.write() = self.renderer.gpu_pool_stats();
}
EngineCommand::NotifySurfaceInvalidated => {
- self.renderer.force_reconfigure();
+ // Defer swapchain reconfigure until next frame (after any concurrent SetViewport
+ // updates dimensions) so minimize-restore and WM_DPICHANGED never reconfigure twice!
+ self.renderer.schedule_reconfigure();
+ self.viewport_commit_pending = true;
self.dirty = true;
+ let _ = self.event_tx.try_send(EngineEvent::ViewportInvalidated);
}
EngineCommand::LiquifyBegin {
multi_layer,
@@ -2079,6 +2882,9 @@ impl EngineThreadState {
self.renderer.remote_notify_tile_delta(&layer_id);
self.dirty = true;
}
+ EngineCommand::SetCollabPointsEnabled(enabled) => {
+ self.collab_points_enabled = enabled;
+ }
EngineCommand::Shutdown => {
return false;
}
@@ -2087,8 +2893,14 @@ impl EngineThreadState {
true
}
- fn drain_tablet_rings(&mut self) {
- self.merged_samples.clear();
+ fn drain_tablet_rings(&mut self) -> bool {
+ self.drain_tablet_rings_inner(true)
+ }
+
+ fn drain_tablet_rings_inner(&mut self, allow_commands: bool) -> bool {
+ if !allow_commands && !self.cmd_rx.is_empty() {
+ return true;
+ }
while let Ok(s) = self.consumers.wintab.pop() {
self.merged_samples.push(s);
}
@@ -2096,7 +2908,22 @@ impl EngineThreadState {
self.merged_samples.push(s);
}
if self.merged_samples.is_empty() {
- return;
+ return true;
+ }
+ // Release/Acquire barrier AFTER popping: any command (e.g. SetFullBrushConfig,
+ // SetCamera, SetInteractionPolicy, SyncActiveDocument) sent before these samples were
+ // pushed is now guaranteed visible in `cmd_rx`.
+ if !self.cmd_rx.is_empty() {
+ if !allow_commands {
+ // Keep popped samples stashed in `self.merged_samples` for the next iteration
+ // right after `drain_commands()` runs (never process ahead of pending commands!).
+ return true;
+ }
+ if !self.drain_commands() {
+ self.merged_samples.clear();
+ return false;
+ }
+ self.sync_active_document_if_needed();
}
if self.merged_samples.len() > 1 {
self.merged_samples.sort_by(|a, b| {
@@ -2106,30 +2933,45 @@ impl EngineThreadState {
});
}
- let samples = std::mem::take(&mut self.merged_samples);
+ let mut samples = std::mem::take(&mut self.merged_samples);
for sample in &samples {
self.process_tablet_sample(*sample);
}
+ samples.clear();
self.merged_samples = samples;
+ true
}
fn process_tablet_sample(&mut self, sample: NativeInputSample) {
- self.last_tablet_sample_ms = sample.timestamp_ms;
- if sample.timestamp_ms > self.newest_input_timestamp_ms {
+ if sample.backend == 1 || sample.backend == 2 {
+ self.last_tablet_sample_ms = sample.timestamp_ms;
+ if sample.backend == 1 {
+ self.last_wintab_sample_ms = sample.timestamp_ms;
+ }
+ }
+ if sample.phase == 1 {
+ // Reset any prior hover timestamp cleanly on pen-down so I2P reflects genuine stroke latency
+ self.newest_input_timestamp_ms = sample.timestamp_ms;
+ } else if sample.phase != 4 && sample.timestamp_ms > self.newest_input_timestamp_ms {
self.newest_input_timestamp_ms = sample.timestamp_ms;
}
if sample.phase == 4 {
- if self.is_any_stroke_active() {
+ if self.is_any_stroke_active()
+ && (self.active_stroke_backend == 0 || self.active_stroke_backend == sample.backend)
+ {
self.finish_and_commit_gpu_stroke(sample.timestamp_ms);
}
- if self.cursor_local_phys.is_some() {
- self.cursor_local_phys = None;
- self.dirty = true;
+ if !self.is_any_stroke_active() {
+ if self.cursor_local_phys.is_some() {
+ self.cursor_local_phys = None;
+ self.dirty = true;
+ }
+ self.newest_input_timestamp_ms = 0.0;
+ self.latest_pointer_doc = None;
+ self.latest_pointer_pressure = 0.0;
+ self.pointer_stat_dirty = true;
}
- self.latest_pointer_doc = None;
- self.latest_pointer_pressure = 0.0;
- self.pointer_stat_dirty = true;
return;
}
@@ -2169,29 +3011,83 @@ impl EngineThreadState {
return;
}
+ let space_held = (sample.buttons & 0x0400) != 0 && !self.hit_test.text_input_focused();
+ let ctrl_or_shift_with_alt =
+ (sample.buttons & 0x0200) != 0 && (sample.buttons & (0x0100 | 0x0800)) != 0;
+
match sample.phase {
1 => {
+ // Never start a brush stroke while Space navigation or Ctrl/Shift+Alt brush resize is held
+ if space_held || ctrl_or_shift_with_alt {
+ return;
+ }
+ // Never let a stray mouse down interrupt an active stylus stroke
+ if sample.backend == 3
+ && self.is_any_stroke_active()
+ && (self.active_stroke_backend == 1 || self.active_stroke_backend == 2)
+ {
+ return;
+ }
if self
.hit_test
.should_capture_native_stroke(sample.phys_x, sample.phys_y)
{
+ // Cleanly commit any previous active stroke (e.g. Mouse -> Stylus handoff)
+ // before beginning the new stroke so no stroke or CoW undo entry is ever dropped.
+ if self.is_any_stroke_active() {
+ self.finish_and_commit_gpu_stroke(sample.timestamp_ms);
+ }
self.begin_native_gpu_stroke(doc_x as f64, doc_y as f64, sample);
+ self.active_stroke_backend = if self.is_any_stroke_active() {
+ sample.backend
+ } else {
+ 0
+ };
}
}
2 => {
- if self.is_any_stroke_active() {
+ if self.is_any_stroke_active()
+ && (self.active_stroke_backend == 0
+ || self.active_stroke_backend == sample.backend)
+ {
self.push_native_gpu_stroke_move(doc_x as f64, doc_y as f64, sample);
}
}
- 3 if self.is_any_stroke_active() => {
- self.finish_and_commit_gpu_stroke(sample.timestamp_ms);
+ 3 => {
+ if self.is_any_stroke_active()
+ && (self.active_stroke_backend == 0
+ || self.active_stroke_backend == sample.backend)
+ {
+ self.finish_and_commit_gpu_stroke(sample.timestamp_ms);
+ }
}
_ => {}
}
}
- fn drain_nav_ring(&mut self) {
- while let Ok(evt) = self.consumers.nav.pop() {
+ fn drain_nav_ring(&mut self) -> bool {
+ self.drain_nav_ring_inner(true)
+ }
+
+ fn drain_nav_ring_inner(&mut self, allow_commands: bool) -> bool {
+ loop {
+ let evt = if let Some(stashed) = self.stashed_nav_events.pop_front() {
+ stashed
+ } else if let Ok(e) = self.consumers.nav.pop() {
+ e
+ } else {
+ break;
+ };
+ if !self.cmd_rx.is_empty() {
+ if !allow_commands {
+ self.stashed_nav_events.push_front(evt);
+ break;
+ }
+ if !self.drain_commands() {
+ return false;
+ }
+ self.sync_active_document_if_needed();
+ }
match evt {
NativeNavEvent::Hover {
phys_x,
@@ -2201,12 +3097,14 @@ impl EngineThreadState {
if timestamp_ms - self.last_tablet_sample_ms < 120.0 {
continue;
}
- if timestamp_ms > self.newest_input_timestamp_ms {
- self.newest_input_timestamp_ms = timestamp_ms;
- }
let in_vp = self.viewport.contains_phys(phys_x, phys_y);
let in_unoccluded = self.hit_test.is_unoccluded_canvas_point(phys_x, phys_y);
if in_vp {
+ if !self.is_any_stroke_active()
+ && timestamp_ms > self.newest_input_timestamp_ms
+ {
+ self.newest_input_timestamp_ms = timestamp_ms;
+ }
let local_phys = self.viewport.phys_to_local_phys(phys_x, phys_y);
self.cursor_local_phys = Some(local_phys);
self.cursor_over_occluded = !in_unoccluded;
@@ -2226,6 +3124,7 @@ impl EngineThreadState {
}
}
NativeNavEvent::HoverLeave => {
+ self.newest_input_timestamp_ms = 0.0;
if self.cursor_local_phys.is_some() {
self.cursor_local_phys = None;
self.latest_pointer_doc = None;
@@ -2299,6 +3198,10 @@ impl EngineThreadState {
if timestamp_ms > self.newest_input_timestamp_ms {
self.newest_input_timestamp_ms = timestamp_ms;
}
+ // Commit any active stroke cleanly before camera zoom/scroll moves the canvas.
+ if self.is_any_stroke_active() {
+ self.finish_and_commit_gpu_stroke(timestamp_ms);
+ }
let (lx, ly) = self.viewport.phys_to_local_css(phys_x, phys_y);
let changed = if (self.policy.wheel_mode == WheelNavMode::Scroll
|| self.policy.is_webtoon_mode)
@@ -2317,18 +3220,37 @@ impl EngineThreadState {
if changed {
self.dirty = true;
self.pending_camera_emit = true;
- self.pending_camera_commit = true;
+ // Debounce React state commit (~120ms after last wheel tick) so wheel
+ // zooming stays 120–240Hz without forcing App re-renders per notch.
+ self.pending_wheel_commit_deadline_ms = Some(clock::now_ms() + 120.0);
}
}
NativeNavEvent::MouseDraw {
phys_x,
phys_y,
phase,
+ shift_held,
timestamp_ms,
} => {
- if timestamp_ms - self.last_tablet_sample_ms < 250.0 {
+ // Never allow mouse events to interfere with an active stylus stroke.
+ if self.active_stroke_backend == 1 || self.active_stroke_backend == 2 {
continue;
}
+ // Always deliver move/up for an already-active mouse stroke so hover packets
+ // never drop drag/release; gate only fresh mouse-down against WinTab CXO_SYSTEM
+ // echo using the same 100ms window as `ll_mouse_proc` (Windows Ink synthesized
+ // mouse events carry MI_WP_SIGNATURE and are already filtered in `ll_mouse_proc`).
+ let is_active_mouse_continuation =
+ (phase == 2 || phase == 3) && self.active_stroke_backend == 3;
+ if !is_active_mouse_continuation
+ && timestamp_ms - self.last_wintab_sample_ms < 100.0
+ {
+ continue;
+ }
+ let mut buttons: u16 = if phase == 3 { 0 } else { 1 };
+ if shift_held {
+ buttons |= 0x0100;
+ }
self.process_tablet_sample(NativeInputSample {
phys_x,
phys_y,
@@ -2337,19 +3259,61 @@ impl EngineThreadState {
tilt_y: 0.0,
twist: 0.0,
timestamp_ms,
- buttons: if phase == 3 { 0 } else { 1 },
+ buttons,
phase,
backend: 3,
});
}
}
}
+ true
}
- fn render_and_present(&mut self, frame_start_ms: f64) {
+ fn render_and_present(&mut self, _frame_start_ms: f64) {
+ // Phase 7 Input-to-Photon optimization: acquire the DXGI swapchain surface texture
+ // (waiting on the waitable frame latency object / VSync) BEFORE performing the final
+ // non-blocking drain of pending nav/tablet rings + flushing stroke dabs so samples
+ // arriving during VSync wait are rendered in the VERY NEXT scanout (-8..16.6 ms latency)!
+ let acquired = match self.renderer.acquire_frame_target(&self.viewport) {
+ Ok(frame) => frame,
+ Err(outcome) => {
+ match outcome {
+ RenderOutcome::Skipped => {
+ self.dirty = false;
+ self.newest_input_timestamp_ms = 0.0;
+ }
+ RenderOutcome::NeedsReconfigure => {
+ if !self.renderer.force_reconfigure() {
+ self.dirty = false;
+ }
+ }
+ RenderOutcome::DeviceLost => {
+ self.recover_from_device_lost();
+ }
+ RenderOutcome::Presented => {}
+ }
+ return;
+ }
+ };
+
+ // Measure pure CPU+GPU frame render time starting right after VSync acquire
+ let frame_start_ms = clock::now_ms();
+
+ // Final non-blocking post-acquire drain (safe: skips cmd_rx so swapchain cannot reconfigure)
+ if self.cmd_rx.is_empty() {
+ let _ = self.drain_nav_ring_inner(false);
+ let _ = self.drain_tablet_rings_inner(false);
+ self.flush_pending_stroke_batch();
+ self.sync_active_document_if_needed();
+ }
+
let cursor_suppressed =
self.cursor_over_occluded || self.navigator.is_active() || self.policy.modal_open;
let stroke_active = self.is_any_stroke_active();
+ let is_mask_stroke = self
+ .active_gpu_stroke
+ .as_ref()
+ .is_some_and(|s| s.is_mask_stroke);
let dabs_are_eraser = self
.active_gpu_stroke
.as_ref()
@@ -2362,7 +3326,8 @@ impl EngineThreadState {
let mgr = self.documents.read();
let scratch = Arc::clone(mgr.scratch_backend());
if let Some(doc) = mgr.active_document() {
- self.renderer.render_document_frame_with_brush(
+ self.renderer.render_document_frame_into_acquired(
+ acquired,
doc,
Some(scratch.as_ref()),
&self.display_config,
@@ -2371,6 +3336,7 @@ impl EngineThreadState {
&self.legacy_pending_dabs,
dabs_are_eraser,
stroke_active,
+ is_mask_stroke,
&predicted_dabs,
dirty_doc_bounds,
&self.cursor_cfg,
@@ -2378,7 +3344,8 @@ impl EngineThreadState {
cursor_suppressed,
)
} else {
- self.renderer.render_frame(
+ self.renderer.render_frame_into_acquired(
+ acquired,
&self.viewport,
&self.camera,
self.show_checkerboard,
@@ -2394,6 +3361,10 @@ impl EngineThreadState {
match outcome {
RenderOutcome::Presented => {
+ if self.viewport_commit_pending {
+ self.renderer.commit_surface_viewport();
+ self.viewport_commit_pending = false;
+ }
self.legacy_pending_dabs.clear();
self.dirty = false;
@@ -2418,20 +3389,78 @@ impl EngineThreadState {
}
self.total_frames = self.total_frames.saturating_add(1);
- self.fps_window_frames = self.fps_window_frames.saturating_add(1);
- let window_elapsed = after_ms - self.fps_window_start_ms;
- if window_elapsed >= 250.0 {
- self.measured_fps =
- (self.fps_window_frames as f64 / (window_elapsed / 1000.0)) as f32;
- self.fps_window_frames = 0;
- self.fps_window_start_ms = after_ms;
+
+ // Track active frame intervals (< 150 ms apart) so on-demand idle sleeps never
+ // divide 1–2 dirty frames by prior idle time and falsely report "3 FPS"!
+ let throughput_fps =
+ (1000.0 / self.ema_frame_time_ms.max(0.5)).min(MAX_DISPLAY_FPS);
+ if self.last_present_ms > 0.0 {
+ let dt_ms = after_ms - self.last_present_ms;
+ if dt_ms > 0.1 && dt_ms < ACTIVE_FRAME_GAP_THRESHOLD_MS {
+ self.ema_active_frame_interval_ms = if self.active_interval_count == 0 {
+ dt_ms as f32
+ } else {
+ self.ema_active_frame_interval_ms * 0.75 + (dt_ms as f32) * 0.25
+ };
+ self.active_interval_count = self.active_interval_count.saturating_add(1);
+
+ if self.active_interval_count >= 2 {
+ let cadence_fps = (1000.0
+ / self.ema_active_frame_interval_ms.max(0.5))
+ .min(MAX_DISPLAY_FPS);
+ // If frame render time itself is fast (< 16 ms) and intervals are sparse
+ // purely due to slow on-demand input arrival, report active throughput.
+ self.measured_fps =
+ if self.ema_frame_time_ms < 16.0 && cadence_fps < 30.0 {
+ throughput_fps
+ } else {
+ cadence_fps
+ };
+ } else {
+ // First 1-2 frames after an idle gap: derive cleanly from throughput
+ self.measured_fps = throughput_fps;
+ }
+ } else {
+ // Prior idle gap >= 150 ms: reset active interval tracker & use throughput
+ self.active_interval_count = 0;
+ self.ema_active_frame_interval_ms = 0.0;
+ self.measured_fps = throughput_fps;
+ }
+ } else {
+ self.active_interval_count = 0;
+ self.ema_active_frame_interval_ms = 0.0;
+ self.measured_fps = throughput_fps;
+ }
+ self.last_present_ms = after_ms;
+
+ // Keep shared_diag numeric counters fresh in-place (zero allocation, ~15ns)
+ // so handle.diagnostics() reflects rendered frames immediately without IPC spam.
+ let (sw, sh) = self.renderer.swapchain_size();
+ let (dw, dh) = self.renderer.doc_size();
+ if let Ok(mut g) = self.shared_diag.lock() {
+ g.ready = true;
+ g.fps = self.measured_fps;
+ g.frame_time_ms = self.ema_frame_time_ms;
+ g.input_to_present_ms = self.ema_input_latency_ms;
+ g.swapchain_width = sw;
+ g.swapchain_height = sh;
+ g.doc_width = dw;
+ g.doc_height = dh;
+ g.active_stroke_dabs = self.active_stroke_dabs;
+ g.total_frames_rendered = self.total_frames;
+ g.is_idle = false;
}
}
RenderOutcome::Skipped => {
self.dirty = false;
+ self.newest_input_timestamp_ms = 0.0;
}
RenderOutcome::NeedsReconfigure => {
- self.renderer.force_reconfigure();
+ if !self.renderer.force_reconfigure() {
+ // Surface is not configured yet (e.g. awaiting initial physical viewport);
+ // clear dirty so the render loop doesn't busy-spin until SetViewport arrives.
+ self.dirty = false;
+ }
}
RenderOutcome::DeviceLost => {
self.recover_from_device_lost();
@@ -2440,28 +3469,51 @@ impl EngineThreadState {
}
fn recover_from_device_lost(&mut self) {
- let (doc_w, doc_h) = self.renderer.doc_size();
- let vram_budget = self.renderer.vram_budget_bytes();
- let target = self.renderer.surface_target_for_recovery();
+ // Extract recovery parameters and DROP the old GpuRenderer FIRST so DX12 frees
+ // the old device, swapchain, tile pool, and compositor targets BEFORE constructing
+ // the replacement (eliminating 2× peak VRAM spikes during recovery!).
+ let (doc_w, doc_h, vram_budget, target) = if let Some(old) = self.renderer.0.take() {
+ let (dw, dh) = old.doc_size();
+ let vb = old.vram_budget_bytes();
+ let tgt = old.surface_target_for_recovery();
+ drop(old);
+ (dw, dh, vb, tgt)
+ } else if let Some(params) = self.pending_recovery.take() {
+ params
+ } else {
+ return;
+ };
+
+ let target_retry = target.clone();
match GpuRenderer::new_with_vram(target, doc_w, doc_h, vram_budget) {
Ok(mut fresh) => {
if self.viewport.width_px > 0 && self.viewport.height_px > 0 {
fresh.resize_surface(self.viewport.width_px, self.viewport.height_px);
}
- self.renderer = fresh;
+ self.renderer.0 = Some(fresh);
*self.shared_pool_stats.write() = self.renderer.gpu_pool_stats();
self.device_lost_recoveries = self.device_lost_recoveries.saturating_add(1);
self.cancel_active_stroke();
self.pending_doc_sync = true;
+ self.viewport_commit_pending = true;
self.dirty = true;
}
Err(_) => {
+ self.pending_recovery = Some((doc_w, doc_h, vram_budget, target_retry));
std::thread::sleep(Duration::from_millis(100));
}
}
}
fn flush_throttled_events(&mut self, now_ms: f64) {
+ if let Some(deadline_ms) = self.pending_wheel_commit_deadline_ms {
+ if now_ms >= deadline_ms {
+ self.pending_wheel_commit_deadline_ms = None;
+ self.pending_camera_emit = true;
+ self.pending_camera_commit = true;
+ }
+ }
+
if self.pending_camera_emit
&& (self.pending_camera_commit || now_ms - self.last_camera_emit_ms >= 16.0)
{
@@ -2469,10 +3521,16 @@ impl EngineThreadState {
self.pending_camera_emit = false;
self.pending_camera_commit = false;
self.last_camera_emit_ms = now_ms;
- let _ = self.event_tx.try_send(EngineEvent::CameraChanged {
+ let evt = EngineEvent::CameraChanged {
camera: self.camera,
commit,
- });
+ };
+ if commit {
+ self.sync_viewport_frustum();
+ let _ = self.event_tx.try_send(evt);
+ } else {
+ self.send_throttled_event(evt);
+ }
}
if self.pointer_stat_dirty && now_ms - self.last_pointer_stat_ms >= 33.0 {
@@ -2482,16 +3540,28 @@ impl EngineThreadState {
Some((x, y)) => (Some(x), Some(y)),
None => (None, None),
};
- let _ = self.event_tx.try_send(EngineEvent::PointerStat {
+ self.send_throttled_event(EngineEvent::PointerStat {
doc_x,
doc_y,
pressure: self.latest_pointer_pressure,
});
}
- if now_ms - self.last_diag_emit_ms >= 250.0 {
+ let is_idle = self.total_frames == 0
+ || (self.last_present_ms > 0.0
+ && now_ms - self.last_present_ms >= IDLE_DISPLAY_TIMEOUT_MS);
+ let idle_changed = is_idle != self.was_idle_diag;
+ if is_idle && !self.was_idle_diag && self.total_frames > 0 && !self.is_any_stroke_active() {
+ // Reclaim oversized resize slack & unused nested compositor stacks once idle.
+ self.renderer.trim_compositor_on_idle();
+ }
+ let should_emit_diag = now_ms - self.last_diag_emit_ms >= 250.0
+ || (idle_changed && now_ms - self.last_diag_emit_ms >= 50.0);
+
+ if should_emit_diag {
self.last_diag_emit_ms = now_ms;
- let fps = if now_ms - self.fps_window_start_ms > 600.0 && self.fps_window_frames == 0 {
+ self.was_idle_diag = is_idle;
+ let fps = if self.total_frames == 0 {
0.0
} else {
self.measured_fps
@@ -2524,11 +3594,12 @@ impl EngineThreadState {
gpu_tiles_capacity: pool_stats.slots_capacity,
stack_cache_hits: cache_stats.cache_hits,
stack_cache_rebuilds: cache_stats.below_rebuilds + cache_stats.above_rebuilds,
+ is_idle,
};
if let Ok(mut g) = self.shared_diag.lock() {
*g = diag.clone();
}
- let _ = self.event_tx.try_send(EngineEvent::Diagnostics(diag));
+ self.send_throttled_event(EngineEvent::Diagnostics(diag));
}
}
}
diff --git a/crates/ink-engine/src/gpu.rs b/crates/ink-engine/src/gpu.rs
index b1f3020..a39e570 100644
--- a/crates/ink-engine/src/gpu.rs
+++ b/crates/ink-engine/src/gpu.rs
@@ -10,11 +10,13 @@ use crate::brush::{
StrokeDabEmitter,
};
use crate::compositor::{
- CompositorDisplayConfig, DocBounds, FlattenOptions, LiveGpuStrokeOverlay, StackCacheStats,
- WgpuCompositor,
+ CompositorDisplayConfig, DocBounds, FlattenOptions, LiveGpuStrokeOverlay, ScissorRect,
+ StackCacheStats, WgpuCompositor,
};
use crate::document::{CanvasColorMode, CanvasDimensions, Document, LayerNode};
-use crate::memory::{GpuPoolStats, GpuTileKey, GpuTilePool, ScratchBackend};
+use crate::memory::{
+ regenerate_grid_lods_batched, GpuPoolStats, GpuTileKey, GpuTilePool, ScratchBackend,
+};
use crate::collab::{RemotePeerDraftManager, RemoteStrokePoint, RemoteStrokeStartParams};
use crate::natural_paint::{
BristleRibbonSimulator, CommittedNaturalPaintBatch, GpuBristleCapsule, RibbonMeshBuilder,
@@ -33,6 +35,7 @@ use bytemuck::{Pod, Zeroable};
use std::borrow::Cow;
use std::collections::HashMap;
use std::ffi::c_void;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
#[repr(C)]
@@ -76,11 +79,19 @@ pub enum RenderOutcome {
DeviceLost,
}
+/// Swapchain frame target acquired BEFORE the final post-VSync input drain so samples arriving
+/// during the DXGI frame-latency wait are rendered into the very next display scanout.
+pub enum AcquiredFrame {
+ Surface(wgpu::SurfaceTexture),
+ Headless,
+}
+
enum OutputTarget {
Surface {
surface: wgpu::Surface<'static>,
config: wgpu::SurfaceConfiguration,
configured: bool,
+ pending_reconfigure: bool,
visual_ptr: usize,
on_configured: Arc<dyn Fn() + Send + Sync>,
},
@@ -93,10 +104,20 @@ enum OutputTarget {
},
}
+/// Lazily-allocated Phase 1 PoC single-texture canvas fallback (zero VRAM when a real `Document` exists).
+struct LegacyDocSurface {
+ _texture: wgpu::Texture,
+ view: wgpu::TextureView,
+ viewport_bind_group: wgpu::BindGroup,
+ width: u32,
+ height: u32,
+}
+
pub struct GpuRenderer {
instance: wgpu::Instance,
adapter: wgpu::Adapter,
device: wgpu::Device,
+ device_error_flag: Arc<AtomicBool>,
queue: wgpu::Queue,
output: OutputTarget,
@@ -104,16 +125,14 @@ pub struct GpuRenderer {
present_mode_label: String,
composition_mode_label: String,
- // Document canvas surface (single Rgba8Unorm GPU texture for Phase 1 PoC)
+ // Document canvas surface (lazily allocated ONLY for Phase 1 PoC fallback when no Document exists)
doc_width: u32,
doc_height: u32,
- doc_texture: wgpu::Texture,
- doc_view: wgpu::TextureView,
+ legacy_doc: Option<LegacyDocSurface>,
// Viewport compositor pipeline
viewport_uniform_buf: wgpu::Buffer,
viewport_bgl: wgpu::BindGroupLayout,
- viewport_bind_group: wgpu::BindGroup,
viewport_pipeline: wgpu::RenderPipeline,
doc_sampler_linear: wgpu::Sampler,
doc_sampler_nearest: wgpu::Sampler,
@@ -207,6 +226,15 @@ impl GpuRenderer {
}))
.map_err(|e| format!("Failed to create DX12 wgpu device: {e}"))?;
+ let device_error_flag = Arc::new(AtomicBool::new(false));
+ {
+ let flag = Arc::clone(&device_error_flag);
+ device.on_uncaptured_error(Arc::new(move |err| {
+ eprintln!("[ink-engine] Uncaptured wgpu device error: {err}");
+ flag.store(true, Ordering::Release);
+ }));
+ }
+
let (output, surface_format, present_mode_label, composition_mode_label) =
if let Some(surface) = raw_surface {
let caps = surface.get_capabilities(&adapter);
@@ -232,6 +260,7 @@ impl GpuRenderer {
surface,
config,
configured: false,
+ pending_reconfigure: false,
visual_ptr: visual_ptr_opt.unwrap_or(0),
on_configured: on_configured_opt.unwrap_or_else(|| Arc::new(|| {})),
},
@@ -274,7 +303,6 @@ impl GpuRenderer {
let max_dim = device.limits().max_texture_dimension_2d.min(16384);
let doc_w = doc_width.clamp(1, max_dim);
let doc_h = doc_height.clamp(1, max_dim);
- let (doc_texture, doc_view) = Self::create_doc_texture(&device, doc_w, doc_h);
let doc_sampler_linear = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("ink-doc-sampler-linear"),
@@ -339,14 +367,6 @@ impl GpuRenderer {
},
],
});
- let viewport_bind_group = Self::create_viewport_bind_group(
- &device,
- &viewport_bgl,
- &viewport_uniform_buf,
- &doc_view,
- &doc_sampler_linear,
- &doc_sampler_nearest,
- );
let viewport_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("ink-viewport-shader"),
source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(VIEWPORT_SHADER_WGSL)),
@@ -596,10 +616,11 @@ impl GpuRenderer {
let tool_preview = GpuToolPreviewOverlay::new(&device, surface_format);
let remote_drafts = RemotePeerDraftManager::new(&device, surface_format);
- let mut renderer = Self {
+ let renderer = Self {
instance,
adapter,
device,
+ device_error_flag,
queue,
output,
adapter_name,
@@ -607,11 +628,9 @@ impl GpuRenderer {
composition_mode_label,
doc_width: doc_w,
doc_height: doc_h,
- doc_texture,
- doc_view,
+ legacy_doc: None,
viewport_uniform_buf,
viewport_bgl,
- viewport_bind_group,
viewport_pipeline,
doc_sampler_linear,
doc_sampler_nearest,
@@ -635,7 +654,6 @@ impl GpuRenderer {
tool_preview,
remote_drafts,
};
- renderer.clear_canvas();
Ok(renderer)
}
@@ -680,10 +698,15 @@ impl GpuRenderer {
}
fn pick_present_mode(modes: &[wgpu::PresentMode]) -> wgpu::PresentMode {
- if modes.contains(&wgpu::PresentMode::Mailbox) {
+ // Prefer Fifo with `desired_maximum_frame_latency = 1` + DXGI waitable latency object
+ // + post-acquire input drain: paces cleanly to native display refresh rate (60–360 Hz)
+ // with zero discarded Mailbox frames / 100% GPU hover burn and minimal input-to-photon!
+ if modes.contains(&wgpu::PresentMode::Fifo) {
+ wgpu::PresentMode::Fifo
+ } else if modes.contains(&wgpu::PresentMode::Mailbox) {
wgpu::PresentMode::Mailbox
} else {
- wgpu::PresentMode::Fifo
+ modes.first().copied().unwrap_or(wgpu::PresentMode::Fifo)
}
}
@@ -811,6 +834,18 @@ impl GpuRenderer {
self.tile_pool.stats()
}
+ pub fn last_composite_scissor(&self) -> Option<ScissorRect> {
+ self.compositor.last_composite_scissor()
+ }
+
+ pub fn doc_mask_rebuilds(&self) -> u64 {
+ self.compositor.doc_mask_rebuilds()
+ }
+
+ pub fn selection_vp_mask_rebuilds(&self) -> u64 {
+ self.selection_overlay.vp_mask_rebuilds()
+ }
+
pub fn vram_budget_bytes(&self) -> u64 {
self.vram_budget_bytes
}
@@ -918,6 +953,10 @@ impl GpuRenderer {
);
}
+ pub fn touched_stroke_coords(&self) -> Vec<TileCoord> {
+ self.brush_engine.touched_tile_coords()
+ }
+
pub fn stamp_gpu_stroke_dabs(
&mut self,
primary_dabs: &[GpuBrushDab],
@@ -1226,6 +1265,12 @@ impl GpuRenderer {
)
}
+ #[inline]
+ pub fn set_natural_paint_stroke_rand_offset(&mut self, offset: [f32; 2]) {
+ self.brush_engine
+ .set_natural_paint_stroke_rand_offset(offset);
+ }
+
#[allow(clippy::type_complexity)]
pub fn dispatch_color_mixing_dabs(
&mut self,
@@ -1233,20 +1278,34 @@ impl GpuRenderer {
active_layer: &LayerNode,
dabs: &[GpuBrushDab],
scratch: Option<&dyn ScratchBackend>,
+ ) -> (Vec<TileCoord>, Option<(f32, f32, f32, f32)>) {
+ self.dispatch_color_mixing_dabs_with_secondary(doc, active_layer, dabs, &[], scratch)
+ }
+
+ #[allow(clippy::type_complexity)]
+ pub fn dispatch_color_mixing_dabs_with_secondary(
+ &mut self,
+ doc: &Document,
+ active_layer: &LayerNode,
+ dabs: &[GpuBrushDab],
+ secondary_dabs: &[GpuBrushDab],
+ scratch: Option<&dyn ScratchBackend>,
) -> (Vec<TileCoord>, Option<(f32, f32, f32, f32)>) {
self.tile_pool.begin_frame();
self.selection_overlay
.sync_from_mask(&self.device, &self.queue, doc.selection.as_ref());
- self.brush_engine.dispatch_color_mixing_dabs_with_selection(
- &self.device,
- &self.queue,
- &mut self.tile_pool,
- doc,
- active_layer,
- dabs,
- scratch,
- Some(&self.selection_overlay),
- )
+ self.brush_engine
+ .dispatch_color_mixing_dabs_with_dual_and_selection(
+ &self.device,
+ &self.queue,
+ &mut self.tile_pool,
+ doc,
+ active_layer,
+ dabs,
+ secondary_dabs,
+ scratch,
+ Some(&self.selection_overlay),
+ )
}
pub fn commit_natural_paint_to_layer(
@@ -1406,15 +1465,29 @@ impl GpuRenderer {
} else if preview_brush.is_color_mixing_stamp_brush() {
let metrics = self.resolve_brush_tip_metrics(&preview_brush);
let mut emitter = StrokeDabEmitter::new(preview_brush.clone(), 0x51A0_9999, metrics.0, metrics.1);
+ let mut sec_emitter = preview_brush.build_secondary_brush_config().map(|sc| {
+ let sm = self.resolve_brush_tip_metrics(&sc);
+ StrokeDabEmitter::new(sc, 0x51A0_AAAA, sm.0, sm.1)
+ });
let segs = polyline_to_bezier_segments(&pts, 0.0);
let mut dabs = Vec::with_capacity(256);
+ let mut s_dabs = Vec::with_capacity(256);
emitter.emit_initial_point(&pts[0], None, 0.0, &mut dabs);
+ if let Some(ref mut se) = sec_emitter {
+ se.emit_initial_point(&pts[0], None, 0.0, &mut s_dabs);
+ }
for seg in &segs {
emitter.emit_segment(seg, None, 0.0, &mut dabs);
+ if let Some(ref mut se) = sec_emitter {
+ se.emit_segment(seg, None, 0.0, &mut s_dabs);
+ }
}
self.begin_natural_paint_stroke(&doc.id, &layer_id, w, h, preview_brush.clone());
+ self.set_natural_paint_stroke_rand_offset(emitter.stroke_grain_offset);
if let Some(layer) = doc.layer(&layer_id).cloned() {
- let _ = self.dispatch_color_mixing_dabs(&doc, &layer, &dabs, None);
+ let _ = self.dispatch_color_mixing_dabs_with_secondary(
+ &doc, &layer, &dabs, &s_dabs, None,
+ );
}
let batch = self.commit_natural_paint_to_layer()?;
if let Some(layer) = doc.layer_mut(&layer_id) {
@@ -1475,70 +1548,75 @@ impl GpuRenderer {
}
/// Regenerates dirty LOD 1..3 compute mipmap tiles directly on GPU for `layer_id`
- /// and evicts any LOD 0 tiles that became completely transparent.
+ /// in **ONE batched `CommandEncoder` + ONE `queue.submit`** and evicts any LOD 0 tiles
+ /// that became completely transparent.
+ ///
+ /// Guarantees every existing sibling child tile in `grid.tiles` (and child LOD 1..2 tiles)
+ /// is resident and pinned before `cs_downsample`, so evicted siblings can NEVER erase
+ /// a quadrant to transparent.
pub fn regenerate_layer_mipmaps(
&mut self,
doc_id: &str,
layer_id: &str,
grid: &mut SparseLayerGrid,
cleared_coords: &[TileCoord],
+ scratch: Option<&dyn ScratchBackend>,
) {
- for &coord in cleared_coords {
- let key = GpuTileKey {
- doc_id: doc_id.to_string(),
- layer_id: layer_id.to_string(),
- lod: 0,
- coord,
- };
- self.tile_pool.evict_key(&key);
- }
+ let dirty_lods: [Vec<TileCoord>; 3] = [
+ grid.dirty_lods[0].drain().collect(),
+ grid.dirty_lods[1].drain().collect(),
+ grid.dirty_lods[2].drain().collect(),
+ ];
+ self.regenerate_layer_mipmaps_from_dirty(
+ doc_id,
+ layer_id,
+ grid,
+ &dirty_lods,
+ cleared_coords,
+ scratch,
+ );
+ }
- let ver = grid.layer_version;
- for lod_idx in 0..3usize {
- let target_lod = (lod_idx + 1) as u8;
- let dirty_coords: Vec<TileCoord> = grid.dirty_lods[lod_idx].drain().collect();
- for parent_coord in dirty_coords {
- let cx = parent_coord.tx * 2;
- let cy = parent_coord.ty * 2;
- let child_coords = [
- TileCoord::new(cx, cy),
- TileCoord::new(cx + 1, cy),
- TileCoord::new(cx, cy + 1),
- TileCoord::new(cx + 1, cy + 1),
- ];
- let mut child_slots = [None; 4];
- let mut any_child = false;
- for (qi, cc) in child_coords.iter().enumerate() {
- let ckey = GpuTileKey {
- doc_id: doc_id.to_string(),
- layer_id: layer_id.to_string(),
- lod: target_lod - 1,
- coord: *cc,
- };
- if let Some(slot) = self.tile_pool.get_slot(&ckey) {
- child_slots[qi] = Some(slot);
- any_child = true;
- }
- }
- let pkey = GpuTileKey {
- doc_id: doc_id.to_string(),
- layer_id: layer_id.to_string(),
- lod: target_lod,
- coord: parent_coord,
+ /// Read-only-grid variant of [`Self::regenerate_layer_mipmaps`] accepting already-drained
+ /// `dirty_lods` so `documents.write()` can be released BEFORE submitting mipmap GPU work.
+ pub fn regenerate_layer_mipmaps_from_dirty(
+ &mut self,
+ doc_id: &str,
+ layer_id: &str,
+ grid: &SparseLayerGrid,
+ dirty_lods: &[Vec<TileCoord>; 3],
+ cleared_coords: &[TileCoord],
+ scratch: Option<&dyn ScratchBackend>,
+ ) {
+ if !cleared_coords.is_empty() {
+ let doc_key = self.tile_pool.intern_doc(doc_id);
+ let layer_key = self.tile_pool.intern_layer(layer_id);
+ for &coord in cleared_coords {
+ let key = GpuTileKey {
+ doc_id: doc_key,
+ layer_id: layer_key,
+ lod: 0,
+ coord,
};
- if any_child {
- self.tile_pool.generate_mipmap_tile(
- &self.device,
- &self.queue,
- pkey,
- child_slots,
- ver,
- );
- } else {
- self.tile_pool.evict_key(&pkey);
- }
+ self.tile_pool.evict_key(&key);
}
}
+
+ let doc_w = self.doc_width;
+ let doc_h = self.doc_height;
+ regenerate_grid_lods_batched(
+ &self.device,
+ &self.queue,
+ &mut self.tile_pool,
+ doc_id,
+ layer_id,
+ grid,
+ doc_w,
+ doc_h,
+ dirty_lods,
+ true,
+ scratch,
+ );
}
/// Executes headless document-space GPU flattening directly on DX12 using the warm L1 tile pool.
@@ -1656,6 +1734,16 @@ impl GpuRenderer {
Ok((w, h, rgba))
}
+ /// O(resident_slots) lazy document metadata sync used by the live render loop under a
+ /// read-only `documents.read()` lock: updates document dimensions and evicts any stale/removed
+ /// resident VRAM keys while deferring actual tile uploads to frustum-culled rendering!
+ pub fn sync_document_lazy(&mut self, doc: &Document) {
+ self.doc_width = doc.dimensions.width.max(1);
+ self.doc_height = doc.dimensions.height.max(1);
+ self.tile_pool.prune_stale_document_keys(doc);
+ self.compositor.invalidate_final_scene_cache();
+ }
+
/// Synchronizes an entire Rust `Document` into L1 GPU VRAM (`GpuTilePool`):
/// 1. Ensures active visible LOD 0 tiles and 8-bit masks are uploaded into the L1
/// `Rgba16Float` / `R8Unorm` `GpuTilePool` texture arrays.
@@ -1672,6 +1760,7 @@ impl GpuRenderer {
self.tile_pool.begin_frame();
let doc_id = doc.id.clone();
+ let doc_key = self.tile_pool.intern_doc(&doc_id);
// 1. Upload visible layers' tiles into L1 Rgba16Float atlas + generate dirty compute mipmaps
let visible_ids: Vec<String> = doc
@@ -1685,12 +1774,13 @@ impl GpuRenderer {
let Some(layer) = doc.layer_mut(layer_id) else {
continue;
};
+ let layer_key = self.tile_pool.intern_layer(layer_id);
// Upload LOD 0 raster tiles (version-checked; skips unchanged tiles in O(1))
for (&coord, tile_arc) in &layer.grid.tiles {
let key = GpuTileKey {
- doc_id: doc_id.clone(),
- layer_id: layer_id.clone(),
+ doc_id: doc_key,
+ layer_id: layer_key,
lod: 0,
coord,
};
@@ -1703,14 +1793,14 @@ impl GpuRenderer {
if layer.grid.has_mask && layer.meta.mask_enabled.unwrap_or(true) {
for (&coord, mask_arc) in &layer.grid.mask_tiles {
let key = GpuTileKey {
- doc_id: doc_id.clone(),
- layer_id: layer_id.clone(),
+ doc_id: doc_key,
+ layer_id: layer_key,
lod: 0,
coord,
};
let _ = self
.tile_pool
- .ensure_mask_uploaded(&self.queue, key, mask_arc, scratch);
+ .ensure_mask_uploaded(&self.device, &self.queue, key, mask_arc, scratch);
}
}
@@ -1718,8 +1808,8 @@ impl GpuRenderer {
if !layer.grid.impasto_tiles.is_empty() {
for (&coord, imp_arc) in &layer.grid.impasto_tiles {
let key = GpuTileKey {
- doc_id: doc_id.clone(),
- layer_id: layer_id.clone(),
+ doc_id: doc_key,
+ layer_id: layer_key,
lod: 0,
coord,
};
@@ -1733,52 +1823,27 @@ impl GpuRenderer {
}
}
- // Regenerate dirty GPU compute mipmap pyramid levels LOD 1 -> 2 -> 3
- let ver = layer.grid.layer_version;
- for lod_idx in 0..3usize {
- let target_lod = (lod_idx + 1) as u8;
- let dirty_coords: Vec<TileCoord> =
- layer.grid.dirty_lods[lod_idx].drain().collect();
- for parent_coord in dirty_coords {
- let cx = parent_coord.tx * 2;
- let cy = parent_coord.ty * 2;
- let child_coords = [
- TileCoord::new(cx, cy),
- TileCoord::new(cx + 1, cy),
- TileCoord::new(cx, cy + 1),
- TileCoord::new(cx + 1, cy + 1),
- ];
- let mut child_slots = [None; 4];
- let mut any_child = false;
- for (qi, cc) in child_coords.iter().enumerate() {
- let ckey = GpuTileKey {
- doc_id: doc_id.clone(),
- layer_id: layer_id.clone(),
- lod: target_lod - 1,
- coord: *cc,
- };
- if let Some(slot) = self.tile_pool.get_slot(&ckey) {
- child_slots[qi] = Some(slot);
- any_child = true;
- }
- }
- if any_child {
- let pkey = GpuTileKey {
- doc_id: doc_id.clone(),
- layer_id: layer_id.clone(),
- lod: target_lod,
- coord: parent_coord,
- };
- self.tile_pool.generate_mipmap_tile(
- &self.device,
- &self.queue,
- pkey,
- child_slots,
- ver,
- );
- }
- }
- }
+ // Regenerate dirty GPU compute mipmap pyramid levels LOD 1 -> 2 -> 3 in ONE batch submit
+ let doc_w = self.doc_width;
+ let doc_h = self.doc_height;
+ let dirty_lods: [Vec<TileCoord>; 3] = [
+ layer.grid.dirty_lods[0].drain().collect(),
+ layer.grid.dirty_lods[1].drain().collect(),
+ layer.grid.dirty_lods[2].drain().collect(),
+ ];
+ regenerate_grid_lods_batched(
+ &self.device,
+ &self.queue,
+ &mut self.tile_pool,
+ &doc_id,
+ layer_id,
+ &layer.grid,
+ doc_w,
+ doc_h,
+ &dirty_lods,
+ true,
+ scratch,
+ );
}
doc.dirty_for_render = false;
@@ -1815,19 +1880,22 @@ impl GpuRenderer {
surface,
config,
configured,
+ pending_reconfigure,
on_configured,
..
} => {
- if *configured && config.width == w && config.height == h {
+ if *configured && !*pending_reconfigure && config.width == w && config.height == h {
return;
}
config.width = w;
config.height = h;
surface.configure(&self.device, config);
*configured = true;
+ *pending_reconfigure = false;
// Critical for SurfaceTargetUnsafe::CompositionVisual:
// wgpu-hal calls visual.SetContent(swapchain) inside configure(),
// and the DirectComposition host must call IDCompositionDevice::Commit().
+ // Any staged DComp offset/clip update is also applied atomically here.
(on_configured)();
}
OutputTarget::Headless {
@@ -1861,21 +1929,61 @@ impl GpuRenderer {
}
}
- pub fn force_reconfigure(&mut self) {
+ /// Marks the swapchain for reconfiguration on the next frame acquire (using the latest
+ /// viewport dimensions rather than stale pre-resize dimensions).
+ pub fn schedule_reconfigure(&mut self) {
+ if let OutputTarget::Surface {
+ pending_reconfigure,
+ ..
+ } = &mut self.output
+ {
+ *pending_reconfigure = true;
+ }
+ }
+
+ /// Commits any staged DirectComposition viewport offset/clip update when swapchain dimensions
+ /// did not change (e.g. dock panel shift or visibility toggle).
+ pub fn commit_surface_viewport(&self) {
+ if let OutputTarget::Surface {
+ configured,
+ on_configured,
+ ..
+ } = &self.output
+ {
+ if *configured {
+ (on_configured)();
+ }
+ }
+ }
+
+ pub fn invalidate_layer_tiles(&mut self, doc_id: &str, layer_id: &str) {
+ self.tile_pool.invalidate_layer(doc_id, layer_id);
+ }
+
+ pub fn trim_compositor_on_idle(&mut self) {
+ self.compositor.trim_on_idle(&self.device);
+ }
+
+ pub fn force_reconfigure(&mut self) -> bool {
if let OutputTarget::Surface {
surface,
config,
configured,
+ pending_reconfigure,
on_configured,
..
} = &mut self.output
{
- if config.width > 0 && config.height > 0 {
+ // Never prematurely configure the initial placeholder 1x1 surface before
+ // the host reports the real physical viewport cutout dimensions.
+ if *configured && config.width > 0 && config.height > 0 {
surface.configure(&self.device, config);
- *configured = true;
+ *pending_reconfigure = false;
(on_configured)();
+ return true;
}
}
+ false
}
pub fn set_document_size(&mut self, width: u32, height: u32) {
@@ -1887,21 +1995,66 @@ impl GpuRenderer {
}
self.doc_width = w;
self.doc_height = h;
- let (tex, view) = Self::create_doc_texture(&self.device, w, h);
- self.doc_texture = tex;
- self.doc_view = view;
- self.viewport_bind_group = Self::create_viewport_bind_group(
- &self.device,
- &self.viewport_bgl,
- &self.viewport_uniform_buf,
- &self.doc_view,
- &self.doc_sampler_linear,
- &self.doc_sampler_nearest,
- );
- self.clear_canvas();
+ // Drop any lazily-allocated legacy PoC canvas so it reallocates only if actually used.
+ self.legacy_doc = None;
+ }
+
+ fn ensure_legacy_doc(&mut self) -> &LegacyDocSurface {
+ let w = self.doc_width.max(1);
+ let h = self.doc_height.max(1);
+ let needs_alloc = self
+ .legacy_doc
+ .as_ref()
+ .is_none_or(|d| d.width != w || d.height != h);
+ if needs_alloc {
+ let (tex, view) = Self::create_doc_texture(&self.device, w, h);
+ let bg = Self::create_viewport_bind_group(
+ &self.device,
+ &self.viewport_bgl,
+ &self.viewport_uniform_buf,
+ &view,
+ &self.doc_sampler_linear,
+ &self.doc_sampler_nearest,
+ );
+ let mut encoder =
+ self.device
+ .create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-clear-legacy-canvas"),
+ });
+ {
+ let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("ink-clear-legacy-canvas-pass"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &view,
+ depth_slice: None,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ multiview_mask: None,
+ });
+ }
+ self.queue.submit(Some(encoder.finish()));
+ self.legacy_doc = Some(LegacyDocSurface {
+ _texture: tex,
+ view,
+ viewport_bind_group: bg,
+ width: w,
+ height: h,
+ });
+ }
+ self.legacy_doc.as_ref().expect("legacy_doc ensured")
}
pub fn clear_canvas(&mut self) {
+ let Some(ref legacy) = self.legacy_doc else {
+ return;
+ };
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
@@ -1911,7 +2064,7 @@ impl GpuRenderer {
let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("ink-clear-canvas-pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
- view: &self.doc_view,
+ view: &legacy.view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
@@ -1979,6 +2132,51 @@ impl GpuRenderer {
)
}
+ /// Acquires the swapchain surface texture (blocking on DXGI waitable latency object = 1 / VSync)
+ /// BEFORE the caller performs its final non-blocking drain of pending nav/tablet rings, cutting
+ /// up to 1 full scanout period (8–16.6 ms) of input-to-photon latency!
+ pub fn acquire_frame_target(&mut self, viewport: &ViewportRect) -> Result<AcquiredFrame, RenderOutcome> {
+ if self.device_error_flag.load(Ordering::Acquire) {
+ return Err(RenderOutcome::DeviceLost);
+ }
+ if viewport.width_px == 0 || viewport.height_px == 0 {
+ return Err(RenderOutcome::Skipped);
+ }
+
+ self.resize_surface(viewport.width_px, viewport.height_px);
+ let (vp_w, vp_h) = self.swapchain_size();
+ if vp_w == 0 || vp_h == 0 {
+ return Err(RenderOutcome::Skipped);
+ }
+
+ match &mut self.output {
+ OutputTarget::Surface {
+ surface,
+ configured,
+ pending_reconfigure,
+ ..
+ } => {
+ if !*configured {
+ return Err(RenderOutcome::Skipped);
+ }
+ match surface.get_current_texture() {
+ wgpu::CurrentSurfaceTexture::Success(tex) => Ok(AcquiredFrame::Surface(tex)),
+ wgpu::CurrentSurfaceTexture::Suboptimal(tex) => {
+ // Present `tex` cleanly this frame AND schedule a reconfigure for the next frame.
+ *pending_reconfigure = true;
+ Ok(AcquiredFrame::Surface(tex))
+ }
+ wgpu::CurrentSurfaceTexture::Timeout
+ | wgpu::CurrentSurfaceTexture::Occluded => Err(RenderOutcome::Skipped),
+ wgpu::CurrentSurfaceTexture::Outdated => Err(RenderOutcome::NeedsReconfigure),
+ wgpu::CurrentSurfaceTexture::Lost
+ | wgpu::CurrentSurfaceTexture::Validation => Err(RenderOutcome::DeviceLost),
+ }
+ }
+ OutputTarget::Headless { .. } => Ok(AcquiredFrame::Headless),
+ }
+ }
+
#[allow(clippy::too_many_arguments)]
pub fn render_document_frame_with_brush(
&mut self,
@@ -1996,43 +2194,62 @@ impl GpuRenderer {
cursor_local_phys: Option<(f32, f32)>,
cursor_suppressed: bool,
) -> RenderOutcome {
- if viewport.width_px == 0 || viewport.height_px == 0 {
- return RenderOutcome::Skipped;
- }
+ let acquired = match self.acquire_frame_target(viewport) {
+ Ok(frame) => frame,
+ Err(outcome) => return outcome,
+ };
+ self.render_document_frame_into_acquired(
+ acquired,
+ doc,
+ scratch,
+ display,
+ viewport,
+ camera,
+ pending_dabs,
+ dabs_are_eraser,
+ stroke_active,
+ false,
+ predicted_dabs,
+ dirty_doc_bounds,
+ cursor_cfg,
+ cursor_local_phys,
+ cursor_suppressed,
+ )
+ }
+ #[allow(clippy::too_many_arguments)]
+ pub fn render_document_frame_into_acquired(
+ &mut self,
+ acquired: AcquiredFrame,
+ doc: &Document,
+ scratch: Option<&dyn ScratchBackend>,
+ display: &CompositorDisplayConfig,
+ viewport: &ViewportRect,
+ camera: &CameraState,
+ pending_dabs: &[DabInstance],
+ dabs_are_eraser: bool,
+ stroke_active: bool,
+ is_mask_stroke: bool,
+ predicted_dabs: &[GpuBrushDab],
+ dirty_doc_bounds: Option<DocBounds>,
+ cursor_cfg: &CursorConfig,
+ cursor_local_phys: Option<(f32, f32)>,
+ cursor_suppressed: bool,
+ ) -> RenderOutcome {
+ if self.device_error_flag.load(Ordering::Acquire) {
+ return RenderOutcome::DeviceLost;
+ }
self.doc_width = doc.dimensions.width.max(1);
self.doc_height = doc.dimensions.height.max(1);
- self.resize_surface(viewport.width_px, viewport.height_px);
let (vp_w, vp_h) = self.swapchain_size();
if vp_w == 0 || vp_h == 0 {
return RenderOutcome::Skipped;
}
- let acquired_surface_tex = match &self.output {
- OutputTarget::Surface {
- surface,
- configured,
- ..
- } => {
- if !*configured {
- return RenderOutcome::NeedsReconfigure;
- }
- match surface.get_current_texture() {
- wgpu::CurrentSurfaceTexture::Success(tex)
- | wgpu::CurrentSurfaceTexture::Suboptimal(tex) => Some(tex),
- wgpu::CurrentSurfaceTexture::Timeout
- | wgpu::CurrentSurfaceTexture::Occluded => return RenderOutcome::Skipped,
- wgpu::CurrentSurfaceTexture::Outdated => {
- return RenderOutcome::NeedsReconfigure;
- }
- wgpu::CurrentSurfaceTexture::Lost
- | wgpu::CurrentSurfaceTexture::Validation => {
- return RenderOutcome::DeviceLost;
- }
- }
- }
- OutputTarget::Headless { .. } => None,
+ let acquired_surface_tex = match acquired {
+ AcquiredFrame::Surface(tex) => Some(tex),
+ AcquiredFrame::Headless => None,
};
let surface_view_owned;
@@ -2047,16 +2264,27 @@ impl GpuRenderer {
_ => return RenderOutcome::Skipped,
};
+ let dpr = viewport.safe_dpr();
+
+ // Combine selection projection, compositor passes, marching ants, and GPU brush cursor
+ // into ONE CommandEncoder + ONE queue.submit per frame (total <= 2 submits on live strokes)!
+ let mut encoder = self
+ .device
+ .create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-viewport-frame-encoder"),
+ });
+
// Project sparse R8Unorm selection mask into viewport space before compositor so live strokes
// clip accurately to the active selection, then draw floating pixels & GPU Marching Ants after!
- self.selection_overlay.project_viewport_mask(
+ self.selection_overlay.encode_viewport_mask(
&self.device,
&self.queue,
+ &mut encoder,
doc.selection.as_ref(),
camera,
vp_w,
vp_h,
- viewport.safe_dpr(),
+ dpr,
);
let sel_vp_view =
@@ -2074,6 +2302,7 @@ impl GpuRenderer {
dirty_doc_bounds,
live_impasto: None,
selection_vp_mask: sel_vp_view,
+ is_mask_stroke,
})
} else {
None
@@ -2104,9 +2333,10 @@ impl GpuRenderer {
None
};
- self.compositor.render_viewport_frame_full(
+ self.compositor.encode_viewport_frame_full(
&self.device,
&self.queue,
+ &mut encoder,
&mut self.tile_pool,
doc,
scratch,
@@ -2114,7 +2344,7 @@ impl GpuRenderer {
camera,
vp_w,
vp_h,
- viewport.safe_dpr(),
+ dpr,
pending_dabs,
dabs_are_eraser,
stroke_active,
@@ -2123,13 +2353,12 @@ impl GpuRenderer {
target_view,
);
- let dpr = viewport.safe_dpr();
-
- // Phase 6: Interactive GPU 5-Mode Transform/Warp live preview
+ // Phase 6: Interactive GPU 5-Mode Transform/Warp live preview (unified into frame encoder!)
if self.transform_engine.is_active() {
- self.transform_engine.render_preview(
+ self.transform_engine.encode_preview(
&self.device,
&self.queue,
+ &mut encoder,
camera,
vp_w,
vp_h,
@@ -2138,11 +2367,11 @@ impl GpuRenderer {
);
}
- // Phase 6: Live GPU Gradient / Shape / Filter / Tonal preview overlay
+ // Phase 6: Live GPU Gradient / Shape / Filter / Tonal preview overlay (unified into frame encoder!)
if self.tool_preview.is_active() {
- self.tool_preview.render(
- &self.device,
+ self.tool_preview.encode(
&self.queue,
+ &mut encoder,
self.doc_width,
self.doc_height,
camera,
@@ -2153,11 +2382,12 @@ impl GpuRenderer {
);
}
- // Phase 6: Multiplayer remote collaborator live GPU draft layers
+ // Phase 6: Multiplayer remote collaborator live GPU draft layers (unified into frame encoder!)
if self.remote_drafts.has_active_drafts() {
- self.remote_drafts.render_drafts(
+ self.remote_drafts.encode_drafts(
&self.device,
&self.queue,
+ &mut encoder,
self.doc_width,
self.doc_height,
camera,
@@ -2171,9 +2401,10 @@ impl GpuRenderer {
// Phase 6: Floating selection pixels + animated display-resolution GPU Marching Ants
if self.selection_overlay.is_active() {
let ants_time = self.ants_start_instant.elapsed().as_secs_f32();
- self.selection_overlay.render_floating_and_ants(
+ self.selection_overlay.encode_floating_and_ants(
&self.device,
&self.queue,
+ &mut encoder,
doc.selection.as_ref(),
camera,
vp_w,
@@ -2215,11 +2446,6 @@ impl GpuRenderer {
bytemuck::bytes_of(&cursor_uniforms),
);
- let mut encoder = self
- .device
- .create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-cursor-overlay-encoder"),
- });
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("ink-cursor-overlay-pass"),
@@ -2241,9 +2467,11 @@ impl GpuRenderer {
pass.set_bind_group(0, &self.cursor_bind_group, &[]);
pass.draw(0..6, 0..1);
}
- self.queue.submit(Some(encoder.finish()));
}
+ // Submit the entire frame (selection + compositor + transform/tool/collab overlays + ants + cursor) in ONE submit!
+ self.queue.submit(Some(encoder.finish()));
+
if let Some(frame) = acquired_surface_tex {
self.queue.present(frame);
} else {
@@ -2267,13 +2495,41 @@ impl GpuRenderer {
cursor_local_phys: Option<(f32, f32)>,
cursor_suppressed: bool,
) -> RenderOutcome {
- if viewport.width_px == 0 || viewport.height_px == 0 {
- return RenderOutcome::Skipped;
- }
-
- // Ensure swapchain matches physical viewport cutout bounds
- self.resize_surface(viewport.width_px, viewport.height_px);
+ let acquired = match self.acquire_frame_target(viewport) {
+ Ok(frame) => frame,
+ Err(outcome) => return outcome,
+ };
+ self.render_frame_into_acquired(
+ acquired,
+ viewport,
+ camera,
+ show_checkerboard,
+ matte_color,
+ pending_dabs,
+ dabs_are_eraser,
+ cursor_cfg,
+ cursor_local_phys,
+ cursor_suppressed,
+ )
+ }
+ #[allow(clippy::too_many_arguments)]
+ pub fn render_frame_into_acquired(
+ &mut self,
+ acquired: AcquiredFrame,
+ viewport: &ViewportRect,
+ camera: &CameraState,
+ show_checkerboard: bool,
+ matte_color: [f32; 4],
+ pending_dabs: &[DabInstance],
+ dabs_are_eraser: bool,
+ cursor_cfg: &CursorConfig,
+ cursor_local_phys: Option<(f32, f32)>,
+ cursor_suppressed: bool,
+ ) -> RenderOutcome {
+ if self.device_error_flag.load(Ordering::Acquire) {
+ return RenderOutcome::DeviceLost;
+ }
let (vp_w, vp_h) = self.swapchain_size();
if vp_w == 0 || vp_h == 0 {
return RenderOutcome::Skipped;
@@ -2343,31 +2599,12 @@ impl GpuRenderer {
bytemuck::bytes_of(&cursor_uniforms),
);
- // Acquire swapchain frame (waits on DXGI waitable latency object = 1)
- let acquired_surface_tex = match &self.output {
- OutputTarget::Surface {
- surface,
- configured,
- ..
- } => {
- if !*configured {
- return RenderOutcome::NeedsReconfigure;
- }
- match surface.get_current_texture() {
- wgpu::CurrentSurfaceTexture::Success(tex)
- | wgpu::CurrentSurfaceTexture::Suboptimal(tex) => Some(tex),
- wgpu::CurrentSurfaceTexture::Timeout
- | wgpu::CurrentSurfaceTexture::Occluded => return RenderOutcome::Skipped,
- wgpu::CurrentSurfaceTexture::Outdated => {
- return RenderOutcome::NeedsReconfigure;
- }
- wgpu::CurrentSurfaceTexture::Lost
- | wgpu::CurrentSurfaceTexture::Validation => {
- return RenderOutcome::DeviceLost;
- }
- }
- }
- OutputTarget::Headless { .. } => None,
+ // Lazily allocate the Phase 1 PoC fallback doc texture only when this legacy path runs
+ self.ensure_legacy_doc();
+
+ let acquired_surface_tex = match acquired {
+ AcquiredFrame::Surface(tex) => Some(tex),
+ AcquiredFrame::Headless => None,
};
let surface_view_owned;
@@ -2382,6 +2619,8 @@ impl GpuRenderer {
_ => return RenderOutcome::Skipped,
};
+ let legacy = self.legacy_doc.as_ref().expect("legacy_doc ensured");
+
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
@@ -2393,7 +2632,7 @@ impl GpuRenderer {
let mut dab_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("ink-dab-pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
- view: &self.doc_view,
+ view: &legacy.view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
@@ -2441,7 +2680,7 @@ impl GpuRenderer {
});
pass.set_pipeline(&self.viewport_pipeline);
- pass.set_bind_group(0, &self.viewport_bind_group, &[]);
+ pass.set_bind_group(0, &legacy.viewport_bind_group, &[]);
pass.draw(0..3, 0..1);
if show_cursor {
@@ -2460,7 +2699,7 @@ impl GpuRenderer {
}
// Keep references alive through instance/adapter fields
- let _ = (&self.instance, &self.adapter, &self.doc_texture);
+ let _ = (&self.instance, &self.adapter);
RenderOutcome::Presented
}
diff --git a/crates/ink-engine/src/history/mod.rs b/crates/ink-engine/src/history/mod.rs
index f4d680a..4b882ab 100644
--- a/crates/ink-engine/src/history/mod.rs
+++ b/crates/ink-engine/src/history/mod.rs
@@ -371,11 +371,15 @@ impl HistoryStack {
let mut steps = Vec::new();
if target_index < cur {
for i in ((target_index + 1)..=cur).rev() {
- steps.push((i, true));
+ if !self.entries[i].meta.undone {
+ steps.push((i, true));
+ }
}
} else {
for i in (cur + 1)..=target_index {
- steps.push((i, false));
+ if !self.entries[i].meta.undone {
+ steps.push((i, false));
+ }
}
}
self.index = target_index as isize;
@@ -499,12 +503,14 @@ impl HistoryStack {
for (_, g) in lt.before_grids.iter().chain(lt.after_grids.iter()) {
out.extend(g.tiles.values());
out.extend(g.mask_tiles.values());
+ out.extend(g.impasto_tiles.values());
}
}
if let Some(ref cr) = e.canvas_resize_delta {
for (_, g) in cr.before_grids.iter().chain(cr.after_grids.iter()) {
out.extend(g.tiles.values());
out.extend(g.mask_tiles.values());
+ out.extend(g.impasto_tiles.values());
}
}
}
diff --git a/crates/ink-engine/src/hit_test.rs b/crates/ink-engine/src/hit_test.rs
index bf34b01..6074402 100644
--- a/crates/ink-engine/src/hit_test.rs
+++ b/crates/ink-engine/src/hit_test.rs
@@ -151,6 +151,22 @@ impl SharedHitTest {
.unwrap_or(false)
}
+ /// Single non-blocking `try_read()` returning `(is_unoccluded_canvas, should_capture_native_stroke)`
+ /// for high-frequency WinTab / Windows Ink hover & routing hot paths.
+ #[inline]
+ pub fn try_classify_canvas_point(&self, phys_x: f32, phys_y: f32) -> (bool, bool) {
+ self.inner
+ .try_read()
+ .map(|g| {
+ let unoccluded = g.is_unoccluded_canvas_point(phys_x, phys_y);
+ let capture = unoccluded
+ && g.policy.native_stroke_enabled
+ && g.policy.active_tool.is_native_stroke_tool();
+ (unoccluded, capture)
+ })
+ .unwrap_or((false, false))
+ }
+
#[inline]
pub fn try_should_capture_native_nav(&self, phys_x: f32, phys_y: f32) -> bool {
self.inner
diff --git a/crates/ink-engine/src/io/compositor_cpu.rs b/crates/ink-engine/src/io/compositor_cpu.rs
index 0eb9036..e208f9f 100644
--- a/crates/ink-engine/src/io/compositor_cpu.rs
+++ b/crates/ink-engine/src/io/compositor_cpu.rs
@@ -6,7 +6,11 @@
use crate::document::{BlendMode, Document, LayerNode, LayerType};
use crate::memory::ScratchBackend;
-use crate::tiles::{parse_hex_rgba8, RectI32, TileStorage, TILE_SIZE, TILE_SIZE_I32};
+use crate::tiles::{
+ parse_hex_rgba8, RectI32, TileCoord, TileData, TileStorage, TILE_SIZE, TILE_SIZE_I32,
+};
+use std::collections::HashMap;
+use std::sync::Arc;
#[inline]
fn blend_channel(mode: BlendMode, cb: f32, cs: f32) -> f32 {
@@ -156,23 +160,9 @@ pub fn fit_thumbnail_dims(doc_w: u32, doc_h: u32, max_w: u32, max_h: u32) -> (u3
(tw, th)
}
-/// Renders a downscaled RGBA8 thumbnail directly from a layer's populated sparse tiles
-/// (zero full-canvas intermediate buffer!).
-pub fn render_layer_thumbnail_rgba(
- layer: &LayerNode,
- doc_w: u32,
- doc_h: u32,
- max_w: u32,
- max_h: u32,
- scratch: Option<&dyn ScratchBackend>,
-) -> Result<(u32, u32, Vec<u8>), String> {
- let (tw, th) = fit_thumbnail_dims(doc_w, doc_h, max_w, max_h);
- let mut out = vec![0u8; (tw as usize) * (th as usize) * 4];
- if layer.grid.tiles.is_empty() || doc_w == 0 || doc_h == 0 {
- return Ok((tw, th, out));
- }
-
- let tint = if layer.meta.layer_color_enabled.unwrap_or(false) {
+/// Extracts optional two-tone layer tint `(primary_rgba8, sub_rgba8)` from a `LayerNode`.
+pub fn extract_layer_tint(layer: &LayerNode) -> Option<([u8; 4], [u8; 4])> {
+ if layer.meta.layer_color_enabled.unwrap_or(false) {
let primary = layer
.meta
.layer_color
@@ -188,7 +178,46 @@ pub fn render_layer_thumbnail_rgba(
Some((primary, sub))
} else {
None
- };
+ }
+}
+
+/// Renders a downscaled RGBA8 thumbnail directly from a layer's populated sparse tiles
+/// (zero full-canvas intermediate buffer!).
+pub fn render_layer_thumbnail_rgba(
+ layer: &LayerNode,
+ doc_w: u32,
+ doc_h: u32,
+ max_w: u32,
+ max_h: u32,
+ scratch: Option<&dyn ScratchBackend>,
+) -> Result<(u32, u32, Vec<u8>), String> {
+ render_layer_thumbnail_rgba_from_tiles(
+ &layer.grid.tiles,
+ extract_layer_tint(layer),
+ doc_w,
+ doc_h,
+ max_w,
+ max_h,
+ scratch,
+ )
+}
+
+/// Renders a downscaled RGBA8 thumbnail directly from a zero-copy `Arc<TileData>` snapshot
+/// (safe to run completely off the DX12 render thread without holding any document locks!).
+pub fn render_layer_thumbnail_rgba_from_tiles(
+ tiles: &HashMap<TileCoord, Arc<TileData>>,
+ tint: Option<([u8; 4], [u8; 4])>,
+ doc_w: u32,
+ doc_h: u32,
+ max_w: u32,
+ max_h: u32,
+ scratch: Option<&dyn ScratchBackend>,
+) -> Result<(u32, u32, Vec<u8>), String> {
+ let (tw, th) = fit_thumbnail_dims(doc_w, doc_h, max_w, max_h);
+ let mut out = vec![0u8; (tw as usize) * (th as usize) * 4];
+ if tiles.is_empty() || doc_w == 0 || doc_h == 0 {
+ return Ok((tw, th, out));
+ }
let scale_x = tw as f64 / doc_w as f64;
let scale_y = th as f64 / doc_h as f64;
@@ -201,7 +230,7 @@ pub fn render_layer_thumbnail_rgba(
let mut acc_a = vec![0.0f32; pixel_count];
let mut acc_w = vec![0.0f32; pixel_count];
- for (&coord, tile) in &layer.grid.tiles {
+ for (&coord, tile) in tiles {
let tile_x0 = coord.tx * TILE_SIZE_I32;
let tile_y0 = coord.ty * TILE_SIZE_I32;
let tile_x1 = tile_x0 + TILE_SIZE_I32;
@@ -309,18 +338,58 @@ pub fn render_mask_thumbnail_rgba(
max_w: u32,
max_h: u32,
scratch: Option<&dyn ScratchBackend>,
+) -> Result<(u32, u32, Vec<u8>), String> {
+ render_mask_thumbnail_rgba_from_tiles(
+ &layer.grid.mask_tiles,
+ layer.grid.mask_default_value,
+ doc_w,
+ doc_h,
+ max_w,
+ max_h,
+ scratch,
+ )
+}
+
+/// Renders a downscaled RGBA8 mask thumbnail directly from a zero-copy `Arc<TileData>` snapshot.
+pub fn render_mask_thumbnail_rgba_from_tiles(
+ mask_tiles: &HashMap<TileCoord, Arc<TileData>>,
+ mask_default_value: u8,
+ doc_w: u32,
+ doc_h: u32,
+ max_w: u32,
+ max_h: u32,
+ scratch: Option<&dyn ScratchBackend>,
) -> Result<(u32, u32, Vec<u8>), String> {
let (tw, th) = fit_thumbnail_dims(doc_w, doc_h, max_w, max_h);
let mut out = vec![0u8; (tw as usize) * (th as usize) * 4];
+ if doc_w == 0 || doc_h == 0 {
+ return Ok((tw, th, out));
+ }
+
+ // Materialize populated mask tiles once so pixel lookups are O(1)
+ let mut materialized: HashMap<TileCoord, Vec<u8>> = HashMap::with_capacity(mask_tiles.len());
+ for (&coord, tile) in mask_tiles {
+ if let Ok(raw) = tile.materialize_raw(scratch) {
+ materialized.insert(coord, raw);
+ }
+ }
+
for py in 0..th {
let doc_y = ((py as f64 + 0.5) * (doc_h as f64 / th as f64))
.floor()
.clamp(0.0, (doc_h.saturating_sub(1)) as f64) as i32;
+ let ty = doc_y.div_euclid(TILE_SIZE_I32);
+ let ly = doc_y.rem_euclid(TILE_SIZE_I32) as usize;
for px in 0..tw {
let doc_x = ((px as f64 + 0.5) * (doc_w as f64 / tw as f64))
.floor()
.clamp(0.0, (doc_w.saturating_sub(1)) as f64) as i32;
- let v = layer.grid.get_mask_alpha(doc_x, doc_y, scratch);
+ let tx = doc_x.div_euclid(TILE_SIZE_I32);
+ let lx = doc_x.rem_euclid(TILE_SIZE_I32) as usize;
+ let v = materialized
+ .get(&TileCoord::new(tx, ty))
+ .and_then(|raw| raw.get(ly * TILE_SIZE + lx).copied())
+ .unwrap_or(mask_default_value);
let off = ((py * tw + px) as usize) * 4;
out[off] = v;
out[off + 1] = v;
diff --git a/crates/ink-engine/src/io/ink_format.rs b/crates/ink-engine/src/io/ink_format.rs
index cc4065e..83552fa 100644
--- a/crates/ink-engine/src/io/ink_format.rs
+++ b/crates/ink-engine/src/io/ink_format.rs
@@ -71,6 +71,8 @@ struct InkProjectManifest {
#[serde(default)]
perspective_ruler: Option<serde_json::Value>,
#[serde(default)]
+ straight_ruler: Option<serde_json::Value>,
+ #[serde(default)]
animation_timeline: Option<serde_json::Value>,
#[serde(default)]
timelapse: Option<serde_json::Value>,
@@ -524,6 +526,7 @@ pub fn serialize_ink_document(
layer_tile_keys,
masks_meta,
perspective_ruler: doc.perspective_ruler.clone(),
+ straight_ruler: doc.straight_ruler.clone(),
animation_timeline: doc.animation_timeline.clone(),
timelapse: doc.timelapse.clone(),
work_time_ms: doc.work_time_ms,
@@ -758,7 +761,7 @@ pub fn parse_ink_document(
if meta.mask_linked.is_none() {
meta.mask_linked = Some(true);
}
- meta.mask_version = Some(grid.layer_version);
+ meta.mask_version = Some(grid.mask_version);
}
let mut node = LayerNode { meta, grid };
@@ -806,6 +809,7 @@ pub fn parse_ink_document(
max_history_steps,
);
doc.perspective_ruler = manifest.perspective_ruler;
+ doc.straight_ruler = manifest.straight_ruler;
doc.animation_timeline = manifest.animation_timeline;
doc.timelapse = manifest.timelapse;
doc.work_time_ms = manifest.work_time_ms;
diff --git a/crates/ink-engine/src/io/png_codec.rs b/crates/ink-engine/src/io/png_codec.rs
index a293292..a95fbcb 100644
--- a/crates/ink-engine/src/io/png_codec.rs
+++ b/crates/ink-engine/src/io/png_codec.rs
@@ -187,6 +187,9 @@ pub fn decode_png_rgba8(png: &[u8]) -> Result<(u32, u32, Vec<u8>), String> {
if bit_depth != 8 && bit_depth != 16 {
return Err(format!("Unsupported PNG bit depth: {bit_depth}"));
}
+ if color_type == 3 && bit_depth != 8 {
+ return Err(format!("Unsupported indexed PNG bit depth: {bit_depth}"));
+ }
let channels: usize = match color_type {
0 => 1, // Grayscale
@@ -204,7 +207,8 @@ pub fn decode_png_rgba8(png: &[u8]) -> Result<(u32, u32, Vec<u8>), String> {
.ok_or_else(|| "PNG buffer overflow".to_string())?;
let mut raw = Vec::with_capacity(expected_raw);
- let mut decoder = ZlibDecoder::new(idat.as_slice());
+ let max_decode = (expected_raw as u64).saturating_add(64);
+ let mut decoder = ZlibDecoder::new(idat.as_slice()).take(max_decode);
decoder
.read_to_end(&mut raw)
.map_err(|e| format!("PNG zlib decode error: {e}"))?;
@@ -305,7 +309,11 @@ pub fn decode_png_rgba8(png: &[u8]) -> Result<(u32, u32, Vec<u8>), String> {
rgba[d + 2] = rgb[2];
rgba[d + 3] = a;
}
- _ => unreachable!(),
+ _ => {
+ return Err(format!(
+ "Unsupported PNG color type/bit depth combination: {color_type}/{bit_depth}"
+ ));
+ }
}
}
std::mem::swap(&mut prev_row, &mut cur_row);
diff --git a/crates/ink-engine/src/io/wal.rs b/crates/ink-engine/src/io/wal.rs
index 4bb8726..423f4fd 100644
--- a/crates/ink-engine/src/io/wal.rs
+++ b/crates/ink-engine/src/io/wal.rs
@@ -13,6 +13,7 @@ use crate::tiles::{
use flate2::read::DeflateDecoder;
use flate2::write::DeflateEncoder;
use flate2::Compression;
+use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::{Read, Write};
@@ -66,6 +67,15 @@ struct LayerMutationWalPayload {
active_layer_id: Option<String>,
}
+#[derive(Debug, Clone, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct VectorStrokeWalPayload {
+ #[serde(default)]
+ layer_id: Option<String>,
+ #[serde(default)]
+ strokes: Vec<serde_json::Value>,
+}
+
fn deflate_fast(raw: &[u8]) -> Result<Vec<u8>, String> {
let mut enc = DeflateEncoder::new(Vec::with_capacity(raw.len() / 3 + 32), Compression::fast());
enc.write_all(raw)
@@ -75,19 +85,35 @@ fn deflate_fast(raw: &[u8]) -> Result<Vec<u8>, String> {
}
fn inflate_or_raw(bytes: &[u8], expected_magic: &[u8]) -> Result<Vec<u8>, String> {
- if bytes.starts_with(expected_magic) {
+ // Multi-byte binary magic headers ("TD", "INKG") cannot collide reliably with valid deflate,
+ // whereas single-byte JSON prefix ("{", 0x7B) is a valid fixed-Huffman DEFLATE lead byte.
+ // For single-byte prefixes, try inflating first and fall back to raw bytes if valid!
+ if expected_magic.len() >= 2 && bytes.starts_with(expected_magic) {
return Ok(bytes.to_vec());
}
let mut dec = DeflateDecoder::new(bytes);
let mut out = Vec::new();
let mut limited = dec.by_ref().take((MAX_DECOMPRESSED_BYTES + 1) as u64);
- limited
- .read_to_end(&mut out)
- .map_err(|e| format!("WAL inflate error: {e}"))?;
- if out.len() > MAX_DECOMPRESSED_BYTES {
- return Err("WAL payload exceeded safety ceiling".to_string());
+ match limited.read_to_end(&mut out) {
+ Ok(_) => {
+ if out.len() > MAX_DECOMPRESSED_BYTES {
+ return Err("WAL payload exceeded safety ceiling".to_string());
+ }
+ if expected_magic.is_empty() || out.starts_with(expected_magic) {
+ return Ok(out);
+ }
+ if bytes.starts_with(expected_magic) {
+ return Ok(bytes.to_vec());
+ }
+ Ok(out)
+ }
+ Err(e) => {
+ if !expected_magic.is_empty() && bytes.starts_with(expected_magic) {
+ return Ok(bytes.to_vec());
+ }
+ Err(format!("WAL inflate error: {e}"))
+ }
}
- Ok(out)
}
/// Encodes CoW tile deltas directly into deflate-compressed `TD v1` WAL frame payload bytes
@@ -167,60 +193,103 @@ pub fn encode_document_checkpoint(
}
// Tiles section (raster tiles + mask tiles encoded under `<layerId>__mask`)
- let mut tile_count = 0u32;
- let count_pos = inkg.len();
- inkg.extend_from_slice(&0u32.to_le_bytes());
+ enum WalTileKind {
+ Raster { io_fmt: TileFormat, thresh: u8 },
+ Mask,
+ Impasto,
+ }
+ struct WalTileTask {
+ key: String,
+ coord: TileCoord,
+ kind: WalTileKind,
+ tile: Arc<TileData>,
+ }
+ let mut tasks: Vec<WalTileTask> = Vec::new();
for layer in &doc.layers {
let io_fmt = layer.grid.format.io_storage_format();
let thresh = layer.meta.mono_threshold.unwrap_or(128);
- let kb = layer.meta.id.as_bytes();
for (&coord, tile) in &layer.grid.tiles {
- let raw = tile.to_format_raw(io_fmt, thresh, true, scratch)?;
- inkg.extend_from_slice(&(kb.len() as u16).to_le_bytes());
- inkg.extend_from_slice(kb);
- inkg.extend_from_slice(&coord.tx.to_le_bytes());
- inkg.extend_from_slice(&coord.ty.to_le_bytes());
- inkg.push(io_fmt.to_ink_byte());
- inkg.extend_from_slice(&(tile.version as u32).to_le_bytes());
- inkg.extend_from_slice(&(raw.len() as u32).to_le_bytes());
- inkg.extend_from_slice(&raw);
- tile_count += 1;
+ tasks.push(WalTileTask {
+ key: layer.meta.id.clone(),
+ coord,
+ kind: WalTileKind::Raster { io_fmt, thresh },
+ tile: Arc::clone(tile),
+ });
}
if layer.grid.has_mask {
let mask_key = format!("{}__mask", layer.meta.id);
- let mkb = mask_key.as_bytes();
for (&coord, tile) in &layer.grid.mask_tiles {
- let raw = tile.materialize_raw(scratch)?;
- inkg.extend_from_slice(&(mkb.len() as u16).to_le_bytes());
- inkg.extend_from_slice(mkb);
- inkg.extend_from_slice(&coord.tx.to_le_bytes());
- inkg.extend_from_slice(&coord.ty.to_le_bytes());
- inkg.push(TileFormat::Grayscale8Bit.to_ink_byte());
- inkg.extend_from_slice(&(tile.version as u32).to_le_bytes());
- inkg.extend_from_slice(&(raw.len() as u32).to_le_bytes());
- inkg.extend_from_slice(&raw);
- tile_count += 1;
+ tasks.push(WalTileTask {
+ key: mask_key.clone(),
+ coord,
+ kind: WalTileKind::Mask,
+ tile: Arc::clone(tile),
+ });
}
}
if !layer.grid.impasto_tiles.is_empty() {
let imp_key = format!("{}__impasto", layer.meta.id);
- let ikb = imp_key.as_bytes();
for (&coord, tile) in &layer.grid.impasto_tiles {
- let raw = tile.to_r16f(scratch)?;
- inkg.extend_from_slice(&(ikb.len() as u16).to_le_bytes());
- inkg.extend_from_slice(ikb);
- inkg.extend_from_slice(&coord.tx.to_le_bytes());
- inkg.extend_from_slice(&coord.ty.to_le_bytes());
- inkg.push(TileFormat::Height16Float.to_ink_byte());
- inkg.extend_from_slice(&(tile.version as u32).to_le_bytes());
- inkg.extend_from_slice(&(raw.len() as u32).to_le_bytes());
- inkg.extend_from_slice(&raw);
- tile_count += 1;
+ tasks.push(WalTileTask {
+ key: imp_key.clone(),
+ coord,
+ kind: WalTileKind::Impasto,
+ tile: Arc::clone(tile),
+ });
}
}
}
- inkg[count_pos..count_pos + 4].copy_from_slice(&tile_count.to_le_bytes());
+
+ let materialize = |task: WalTileTask| -> Result<(String, TileCoord, u8, u32, Vec<u8>), String> {
+ let (fmt_byte, raw) = match task.kind {
+ WalTileKind::Raster { io_fmt, thresh } => (
+ io_fmt.to_ink_byte(),
+ task.tile.to_format_raw(io_fmt, thresh, true, scratch)?,
+ ),
+ WalTileKind::Mask => (
+ TileFormat::Grayscale8Bit.to_ink_byte(),
+ task.tile.materialize_raw(scratch)?,
+ ),
+ WalTileKind::Impasto => (
+ TileFormat::Height16Float.to_ink_byte(),
+ task.tile.to_r16f(scratch)?,
+ ),
+ };
+ Ok((
+ task.key,
+ task.coord,
+ fmt_byte,
+ task.tile.version as u32,
+ raw,
+ ))
+ };
+
+ let encoded_tiles: Vec<(String, TileCoord, u8, u32, Vec<u8>)> = if tasks.len() >= 8 {
+ tasks
+ .into_par_iter()
+ .map(materialize)
+ .collect::<Result<Vec<_>, String>>()?
+ } else {
+ tasks
+ .into_iter()
+ .map(materialize)
+ .collect::<Result<Vec<_>, String>>()?
+ };
+
+ let tile_count = encoded_tiles.len() as u32;
+ inkg.extend_from_slice(&tile_count.to_le_bytes());
+ for (key, coord, fmt_byte, version, raw) in &encoded_tiles {
+ let kb = key.as_bytes();
+ inkg.extend_from_slice(&(kb.len() as u16).to_le_bytes());
+ inkg.extend_from_slice(kb);
+ inkg.extend_from_slice(&coord.tx.to_le_bytes());
+ inkg.extend_from_slice(&coord.ty.to_le_bytes());
+ inkg.push(*fmt_byte);
+ inkg.extend_from_slice(&version.to_le_bytes());
+ inkg.extend_from_slice(&(raw.len() as u32).to_le_bytes());
+ inkg.extend_from_slice(raw);
+ }
let compressed_snapshot = deflate_fast(&inkg)?;
@@ -311,13 +380,47 @@ pub fn replay_recovery_into_document(
}
}
}
+ WAL_ENTRY_VECTOR_STROKE => {
+ if let Ok(raw_json) = inflate_or_raw(&entry.payload, b"{") {
+ if let Ok(vec_payload) =
+ serde_json::from_slice::<VectorStrokeWalPayload>(&raw_json)
+ {
+ if let Some(lid) = vec_payload.layer_id.as_deref() {
+ if let Some(layer_meta) =
+ current_layers.iter_mut().find(|l| l.id == lid)
+ {
+ layer_meta.vector_strokes =
+ Some(serde_json::Value::Array(vec_payload.strokes));
+ strokes_replayed += 1;
+ }
+ }
+ }
+ }
+ }
WAL_ENTRY_LAYER_MUTATION => {
if let Ok(raw_json) = inflate_or_raw(&entry.payload, b"{") {
if let Ok(mut_payload) =
serde_json::from_slice::<LayerMutationWalPayload>(&raw_json)
{
if !mut_payload.layers.is_empty() {
- current_layers = mut_payload.layers;
+ // Preserve vectorStrokes when layer mutation WAL frames stripped them
+ let prev_vectors: HashMap<String, serde_json::Value> = current_layers
+ .iter()
+ .filter_map(|l| {
+ l.vector_strokes
+ .as_ref()
+ .map(|vs| (l.id.clone(), vs.clone()))
+ })
+ .collect();
+ let mut next_layers = mut_payload.layers;
+ for l in &mut next_layers {
+ if l.vector_strokes.is_none() {
+ if let Some(vs) = prev_vectors.get(&l.id) {
+ l.vector_strokes = Some(vs.clone());
+ }
+ }
+ }
+ current_layers = next_layers;
if mut_payload.active_layer_id.is_some() {
active_layer_id = mut_payload.active_layer_id;
}
@@ -337,9 +440,12 @@ pub fn replay_recovery_into_document(
.expression_color
.map(ExpressionColor::to_tile_format)
.unwrap_or(TileFormat::Color32Bit);
- let grid = grids_by_layer
+ let mut grid = grids_by_layer
.remove(&meta.id)
.unwrap_or_else(|| SparseLayerGrid::new(fmt));
+ if meta.has_mask && !grid.has_mask {
+ grid.init_mask(255);
+ }
LayerNode { meta, grid }
})
.collect();
@@ -573,6 +679,7 @@ fn apply_td_wal_frame(
let g = grids
.entry(raw_lid.to_string())
.or_insert_with(|| SparseLayerGrid::new(fmt));
+ g.format = fmt;
if let Some(d) = after_data {
if d.len() == fmt.byte_size() {
g.set_tile(
diff --git a/crates/ink-engine/src/lib.rs b/crates/ink-engine/src/lib.rs
index c3478ed..b276b51 100644
--- a/crates/ink-engine/src/lib.rs
+++ b/crates/ink-engine/src/lib.rs
@@ -35,6 +35,12 @@ mod phase4_tests;
mod phase5_tests;
#[cfg(test)]
mod phase6_tests;
+#[cfg(test)]
+mod regression_dx12_tests;
+#[cfg(test)]
+mod brush_parity_dx12_tests;
+#[cfg(test)]
+mod audit_regression_tests;
pub use camera::{
clamp_zoom, compute_smooth_rotation_delta, doc_to_viewport_css, viewport_css_to_doc,
@@ -49,7 +55,7 @@ pub use document::{
DocumentManager, DocumentMetaSnapshot, ExpressionColor, LayerColorLabel, LayerId, LayerNode,
LayerNodeMeta, LayerPropsPatch, LayerType, ToneDensityType, ToneDotShape,
};
-pub use engine::{EngineConfig, EngineHandle};
+pub use engine::{EngineConfig, EngineHandle, EnginePerfSnapshot};
pub use history::{
AppliedHistoryChange, CanvasResizeDelta, HistoryEntry, HistoryItemMeta, HistoryStack,
HistoryStateSnapshot, LayerTreeMutation, SelectiveUndoOutcome,
@@ -88,6 +94,15 @@ pub use types::{
SurfaceTarget, ThumbnailUpdate, UiRect, ViewportRect, WheelNavMode,
};
+/// Serializes DX12 GPU test device allocations across all test modules so default parallel
+/// `cargo test --workspace` never oversubscribes integrated GPU VRAM (e.g. Intel Iris Xe).
+#[cfg(test)]
+pub(crate) fn lock_dx12_test() -> std::sync::MutexGuard<'static, ()> {
+ static DX12_TEST_LOCK: std::sync::LazyLock<std::sync::Mutex<()>> =
+ std::sync::LazyLock::new(|| std::sync::Mutex::new(()));
+ DX12_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner())
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -95,6 +110,7 @@ mod tests {
#[test]
fn test_headless_dx12_engine_vertical_slice_stroke_and_camera() {
+ let _dx12_guard = crate::lock_dx12_test();
let (handle, mut producers) = match EngineHandle::spawn(
SurfaceTarget::Headless {
width: 320,
diff --git a/crates/ink-engine/src/memory/gpu_pool.rs b/crates/ink-engine/src/memory/gpu_pool.rs
index ae4a452..1f8e5fe 100644
--- a/crates/ink-engine/src/memory/gpu_pool.rs
+++ b/crates/ink-engine/src/memory/gpu_pool.rs
@@ -5,10 +5,17 @@
//! so blending, filtering, and zoomed-out mipmaps execute with zero 8-bit banding.
use crate::memory::ScratchBackend;
-use crate::tiles::{TileCoord, TileData, BYTES_16F, BYTES_R16F, TILE_SIZE};
+use crate::tiles::{
+ SparseLayerGrid, TileCoord, TileData, TileFormat, BYTES_16F, BYTES_R16F, TILE_SIZE,
+};
use bytemuck::{Pod, Zeroable};
use std::borrow::Cow;
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
+use std::num::NonZeroU64;
+use std::sync::atomic::{AtomicU64, Ordering};
+
+const MIPMAP_UNIFORM_STRIDE: u64 = 256;
+static NEXT_POOL_ID: AtomicU64 = AtomicU64::new(1);
/// WGSL Compute Shader for 2×2 premultiplied-alpha box-filtered mipmap downsampling
/// (`4 child Rgba16Float tiles at LOD k-1 -> 1 parent Rgba16Float tile at LOD k`).
@@ -85,11 +92,12 @@ struct MipmapUniforms {
_pad: [u32; 4],
}
-/// Key identifying a single GPU-resident tile slice inside the L1 VRAM atlas.
-#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+/// Compact `Copy` key identifying a single GPU-resident tile slice inside the L1 VRAM atlas.
+/// Uses interned `u32` IDs for `doc_id` and `layer_id` (zero per-tile heap `String` allocations).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GpuTileKey {
- pub doc_id: String,
- pub layer_id: String,
+ pub doc_id: u32,
+ pub layer_id: u32,
pub lod: u8,
pub coord: TileCoord,
}
@@ -97,8 +105,80 @@ pub struct GpuTileKey {
#[derive(Debug, Clone)]
struct SlotRecord {
key: Option<GpuTileKey>,
+ solid_color: Option<[u16; 4]>,
version: u64,
- last_used_frame: u64,
+ last_access_seq: u64,
+ pin_count: u32,
+ ref_bit: bool,
+}
+
+impl SlotRecord {
+ #[inline]
+ fn empty() -> Self {
+ Self {
+ key: None,
+ solid_color: None,
+ version: 0,
+ last_access_seq: 0,
+ pin_count: 0,
+ ref_bit: false,
+ }
+ }
+
+ #[inline]
+ fn is_free(&self) -> bool {
+ self.key.is_none() && self.solid_color.is_none() && self.pin_count == 0
+ }
+}
+
+/// O(1) amortized Clock (Second-Chance LRU) victim selector that strictly skips pinned slots.
+/// Returns `None` if every single slot in `slots` currently has `pin_count > 0`.
+fn select_clock_victim(slots: &mut [SlotRecord], hand: &mut usize) -> Option<usize> {
+ let n = slots.len();
+ if n == 0 {
+ return None;
+ }
+ let mut idx = *hand % n;
+ // Two full revolutions guarantee finding any unpinned slot (first pass clears ref_bit, second evicts).
+ for _ in 0..(n * 2) {
+ let rec = &mut slots[idx];
+ if rec.pin_count == 0 {
+ if !rec.ref_bit {
+ *hand = (idx + 1) % n;
+ return Some(idx);
+ }
+ rec.ref_bit = false;
+ }
+ idx += 1;
+ if idx == n {
+ idx = 0;
+ }
+ }
+ None
+}
+
+/// Extreme fallback only if every slot in the atlas is simultaneously pinned and cannot grow.
+/// Picks the oldest slot WITHOUT resetting its `pin_count` (preserving caller ref-counting).
+fn select_oldest_pinned_fallback(slots: &[SlotRecord]) -> usize {
+ let mut fallback_idx = 0usize;
+ let mut oldest = u64::MAX;
+ for (i, rec) in slots.iter().enumerate() {
+ if rec.last_access_seq < oldest {
+ oldest = rec.last_access_seq;
+ fallback_idx = i;
+ }
+ }
+ fallback_idx
+}
+
+fn pop_free_slot(slots: &[SlotRecord], free_list: &mut Vec<u32>) -> Option<usize> {
+ while let Some(s) = free_list.pop() {
+ let idx = s as usize;
+ if idx < slots.len() && slots[idx].is_free() {
+ return Some(idx);
+ }
+ }
+ None
}
/// Live L1 GPU VRAM tile atlas telemetry.
@@ -119,18 +199,33 @@ struct ImpastoGpuAtlas {
view: wgpu::TextureView,
capacity: u32,
slots: Vec<SlotRecord>,
+ free_slots: Vec<u32>,
+ clock_hand: usize,
key_to_slot: HashMap<GpuTileKey, u32>,
}
+/// Job descriptor for batched GPU compute mipmap generation (`generate_mipmap_batch`).
+#[derive(Debug, Clone)]
+pub struct MipmapBatchJob {
+ pub parent_key: GpuTileKey,
+ pub child_slots: [Option<u32>; 4],
+ pub version: u64,
+}
+
/// L1 GPU VRAM tiled atlas (`256×256×N` `Rgba16Float`) + LRU allocator + compute mipmap generator.
pub struct GpuTilePool {
+ atlas_id: u64,
atlas_texture: wgpu::Texture,
atlas_array_view: wgpu::TextureView,
capacity: u32,
// Dedicated 256×256 Rgba16Float storage target for compute mipmap output (512 KB)
mipmap_scratch_tex: wgpu::Texture,
+ mipmap_scratch_view: wgpu::TextureView,
+ mipmap_bgl: wgpu::BindGroupLayout,
mipmap_uniform_buf: wgpu::Buffer,
+ mipmap_uniform_cap: usize,
+ mipmap_uniform_staging: Vec<u8>,
mipmap_bind_group: wgpu::BindGroup,
mipmap_pipeline: wgpu::ComputePipeline,
@@ -139,19 +234,40 @@ pub struct GpuTilePool {
mask_atlas_view: wgpu::TextureView,
mask_capacity: u32,
mask_slots: Vec<SlotRecord>,
+ mask_free_slots: Vec<u32>,
+ mask_clock_hand: usize,
mask_key_to_slot: HashMap<GpuTileKey, u32>,
// Lazily-allocated R16Float 2D array pool for persistent 3D impasto heightfield tiles (128 KB/slot)
impasto_atlas: Option<ImpastoGpuAtlas>,
+ impasto_atlas_id: u64,
impasto_desired_capacity: u32,
_dummy_impasto_tex: wgpu::Texture,
dummy_impasto_view: wgpu::TextureView,
+ // Reusable CPU upload scratch buffers (eliminates per-tile 512 KB heap allocations!)
+ upload_rgba16f_scratch: Vec<u8>,
+ upload_rgba8_scratch: Vec<u8>,
+ upload_r16f_scratch: Vec<u8>,
+ upload_mask8_scratch: Vec<u8>,
+
+ // Compact string interners so tile lookups on the render thread perform ZERO heap allocations
+ doc_intern: HashMap<String, u32>,
+ next_doc_id: u32,
+ layer_intern: HashMap<String, u32>,
+ next_layer_id: u32,
+
slots: Vec<SlotRecord>,
+ free_slots: Vec<u32>,
+ clock_hand: usize,
key_to_slot: HashMap<GpuTileKey, u32>,
+ solid_color_to_slot: HashMap<[u16; 4], u32>,
+ pinned_slots_count: u32,
+ access_seq: u64,
frame_counter: u64,
evictions: u64,
mipmaps_generated: u64,
+ mipmap_submits: u64,
}
impl GpuTilePool {
@@ -185,9 +301,10 @@ impl GpuTilePool {
let mipmap_scratch_view =
mipmap_scratch_tex.create_view(&wgpu::TextureViewDescriptor::default());
+ let mipmap_uniform_cap = 64usize;
let mipmap_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("ink-mipmap-uniforms"),
- size: std::mem::size_of::<MipmapUniforms>() as u64,
+ label: Some("ink-mipmap-uniforms-dyn"),
+ size: mipmap_uniform_cap as u64 * MIPMAP_UNIFORM_STRIDE,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
@@ -200,8 +317,10 @@ impl GpuTilePool {
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
- has_dynamic_offset: false,
- min_binding_size: None,
+ has_dynamic_offset: true,
+ min_binding_size: NonZeroU64::new(
+ std::mem::size_of::<MipmapUniforms>() as u64,
+ ),
},
count: None,
},
@@ -228,24 +347,13 @@ impl GpuTilePool {
],
});
- let mipmap_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-mipmap-bg"),
- layout: &mipmap_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: mipmap_uniform_buf.as_entire_binding(),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(&atlas_array_view),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::TextureView(&mipmap_scratch_view),
- },
- ],
- });
+ let mipmap_bind_group = Self::create_mipmap_bind_group(
+ device,
+ &mipmap_bgl,
+ &mipmap_uniform_buf,
+ &atlas_array_view,
+ &mipmap_scratch_view,
+ );
let mipmap_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("ink-mipmap-compute-shader"),
@@ -265,47 +373,193 @@ impl GpuTilePool {
cache: None,
});
- let slots = (0..capacity)
- .map(|_| SlotRecord {
- key: None,
- version: 0,
- last_used_frame: 0,
- })
- .collect();
- let mask_slots = (0..mask_capacity)
- .map(|_| SlotRecord {
- key: None,
- version: 0,
- last_used_frame: 0,
- })
- .collect();
+ let slots = (0..capacity).map(|_| SlotRecord::empty()).collect();
+ let free_slots: Vec<u32> = (0..capacity).rev().collect();
+ let mask_slots = (0..mask_capacity).map(|_| SlotRecord::empty()).collect();
+ let mask_free_slots: Vec<u32> = (0..mask_capacity).rev().collect();
let (_dummy_impasto_tex, dummy_impasto_view) = Self::create_dummy_impasto_atlas(device);
let impasto_desired_capacity = (capacity / 2).clamp(32, max_layers);
Self {
+ atlas_id: NEXT_POOL_ID.fetch_add(1, Ordering::Relaxed),
atlas_texture,
atlas_array_view,
capacity,
mipmap_scratch_tex,
+ mipmap_scratch_view,
+ mipmap_bgl,
mipmap_uniform_buf,
+ mipmap_uniform_cap,
+ mipmap_uniform_staging: Vec::with_capacity(64 * MIPMAP_UNIFORM_STRIDE as usize),
mipmap_bind_group,
mipmap_pipeline,
mask_atlas_texture,
mask_atlas_view,
mask_capacity,
mask_slots,
+ mask_free_slots,
+ mask_clock_hand: 0,
mask_key_to_slot: HashMap::with_capacity(mask_capacity as usize),
impasto_atlas: None,
+ impasto_atlas_id: 0,
impasto_desired_capacity,
_dummy_impasto_tex,
dummy_impasto_view,
+ upload_rgba16f_scratch: Vec::new(),
+ upload_rgba8_scratch: Vec::new(),
+ upload_r16f_scratch: Vec::new(),
+ upload_mask8_scratch: Vec::new(),
+ doc_intern: HashMap::with_capacity(8),
+ next_doc_id: 1,
+ layer_intern: HashMap::with_capacity(64),
+ next_layer_id: 1,
slots,
+ free_slots,
+ clock_hand: 0,
key_to_slot: HashMap::with_capacity(capacity as usize),
+ solid_color_to_slot: HashMap::with_capacity(8),
+ pinned_slots_count: 0,
+ access_seq: 1,
frame_counter: 1,
evictions: 0,
mipmaps_generated: 0,
+ mipmap_submits: 0,
+ }
+ }
+
+ fn create_mipmap_bind_group(
+ device: &wgpu::Device,
+ layout: &wgpu::BindGroupLayout,
+ uniform_buf: &wgpu::Buffer,
+ atlas_view: &wgpu::TextureView,
+ scratch_view: &wgpu::TextureView,
+ ) -> wgpu::BindGroup {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-mipmap-bg"),
+ layout,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(std::mem::size_of::<MipmapUniforms>() as u64),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(atlas_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(scratch_view),
+ },
+ ],
+ })
+ }
+
+ fn ensure_mipmap_uniform_capacity(&mut self, device: &wgpu::Device, needed: usize) {
+ if needed <= self.mipmap_uniform_cap {
+ return;
+ }
+ let new_cap = needed.next_power_of_two().max(64);
+ self.mipmap_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-mipmap-uniforms-dyn"),
+ size: new_cap as u64 * MIPMAP_UNIFORM_STRIDE,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ self.mipmap_uniform_cap = new_cap;
+ self.mipmap_bind_group = Self::create_mipmap_bind_group(
+ device,
+ &self.mipmap_bgl,
+ &self.mipmap_uniform_buf,
+ &self.atlas_array_view,
+ &self.mipmap_scratch_view,
+ );
+ }
+
+ /// Unique monotonic ID for this pool's color+mask atlas texture views (for compositor BG caching).
+ #[inline]
+ pub fn atlas_id(&self) -> u64 {
+ self.atlas_id
+ }
+
+ /// Unique monotonic ID for the lazily-allocated impasto height atlas (`0` while dummy 1×1 is bound).
+ #[inline]
+ pub fn impasto_atlas_id(&self) -> u64 {
+ self.impasto_atlas_id
+ }
+
+ /// Interns a document ID string into a compact `u32` (zero heap allocations on cache hit).
+ #[inline]
+ pub fn intern_doc(&mut self, doc_id: &str) -> u32 {
+ if let Some(&id) = self.doc_intern.get(doc_id) {
+ return id;
}
+ let id = self.next_doc_id;
+ self.next_doc_id = self.next_doc_id.saturating_add(1);
+ self.doc_intern.insert(doc_id.to_string(), id);
+ id
+ }
+
+ /// Interns a layer ID string into a compact `u32` (zero heap allocations on cache hit).
+ #[inline]
+ pub fn intern_layer(&mut self, layer_id: &str) -> u32 {
+ if let Some(&id) = self.layer_intern.get(layer_id) {
+ return id;
+ }
+ let id = self.next_layer_id;
+ self.next_layer_id = self.next_layer_id.saturating_add(1);
+ self.layer_intern.insert(layer_id.to_string(), id);
+ id
+ }
+
+ #[inline]
+ pub fn lookup_doc_id(&self, doc_id: &str) -> Option<u32> {
+ self.doc_intern.get(doc_id).copied()
+ }
+
+ #[inline]
+ pub fn lookup_layer_id(&self, layer_id: &str) -> Option<u32> {
+ self.layer_intern.get(layer_id).copied()
+ }
+
+ /// Convenience helper building a compact `GpuTileKey` using the pool's string interner.
+ #[inline]
+ pub fn make_key(&mut self, doc_id: &str, layer_id: &str, lod: u8, coord: TileCoord) -> GpuTileKey {
+ let doc_id = self.intern_doc(doc_id);
+ let layer_id = self.intern_layer(layer_id);
+ GpuTileKey {
+ doc_id,
+ layer_id,
+ lod,
+ coord,
+ }
+ }
+
+ /// Read-only key builder that returns `None` if `doc_id` or `layer_id` has never been interned.
+ #[inline]
+ pub fn try_make_key(
+ &self,
+ doc_id: &str,
+ layer_id: &str,
+ lod: u8,
+ coord: TileCoord,
+ ) -> Option<GpuTileKey> {
+ Some(GpuTileKey {
+ doc_id: self.lookup_doc_id(doc_id)?,
+ layer_id: self.lookup_layer_id(layer_id)?,
+ lod,
+ coord,
+ })
+ }
+
+ /// Total GPU queue submissions issued for mipmap generation (for perf telemetry/tests).
+ #[inline]
+ pub fn mipmap_submits(&self) -> u64 {
+ self.mipmap_submits
}
fn create_dummy_impasto_atlas(device: &wgpu::Device) -> (wgpu::Texture, wgpu::TextureView) {
@@ -354,18 +608,15 @@ impl GpuTilePool {
dimension: Some(wgpu::TextureViewDimension::D2Array),
..Default::default()
});
- let slots = (0..capacity)
- .map(|_| SlotRecord {
- key: None,
- version: 0,
- last_used_frame: 0,
- })
- .collect();
+ let slots = (0..capacity).map(|_| SlotRecord::empty()).collect();
+ let free_slots: Vec<u32> = (0..capacity).rev().collect();
ImpastoGpuAtlas {
texture,
view,
capacity,
slots,
+ free_slots,
+ clock_hand: 0,
key_to_slot: HashMap::with_capacity(capacity as usize),
}
}
@@ -414,7 +665,9 @@ impl GpuTilePool {
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::R8Unorm,
- usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING
+ | wgpu::TextureUsages::COPY_DST
+ | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let view = texture.create_view(&wgpu::TextureViewDescriptor {
@@ -430,6 +683,111 @@ impl GpuTilePool {
self.frame_counter = self.frame_counter.saturating_add(1);
}
+ #[inline]
+ fn next_access_seq(&mut self) -> u64 {
+ self.access_seq = self.access_seq.saturating_add(1);
+ self.access_seq
+ }
+
+ /// Pins a color atlas slot so LRU eviction will NEVER evict it until unpinned.
+ /// Reference-counted so overlapping/nested pin scopes compose cleanly.
+ #[inline]
+ pub fn pin_slot(&mut self, slot: u32) {
+ if let Some(rec) = self.slots.get_mut(slot as usize) {
+ if rec.pin_count == 0 {
+ self.pinned_slots_count = self.pinned_slots_count.saturating_add(1);
+ }
+ rec.pin_count = rec.pin_count.saturating_add(1);
+ }
+ }
+
+ /// Decrements the pin count for a color atlas slot.
+ #[inline]
+ pub fn unpin_slot(&mut self, slot: u32) {
+ if let Some(rec) = self.slots.get_mut(slot as usize) {
+ if rec.pin_count > 0 {
+ rec.pin_count -= 1;
+ if rec.pin_count == 0 {
+ self.pinned_slots_count = self.pinned_slots_count.saturating_sub(1);
+ }
+ }
+ }
+ }
+
+ /// Returns whether a color atlas slot currently has a non-zero pin count.
+ #[inline]
+ pub fn is_slot_pinned(&self, slot: u32) -> bool {
+ self.slots
+ .get(slot as usize)
+ .is_some_and(|rec| rec.pin_count > 0)
+ }
+
+ /// Number of color atlas slots currently unpinned and available for LRU eviction.
+ #[inline]
+ pub fn unpinned_slot_count(&self) -> u32 {
+ self.capacity.saturating_sub(self.pinned_slots_count)
+ }
+
+ /// Pins a mask atlas slot so LRU eviction will not evict it until unpinned.
+ #[inline]
+ pub fn pin_mask_slot(&mut self, slot: u32) {
+ if let Some(rec) = self.mask_slots.get_mut(slot as usize) {
+ rec.pin_count = rec.pin_count.saturating_add(1);
+ }
+ }
+
+ /// Unpins a mask atlas slot.
+ #[inline]
+ pub fn unpin_mask_slot(&mut self, slot: u32) {
+ if let Some(rec) = self.mask_slots.get_mut(slot as usize) {
+ rec.pin_count = rec.pin_count.saturating_sub(1);
+ }
+ }
+
+ /// Pins an impasto heightfield atlas slot so LRU eviction will not evict it until unpinned.
+ #[inline]
+ pub fn pin_impasto_slot(&mut self, slot: u32) {
+ if let Some(atlas) = self.impasto_atlas.as_mut() {
+ if let Some(rec) = atlas.slots.get_mut(slot as usize) {
+ rec.pin_count = rec.pin_count.saturating_add(1);
+ }
+ }
+ }
+
+ /// Unpins an impasto heightfield atlas slot.
+ #[inline]
+ pub fn unpin_impasto_slot(&mut self, slot: u32) {
+ if let Some(atlas) = self.impasto_atlas.as_mut() {
+ if let Some(rec) = atlas.slots.get_mut(slot as usize) {
+ rec.pin_count = rec.pin_count.saturating_sub(1);
+ }
+ }
+ }
+
+ /// Releases all pins across color, mask, and impasto pools (typically at frame end).
+ pub fn unpin_all_pinned(&mut self) {
+ for rec in &mut self.slots {
+ rec.pin_count = 0;
+ }
+ self.pinned_slots_count = 0;
+ for rec in &mut self.mask_slots {
+ rec.pin_count = 0;
+ }
+ if let Some(atlas) = self.impasto_atlas.as_mut() {
+ for rec in &mut atlas.slots {
+ rec.pin_count = 0;
+ }
+ }
+ }
+
+ #[inline]
+ pub fn impasto_capacity(&self) -> u32 {
+ self.impasto_atlas
+ .as_ref()
+ .map(|a| a.capacity)
+ .unwrap_or(self.impasto_desired_capacity)
+ }
+
#[inline]
pub fn atlas_texture(&self) -> &wgpu::Texture {
&self.atlas_texture
@@ -480,7 +838,7 @@ impl GpuTilePool {
}
pub fn stats(&self) -> GpuPoolStats {
- let used = self.key_to_slot.len() as u32;
+ let used = (self.key_to_slot.len() + self.solid_color_to_slot.len()) as u32;
let (imp_used_bytes, imp_cap_bytes) = self
.impasto_atlas
.as_ref()
@@ -505,40 +863,198 @@ impl GpuTilePool {
}
}
- /// Looks up a resident GPU tile slot and touches its LRU timestamp.
+ /// Looks up a resident GPU tile slot and touches its monotonic LRU sequence + clock ref bit.
pub fn get_slot(&mut self, key: &GpuTileKey) -> Option<u32> {
let &slot = self.key_to_slot.get(key)?;
- self.slots[slot as usize].last_used_frame = self.frame_counter;
+ let seq = self.next_access_seq();
+ let rec = &mut self.slots[slot as usize];
+ rec.last_access_seq = seq;
+ rec.ref_bit = true;
+ Some(slot)
+ }
+
+ /// Looks up a resident shared `SolidColor` VRAM slot and touches its monotonic LRU sequence.
+ pub fn get_solid_color_slot(&mut self, rgba16f: [u16; 4]) -> Option<u32> {
+ let &slot = self.solid_color_to_slot.get(&rgba16f)?;
+ let seq = self.next_access_seq();
+ let rec = &mut self.slots[slot as usize];
+ rec.last_access_seq = seq;
+ rec.ref_bit = true;
Some(slot)
}
+ /// Ensures a single shared `Rgba16Float` VRAM slot exists for uniform `rgba16f` solid color,
+ /// uploading once per unique solid color so full-canvas solid backgrounds consume 1 slot total.
+ pub fn ensure_solid_color_slot(&mut self, queue: &wgpu::Queue, rgba16f: [u16; 4]) -> u32 {
+ if let Some(slot) = self.get_solid_color_slot(rgba16f) {
+ return slot;
+ }
+ let slot = self.acquire_solid_color_slot(rgba16f);
+ self.upload_rgba16f_scratch.resize(BYTES_16F, 0);
+ let mut px = [0u8; 8];
+ px[0..2].copy_from_slice(&rgba16f[0].to_le_bytes());
+ px[2..4].copy_from_slice(&rgba16f[1].to_le_bytes());
+ px[4..6].copy_from_slice(&rgba16f[2].to_le_bytes());
+ px[6..8].copy_from_slice(&rgba16f[3].to_le_bytes());
+ for chunk in self.upload_rgba16f_scratch.chunks_exact_mut(8) {
+ chunk.copy_from_slice(&px);
+ }
+ Self::write_rgba16f_slice(&self.atlas_texture, queue, slot, &self.upload_rgba16f_scratch);
+ slot
+ }
+
/// Looks up a resident GPU tile slot only if its cached version matches `expected_version`.
pub fn get_slot_if_version(&mut self, key: &GpuTileKey, expected_version: u64) -> Option<u32> {
let &slot = self.key_to_slot.get(key)?;
- let rec = &mut self.slots[slot as usize];
- if rec.version != expected_version {
+ if self.slots[slot as usize].version != expected_version {
return None;
}
- rec.last_used_frame = self.frame_counter;
+ let seq = self.next_access_seq();
+ let rec = &mut self.slots[slot as usize];
+ rec.last_access_seq = seq;
+ rec.ref_bit = true;
Some(slot)
}
- /// Looks up a resident GPU mask tile slot and touches its LRU timestamp.
+ /// Looks up a resident GPU mask tile slot and touches its monotonic LRU sequence.
pub fn get_mask_slot(&mut self, key: &GpuTileKey) -> Option<u32> {
let &slot = self.mask_key_to_slot.get(key)?;
- self.mask_slots[slot as usize].last_used_frame = self.frame_counter;
+ let seq = self.next_access_seq();
+ let rec = &mut self.mask_slots[slot as usize];
+ rec.last_access_seq = seq;
+ rec.ref_bit = true;
Some(slot)
}
- /// Looks up a resident GPU `R16Float` impasto heightfield tile slot and touches its LRU timestamp.
+ /// Looks up a resident GPU `R16Float` impasto heightfield tile slot and touches its monotonic LRU sequence.
pub fn get_impasto_slot(&mut self, key: &GpuTileKey) -> Option<u32> {
- let frame = self.frame_counter;
+ let seq = self.next_access_seq();
let atlas = self.impasto_atlas.as_mut()?;
let &slot = atlas.key_to_slot.get(key)?;
- atlas.slots[slot as usize].last_used_frame = frame;
+ let rec = &mut atlas.slots[slot as usize];
+ rec.last_access_seq = seq;
+ rec.ref_bit = true;
Some(slot)
}
+ /// Grows the `R16Float` impasto atlas texture array if all slots are pinned and capacity < max_layers.
+ fn try_grow_impasto_atlas(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) -> bool {
+ let max_layers = device.limits().max_texture_array_layers.max(16);
+ let Some(atlas) = self.impasto_atlas.as_mut() else {
+ return false;
+ };
+ if atlas.capacity >= max_layers {
+ return false;
+ }
+ let old_cap = atlas.capacity;
+ let new_cap = (old_cap.saturating_mul(2)).min(max_layers);
+ if new_cap <= old_cap {
+ return false;
+ }
+ let new_atlas_tex = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("ink-l1-impasto-atlas-r16f"),
+ size: wgpu::Extent3d {
+ width: TILE_SIZE as u32,
+ height: TILE_SIZE as u32,
+ depth_or_array_layers: new_cap,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::R16Float,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING
+ | wgpu::TextureUsages::COPY_DST
+ | wgpu::TextureUsages::COPY_SRC
+ | wgpu::TextureUsages::RENDER_ATTACHMENT,
+ view_formats: &[],
+ });
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-impasto-atlas-grow-copy"),
+ });
+ encoder.copy_texture_to_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: &atlas.texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::TexelCopyTextureInfo {
+ texture: &new_atlas_tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::Extent3d {
+ width: TILE_SIZE as u32,
+ height: TILE_SIZE as u32,
+ depth_or_array_layers: old_cap,
+ },
+ );
+ queue.submit(Some(encoder.finish()));
+
+ atlas.view = new_atlas_tex.create_view(&wgpu::TextureViewDescriptor {
+ label: Some("ink-l1-impasto-atlas-r16f-view"),
+ dimension: Some(wgpu::TextureViewDimension::D2Array),
+ ..Default::default()
+ });
+ atlas.texture = new_atlas_tex;
+ atlas.capacity = new_cap;
+ atlas.slots.resize_with(new_cap as usize, SlotRecord::empty);
+ for s in (old_cap..new_cap).rev() {
+ atlas.free_slots.push(s);
+ }
+ self.impasto_atlas_id = NEXT_POOL_ID.fetch_add(1, Ordering::Relaxed);
+ true
+ }
+
+ /// Grows the `R8Unorm` mask atlas texture array if all slots are pinned and capacity < max_layers.
+ fn try_grow_mask_atlas(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) -> bool {
+ let max_layers = device.limits().max_texture_array_layers.max(16);
+ if self.mask_capacity >= max_layers {
+ return false;
+ }
+ let old_cap = self.mask_capacity;
+ let new_cap = (old_cap.saturating_mul(2)).min(max_layers);
+ if new_cap <= old_cap {
+ return false;
+ }
+ let (new_tex, new_view) = Self::create_mask_atlas(device, new_cap);
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-mask-atlas-grow-copy"),
+ });
+ encoder.copy_texture_to_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: &self.mask_atlas_texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::TexelCopyTextureInfo {
+ texture: &new_tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::Extent3d {
+ width: TILE_SIZE as u32,
+ height: TILE_SIZE as u32,
+ depth_or_array_layers: old_cap,
+ },
+ );
+ queue.submit(Some(encoder.finish()));
+
+ self.mask_atlas_texture = new_tex;
+ self.mask_atlas_view = new_view;
+ self.mask_capacity = new_cap;
+ self.mask_slots
+ .resize_with(new_cap as usize, SlotRecord::empty);
+ for s in (old_cap..new_cap).rev() {
+ self.mask_free_slots.push(s);
+ }
+ self.atlas_id = NEXT_POOL_ID.fetch_add(1, Ordering::Relaxed);
+ true
+ }
+
/// Lazily allocates an `R16Float` impasto heightfield slot (creating the atlas on first use).
pub fn acquire_impasto_slot(
&mut self,
@@ -546,43 +1062,78 @@ impl GpuTilePool {
key: GpuTileKey,
version: u64,
) -> u32 {
- let frame = self.frame_counter;
+ self.acquire_impasto_slot_inner(device, None, key, version)
+ }
+
+ fn acquire_impasto_slot_inner(
+ &mut self,
+ device: &wgpu::Device,
+ queue: Option<&wgpu::Queue>,
+ key: GpuTileKey,
+ version: u64,
+ ) -> u32 {
+ let seq = self.next_access_seq();
let cap = self.impasto_desired_capacity;
- let atlas = self
- .impasto_atlas
- .get_or_insert_with(|| Self::create_impasto_atlas(device, cap));
+ let impasto_id = &mut self.impasto_atlas_id;
+ let atlas = self.impasto_atlas.get_or_insert_with(|| {
+ *impasto_id = NEXT_POOL_ID.fetch_add(1, Ordering::Relaxed);
+ Self::create_impasto_atlas(device, cap)
+ });
if let Some(&existing) = atlas.key_to_slot.get(&key) {
let rec = &mut atlas.slots[existing as usize];
rec.version = version;
- rec.last_used_frame = frame;
+ rec.last_access_seq = seq;
+ rec.ref_bit = true;
return existing;
}
- for (i, rec) in atlas.slots.iter_mut().enumerate() {
- if rec.key.is_none() {
- rec.key = Some(key.clone());
- rec.version = version;
- rec.last_used_frame = frame;
- atlas.key_to_slot.insert(key, i as u32);
- return i as u32;
- }
+ if let Some(free_idx) = pop_free_slot(&atlas.slots, &mut atlas.free_slots) {
+ let rec = &mut atlas.slots[free_idx];
+ rec.key = Some(key);
+ rec.solid_color = None;
+ rec.version = version;
+ rec.last_access_seq = seq;
+ rec.ref_bit = true;
+ atlas.key_to_slot.insert(key, free_idx as u32);
+ return free_idx as u32;
}
- let mut victim = 0usize;
- let mut oldest = u64::MAX;
- for (i, rec) in atlas.slots.iter().enumerate() {
- if rec.last_used_frame < oldest {
- oldest = rec.last_used_frame;
- victim = i;
+
+ let victim_opt = select_clock_victim(&mut atlas.slots, &mut atlas.clock_hand);
+ let victim = match victim_opt {
+ Some(v) => v,
+ None => {
+ // Every impasto slot is currently pinned: grow cleanly if queue is available!
+ if let Some(q) = queue {
+ if self.try_grow_impasto_atlas(device, q) {
+ let atlas = self.impasto_atlas.as_mut().expect("impasto atlas grown");
+ if let Some(free_idx) = pop_free_slot(&atlas.slots, &mut atlas.free_slots) {
+ let rec = &mut atlas.slots[free_idx];
+ rec.key = Some(key);
+ rec.solid_color = None;
+ rec.version = version;
+ rec.last_access_seq = seq;
+ rec.ref_bit = true;
+ atlas.key_to_slot.insert(key, free_idx as u32);
+ return free_idx as u32;
+ }
+ }
+ }
+ let atlas = self.impasto_atlas.as_mut().expect("impasto atlas exists");
+ select_oldest_pinned_fallback(&atlas.slots)
}
- }
+ };
+
+ let atlas = self.impasto_atlas.as_mut().expect("impasto atlas exists");
if let Some(old) = atlas.slots[victim].key.take() {
atlas.key_to_slot.remove(&old);
self.evictions = self.evictions.saturating_add(1);
}
- atlas.slots[victim] = SlotRecord {
- key: Some(key.clone()),
- version,
- last_used_frame: frame,
- };
+ // Update fields in-place to preserve `pin_count` if extreme fallback was hit
+ let rec = &mut atlas.slots[victim];
+ rec.key = Some(key);
+ rec.solid_color = None;
+ rec.version = version;
+ rec.last_access_seq = seq;
+ rec.ref_bit = true;
atlas.key_to_slot.insert(key, victim as u32);
victim as u32
}
@@ -597,31 +1148,30 @@ impl GpuTilePool {
tile: &TileData,
scratch: Option<&dyn ScratchBackend>,
) -> Result<u32, String> {
- let frame = self.frame_counter;
+ let seq = self.next_access_seq();
if let Some(atlas) = self.impasto_atlas.as_mut() {
if let Some(&slot) = atlas.key_to_slot.get(&key) {
let rec = &mut atlas.slots[slot as usize];
- rec.last_used_frame = frame;
+ rec.last_access_seq = seq;
+ rec.ref_bit = true;
if rec.version == tile.version {
return Ok(slot);
}
}
}
- let raw_r16f = tile.to_r16f(scratch)?;
- let slot = self.acquire_impasto_slot(device, key, tile.version);
- self.upload_impasto_r16f_slot(queue, slot, &raw_r16f);
+ tile.write_r16f_into(scratch, &mut self.upload_r16f_scratch)?;
+ let slot = self.acquire_impasto_slot_inner(device, Some(queue), key, tile.version);
+ if let Some(atlas) = self.impasto_atlas.as_ref() {
+ Self::write_r16f_slice(&atlas.texture, queue, slot, &self.upload_r16f_scratch);
+ }
Ok(slot)
}
- /// Writes 131,072 bytes (`256×256` `R16Float`, `bytes_per_row = 512`) into impasto atlas `slot`.
- pub fn upload_impasto_r16f_slot(&self, queue: &wgpu::Queue, slot: u32, r16f: &[u8]) {
+ fn write_r16f_slice(texture: &wgpu::Texture, queue: &wgpu::Queue, slot: u32, r16f: &[u8]) {
debug_assert_eq!(r16f.len(), BYTES_R16F);
- let Some(atlas) = self.impasto_atlas.as_ref() else {
- return;
- };
queue.write_texture(
wgpu::TexelCopyTextureInfo {
- texture: &atlas.texture,
+ texture,
mip_level: 0,
origin: wgpu::Origin3d {
x: 0,
@@ -644,12 +1194,24 @@ impl GpuTilePool {
);
}
+ /// Writes 131,072 bytes (`256×256` `R16Float`, `bytes_per_row = 512`) into impasto atlas `slot`.
+ pub fn upload_impasto_r16f_slot(&self, queue: &wgpu::Queue, slot: u32, r16f: &[u8]) {
+ let Some(atlas) = self.impasto_atlas.as_ref() else {
+ return;
+ };
+ Self::write_r16f_slice(&atlas.texture, queue, slot, r16f);
+ }
+
/// Evicts a single cached `R16Float` impasto tile key if resident.
pub fn evict_impasto_key(&mut self, key: &GpuTileKey) {
if let Some(atlas) = self.impasto_atlas.as_mut() {
if let Some(slot) = atlas.key_to_slot.remove(key) {
- atlas.slots[slot as usize].key = None;
- atlas.slots[slot as usize].version = 0;
+ let rec = &mut atlas.slots[slot as usize];
+ rec.key = None;
+ rec.version = 0;
+ rec.pin_count = 0;
+ rec.ref_bit = false;
+ atlas.free_slots.push(slot);
}
}
}
@@ -657,56 +1219,83 @@ impl GpuTilePool {
/// Evicts a single cached mask tile key if resident.
pub fn evict_mask_key(&mut self, key: &GpuTileKey) {
if let Some(slot) = self.mask_key_to_slot.remove(key) {
- self.mask_slots[slot as usize].key = None;
- self.mask_slots[slot as usize].version = 0;
+ let rec = &mut self.mask_slots[slot as usize];
+ rec.key = None;
+ rec.version = 0;
+ rec.pin_count = 0;
+ rec.ref_bit = false;
+ self.mask_free_slots.push(slot);
}
}
- /// Allocates a free slot or evicts the least-recently-used slot from the L1 VRAM pool.
- pub fn acquire_slot(&mut self, key: GpuTileKey, version: u64) -> u32 {
- if let Some(&existing) = self.key_to_slot.get(&key) {
- let rec = &mut self.slots[existing as usize];
- rec.version = version;
- rec.last_used_frame = self.frame_counter;
- return existing;
+ fn allocate_color_victim(&mut self) -> usize {
+ if let Some(free_idx) = pop_free_slot(&self.slots, &mut self.free_slots) {
+ return free_idx;
}
-
- // First look for an empty slot
- for (i, rec) in self.slots.iter_mut().enumerate() {
- if rec.key.is_none() {
- rec.key = Some(key.clone());
- rec.version = version;
- rec.last_used_frame = self.frame_counter;
- self.key_to_slot.insert(key, i as u32);
- return i as u32;
+ let victim_idx = match select_clock_victim(&mut self.slots, &mut self.clock_hand) {
+ Some(idx) => idx,
+ None => {
+ // Extreme fallback: every slot in the color atlas is simultaneously pinned.
+ // NEVER reset `pin_count` or decrement `pinned_slots_count` here so active
+ // pin-scope holders' subsequent `unpin_slot()` calls remain balanced!
+ select_oldest_pinned_fallback(&self.slots)
}
+ };
+ if let Some(old_key) = self.slots[victim_idx].key.take() {
+ self.key_to_slot.remove(&old_key);
+ self.evictions = self.evictions.saturating_add(1);
+ } else if let Some(old_solid) = self.slots[victim_idx].solid_color.take() {
+ self.solid_color_to_slot.remove(&old_solid);
+ self.evictions = self.evictions.saturating_add(1);
}
+ victim_idx
+ }
- // Pool full -> evict the strictly least-recently-used slot
- let mut victim_idx = 0usize;
- let mut oldest_frame = u64::MAX;
- for (i, rec) in self.slots.iter().enumerate() {
- if rec.last_used_frame < oldest_frame {
- oldest_frame = rec.last_used_frame;
- victim_idx = i;
- }
+ fn acquire_solid_color_slot(&mut self, rgba16f: [u16; 4]) -> u32 {
+ let seq = self.next_access_seq();
+ if let Some(&existing) = self.solid_color_to_slot.get(&rgba16f) {
+ let rec = &mut self.slots[existing as usize];
+ rec.last_access_seq = seq;
+ rec.ref_bit = true;
+ return existing;
}
+ let victim_idx = self.allocate_color_victim();
+ let rec = &mut self.slots[victim_idx];
+ rec.key = None;
+ rec.solid_color = Some(rgba16f);
+ rec.version = 0;
+ rec.last_access_seq = seq;
+ rec.ref_bit = true;
+ self.solid_color_to_slot.insert(rgba16f, victim_idx as u32);
+ victim_idx as u32
+ }
- if let Some(old_key) = self.slots[victim_idx].key.take() {
- self.key_to_slot.remove(&old_key);
- self.evictions = self.evictions.saturating_add(1);
+ /// Allocates a free slot or evicts the least-recently-used unpinned slot from the L1 VRAM pool.
+ pub fn acquire_slot(&mut self, key: GpuTileKey, version: u64) -> u32 {
+ let seq = self.next_access_seq();
+ if let Some(&existing) = self.key_to_slot.get(&key) {
+ let rec = &mut self.slots[existing as usize];
+ rec.version = version;
+ rec.last_access_seq = seq;
+ rec.ref_bit = true;
+ return existing;
}
- self.slots[victim_idx] = SlotRecord {
- key: Some(key.clone()),
- version,
- last_used_frame: self.frame_counter,
- };
+
+ let victim_idx = self.allocate_color_victim();
+ let rec = &mut self.slots[victim_idx];
+ rec.key = Some(key);
+ rec.solid_color = None;
+ rec.version = version;
+ rec.last_access_seq = seq;
+ rec.ref_bit = true;
self.key_to_slot.insert(key, victim_idx as u32);
victim_idx as u32
}
/// Ensures a CPU/L2/L3 [`TileData`] is uploaded to an L1 VRAM `Rgba16Float` slot,
- /// skipping redundant GPU uploads when `version` matches.
+ /// deduplicating uniform `SolidColor` tiles onto a single shared slot per unique color,
+ /// reusing a persistent scratch upload buffer (zero per-tile 512 KB heap allocations!),
+ /// and skipping redundant GPU uploads when `version` matches.
pub fn ensure_tile_uploaded(
&mut self,
queue: &wgpu::Queue,
@@ -714,26 +1303,51 @@ impl GpuTilePool {
tile: &TileData,
scratch: Option<&dyn ScratchBackend>,
) -> Result<u32, String> {
+ if let Some(solid_16f) = tile.solid_rgba16f() {
+ // If this key previously held a non-solid per-tile slot, release it.
+ self.evict_key(&key);
+ return Ok(self.ensure_solid_color_slot(queue, solid_16f));
+ }
+
if let Some(&slot) = self.key_to_slot.get(&key) {
+ let seq = self.next_access_seq();
let rec = &mut self.slots[slot as usize];
- rec.last_used_frame = self.frame_counter;
+ rec.last_access_seq = seq;
+ rec.ref_bit = true;
if rec.version == tile.version {
return Ok(slot);
}
}
- let rgba16f = tile.to_rgba16f(scratch)?;
+ // Fast zero-copy path when tile is already Raw Rgba16Float
+ if tile.format == TileFormat::Rgba16Float {
+ if let crate::tiles::TileStorage::Raw(ref raw_16f) = tile.storage {
+ let slot = self.acquire_slot(key, tile.version);
+ Self::write_rgba16f_slice(&self.atlas_texture, queue, slot, raw_16f);
+ return Ok(slot);
+ }
+ }
+
+ tile.write_rgba16f_into(
+ scratch,
+ &mut self.upload_rgba16f_scratch,
+ &mut self.upload_rgba8_scratch,
+ )?;
let slot = self.acquire_slot(key, tile.version);
- self.upload_rgba16f_slot(queue, slot, &rgba16f);
+ Self::write_rgba16f_slice(&self.atlas_texture, queue, slot, &self.upload_rgba16f_scratch);
Ok(slot)
}
- /// Directly writes 524,288 bytes of `Rgba16Float` pixel data into `slot`.
- pub fn upload_rgba16f_slot(&self, queue: &wgpu::Queue, slot: u32, rgba16f: &[u8]) {
+ fn write_rgba16f_slice(
+ texture: &wgpu::Texture,
+ queue: &wgpu::Queue,
+ slot: u32,
+ rgba16f: &[u8],
+ ) {
debug_assert_eq!(rgba16f.len(), BYTES_16F);
queue.write_texture(
wgpu::TexelCopyTextureInfo {
- texture: &self.atlas_texture,
+ texture,
mip_level: 0,
origin: wgpu::Origin3d {
x: 0,
@@ -756,26 +1370,49 @@ impl GpuTilePool {
);
}
- /// Uploads an 8-bit mask tile (`65,536` bytes) into the compact `R8Unorm` mask atlas.
+ /// Directly writes 524,288 bytes of `Rgba16Float` pixel data into `slot`.
+ pub fn upload_rgba16f_slot(&self, queue: &wgpu::Queue, slot: u32, rgba16f: &[u8]) {
+ Self::write_rgba16f_slice(&self.atlas_texture, queue, slot, rgba16f);
+ }
+
+ /// Uploads an 8-bit mask tile (`65,536` bytes) into the compact `R8Unorm` mask atlas,
+ /// protecting pinned mask slots and cleanly growing capacity if all slots are pinned.
pub fn ensure_mask_uploaded(
&mut self,
+ device: &wgpu::Device,
queue: &wgpu::Queue,
key: GpuTileKey,
tile: &TileData,
scratch: Option<&dyn ScratchBackend>,
) -> Result<u32, String> {
if let Some(&slot) = self.mask_key_to_slot.get(&key) {
+ let seq = self.next_access_seq();
let rec = &mut self.mask_slots[slot as usize];
- rec.last_used_frame = self.frame_counter;
+ rec.last_access_seq = seq;
+ rec.ref_bit = true;
if rec.version == tile.version {
return Ok(slot);
}
}
- let raw_mask = tile.materialize_raw(scratch)?;
- let slot = self.acquire_mask_slot(key, tile.version);
+ let slot = self.acquire_mask_slot(device, queue, key, tile.version);
+ if let crate::tiles::TileStorage::Raw(ref raw_mask) = tile.storage {
+ Self::write_mask8_slice(&self.mask_atlas_texture, queue, slot, raw_mask);
+ return Ok(slot);
+ }
+ tile.write_mask8_into(scratch, &mut self.upload_mask8_scratch)?;
+ Self::write_mask8_slice(
+ &self.mask_atlas_texture,
+ queue,
+ slot,
+ &self.upload_mask8_scratch,
+ );
+ Ok(slot)
+ }
+
+ fn write_mask8_slice(texture: &wgpu::Texture, queue: &wgpu::Queue, slot: u32, mask8: &[u8]) {
queue.write_texture(
wgpu::TexelCopyTextureInfo {
- texture: &self.mask_atlas_texture,
+ texture,
mip_level: 0,
origin: wgpu::Origin3d {
x: 0,
@@ -784,7 +1421,7 @@ impl GpuTilePool {
},
aspect: wgpu::TextureAspect::All,
},
- &raw_mask,
+ mask8,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(TILE_SIZE as u32), // 256 bytes (exact alignment!)
@@ -796,45 +1433,195 @@ impl GpuTilePool {
depth_or_array_layers: 1,
},
);
- Ok(slot)
}
- fn acquire_mask_slot(&mut self, key: GpuTileKey, version: u64) -> u32 {
+ fn acquire_mask_slot(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ key: GpuTileKey,
+ version: u64,
+ ) -> u32 {
+ let seq = self.next_access_seq();
if let Some(&existing) = self.mask_key_to_slot.get(&key) {
let rec = &mut self.mask_slots[existing as usize];
rec.version = version;
- rec.last_used_frame = self.frame_counter;
+ rec.last_access_seq = seq;
+ rec.ref_bit = true;
return existing;
}
- for (i, rec) in self.mask_slots.iter_mut().enumerate() {
- if rec.key.is_none() {
- rec.key = Some(key.clone());
- rec.version = version;
- rec.last_used_frame = self.frame_counter;
- self.mask_key_to_slot.insert(key, i as u32);
- return i as u32;
- }
+ if let Some(free_idx) = pop_free_slot(&self.mask_slots, &mut self.mask_free_slots) {
+ let rec = &mut self.mask_slots[free_idx];
+ rec.key = Some(key);
+ rec.solid_color = None;
+ rec.version = version;
+ rec.last_access_seq = seq;
+ rec.ref_bit = true;
+ self.mask_key_to_slot.insert(key, free_idx as u32);
+ return free_idx as u32;
}
- let mut victim = 0usize;
- let mut oldest = u64::MAX;
- for (i, rec) in self.mask_slots.iter().enumerate() {
- if rec.last_used_frame < oldest {
- oldest = rec.last_used_frame;
- victim = i;
+ let victim = match select_clock_victim(&mut self.mask_slots, &mut self.mask_clock_hand) {
+ Some(v) => v,
+ None => {
+ if self.try_grow_mask_atlas(device, queue) {
+ if let Some(free_idx) =
+ pop_free_slot(&self.mask_slots, &mut self.mask_free_slots)
+ {
+ let rec = &mut self.mask_slots[free_idx];
+ rec.key = Some(key);
+ rec.solid_color = None;
+ rec.version = version;
+ rec.last_access_seq = seq;
+ rec.ref_bit = true;
+ self.mask_key_to_slot.insert(key, free_idx as u32);
+ return free_idx as u32;
+ }
+ }
+ select_oldest_pinned_fallback(&self.mask_slots)
}
- }
+ };
if let Some(old) = self.mask_slots[victim].key.take() {
self.mask_key_to_slot.remove(&old);
}
- self.mask_slots[victim] = SlotRecord {
- key: Some(key.clone()),
- version,
- last_used_frame: self.frame_counter,
- };
+ let rec = &mut self.mask_slots[victim];
+ rec.key = Some(key);
+ rec.solid_color = None;
+ rec.version = version;
+ rec.last_access_seq = seq;
+ rec.ref_bit = true;
self.mask_key_to_slot.insert(key, victim as u32);
victim as u32
}
+ /// Internal helper: uploads all `dispatches` uniforms into the dynamic uniform buffer
+ /// in ONE `queue.write_buffer` and encodes every compute downsample + atlas copy into
+ /// **ONE `CommandEncoder` + ONE `queue.submit`**!
+ fn submit_mipmap_jobs(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ dispatches: &[(MipmapUniforms, u32)],
+ ) {
+ if dispatches.is_empty() {
+ return;
+ }
+ self.ensure_mipmap_uniform_capacity(device, dispatches.len());
+ let stride = MIPMAP_UNIFORM_STRIDE as usize;
+ let total_bytes = dispatches.len() * stride;
+ self.mipmap_uniform_staging.clear();
+ self.mipmap_uniform_staging.resize(total_bytes, 0);
+ for (i, (u, _)) in dispatches.iter().enumerate() {
+ let src = bytemuck::bytes_of(u);
+ let off = i * stride;
+ self.mipmap_uniform_staging[off..off + src.len()].copy_from_slice(src);
+ }
+ queue.write_buffer(&self.mipmap_uniform_buf, 0, &self.mipmap_uniform_staging);
+
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-mipmap-batch-compute-encoder"),
+ });
+
+ for (i, &(_, dst_slot)) in dispatches.iter().enumerate() {
+ let dyn_off = (i as u32) * (MIPMAP_UNIFORM_STRIDE as u32);
+ {
+ let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("ink-mipmap-compute-pass"),
+ timestamp_writes: None,
+ });
+ pass.set_pipeline(&self.mipmap_pipeline);
+ pass.set_bind_group(0, &self.mipmap_bind_group, &[dyn_off]);
+ // 256 / 16 = 16 workgroups along X and Y
+ pass.dispatch_workgroups(16, 16, 1);
+ }
+
+ // Copy compute output from scratch 2D texture into destination atlas slice
+ encoder.copy_texture_to_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: &self.mipmap_scratch_tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::TexelCopyTextureInfo {
+ texture: &self.atlas_texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d {
+ x: 0,
+ y: 0,
+ z: dst_slot,
+ },
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::Extent3d {
+ width: TILE_SIZE as u32,
+ height: TILE_SIZE as u32,
+ depth_or_array_layers: 1,
+ },
+ );
+ }
+
+ queue.submit(Some(encoder.finish()));
+ self.mipmaps_generated = self
+ .mipmaps_generated
+ .saturating_add(dispatches.len() as u64);
+ self.mipmap_submits = self.mipmap_submits.saturating_add(1);
+ }
+
+ /// Generates a batch of parent mipmap tiles (LOD `1..=3`) on the GPU using the
+ /// dynamic-offset `cs_downsample` compute shader in **ONE `CommandEncoder` + ONE `queue.submit`**
+ /// (automatically chunking only when VRAM pool unpinned capacity is tight).
+ ///
+ /// Returns the destination atlas slot for each input job in matching order.
+ pub fn generate_mipmap_batch(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ jobs: &[MipmapBatchJob],
+ ) -> Vec<u32> {
+ if jobs.is_empty() {
+ return Vec::new();
+ }
+ let mut dst_slots = Vec::with_capacity(jobs.len());
+ let mut dispatches: Vec<(MipmapUniforms, u32)> = Vec::with_capacity(jobs.len());
+ let mut chunk_pins: Vec<u32> = Vec::with_capacity(jobs.len() * 5);
+
+ for job in jobs {
+ if self.unpinned_slot_count() <= 5 && !dispatches.is_empty() {
+ self.submit_mipmap_jobs(device, queue, &dispatches);
+ dispatches.clear();
+ for s in chunk_pins.drain(..) {
+ self.unpin_slot(s);
+ }
+ }
+ for s in job.child_slots.into_iter().flatten() {
+ self.pin_slot(s);
+ chunk_pins.push(s);
+ }
+ let dst_slot = self.acquire_slot(job.parent_key.clone(), job.version);
+ self.pin_slot(dst_slot);
+ chunk_pins.push(dst_slot);
+ dst_slots.push(dst_slot);
+ let uniforms = MipmapUniforms {
+ child_slots: [
+ job.child_slots[0].map(|s| s as i32).unwrap_or(-1),
+ job.child_slots[1].map(|s| s as i32).unwrap_or(-1),
+ job.child_slots[2].map(|s| s as i32).unwrap_or(-1),
+ job.child_slots[3].map(|s| s as i32).unwrap_or(-1),
+ ],
+ _pad: [0; 4],
+ };
+ dispatches.push((uniforms, dst_slot));
+ }
+
+ if !dispatches.is_empty() {
+ self.submit_mipmap_jobs(device, queue, &dispatches);
+ }
+ for s in chunk_pins {
+ self.unpin_slot(s);
+ }
+ dst_slots
+ }
+
/// Generates a parent mipmap tile (LOD `target_lod` in `1..=3`) on the GPU using the
/// `cs_downsample` compute shader from up to 4 child atlas slots `(TL, TR, BL, BR)`.
///
@@ -847,61 +1634,16 @@ impl GpuTilePool {
child_slots: [Option<u32>; 4],
version: u64,
) -> u32 {
- let dst_slot = self.acquire_slot(parent_key, version);
- let uniforms = MipmapUniforms {
- child_slots: [
- child_slots[0].map(|s| s as i32).unwrap_or(-1),
- child_slots[1].map(|s| s as i32).unwrap_or(-1),
- child_slots[2].map(|s| s as i32).unwrap_or(-1),
- child_slots[3].map(|s| s as i32).unwrap_or(-1),
- ],
- _pad: [0; 4],
- };
- queue.write_buffer(&self.mipmap_uniform_buf, 0, bytemuck::bytes_of(&uniforms));
-
- let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-mipmap-compute-encoder"),
- });
-
- {
- let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
- label: Some("ink-mipmap-compute-pass"),
- timestamp_writes: None,
- });
- pass.set_pipeline(&self.mipmap_pipeline);
- pass.set_bind_group(0, &self.mipmap_bind_group, &[]);
- // 256 / 16 = 16 workgroups along X and Y
- pass.dispatch_workgroups(16, 16, 1);
- }
-
- // Copy compute output from scratch 2D texture into destination atlas slice
- encoder.copy_texture_to_texture(
- wgpu::TexelCopyTextureInfo {
- texture: &self.mipmap_scratch_tex,
- mip_level: 0,
- origin: wgpu::Origin3d::ZERO,
- aspect: wgpu::TextureAspect::All,
- },
- wgpu::TexelCopyTextureInfo {
- texture: &self.atlas_texture,
- mip_level: 0,
- origin: wgpu::Origin3d {
- x: 0,
- y: 0,
- z: dst_slot,
- },
- aspect: wgpu::TextureAspect::All,
- },
- wgpu::Extent3d {
- width: TILE_SIZE as u32,
- height: TILE_SIZE as u32,
- depth_or_array_layers: 1,
- },
+ let slots = self.generate_mipmap_batch(
+ device,
+ queue,
+ &[MipmapBatchJob {
+ parent_key,
+ child_slots,
+ version,
+ }],
);
-
- queue.submit(Some(encoder.finish()));
- self.mipmaps_generated = self.mipmaps_generated.saturating_add(1);
- dst_slot
+ slots[0]
}
/// Reads back a `256×256` `Rgba16Float` atlas slice (524,288 bytes) from GPU VRAM into CPU memory.
@@ -969,36 +1711,64 @@ impl GpuTilePool {
/// Evicts a single cached tile key from L1 VRAM if resident (e.g. tile erased completely empty).
pub fn evict_key(&mut self, key: &GpuTileKey) {
if let Some(slot) = self.key_to_slot.remove(key) {
- self.slots[slot as usize].key = None;
- self.slots[slot as usize].version = 0;
+ let rec = &mut self.slots[slot as usize];
+ rec.key = None;
+ rec.version = 0;
+ rec.ref_bit = false;
+ if rec.pin_count > 0 {
+ rec.pin_count = 0;
+ self.pinned_slots_count = self.pinned_slots_count.saturating_sub(1);
+ }
+ self.free_slots.push(slot);
}
}
/// Invalidates all cached VRAM slices belonging to a document.
pub fn invalidate_document(&mut self, doc_id: &str) {
+ let Some(doc_key) = self.lookup_doc_id(doc_id) else {
+ return;
+ };
+ let free_slots = &mut self.free_slots;
self.key_to_slot.retain(|k, &mut slot| {
- if k.doc_id == doc_id {
- self.slots[slot as usize].key = None;
- self.slots[slot as usize].version = 0;
+ if k.doc_id == doc_key {
+ let rec = &mut self.slots[slot as usize];
+ rec.key = None;
+ rec.version = 0;
+ rec.ref_bit = false;
+ if rec.pin_count > 0 {
+ rec.pin_count = 0;
+ self.pinned_slots_count = self.pinned_slots_count.saturating_sub(1);
+ }
+ free_slots.push(slot);
false
} else {
true
}
});
+ let mask_free = &mut self.mask_free_slots;
self.mask_key_to_slot.retain(|k, &mut slot| {
- if k.doc_id == doc_id {
- self.mask_slots[slot as usize].key = None;
- self.mask_slots[slot as usize].version = 0;
+ if k.doc_id == doc_key {
+ let rec = &mut self.mask_slots[slot as usize];
+ rec.key = None;
+ rec.version = 0;
+ rec.pin_count = 0;
+ rec.ref_bit = false;
+ mask_free.push(slot);
false
} else {
true
}
});
if let Some(atlas) = self.impasto_atlas.as_mut() {
+ let imp_free = &mut atlas.free_slots;
atlas.key_to_slot.retain(|k, &mut slot| {
- if k.doc_id == doc_id {
- atlas.slots[slot as usize].key = None;
- atlas.slots[slot as usize].version = 0;
+ if k.doc_id == doc_key {
+ let rec = &mut atlas.slots[slot as usize];
+ rec.key = None;
+ rec.version = 0;
+ rec.pin_count = 0;
+ rec.ref_bit = false;
+ imp_free.push(slot);
false
} else {
true
@@ -1009,29 +1779,52 @@ impl GpuTilePool {
/// Invalidates all cached VRAM slices belonging to a specific layer.
pub fn invalidate_layer(&mut self, doc_id: &str, layer_id: &str) {
+ let (Some(doc_key), Some(layer_key)) =
+ (self.lookup_doc_id(doc_id), self.lookup_layer_id(layer_id))
+ else {
+ return;
+ };
+ let free_slots = &mut self.free_slots;
self.key_to_slot.retain(|k, &mut slot| {
- if k.doc_id == doc_id && k.layer_id == layer_id {
- self.slots[slot as usize].key = None;
- self.slots[slot as usize].version = 0;
+ if k.doc_id == doc_key && k.layer_id == layer_key {
+ let rec = &mut self.slots[slot as usize];
+ rec.key = None;
+ rec.version = 0;
+ rec.ref_bit = false;
+ if rec.pin_count > 0 {
+ rec.pin_count = 0;
+ self.pinned_slots_count = self.pinned_slots_count.saturating_sub(1);
+ }
+ free_slots.push(slot);
false
} else {
true
}
});
+ let mask_free = &mut self.mask_free_slots;
self.mask_key_to_slot.retain(|k, &mut slot| {
- if k.doc_id == doc_id && k.layer_id == layer_id {
- self.mask_slots[slot as usize].key = None;
- self.mask_slots[slot as usize].version = 0;
+ if k.doc_id == doc_key && k.layer_id == layer_key {
+ let rec = &mut self.mask_slots[slot as usize];
+ rec.key = None;
+ rec.version = 0;
+ rec.pin_count = 0;
+ rec.ref_bit = false;
+ mask_free.push(slot);
false
} else {
true
}
});
if let Some(atlas) = self.impasto_atlas.as_mut() {
+ let imp_free = &mut atlas.free_slots;
atlas.key_to_slot.retain(|k, &mut slot| {
- if k.doc_id == doc_id && k.layer_id == layer_id {
- atlas.slots[slot as usize].key = None;
- atlas.slots[slot as usize].version = 0;
+ if k.doc_id == doc_key && k.layer_id == layer_key {
+ let rec = &mut atlas.slots[slot as usize];
+ rec.key = None;
+ rec.version = 0;
+ rec.pin_count = 0;
+ rec.ref_bit = false;
+ imp_free.push(slot);
false
} else {
true
@@ -1040,27 +1833,591 @@ impl GpuTilePool {
}
}
+ /// O(resident_slots) lazy sync: evicts any resident VRAM tiles for `doc` whose layer or
+ /// tile was removed or mutated, without iterating or uploading offscreen document tiles.
+ pub fn prune_stale_document_keys(&mut self, doc: &crate::document::Document) {
+ let Some(doc_key) = self.lookup_doc_id(&doc.id) else {
+ return;
+ };
+ let mut layer_map: HashMap<u32, &crate::document::LayerNode> =
+ HashMap::with_capacity(doc.layers.len());
+ for layer in &doc.layers {
+ if let Some(lid) = self.lookup_layer_id(&layer.meta.id) {
+ layer_map.insert(lid, layer);
+ }
+ }
+
+ let slots = &mut self.slots;
+ let pinned_count = &mut self.pinned_slots_count;
+ let free_slots = &mut self.free_slots;
+ self.key_to_slot.retain(|k, &mut slot| {
+ if k.doc_id != doc_key {
+ return true;
+ }
+ let valid = if let Some(layer) = layer_map.get(&k.layer_id) {
+ if k.lod == 0 {
+ layer
+ .grid
+ .tiles
+ .get(&k.coord)
+ .is_some_and(|t| slots[slot as usize].version == t.version)
+ } else {
+ let expected = compute_lod_tile_version(&layer.grid, k.lod, k.coord);
+ expected != 0 && slots[slot as usize].version == expected
+ }
+ } else {
+ false
+ };
+ if !valid {
+ let rec = &mut slots[slot as usize];
+ rec.key = None;
+ rec.version = 0;
+ rec.ref_bit = false;
+ if rec.pin_count > 0 {
+ rec.pin_count = 0;
+ *pinned_count = pinned_count.saturating_sub(1);
+ }
+ free_slots.push(slot);
+ }
+ valid
+ });
+
+ let mask_slots = &mut self.mask_slots;
+ let mask_free = &mut self.mask_free_slots;
+ self.mask_key_to_slot.retain(|k, &mut slot| {
+ if k.doc_id != doc_key {
+ return true;
+ }
+ let valid = layer_map.get(&k.layer_id).is_some_and(|layer| {
+ layer.grid.has_mask
+ && layer
+ .grid
+ .mask_tiles
+ .get(&k.coord)
+ .is_some_and(|t| mask_slots[slot as usize].version == t.version)
+ });
+ if !valid {
+ let rec = &mut mask_slots[slot as usize];
+ rec.key = None;
+ rec.version = 0;
+ rec.pin_count = 0;
+ rec.ref_bit = false;
+ mask_free.push(slot);
+ }
+ valid
+ });
+
+ if let Some(atlas) = self.impasto_atlas.as_mut() {
+ let imp_slots = &mut atlas.slots;
+ let imp_free = &mut atlas.free_slots;
+ atlas.key_to_slot.retain(|k, &mut slot| {
+ if k.doc_id != doc_key {
+ return true;
+ }
+ let valid = layer_map.get(&k.layer_id).is_some_and(|layer| {
+ layer
+ .grid
+ .impasto_tiles
+ .get(&k.coord)
+ .is_some_and(|t| imp_slots[slot as usize].version == t.version)
+ });
+ if !valid {
+ let rec = &mut imp_slots[slot as usize];
+ rec.key = None;
+ rec.version = 0;
+ rec.pin_count = 0;
+ rec.ref_bit = false;
+ imp_free.push(slot);
+ }
+ valid
+ });
+ }
+ }
+
/// Flushes all resident slots (e.g. explicit GPU cache purge).
pub fn flush_all(&mut self) {
self.key_to_slot.clear();
+ self.solid_color_to_slot.clear();
+ self.pinned_slots_count = 0;
for rec in &mut self.slots {
- rec.key = None;
- rec.version = 0;
- rec.last_used_frame = 0;
+ *rec = SlotRecord::empty();
}
+ self.free_slots = (0..self.capacity).rev().collect();
+ self.clock_hand = 0;
self.mask_key_to_slot.clear();
for rec in &mut self.mask_slots {
- rec.key = None;
- rec.version = 0;
- rec.last_used_frame = 0;
+ *rec = SlotRecord::empty();
}
+ self.mask_free_slots = (0..self.mask_capacity).rev().collect();
+ self.mask_clock_hand = 0;
if let Some(atlas) = self.impasto_atlas.as_mut() {
atlas.key_to_slot.clear();
for rec in &mut atlas.slots {
- rec.key = None;
- rec.version = 0;
- rec.last_used_frame = 0;
+ *rec = SlotRecord::empty();
}
+ atlas.free_slots = (0..atlas.capacity).rev().collect();
+ atlas.clock_hand = 0;
}
}
}
+
+/// Returns `Some(rgba16f)` if every in-bounds LOD-0 tile covered by `(lod, coord)` within
+/// `[0..doc_w, 0..doc_h]` exists in `grid` and shares the exact same uniform `SolidColor`.
+///
+/// Allows LOD 0..=3 rendering & mipmap generation to reuse a single shared VRAM slot with
+/// zero compute mipmap overhead for uniform solid backgrounds and fills.
+pub fn uniform_solid_color_for_lod_tile(
+ grid: &SparseLayerGrid,
+ lod: u8,
+ coord: TileCoord,
+ doc_w: u32,
+ doc_h: u32,
+) -> Option<[u16; 4]> {
+ if lod == 0 {
+ return grid.tiles.get(&coord).and_then(|t| t.solid_rgba16f());
+ }
+ let scale = 1i32 << lod;
+ let doc_tiles_x = doc_w.max(1).div_ceil(TILE_SIZE as u32) as i32;
+ let doc_tiles_y = doc_h.max(1).div_ceil(TILE_SIZE as u32) as i32;
+ let start_tx = (coord.tx * scale).max(0);
+ let start_ty = (coord.ty * scale).max(0);
+ let end_tx = (coord.tx * scale + scale).min(doc_tiles_x);
+ let end_ty = (coord.ty * scale + scale).min(doc_tiles_y);
+
+ if start_tx >= end_tx || start_ty >= end_ty {
+ return None;
+ }
+
+ let mut expected: Option<[u16; 4]> = None;
+ for ty in start_ty..end_ty {
+ for tx in start_tx..end_tx {
+ let tile = grid.tiles.get(&TileCoord::new(tx, ty))?;
+ let solid = tile.solid_rgba16f()?;
+ match expected {
+ None => expected = Some(solid),
+ Some(prev) if prev == solid => {}
+ Some(_) => return None,
+ }
+ }
+ }
+ expected
+}
+
+/// Computes a deterministic 64-bit version for mipmap tile `(lod, coord)` purely from its
+/// 4 child quadrant versions (down to LOD-0 per-tile `TileData::version`).
+///
+/// Returns `0` when all descendant LOD-0 tiles are absent/empty.
+/// Unmodified sibling subtrees retain the exact same version across localized strokes, so
+/// untouched LOD 1..3 tiles stay resident in VRAM with zero invalidation or recompute!
+pub fn compute_lod_tile_version(grid: &SparseLayerGrid, lod: u8, coord: TileCoord) -> u64 {
+ if lod == 0 {
+ return grid.tiles.get(&coord).map(|t| t.version).unwrap_or(0);
+ }
+ let c0 = compute_lod_tile_version(grid, lod - 1, TileCoord::new(coord.tx * 2, coord.ty * 2));
+ let c1 = compute_lod_tile_version(grid, lod - 1, TileCoord::new(coord.tx * 2 + 1, coord.ty * 2));
+ let c2 = compute_lod_tile_version(grid, lod - 1, TileCoord::new(coord.tx * 2, coord.ty * 2 + 1));
+ let c3 = compute_lod_tile_version(grid, lod - 1, TileCoord::new(coord.tx * 2 + 1, coord.ty * 2 + 1));
+ if (c0 | c1 | c2 | c3) == 0 {
+ return 0;
+ }
+ let mut h: u64 = 0xcbf29ce484222325 ^ (lod as u64);
+ for v in [c0, c1, c2, c3] {
+ h ^= v.wrapping_add(0x9e3779b97f4a7c15);
+ h = h.wrapping_mul(0x100000001b3);
+ h ^= h >> 31;
+ }
+ if h == 0 { 1 } else { h }
+}
+
+/// Ensures tile `(lod, coord)` of `grid` is resident in `tile_pool`, recursively uploading
+/// missing LOD-0 children and generating parent mipmaps while pinning each resolved sibling
+/// so computing later siblings or acquiring the destination slot can NEVER evict an earlier one.
+///
+/// Uniform `SolidColor` regions at any LOD `0..=3` resolve in O(1) VRAM via the shared solid
+/// slot cache with zero mipmap generation overhead.
+#[allow(clippy::too_many_arguments)]
+pub fn ensure_grid_lod_tile_recursive(
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ tile_pool: &mut GpuTilePool,
+ doc_id: &str,
+ layer_id: &str,
+ grid: &SparseLayerGrid,
+ doc_w: u32,
+ doc_h: u32,
+ lod: u8,
+ coord: TileCoord,
+ scratch: Option<&dyn ScratchBackend>,
+) -> Option<u32> {
+ let doc_key = tile_pool.intern_doc(doc_id);
+ let layer_key = tile_pool.intern_layer(layer_id);
+ ensure_grid_lod_tile_recursive_interned(
+ device,
+ queue,
+ tile_pool,
+ doc_key,
+ layer_key,
+ grid,
+ doc_w,
+ doc_h,
+ lod,
+ coord,
+ scratch,
+ )
+}
+
+#[allow(clippy::too_many_arguments)]
+fn ensure_grid_lod_tile_recursive_interned(
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ tile_pool: &mut GpuTilePool,
+ doc_key: u32,
+ layer_key: u32,
+ grid: &SparseLayerGrid,
+ doc_w: u32,
+ doc_h: u32,
+ lod: u8,
+ coord: TileCoord,
+ scratch: Option<&dyn ScratchBackend>,
+) -> Option<u32> {
+ if lod == 0 {
+ let tile = grid.tiles.get(&coord)?;
+ let key = GpuTileKey {
+ doc_id: doc_key,
+ layer_id: layer_key,
+ lod: 0,
+ coord,
+ };
+ return tile_pool.ensure_tile_uploaded(queue, key, tile, scratch).ok();
+ }
+
+ let key = GpuTileKey {
+ doc_id: doc_key,
+ layer_id: layer_key,
+ lod,
+ coord,
+ };
+
+ if let Some(solid_16f) = uniform_solid_color_for_lod_tile(grid, lod, coord, doc_w, doc_h) {
+ tile_pool.evict_key(&key);
+ return Some(tile_pool.ensure_solid_color_slot(queue, solid_16f));
+ }
+
+ let expected_ver = compute_lod_tile_version(grid, lod, coord);
+ if expected_ver == 0 {
+ tile_pool.evict_key(&key);
+ return None;
+ }
+
+ if let Some(slot) = tile_pool.get_slot_if_version(&key, expected_ver) {
+ return Some(slot);
+ }
+
+ let child_coords = [
+ TileCoord::new(coord.tx * 2, coord.ty * 2),
+ TileCoord::new(coord.tx * 2 + 1, coord.ty * 2),
+ TileCoord::new(coord.tx * 2, coord.ty * 2 + 1),
+ TileCoord::new(coord.tx * 2 + 1, coord.ty * 2 + 1),
+ ];
+ let mut child_slots = [None; 4];
+ for (qi, cc) in child_coords.iter().enumerate() {
+ if let Some(slot) = ensure_grid_lod_tile_recursive_interned(
+ device,
+ queue,
+ tile_pool,
+ doc_key,
+ layer_key,
+ grid,
+ doc_w,
+ doc_h,
+ lod - 1,
+ *cc,
+ scratch,
+ ) {
+ tile_pool.pin_slot(slot);
+ child_slots[qi] = Some(slot);
+ }
+ }
+
+ let res = if child_slots.iter().any(|s| s.is_some()) {
+ Some(tile_pool.generate_mipmap_tile(
+ device,
+ queue,
+ key,
+ child_slots,
+ expected_ver,
+ ))
+ } else {
+ tile_pool.evict_key(&key);
+ None
+ };
+
+ for s in child_slots.into_iter().flatten() {
+ tile_pool.unpin_slot(s);
+ }
+
+ res
+}
+
+fn grid_has_any_tile_in_lod(grid: &SparseLayerGrid, lod: u8, coord: TileCoord) -> bool {
+ if lod == 0 {
+ return grid.tiles.contains_key(&coord);
+ }
+ let scale = 1i32 << lod;
+ let base_tx = coord.tx * scale;
+ let base_ty = coord.ty * scale;
+ for dy in 0..scale {
+ for dx in 0..scale {
+ if grid.tiles.contains_key(&TileCoord::new(base_tx + dx, base_ty + dy)) {
+ return true;
+ }
+ }
+ }
+ false
+}
+
+/// Regenerates all dirty/requested mipmap tiles across LOD 1 -> 2 -> 3 in a **SINGLE batched
+/// `CommandEncoder` + `queue.submit`** (gracefully chunking only when tight VRAM limits require it).
+///
+/// Preserves evicted-sibling safety identically to [`ensure_grid_lod_tile_recursive`] and skips
+/// compute completely for uniform `SolidColor` regions and unmodified sibling subtrees.
+#[allow(clippy::too_many_arguments)]
+pub fn regenerate_grid_lods_batched(
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ tile_pool: &mut GpuTilePool,
+ doc_id: &str,
+ layer_id: &str,
+ grid: &SparseLayerGrid,
+ doc_w: u32,
+ doc_h: u32,
+ dirty_lods: &[Vec<TileCoord>; 3],
+ evict_dirty_first: bool,
+ scratch: Option<&dyn ScratchBackend>,
+) {
+ if dirty_lods[0].is_empty() && dirty_lods[1].is_empty() && dirty_lods[2].is_empty() {
+ return;
+ }
+
+ let doc_key = tile_pool.intern_doc(doc_id);
+ let layer_key = tile_pool.intern_layer(layer_id);
+
+ // 1. Optionally evict explicitly dirty keys first so stale versions are never reused
+ if evict_dirty_first {
+ for (lod_idx, coords) in dirty_lods.iter().enumerate() {
+ let target_lod = (lod_idx + 1) as u8;
+ for &coord in coords {
+ tile_pool.evict_key(&GpuTileKey {
+ doc_id: doc_key,
+ layer_id: layer_key,
+ lod: target_lod,
+ coord,
+ });
+ }
+ }
+ }
+
+ // 2. Build dependency DAG top-down (LOD 3 -> 2 -> 1), skipping solid-color & up-to-date tiles
+ let mut levels: [HashSet<TileCoord>; 3] = [
+ dirty_lods[0].iter().copied().collect(),
+ dirty_lods[1].iter().copied().collect(),
+ dirty_lods[2].iter().copied().collect(),
+ ];
+ let mut expected_versions: [HashMap<TileCoord, u64>; 3] = [
+ HashMap::new(),
+ HashMap::new(),
+ HashMap::new(),
+ ];
+
+ for lod_idx in (0..3usize).rev() {
+ let lod = (lod_idx + 1) as u8;
+ let current: Vec<TileCoord> = levels[lod_idx].iter().copied().collect();
+ for coord in current {
+ let key = GpuTileKey {
+ doc_id: doc_key,
+ layer_id: layer_key,
+ lod,
+ coord,
+ };
+ if let Some(solid_16f) = uniform_solid_color_for_lod_tile(grid, lod, coord, doc_w, doc_h)
+ {
+ tile_pool.evict_key(&key);
+ let _ = tile_pool.ensure_solid_color_slot(queue, solid_16f);
+ levels[lod_idx].remove(&coord);
+ continue;
+ }
+ let expected_ver = compute_lod_tile_version(grid, lod, coord);
+ if expected_ver == 0 {
+ tile_pool.evict_key(&key);
+ levels[lod_idx].remove(&coord);
+ continue;
+ }
+ if tile_pool.get_slot_if_version(&key, expected_ver).is_some() {
+ levels[lod_idx].remove(&coord);
+ continue;
+ }
+ expected_versions[lod_idx].insert(coord, expected_ver);
+ if lod > 1 {
+ let child_coords = [
+ TileCoord::new(coord.tx * 2, coord.ty * 2),
+ TileCoord::new(coord.tx * 2 + 1, coord.ty * 2),
+ TileCoord::new(coord.tx * 2, coord.ty * 2 + 1),
+ TileCoord::new(coord.tx * 2 + 1, coord.ty * 2 + 1),
+ ];
+ for cc in child_coords {
+ if grid_has_any_tile_in_lod(grid, lod - 1, cc) {
+ levels[lod_idx - 1].insert(cc);
+ }
+ }
+ }
+ }
+ }
+
+ // 3. Emit LOD 1 -> 2 -> 3 bottom-up into ONE dynamic-uniform CommandEncoder + queue.submit!
+ let mut dispatches: Vec<(MipmapUniforms, u32)> = Vec::with_capacity(
+ levels[0].len() + levels[1].len() + levels[2].len(),
+ );
+ let mut chunk_pins: Vec<u32> = Vec::with_capacity(dispatches.capacity() * 5);
+
+ for (lod_idx, level_set) in levels.iter().enumerate() {
+ if level_set.is_empty() {
+ continue;
+ }
+ let lod = (lod_idx + 1) as u8;
+ let mut coords: Vec<TileCoord> = level_set.iter().copied().collect();
+ coords.sort_by_key(|c| (c.ty, c.tx));
+
+ for coord in coords {
+ let parent_key = GpuTileKey {
+ doc_id: doc_key,
+ layer_id: layer_key,
+ lod,
+ coord,
+ };
+ let parent_ver = expected_versions[lod_idx]
+ .get(&coord)
+ .copied()
+ .unwrap_or_else(|| compute_lod_tile_version(grid, lod, coord));
+
+ // If pool unpinned space is tight, submit current batch and release pins first
+ if tile_pool.unpinned_slot_count() <= 5 && !dispatches.is_empty() {
+ tile_pool.submit_mipmap_jobs(device, queue, &dispatches);
+ dispatches.clear();
+ for s in chunk_pins.drain(..) {
+ tile_pool.unpin_slot(s);
+ }
+ }
+
+ let child_coords = [
+ TileCoord::new(coord.tx * 2, coord.ty * 2),
+ TileCoord::new(coord.tx * 2 + 1, coord.ty * 2),
+ TileCoord::new(coord.tx * 2, coord.ty * 2 + 1),
+ TileCoord::new(coord.tx * 2 + 1, coord.ty * 2 + 1),
+ ];
+ let mut child_slots = [None; 4];
+
+ for (qi, cc) in child_coords.iter().enumerate() {
+ if lod == 1 {
+ if let Some(tile) = grid.tiles.get(cc) {
+ let ckey = GpuTileKey {
+ doc_id: doc_key,
+ layer_id: layer_key,
+ lod: 0,
+ coord: *cc,
+ };
+ if let Ok(slot) = tile_pool.ensure_tile_uploaded(queue, ckey, tile, scratch)
+ {
+ tile_pool.pin_slot(slot);
+ chunk_pins.push(slot);
+ child_slots[qi] = Some(slot);
+ }
+ }
+ } else if let Some(solid_16f) =
+ uniform_solid_color_for_lod_tile(grid, lod - 1, *cc, doc_w, doc_h)
+ {
+ let slot = tile_pool.ensure_solid_color_slot(queue, solid_16f);
+ tile_pool.pin_slot(slot);
+ chunk_pins.push(slot);
+ child_slots[qi] = Some(slot);
+ } else {
+ let ckey = GpuTileKey {
+ doc_id: doc_key,
+ layer_id: layer_key,
+ lod: lod - 1,
+ coord: *cc,
+ };
+ let child_ver = expected_versions[lod_idx - 1]
+ .get(cc)
+ .copied()
+ .unwrap_or_else(|| compute_lod_tile_version(grid, lod - 1, *cc));
+ if child_ver != 0 {
+ if let Some(slot) = tile_pool.get_slot_if_version(&ckey, child_ver) {
+ tile_pool.pin_slot(slot);
+ chunk_pins.push(slot);
+ child_slots[qi] = Some(slot);
+ } else {
+ // Only reachable under ultra-tight VRAM chunk eviction: flush pending batch
+ // and regenerate the evicted child cleanly.
+ if !dispatches.is_empty() {
+ tile_pool.submit_mipmap_jobs(device, queue, &dispatches);
+ dispatches.clear();
+ for s in chunk_pins.drain(..) {
+ tile_pool.unpin_slot(s);
+ }
+ // Re-pin earlier quadrants of this tile so they stay protected
+ for prev_s in child_slots.iter().take(qi).flatten() {
+ tile_pool.pin_slot(*prev_s);
+ chunk_pins.push(*prev_s);
+ }
+ }
+ if let Some(slot) = ensure_grid_lod_tile_recursive_interned(
+ device,
+ queue,
+ tile_pool,
+ doc_key,
+ layer_key,
+ grid,
+ doc_w,
+ doc_h,
+ lod - 1,
+ *cc,
+ scratch,
+ ) {
+ tile_pool.pin_slot(slot);
+ chunk_pins.push(slot);
+ child_slots[qi] = Some(slot);
+ }
+ }
+ }
+ }
+ }
+
+ if child_slots.iter().any(|s| s.is_some()) {
+ let dst_slot = tile_pool.acquire_slot(parent_key, parent_ver);
+ tile_pool.pin_slot(dst_slot);
+ chunk_pins.push(dst_slot);
+ dispatches.push((
+ MipmapUniforms {
+ child_slots: [
+ child_slots[0].map(|s| s as i32).unwrap_or(-1),
+ child_slots[1].map(|s| s as i32).unwrap_or(-1),
+ child_slots[2].map(|s| s as i32).unwrap_or(-1),
+ child_slots[3].map(|s| s as i32).unwrap_or(-1),
+ ],
+ _pad: [0; 4],
+ },
+ dst_slot,
+ ));
+ } else {
+ tile_pool.evict_key(&parent_key);
+ }
+ }
+ }
+
+ if !dispatches.is_empty() {
+ tile_pool.submit_mipmap_jobs(device, queue, &dispatches);
+ }
+ for s in chunk_pins {
+ tile_pool.unpin_slot(s);
+ }
+}
diff --git a/crates/ink-engine/src/memory/mod.rs b/crates/ink-engine/src/memory/mod.rs
index df855da..3a40959 100644
--- a/crates/ink-engine/src/memory/mod.rs
+++ b/crates/ink-engine/src/memory/mod.rs
@@ -5,7 +5,11 @@ pub mod gpu_pool;
pub mod scratch;
pub mod tiered;
-pub use gpu_pool::{GpuPoolStats, GpuTileKey, GpuTilePool, MIPMAP_COMPUTE_WGSL};
+pub use gpu_pool::{
+ compute_lod_tile_version, ensure_grid_lod_tile_recursive, regenerate_grid_lods_batched,
+ uniform_solid_color_for_lod_tile, GpuPoolStats, GpuTileKey, GpuTilePool, MipmapBatchJob,
+ MIPMAP_COMPUTE_WGSL,
+};
pub use scratch::{FileScratchBackend, InMemoryScratchBackend, ScratchBackend, ScratchTileWrite};
pub use tiered::{
EvictionContext, MemoryBudgetConfig, MemoryStats, TieredMemoryManager, ViewportFrustum,
diff --git a/crates/ink-engine/src/memory/tiered.rs b/crates/ink-engine/src/memory/tiered.rs
index 8aaa3a7..d777386 100644
--- a/crates/ink-engine/src/memory/tiered.rs
+++ b/crates/ink-engine/src/memory/tiered.rs
@@ -29,7 +29,7 @@ pub struct ViewportFrustum {
pub struct MemoryBudgetConfig {
/// Hard CPU RAM budget for tile data across all open documents (default 1024 MB).
pub ram_budget_bytes: u64,
- /// Target L1 GPU VRAM tile atlas budget (default 128 MB = 256 `Rgba16Float` slots).
+ /// Target L1 GPU VRAM tile atlas budget (default 512 MB = 1024 `Rgba16Float` slots).
pub vram_budget_bytes: u64,
/// Maximum history steps retained per document (clamped 10..=200, default 50).
pub max_history_steps: usize,
@@ -41,7 +41,7 @@ impl Default for MemoryBudgetConfig {
fn default() -> Self {
Self {
ram_budget_bytes: 1024 * 1024 * 1024,
- vram_budget_bytes: 128 * 1024 * 1024,
+ vram_budget_bytes: 512 * 1024 * 1024,
max_history_steps: 50,
offload_inactive_tabs: true,
}
@@ -86,6 +86,8 @@ pub struct ManagedTileSlot<'a> {
pub kind: TileKind,
pub coord: TileCoord,
pub tile: &'a mut Arc<TileData>,
+ /// True when this slot belongs to an Undo/Redo history snapshot rather than a live layer grid.
+ pub is_history: bool,
}
/// Coordinates L2 LZ4 RAM compression and L3 Scratch Disk paging.
@@ -162,6 +164,12 @@ impl TieredMemoryManager {
}
/// Enforces `ram_budget_bytes` across all supplied tiles:
+ /// - Deduplicates CoW-shared `Arc<TileData>` handles by `Arc::as_ptr` so shared tiles are
+ /// never CoW-cloned via `Arc::make_mut` while another holder retains the original raw buffer.
+ /// - Only demotes a tile group when `Arc::strong_count == group.len()` (every holder is
+ /// present in `slots` and updated atomically to the compressed/paged `Arc`, genuinely
+ /// dropping the old raw buffer). External holders with `strong_count > group.len()` are
+ /// skipped so RAM can NEVER increase.
/// - Pass 1 (L2): Compresses lowest-priority `Raw` tiles to `CompressedLz4` (or `SolidColor`)
/// when total RAM exceeds `soft_target` (80% of budget).
/// - Pass 2 (L3): Pages lowest-priority remaining `Raw` / `CompressedLz4` tiles to scratch disk
@@ -177,152 +185,279 @@ impl TieredMemoryManager {
let soft_limit = (budget * 4) / 5; // 80% triggers fast L2 LZ4 compression
let target_after_evict = (budget * 9) / 10; // 90% target after L3 paging
- let mut total_ram = Self::unique_ram_bytes(&slots);
+ let initial_ram = Self::unique_ram_bytes(&slots);
+ let mut total_ram = initial_ram;
if total_ram <= soft_limit {
return Ok((0, 0, 0));
}
- // Score every slot by 4-tier frustum-aware LRU priority
- let mut order: Vec<(usize, u8, i64, u64)> = slots
- .iter()
- .enumerate()
- .filter(|(_, s)| s.tile.ram_bytes() > 0)
- .map(|(idx, s)| {
- let (tier, dist) = Self::score_slot(s, ctx);
- (idx, tier, dist, s.tile.last_access_seq)
- })
- .collect();
-
- order.sort_by(|a, b| {
- a.1.cmp(&b.1)
- .then_with(|| b.2.cmp(&a.2)) // Farthest outside frustum first
- .then_with(|| a.3.cmp(&b.3)) // Oldest access sequence first
+ // Deduplicate CoW-shared Arcs by pointer so all holders of the same Arc are managed as one unit.
+ // Group priority = highest (hardest-to-evict) priority among all holders in the group.
+ struct TileGroup {
+ indices: Vec<usize>,
+ tier: u8,
+ dist: i64,
+ last_access_seq: u64,
+ }
+
+ let mut ptr_to_group: HashMap<*const TileData, usize> = HashMap::with_capacity(slots.len());
+ let mut groups: Vec<TileGroup> = Vec::with_capacity(slots.len());
+
+ for (idx, s) in slots.iter().enumerate() {
+ if s.tile.ram_bytes() == 0 {
+ continue;
+ }
+ let ptr = Arc::as_ptr(s.tile);
+ let (tier, dist) = Self::score_slot(s, ctx);
+ if let Some(&g_idx) = ptr_to_group.get(&ptr) {
+ let g = &mut groups[g_idx];
+ g.indices.push(idx);
+ // Keep the highest retention priority among all holders (higher tier / closer dist)
+ if tier > g.tier || (tier == g.tier && dist < g.dist) {
+ g.tier = tier;
+ g.dist = dist;
+ }
+ g.last_access_seq = g.last_access_seq.max(s.tile.last_access_seq);
+ } else {
+ let g_idx = groups.len();
+ ptr_to_group.insert(ptr, g_idx);
+ groups.push(TileGroup {
+ indices: vec![idx],
+ tier,
+ dist,
+ last_access_seq: s.tile.last_access_seq,
+ });
+ }
+ }
+
+ groups.sort_by(|a, b| {
+ a.tier
+ .cmp(&b.tier)
+ .then_with(|| b.dist.cmp(&a.dist)) // Farthest outside frustum first
+ .then_with(|| a.last_access_seq.cmp(&b.last_access_seq)) // Oldest access sequence first
});
let mut lz4_count = 0usize;
let mut disk_count = 0usize;
- let mut freed_total = 0u64;
// Pass 1: Demote Raw -> L2 LZ4 RAM (fast, zero disk I/O)
- for &(idx, _, _, _) in &order {
+ for group in &groups {
if total_ram <= soft_limit {
break;
}
- let slot = &mut slots[idx];
- if !matches!(slot.tile.storage, TileStorage::Raw(_)) {
+ let lead_idx = group.indices[0];
+ if !matches!(slots[lead_idx].tile.storage, TileStorage::Raw(_)) {
continue;
}
- // Only mutate in-place when uniquely owned or make CoW copy (still shrinks total unique RAM
- // if the old Arc is no longer held elsewhere).
- let td = Arc::make_mut(slot.tile);
- let freed = td.demote_to_lz4() as u64;
- if freed > 0 {
- lz4_count += 1;
- freed_total += freed;
- total_ram = total_ram.saturating_sub(freed);
+ // Safety invariant: only demote when EVERY strong reference to this Arc is in `group`.
+ // Otherwise an external holder would keep the old Raw buffer alive and cloning would INCREASE RAM!
+ let strong = Arc::strong_count(slots[lead_idx].tile);
+ if strong > group.indices.len() {
+ continue;
+ }
+ if strong == 1 && group.indices.len() == 1 {
+ let td = Arc::make_mut(slots[lead_idx].tile);
+ let freed = td.demote_to_lz4() as u64;
+ if freed > 0 {
+ lz4_count += 1;
+ total_ram = total_ram.saturating_sub(freed);
+ }
+ } else if let Some((new_td, freed)) = slots[lead_idx].tile.to_demoted_lz4() {
+ let new_arc = Arc::new(new_td);
+ for &idx in &group.indices {
+ *slots[idx].tile = Arc::clone(&new_arc);
+ }
+ if freed > 0 {
+ lz4_count += 1;
+ total_ram = total_ram.saturating_sub(freed as u64);
+ }
}
}
total_ram = Self::unique_ram_bytes(&slots);
if total_ram <= budget {
- return Ok((lz4_count, disk_count, freed_total));
+ let actual_freed = initial_ram.saturating_sub(total_ram);
+ return Ok((lz4_count, disk_count, actual_freed));
}
// Pass 2: Demote L2/Raw -> L3 Scratch Disk (in-process zero-IPC write!)
- // Group writes by session_id for batched disk I/O
let mut to_page: Vec<usize> = Vec::new();
let mut projected = total_ram;
- for &(idx, _, _, _) in &order {
+ for (g_idx, group) in groups.iter().enumerate() {
if projected <= target_after_evict {
break;
}
- let ram = slots[idx].tile.ram_bytes() as u64;
+ let lead_idx = group.indices[0];
+ let ram = slots[lead_idx].tile.ram_bytes() as u64;
if ram == 0 {
continue;
}
- to_page.push(idx);
+ if Arc::strong_count(slots[lead_idx].tile) > group.indices.len() {
+ continue;
+ }
+ to_page.push(g_idx);
projected = projected.saturating_sub(ram);
}
if !to_page.is_empty() {
let mut initialized_sessions: HashSet<&str> = HashSet::new();
- for idx in to_page {
- let slot = &mut slots[idx];
- if initialized_sessions.insert(slot.doc_id) {
- self.scratch.init_session(slot.doc_id)?;
+ for g_idx in to_page {
+ let group = &groups[g_idx];
+ let lead_idx = group.indices[0];
+ let strong = Arc::strong_count(slots[lead_idx].tile);
+ if strong > group.indices.len() {
+ continue;
+ }
+ let doc_id = slots[lead_idx].doc_id;
+ let layer_id = slots[lead_idx].layer_id;
+ let kind = slots[lead_idx].kind;
+ let coord = slots[lead_idx].coord;
+ if initialized_sessions.insert(doc_id) {
+ self.scratch.init_session(doc_id)?;
}
- let layer_key = match slot.kind {
- TileKind::Raster => slot.layer_id.to_string(),
- TileKind::Mask => format!("{}__mask", slot.layer_id),
- TileKind::ImpastoHeight => format!("{}__impasto", slot.layer_id),
+ let layer_key = match kind {
+ TileKind::Raster => format!("{layer_id}__v{}", slots[lead_idx].tile.version),
+ TileKind::Mask => {
+ format!("{layer_id}__mask__v{}", slots[lead_idx].tile.version)
+ }
+ TileKind::ImpastoHeight => {
+ format!("{layer_id}__impasto__v{}", slots[lead_idx].tile.version)
+ }
};
- let td = Arc::make_mut(slot.tile);
- let freed = td.demote_to_disk(
- slot.doc_id,
+
+ if strong == 1 && group.indices.len() == 1 {
+ let td = Arc::make_mut(slots[lead_idx].tile);
+ let freed = td.demote_to_disk(
+ doc_id,
+ &layer_key,
+ coord,
+ self.scratch.as_ref(),
+ )? as u64;
+ if freed > 0 {
+ disk_count += 1;
+ }
+ } else if let Some((new_td, freed)) = slots[lead_idx].tile.to_demoted_disk(
+ doc_id,
&layer_key,
- slot.coord,
+ coord,
self.scratch.as_ref(),
- )? as u64;
- if freed > 0 {
- disk_count += 1;
- freed_total += freed;
+ )? {
+ let new_arc = Arc::new(new_td);
+ for &idx in &group.indices {
+ *slots[idx].tile = Arc::clone(&new_arc);
+ }
+ if freed > 0 {
+ disk_count += 1;
+ }
}
}
}
- Ok((lz4_count, disk_count, freed_total))
+ let final_ram = Self::unique_ram_bytes(&slots);
+ let actual_freed = initial_ram.saturating_sub(final_ram);
+ Ok((lz4_count, disk_count, actual_freed))
}
- /// Compresses all `Raw` tiles in `slots` to L2 LZ4 RAM (e.g. when switching away from a tab).
+ /// Compresses all eligible `Raw` tiles in `slots` to L2 LZ4 RAM (e.g. when switching away from a tab),
+ /// deduplicating CoW-shared `Arc`s and skipping any `Arc` with external holders so RAM never grows.
pub fn compress_all_to_lz4(&self, mut slots: Vec<ManagedTileSlot<'_>>) -> (usize, u64) {
+ let initial_ram = Self::unique_ram_bytes(&slots);
+ let mut ptr_to_indices: HashMap<*const TileData, Vec<usize>> =
+ HashMap::with_capacity(slots.len());
+ for (idx, s) in slots.iter().enumerate() {
+ if matches!(s.tile.storage, TileStorage::Raw(_)) {
+ ptr_to_indices
+ .entry(Arc::as_ptr(s.tile))
+ .or_default()
+ .push(idx);
+ }
+ }
let mut count = 0usize;
- let mut freed = 0u64;
- for slot in &mut slots {
- if matches!(slot.tile.storage, TileStorage::Raw(_)) {
- let td = Arc::make_mut(slot.tile);
- let f = td.demote_to_lz4() as u64;
- if f > 0 {
+ for indices in ptr_to_indices.values() {
+ let lead = indices[0];
+ let strong = Arc::strong_count(slots[lead].tile);
+ if strong > indices.len() {
+ continue;
+ }
+ if strong == 1 && indices.len() == 1 {
+ let td = Arc::make_mut(slots[lead].tile);
+ if td.demote_to_lz4() > 0 {
+ count += 1;
+ }
+ } else if let Some((new_td, freed)) = slots[lead].tile.to_demoted_lz4() {
+ let new_arc = Arc::new(new_td);
+ for &idx in indices {
+ *slots[idx].tile = Arc::clone(&new_arc);
+ }
+ if freed > 0 {
count += 1;
- freed += f;
}
}
}
- (count, freed)
+ let final_ram = Self::unique_ram_bytes(&slots);
+ (count, initial_ram.saturating_sub(final_ram))
}
- /// Pages all eligible tiles in `slots` to L3 Scratch Disk (explicit memory purge / tab offload).
+ /// Pages all eligible tiles in `slots` to L3 Scratch Disk (explicit memory purge / tab offload),
+ /// deduplicating CoW-shared `Arc`s and skipping any `Arc` with external holders so RAM never grows.
pub fn evict_all_to_disk(
&self,
mut slots: Vec<ManagedTileSlot<'_>>,
) -> Result<(usize, u64), String> {
+ let initial_ram = Self::unique_ram_bytes(&slots);
+ let mut ptr_to_indices: HashMap<*const TileData, Vec<usize>> =
+ HashMap::with_capacity(slots.len());
+ for (idx, s) in slots.iter().enumerate() {
+ if s.tile.ram_bytes() > 0 {
+ ptr_to_indices
+ .entry(Arc::as_ptr(s.tile))
+ .or_default()
+ .push(idx);
+ }
+ }
let mut count = 0usize;
- let mut freed = 0u64;
let mut initialized: HashSet<String> = HashSet::new();
- for slot in &mut slots {
- if slot.tile.ram_bytes() == 0 {
+ for indices in ptr_to_indices.values() {
+ let lead = indices[0];
+ let strong = Arc::strong_count(slots[lead].tile);
+ if strong > indices.len() {
continue;
}
- if initialized.insert(slot.doc_id.to_string()) {
- self.scratch.init_session(slot.doc_id)?;
+ let doc_id = slots[lead].doc_id;
+ let layer_id = slots[lead].layer_id;
+ let kind = slots[lead].kind;
+ let coord = slots[lead].coord;
+ if initialized.insert(doc_id.to_string()) {
+ self.scratch.init_session(doc_id)?;
}
- let layer_key = match slot.kind {
- TileKind::Raster => slot.layer_id.to_string(),
- TileKind::Mask => format!("{}__mask", slot.layer_id),
- TileKind::ImpastoHeight => format!("{}__impasto", slot.layer_id),
+ let layer_key = match kind {
+ TileKind::Raster => format!("{layer_id}__v{}", slots[lead].tile.version),
+ TileKind::Mask => format!("{layer_id}__mask__v{}", slots[lead].tile.version),
+ TileKind::ImpastoHeight => {
+ format!("{layer_id}__impasto__v{}", slots[lead].tile.version)
+ }
};
- let td = Arc::make_mut(slot.tile);
- let f = td.demote_to_disk(
- slot.doc_id,
- &layer_key,
- slot.coord,
- self.scratch.as_ref(),
- )? as u64;
- if f > 0 {
- count += 1;
- freed += f;
+ if strong == 1 && indices.len() == 1 {
+ let td = Arc::make_mut(slots[lead].tile);
+ if td.demote_to_disk(doc_id, &layer_key, coord, self.scratch.as_ref())? > 0 {
+ count += 1;
+ }
+ } else if let Some((new_td, freed)) =
+ slots[lead]
+ .tile
+ .to_demoted_disk(doc_id, &layer_key, coord, self.scratch.as_ref())?
+ {
+ let new_arc = Arc::new(new_td);
+ for &idx in indices {
+ *slots[idx].tile = Arc::clone(&new_arc);
+ }
+ if freed > 0 {
+ count += 1;
+ }
}
}
- Ok((count, freed))
+ let final_ram = Self::unique_ram_bytes(&slots);
+ Ok((count, initial_ram.saturating_sub(final_ram)))
}
fn unique_ram_bytes(slots: &[ManagedTileSlot<'_>]) -> u64 {
@@ -335,6 +470,10 @@ impl TieredMemoryManager {
}
fn score_slot(slot: &ManagedTileSlot<'_>, ctx: &EvictionContext) -> (u8, i64) {
+ if slot.is_history {
+ // Cold undo/redo history snapshots are lowest retention priority (evict before live canvas tiles)
+ return (0, i64::MAX / 4);
+ }
let is_active_doc = ctx
.active_doc_id
.as_deref()
diff --git a/crates/ink-engine/src/natural_paint/bristle_ribbon.rs b/crates/ink-engine/src/natural_paint/bristle_ribbon.rs
index 9477b76..098da7f 100644
--- a/crates/ink-engine/src/natural_paint/bristle_ribbon.rs
+++ b/crates/ink-engine/src/natural_paint/bristle_ribbon.rs
@@ -15,7 +15,7 @@ use crate::brush::{
evaluate_csp_sensor, BristleProfilePreset, BristleSettings, BrushRenderMode,
CompiledSensorLuts, NativeBrushConfig,
};
-use crate::natural_paint::pigment::MAX_BRISTLES;
+use crate::natural_paint::pigment::{MAX_BRISTLES, UNDERBED_BANDS, UNDERBED_SLOT_BASE};
use crate::stroke::StrokePoint;
use bytemuck::{Pod, Zeroable};
@@ -109,6 +109,11 @@ pub struct BristleRibbonSimulator {
strands: Vec<BristleStrand>,
underbed: Vec<UnderbedBand>,
+ // Pre-compiled sensor LUTs (compiled ONCE on stroke start — zero per-frame rebuild!)
+ size_luts: CompiledSensorLuts,
+ op_luts: CompiledSensorLuts,
+ splay_luts: CompiledSensorLuts,
+
// Parallel-transported stroke frame
has_frame: bool,
last_x: f32,
@@ -271,18 +276,18 @@ impl BristleRibbonSimulator {
}
// 5-band cohesive under-bed spans [-0.72, -0.36, 0.0, +0.36, +0.72] across ferrule
+ // with dedicated reservoir slots (`64..69`) so they NEVER collide with real bristles `0..64`!
// (skipped for Rake & Fan which should expose discrete bristle gaps!)
let mut underbed = Vec::new();
if !matches!(
bs.profile,
BristleProfilePreset::Rake | BristleProfilePreset::Fan
) {
- for b in 0..5usize {
- let u = (b as f32 / 4.0) * 1.44 - 0.72;
- let nearest_idx = ((u * 0.5 + 0.5) * (count - 1) as f32).round() as usize;
+ for b in 0..UNDERBED_BANDS {
+ let u = (b as f32 / (UNDERBED_BANDS.saturating_sub(1).max(1) as f32)) * 1.44 - 0.72;
underbed.push(UnderbedBand {
lateral_u: u,
- bristle_idx: nearest_idx.min(count - 1),
+ bristle_idx: UNDERBED_SLOT_BASE + b,
prev_x: 0.0,
prev_y: 0.0,
prev_radius: 1.0,
@@ -298,12 +303,19 @@ impl BristleRibbonSimulator {
| crate::brush::CspAngleDynamicsMode::Tilt
) || bs.profile != BristleProfilePreset::Round;
+ let size_luts = CompiledSensorLuts::from_sensor(config.size_sensor.as_ref());
+ let op_luts = CompiledSensorLuts::from_sensor(config.opacity_sensor.as_ref());
+ let splay_luts = CompiledSensorLuts::from_sensor(config.bristle_splay_sensor.as_ref());
+
Self {
profile: bs.profile,
render_mode: config.render_mode,
settings: bs,
strands,
underbed,
+ size_luts,
+ op_luts,
+ splay_luts,
has_frame: false,
last_x: 0.0,
last_y: 0.0,
@@ -333,18 +345,8 @@ impl BristleRibbonSimulator {
config: &NativeBrushConfig,
out_capsules: &mut Vec<GpuBristleCapsule>,
) {
- let size_luts = CompiledSensorLuts::from_sensor(config.size_sensor.as_ref());
- let op_luts = CompiledSensorLuts::from_sensor(config.opacity_sensor.as_ref());
- let splay_luts = CompiledSensorLuts::from_sensor(config.bristle_splay_sensor.as_ref());
for &pt in points {
- self.step_single_point(
- pt,
- config,
- Some(&size_luts),
- Some(&op_luts),
- Some(&splay_luts),
- out_capsules,
- );
+ self.step_single_point(pt, config, out_capsules);
}
}
@@ -352,9 +354,6 @@ impl BristleRibbonSimulator {
&mut self,
pt: StrokePoint,
config: &NativeBrushConfig,
- size_luts: Option<&CompiledSensorLuts>,
- op_luts: Option<&CompiledSensorLuts>,
- splay_luts: Option<&CompiledSensorLuts>,
out_capsules: &mut Vec<GpuBristleCapsule>,
) {
let px = pt.x as f32;
@@ -389,14 +388,14 @@ impl BristleRibbonSimulator {
let size_factor = if let Some(ref s) = config.size_sensor {
evaluate_csp_sensor(
s,
- size_luts,
+ Some(&self.size_luts),
pressure,
tilt_mag,
velocity,
self.stroke_distance,
0.5,
)
- .clamp(config.min_size_factor.max(0.05), 1.5)
+ .clamp(config.min_size_factor.max(0.05), 4.0)
} else if config.use_pressure {
let min_f = config.min_size_factor.clamp(0.05, 1.0);
min_f + (1.0 - min_f) * pressure
@@ -411,7 +410,7 @@ impl BristleRibbonSimulator {
.map(|s| {
evaluate_csp_sensor(
s,
- splay_luts,
+ Some(&self.splay_luts),
pressure,
tilt_mag,
velocity,
@@ -435,7 +434,7 @@ impl BristleRibbonSimulator {
let op_factor = if let Some(ref s) = config.opacity_sensor {
evaluate_csp_sensor(
s,
- op_luts,
+ Some(&self.op_luts),
pressure,
tilt_mag,
velocity,
@@ -478,9 +477,10 @@ impl BristleRibbonSimulator {
return;
}
- // Subdivide large jumps into smooth physical substeps (max step <= max(2.0, brush_radius * 0.18))
- let max_step = (brush_radius * 0.18).clamp(2.0, 14.0);
- let steps = ((dist / max_step).ceil() as usize).clamp(1, 32);
+ // Subdivide large jumps into smooth physical substeps without double-subdividing
+ // already-sampled Bezier segments (keeps capsule counts ~150-400/frame instead of 3,000!).
+ let max_step = (brush_radius * 0.28).clamp(3.5, 16.0);
+ let steps = ((dist / max_step).ceil() as usize).clamp(1, 16);
let prev_x = self.last_x;
let prev_y = self.last_y;
let prev_p = self.last_pressure;
diff --git a/crates/ink-engine/src/natural_paint/impasto.rs b/crates/ink-engine/src/natural_paint/impasto.rs
index 5feb123..48e03df 100644
--- a/crates/ink-engine/src/natural_paint/impasto.rs
+++ b/crates/ink-engine/src/natural_paint/impasto.rs
@@ -14,13 +14,13 @@
use crate::document::{Document, LayerNode};
use crate::memory::{GpuTileKey, GpuTilePool, ScratchBackend};
-use crate::tiles::{
- allocate_tile_version, format::rgba16f_to_rgba8_dithered, TileCoord, BYTES_16F, BYTES_32BIT,
- BYTES_R16F, TILE_SIZE,
-};
+use crate::tiles::{allocate_tile_version, TileCoord, BYTES_32BIT, BYTES_R16F, TILE_SIZE};
use bytemuck::{Pod, Zeroable};
use std::borrow::Cow;
use std::collections::HashMap;
+use std::num::NonZeroU64;
+
+const NP_UNIFORM_STRIDE: u64 = 256;
/// Fullscreen 1-triangle hardware blit converting `R32Float` compute scratch -> `R16Float` height slice.
const R32F_TO_R16F_BLIT_WGSL: &str = r#"
@@ -84,6 +84,65 @@ fn cs_composite_ground(@builtin(global_invocation_id) gid: vec3<u32>) {
}
"#;
+/// GPU compute shader packing straight `Rgba16Float` tiles directly into 4×4 Bayer-dithered
+/// packed `u32` RGBA8 (256 KB/tile instead of 512 KB/tile) so pen-up commit cuts PCIe readback
+/// bandwidth in half and removes 100% of CPU `rgba16f_to_rgba8_dithered` work from the render thread!
+const NP_PACK_RGBA8_WGSL: &str = r#"
+struct NpPackUniforms {
+ src_slot: i32,
+ out_tile_idx: u32,
+ _pad0: u32,
+ _pad1: u32,
+};
+
+@group(0) @binding(0) var<uniform> u: NpPackUniforms;
+@group(0) @binding(1) var src_color_atlas: texture_2d_array<f32>;
+@group(0) @binding(2) var<storage, read_write> out_rgba8_buf: array<u32>;
+
+const BAYER_4X4: array<f32, 16> = array<f32, 16>(
+ -0.46875, 0.03125, -0.34375, 0.15625,
+ 0.28125, -0.21875, 0.40625, -0.09375,
+ -0.28125, 0.21875, -0.40625, 0.09375,
+ 0.46875, -0.03125, 0.34375, -0.15625,
+);
+
+fn quantize_dither(v_in: f32, dither: f32) -> u32 {
+ let v = clamp(v_in, 0.0, 1.0);
+ if (v <= 0.0) {
+ return 0u;
+ }
+ if (v >= 1.0) {
+ return 255u;
+ }
+ return u32(floor(clamp(v * 255.0 + dither, 0.0, 255.0) + 0.5));
+}
+
+@compute @workgroup_size(16, 16, 1)
+fn cs_pack_rgba8(@builtin(global_invocation_id) gid: vec3<u32>) {
+ if (gid.x >= 256u || gid.y >= 256u) {
+ return;
+ }
+ let xy = vec2<i32>(i32(gid.x), i32(gid.y));
+ let c = textureLoad(src_color_atlas, xy, u.src_slot, 0);
+ let dither = BAYER_4X4[(gid.y & 3u) * 4u + (gid.x & 3u)];
+ let r = quantize_dither(c.r, dither);
+ let g = quantize_dither(c.g, dither);
+ let b = quantize_dither(c.b, dither);
+ let a = quantize_dither(c.a, dither);
+ let flat = u.out_tile_idx * 65536u + gid.y * 256u + gid.x;
+ out_rgba8_buf[flat] = r | (g << 8u) | (b << 16u) | (a << 24u);
+}
+"#;
+
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Pod, Zeroable)]
+struct NpPackUniforms {
+ src_slot: i32,
+ out_tile_idx: u32,
+ _pad0: u32,
+ _pad1: u32,
+}
+
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct GroundLayerUniforms {
@@ -93,6 +152,26 @@ struct GroundLayerUniforms {
_pad: u32,
}
+/// Prepared GPU tile-initialization plan encoded into the caller's single `CommandEncoder`.
+pub struct InitTilesPlan {
+ tile_inits: Vec<TileInitOp>,
+ ground_inits: Vec<GroundInitOp>,
+ pinned_color_slots: Vec<u32>,
+ pinned_impasto_slots: Vec<u32>,
+}
+
+struct TileInitOp {
+ dst_slot: u32,
+ color_src_slot: Option<u32>,
+ height_src_slot: Option<u32>,
+}
+
+struct GroundInitOp {
+ dst_slot: u32,
+ start_uniform_idx: usize,
+ layer_count: usize,
+}
+
/// Output of committing an active GPU natural-paint / impasto stroke back to CPU CoW tiles.
pub struct CommittedNaturalPaintBatch {
/// `(coord, rgba8_256kb, gpu_slot_version)` ready for `SparseLayerGrid::apply_gpu_committed_tiles`.
@@ -101,6 +180,13 @@ pub struct CommittedNaturalPaintBatch {
pub impasto_tiles: Vec<(TileCoord, Vec<u8>, u64)>,
}
+/// Lazy `Rgba16Float` `256×256` `Texture2DArray` pool used for ColorMixing opacity-capping & wet-edge.
+pub struct LazyRgba16fArray {
+ pub tex: wgpu::Texture,
+ pub array_view: wgpu::TextureView,
+ pub slice_views: Vec<wgpu::TextureView>,
+}
+
/// Sparse GPU `256×256` working tile pools for a live Natural Paint / Color Mixing / Impasto stroke.
pub struct NaturalPaintTilePools {
/// Active stroke updated layer color (`Rgba16Float`, straight sRGB matching `GpuTilePool`).
@@ -116,10 +202,23 @@ pub struct NaturalPaintTilePools {
/// Lazy 1:1 document-space ground below active layer (`Rgba16Float`, populated only when `mixGroundColor` is true).
pub ground_tex: wgpu::Texture,
pub ground_array_view: wgpu::TextureView,
+ ground_slice_views: Vec<wgpu::TextureView>,
+
+ /// Lazy ColorMixing pre-stroke base snapshot & resolved opacity/wet-edge display pools
+ /// (allocated on-demand ONLY when a ColorMixing stroke uses `opacity < 1.0` or `wet_edge > 0.01`).
+ pub cmix_base: Option<LazyRgba16fArray>,
+ pub cmix_display: Option<LazyRgba16fArray>,
+ pub cmix_cov: Option<LazyRgba16fArray>,
+ pub use_cmix_display: bool,
+ pub use_cmix_cov: bool,
/// Reusable `256×256` compute storage scratch textures (avoiding read/write aliasing hazards).
pub color_scratch_tex: wgpu::Texture,
pub color_scratch_view: wgpu::TextureView,
+ pub cmix_cov_scratch_tex: wgpu::Texture,
+ pub cmix_cov_scratch_view: wgpu::TextureView,
+ _dummy_rgba16f_array_tex: wgpu::Texture,
+ pub dummy_rgba16f_array_view: wgpu::TextureView,
pub height_scratch_r32f_tex: wgpu::Texture,
pub height_scratch_r32f_view: wgpu::TextureView,
pub ground_scratch_a_tex: wgpu::Texture,
@@ -127,14 +226,32 @@ pub struct NaturalPaintTilePools {
pub ground_scratch_b_tex: wgpu::Texture,
pub ground_scratch_b_view: wgpu::TextureView,
- /// Hardware `R32Float -> R16Float` blit pipeline + ground layer composite compute pipeline.
- r32_to_r16_bgl: wgpu::BindGroupLayout,
+ /// Hardware `R32Float -> R16Float` blit pipeline + ground layer composite + GPU RGBA8 pack pipeline.
+ r32_to_r16_bg: wgpu::BindGroup,
r32_to_r16_pipe: wgpu::RenderPipeline,
ground_bgl: wgpu::BindGroupLayout,
ground_pipe: wgpu::ComputePipeline,
ground_uniform_buf: wgpu::Buffer,
+ ground_uniform_cap: usize,
+ pack_bgl: wgpu::BindGroupLayout,
+ pack_pipe: wgpu::ComputePipeline,
+ pack_uniform_buf: wgpu::Buffer,
+ pack_uniform_cap: usize,
+ pack_uniform_gen: u64,
+ pack_uniform_staging: Vec<u8>,
+ cached_pack_bg: Option<((u64, u64, u64, bool), wgpu::BindGroup)>,
+
+ // GPU packed RGBA8 storage + double-buffered reusable commit readback staging buffers
+ commit_rgba8_storage: Option<wgpu::Buffer>,
+ commit_rgba8_storage_gen: u64,
+ commit_color_staging: [Option<wgpu::Buffer>; 2],
+ commit_color_staging_cap: usize,
+ commit_height_staging: [Option<wgpu::Buffer>; 2],
+ commit_height_staging_cap: usize,
+ commit_rb_idx: usize,
capacity: u32,
+ pub atlas_gen: u64,
/// Map of touched `TileCoord -> slot index` for the active stroke.
pub coord_to_slot: HashMap<TileCoord, u32>,
/// Tracks which slots already had their ground-below tiles composited.
@@ -152,7 +269,7 @@ impl NaturalPaintTilePools {
Self::create_rgba16f_array(device, "ink-np-color-pool", cap);
let (height_tex, height_array_view, height_slice_views) =
Self::create_r16f_array(device, "ink-np-height-pool", cap);
- let (ground_tex, ground_array_view, _) =
+ let (ground_tex, ground_array_view, ground_slice_views) =
Self::create_rgba16f_array(device, "ink-np-ground-pool", cap);
let mk_rgba16f_scratch = |label: &str| {
@@ -178,6 +295,29 @@ impl NaturalPaintTilePools {
};
let (color_scratch_tex, color_scratch_view) = mk_rgba16f_scratch("ink-np-color-scratch");
+ let (cmix_cov_scratch_tex, cmix_cov_scratch_view) =
+ mk_rgba16f_scratch("ink-np-cmix-cov-scratch");
+ let dummy_rgba16f_array_tex = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("ink-np-dummy-rgba16f-array"),
+ size: wgpu::Extent3d {
+ width: 1,
+ height: 1,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba16Float,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
+ view_formats: &[],
+ });
+ let dummy_rgba16f_array_view =
+ dummy_rgba16f_array_tex.create_view(&wgpu::TextureViewDescriptor {
+ dimension: Some(wgpu::TextureViewDimension::D2Array),
+ base_array_layer: 0,
+ array_layer_count: Some(1),
+ ..Default::default()
+ });
let (ground_scratch_a_tex, ground_scratch_a_view) =
mk_rgba16f_scratch("ink-np-ground-scratch-a");
let (ground_scratch_b_tex, ground_scratch_b_view) =
@@ -250,6 +390,15 @@ impl NaturalPaintTilePools {
cache: None,
});
+ let r32_to_r16_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-np-r32-to-r16-bg"),
+ layout: &r32_to_r16_bgl,
+ entries: &[wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::TextureView(&height_scratch_r32f_view),
+ }],
+ });
+
let ground_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("ink-np-ground-bgl"),
entries: &[
@@ -258,8 +407,10 @@ impl NaturalPaintTilePools {
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
- has_dynamic_offset: false,
- min_binding_size: None,
+ has_dynamic_offset: true,
+ min_binding_size: NonZeroU64::new(
+ std::mem::size_of::<GroundLayerUniforms>() as u64,
+ ),
},
count: None,
},
@@ -312,9 +463,72 @@ impl NaturalPaintTilePools {
compilation_options: Default::default(),
cache: None,
});
+ let ground_uniform_cap = 64usize;
let ground_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("ink-np-ground-uniforms"),
- size: std::mem::size_of::<GroundLayerUniforms>() as u64,
+ label: Some("ink-np-ground-uniforms-dyn"),
+ size: ground_uniform_cap as u64 * NP_UNIFORM_STRIDE,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+
+ let pack_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("ink-np-pack-rgba8-bgl"),
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: true,
+ min_binding_size: NonZeroU64::new(
+ std::mem::size_of::<NpPackUniforms>() as u64,
+ ),
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 1,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Texture {
+ sample_type: wgpu::TextureSampleType::Float { filterable: false },
+ view_dimension: wgpu::TextureViewDimension::D2Array,
+ multisampled: false,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 2,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ ],
+ });
+ let pack_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("ink-np-pack-rgba8-wgsl"),
+ source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(NP_PACK_RGBA8_WGSL)),
+ });
+ let pack_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("ink-np-pack-rgba8-pl"),
+ bind_group_layouts: &[Some(&pack_bgl)],
+ immediate_size: 0,
+ });
+ let pack_pipe = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: Some("ink-np-pack-rgba8-pipe"),
+ layout: Some(&pack_pl),
+ module: &pack_shader,
+ entry_point: Some("cs_pack_rgba8"),
+ compilation_options: Default::default(),
+ cache: None,
+ });
+ let pack_uniform_cap = 64usize;
+ let pack_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-np-pack-uniforms-dyn"),
+ size: pack_uniform_cap as u64 * NP_UNIFORM_STRIDE,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
@@ -328,20 +542,46 @@ impl NaturalPaintTilePools {
height_slice_views,
ground_tex,
ground_array_view,
+ ground_slice_views,
+ cmix_base: None,
+ cmix_display: None,
+ cmix_cov: None,
+ use_cmix_display: false,
+ use_cmix_cov: false,
color_scratch_tex,
color_scratch_view,
+ cmix_cov_scratch_tex,
+ cmix_cov_scratch_view,
+ _dummy_rgba16f_array_tex: dummy_rgba16f_array_tex,
+ dummy_rgba16f_array_view,
height_scratch_r32f_tex,
height_scratch_r32f_view,
ground_scratch_a_tex,
ground_scratch_a_view,
ground_scratch_b_tex,
ground_scratch_b_view,
- r32_to_r16_bgl,
+ r32_to_r16_bg,
r32_to_r16_pipe,
ground_bgl,
ground_pipe,
ground_uniform_buf,
+ ground_uniform_cap,
+ pack_bgl,
+ pack_pipe,
+ pack_uniform_buf,
+ pack_uniform_cap,
+ pack_uniform_gen: 1,
+ pack_uniform_staging: Vec::with_capacity(64 * NP_UNIFORM_STRIDE as usize),
+ cached_pack_bg: None,
+ commit_rgba8_storage: None,
+ commit_rgba8_storage_gen: 1,
+ commit_color_staging: [None, None],
+ commit_color_staging_cap: 0,
+ commit_height_staging: [None, None],
+ commit_height_staging_cap: 0,
+ commit_rb_idx: 0,
capacity: cap,
+ atlas_gen: 1,
coord_to_slot: HashMap::new(),
ground_populated: HashMap::new(),
impasto_dirty: false,
@@ -432,6 +672,80 @@ impl NaturalPaintTilePools {
self.coord_to_slot.clear();
self.ground_populated.clear();
self.impasto_dirty = false;
+ if self.use_cmix_display || self.use_cmix_cov {
+ self.use_cmix_display = false;
+ self.use_cmix_cov = false;
+ self.atlas_gen = self.atlas_gen.saturating_add(1);
+ }
+ }
+
+ /// Configures lazy ColorMixing post-processing pools (`cmix_base`, `cmix_display`, `cmix_cov`)
+ /// for the active stroke. Allocates ZERO VRAM when both `need_display` and `need_cov` are false!
+ pub fn configure_cmix_post_pools(
+ &mut self,
+ device: &wgpu::Device,
+ need_display: bool,
+ need_cov: bool,
+ ) {
+ let mut bumped = false;
+ if need_display && (self.cmix_base.is_none() || self.cmix_display.is_none()) {
+ let (bt, bv, bs) =
+ Self::create_rgba16f_array(device, "ink-np-cmix-base-pool", self.capacity);
+ let (dt, dv, ds) =
+ Self::create_rgba16f_array(device, "ink-np-cmix-display-pool", self.capacity);
+ self.cmix_base = Some(LazyRgba16fArray {
+ tex: bt,
+ array_view: bv,
+ slice_views: bs,
+ });
+ self.cmix_display = Some(LazyRgba16fArray {
+ tex: dt,
+ array_view: dv,
+ slice_views: ds,
+ });
+ bumped = true;
+ }
+ if need_cov && self.cmix_cov.is_none() {
+ let (ct, cv, cs) =
+ Self::create_rgba16f_array(device, "ink-np-cmix-cov-pool", self.capacity);
+ self.cmix_cov = Some(LazyRgba16fArray {
+ tex: ct,
+ array_view: cv,
+ slice_views: cs,
+ });
+ bumped = true;
+ }
+ if self.use_cmix_display != need_display || self.use_cmix_cov != need_cov {
+ self.use_cmix_display = need_display;
+ self.use_cmix_cov = need_cov;
+ bumped = true;
+ }
+ if bumped {
+ self.atlas_gen = self.atlas_gen.saturating_add(1);
+ }
+ }
+
+ /// Returns the color atlas view that should be projected live into the viewport (display pool
+ /// when opacity-capping or wet-edge post-resolve is active, raw `color_array_view` otherwise).
+ #[inline]
+ pub fn active_display_color_view(&self) -> &wgpu::TextureView {
+ if self.use_cmix_display {
+ if let Some(ref disp) = self.cmix_display {
+ return &disp.array_view;
+ }
+ }
+ &self.color_array_view
+ }
+
+ /// Returns the coverage pool view (or a 1×1 dummy view when wet-edge coverage tracking is off).
+ #[inline]
+ pub fn cmix_cov_array_view(&self) -> &wgpu::TextureView {
+ if self.use_cmix_cov {
+ if let Some(ref cov) = self.cmix_cov {
+ return &cov.array_view;
+ }
+ }
+ &self.dummy_rgba16f_array_view
}
/// Ensures the pool has room for at least `needed` slots (grows cleanly on GPU if needed).
@@ -454,8 +768,38 @@ impl NaturalPaintTilePools {
Self::create_rgba16f_array(device, "ink-np-color-pool", new_cap);
let (new_height, new_height_v, new_height_slices) =
Self::create_r16f_array(device, "ink-np-height-pool", new_cap);
- let (new_ground, new_ground_v, _) =
+ let (new_ground, new_ground_v, new_ground_slices) =
Self::create_rgba16f_array(device, "ink-np-ground-pool", new_cap);
+ let new_cmix_base = if self.cmix_base.is_some() {
+ let (t, v, s) = Self::create_rgba16f_array(device, "ink-np-cmix-base-pool", new_cap);
+ Some(LazyRgba16fArray {
+ tex: t,
+ array_view: v,
+ slice_views: s,
+ })
+ } else {
+ None
+ };
+ let new_cmix_display = if self.cmix_display.is_some() {
+ let (t, v, s) = Self::create_rgba16f_array(device, "ink-np-cmix-display-pool", new_cap);
+ Some(LazyRgba16fArray {
+ tex: t,
+ array_view: v,
+ slice_views: s,
+ })
+ } else {
+ None
+ };
+ let new_cmix_cov = if self.cmix_cov.is_some() {
+ let (t, v, s) = Self::create_rgba16f_array(device, "ink-np-cmix-cov-pool", new_cap);
+ Some(LazyRgba16fArray {
+ tex: t,
+ array_view: v,
+ slice_views: s,
+ })
+ } else {
+ None
+ };
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("ink-np-pool-grow"),
@@ -512,6 +856,59 @@ impl NaturalPaintTilePools {
},
ext,
);
+ if let (Some(old_b), Some(new_b)) = (self.cmix_base.as_ref(), new_cmix_base.as_ref()) {
+ encoder.copy_texture_to_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: &old_b.tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::TexelCopyTextureInfo {
+ texture: &new_b.tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ ext,
+ );
+ }
+ if let (Some(old_d), Some(new_d)) =
+ (self.cmix_display.as_ref(), new_cmix_display.as_ref())
+ {
+ encoder.copy_texture_to_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: &old_d.tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::TexelCopyTextureInfo {
+ texture: &new_d.tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ ext,
+ );
+ }
+ if let (Some(old_c), Some(new_c)) = (self.cmix_cov.as_ref(), new_cmix_cov.as_ref()) {
+ encoder.copy_texture_to_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: &old_c.tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::TexelCopyTextureInfo {
+ texture: &new_c.tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ ext,
+ );
+ }
}
queue.submit(Some(encoder.finish()));
@@ -523,142 +920,482 @@ impl NaturalPaintTilePools {
self.height_slice_views = new_height_slices;
self.ground_tex = new_ground;
self.ground_array_view = new_ground_v;
+ self.ground_slice_views = new_ground_slices;
+ self.cmix_base = new_cmix_base;
+ self.cmix_display = new_cmix_display;
+ self.cmix_cov = new_cmix_cov;
self.capacity = new_cap;
+ self.atlas_gen = self.atlas_gen.saturating_add(1);
}
- /// Ensures `coord` has an allocated slot in `color_pool` & `height_pool`, initializing it
- /// purely on GPU from the active layer's resident `GpuTilePool` tiles (ZERO CPU `readPixels`!).
- /// If `mix_ground_color` is true, also composites visible lower layers into `ground_pool[slot]` on GPU.
+ fn ensure_ground_uniform_capacity(&mut self, device: &wgpu::Device, needed: usize) {
+ if needed <= self.ground_uniform_cap {
+ return;
+ }
+ let new_cap = needed.next_power_of_two().max(64);
+ self.ground_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-np-ground-uniforms-dyn"),
+ size: new_cap as u64 * NP_UNIFORM_STRIDE,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ self.ground_uniform_cap = new_cap;
+ }
+
+ /// Prepares batched GPU initialization for all `coords` (allocating slots, uploading missing
+ /// source tiles to `GpuTilePool`, pinning source slots, and uploading all `GroundLayerUniforms`
+ /// in ONE `queue.write_buffer`). Call [`Self::encode_init_tiles_plan`] inside the single
+ /// dispatch `CommandEncoder` and [`Self::unpin_init_plan`] after `queue.submit`!
#[allow(clippy::too_many_arguments)]
- pub fn ensure_tile_initialized(
+ pub fn prepare_init_tiles_batch(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
tile_pool: &mut GpuTilePool,
doc: &Document,
active_layer: &LayerNode,
- coord: TileCoord,
+ coords: &[TileCoord],
mix_ground_color: bool,
scratch: Option<&dyn ScratchBackend>,
- ) -> u32 {
- if let Some(&slot) = self.coord_to_slot.get(&coord) {
+ ) -> InitTilesPlan {
+ let mut new_count = 0u32;
+ for &coord in coords {
+ if !self.coord_to_slot.contains_key(&coord) {
+ new_count += 1;
+ }
+ }
+ if new_count > 0 {
+ let needed = self.coord_to_slot.len() as u32 + new_count;
+ self.grow_if_needed(device, queue, needed);
+ }
+
+ let active_idx = doc
+ .layers
+ .iter()
+ .position(|l| l.meta.id == active_layer.meta.id);
+
+ let mut tile_inits = Vec::new();
+ let mut ground_inits = Vec::new();
+ let mut ground_uniforms: Vec<GroundLayerUniforms> = Vec::new();
+ let mut pinned_color_slots = Vec::new();
+ let mut pinned_impasto_slots = Vec::new();
+ let mut has_any_impasto_copy = false;
+
+ for &coord in coords {
+ let (slot, newly_alloc) = if let Some(&existing) = self.coord_to_slot.get(&coord) {
+ (existing, false)
+ } else {
+ let s = (self.coord_to_slot.len() as u32).min(self.capacity - 1);
+ self.coord_to_slot.insert(coord, s);
+ self.gpu_pickup_tile_inits += 1;
+ (s, true)
+ };
+
+ if newly_alloc {
+ let doc_key = tile_pool.intern_doc(&doc.id);
+ let active_layer_key = tile_pool.intern_layer(&active_layer.meta.id);
+ let color_src_slot = active_layer.grid.get_tile(coord).and_then(|tile| {
+ let key = GpuTileKey {
+ doc_id: doc_key,
+ layer_id: active_layer_key,
+ lod: 0,
+ coord,
+ };
+ tile_pool.ensure_tile_uploaded(queue, key, tile, scratch).ok()
+ });
+ if let Some(s) = color_src_slot {
+ tile_pool.pin_slot(s);
+ pinned_color_slots.push(s);
+ }
+
+ let height_src_slot = active_layer.grid.get_impasto_tile(coord).and_then(|tile| {
+ let key = GpuTileKey {
+ doc_id: doc_key,
+ layer_id: active_layer_key,
+ lod: 0,
+ coord,
+ };
+ tile_pool
+ .ensure_impasto_uploaded(device, queue, key, tile, scratch)
+ .ok()
+ });
+ if let Some(s) = height_src_slot {
+ tile_pool.pin_impasto_slot(s);
+ pinned_impasto_slots.push(s);
+ has_any_impasto_copy = true;
+ }
+
+ tile_inits.push(TileInitOp {
+ dst_slot: slot,
+ color_src_slot,
+ height_src_slot,
+ });
+ }
+
if mix_ground_color && !self.ground_populated.get(&coord).copied().unwrap_or(false) {
- self.build_ground_tile_gpu(
- device,
- queue,
- tile_pool,
- doc,
- &active_layer.meta.id,
- coord,
- slot,
- scratch,
- );
+ let mut lower_slots: Vec<(u32, f32)> = Vec::new();
+ if let Some(aidx) = active_idx {
+ let doc_key = tile_pool.intern_doc(&doc.id);
+ for layer in doc.layers[aidx + 1..].iter().rev() {
+ if !doc.is_layer_effectively_visible(&layer.meta.id)
+ || !layer.meta.layer_type.has_tiles()
+ {
+ continue;
+ }
+ let eff_op = doc.effective_opacity(&layer.meta.id);
+ if eff_op <= 0.001 {
+ continue;
+ }
+ if let Some(tile) = layer.grid.get_tile(coord) {
+ let layer_key = tile_pool.intern_layer(&layer.meta.id);
+ let key = GpuTileKey {
+ doc_id: doc_key,
+ layer_id: layer_key,
+ lod: 0,
+ coord,
+ };
+ if let Ok(src_slot) =
+ tile_pool.ensure_tile_uploaded(queue, key, tile, scratch)
+ {
+ tile_pool.pin_slot(src_slot);
+ pinned_color_slots.push(src_slot);
+ lower_slots.push((src_slot, eff_op));
+ }
+ }
+ }
+ }
+ let start_uniform_idx = ground_uniforms.len();
+ for (idx, &(src_slot, opacity)) in lower_slots.iter().enumerate() {
+ ground_uniforms.push(GroundLayerUniforms {
+ src_slot: src_slot as i32,
+ opacity,
+ is_first: u32::from(idx == 0),
+ _pad: 0,
+ });
+ }
+ ground_inits.push(GroundInitOp {
+ dst_slot: slot,
+ start_uniform_idx,
+ layer_count: lower_slots.len(),
+ });
self.ground_populated.insert(coord, true);
}
- return slot;
}
- let slot = self.coord_to_slot.len() as u32;
- self.grow_if_needed(device, queue, slot + 1);
- let slot = slot.min(self.capacity - 1);
- self.coord_to_slot.insert(coord, slot);
- self.gpu_pickup_tile_inits += 1;
-
- // 1. Initialize color_pool[slot] directly on GPU from active layer's tile (or clear transparent)
- let color_src_slot = active_layer.grid.get_tile(coord).and_then(|tile| {
- let key = GpuTileKey {
- doc_id: doc.id.clone(),
- layer_id: active_layer.meta.id.clone(),
- lod: 0,
- coord,
- };
- tile_pool.ensure_tile_uploaded(queue, key, tile, scratch).ok()
- });
+ if has_any_impasto_copy {
+ let _ = tile_pool.ensure_impasto_atlas_texture(device);
+ }
- // 2. Initialize height_pool[slot] directly on GPU from active layer's impasto tile (or clear 0.0)
- let height_src_slot = active_layer.grid.get_impasto_tile(coord).and_then(|tile| {
- let key = GpuTileKey {
- doc_id: doc.id.clone(),
- layer_id: active_layer.meta.id.clone(),
- lod: 0,
- coord,
- };
- tile_pool
- .ensure_impasto_uploaded(device, queue, key, tile, scratch)
- .ok()
- });
+ if !ground_uniforms.is_empty() {
+ self.ensure_ground_uniform_capacity(device, ground_uniforms.len());
+ let stride = NP_UNIFORM_STRIDE as usize;
+ let mut ubytes = vec![0u8; ground_uniforms.len() * stride];
+ for (i, u) in ground_uniforms.iter().enumerate() {
+ let src = bytemuck::bytes_of(u);
+ ubytes[i * stride..i * stride + src.len()].copy_from_slice(src);
+ }
+ queue.write_buffer(&self.ground_uniform_buf, 0, &ubytes);
+ }
- let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-np-init-tile-enc"),
- });
+ InitTilesPlan {
+ tile_inits,
+ ground_inits,
+ pinned_color_slots,
+ pinned_impasto_slots,
+ }
+ }
- if let Some(src_slot) = color_src_slot {
- encoder.copy_texture_to_texture(
- wgpu::TexelCopyTextureInfo {
- texture: tile_pool.atlas_texture(),
- mip_level: 0,
- origin: wgpu::Origin3d {
- x: 0,
- y: 0,
- z: src_slot,
+ /// Encodes all tile initializations and ground layer composites from `plan` directly into the
+ /// caller's single `CommandEncoder` (zero extra `queue.submit`!).
+ pub fn encode_init_tiles_plan(
+ &self,
+ device: &wgpu::Device,
+ tile_pool: &mut GpuTilePool,
+ encoder: &mut wgpu::CommandEncoder,
+ plan: &InitTilesPlan,
+ ) {
+ for op in &plan.tile_inits {
+ if let Some(src_slot) = op.color_src_slot {
+ encoder.copy_texture_to_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: tile_pool.atlas_texture(),
+ mip_level: 0,
+ origin: wgpu::Origin3d {
+ x: 0,
+ y: 0,
+ z: src_slot,
+ },
+ aspect: wgpu::TextureAspect::All,
},
- aspect: wgpu::TextureAspect::All,
- },
- wgpu::TexelCopyTextureInfo {
- texture: &self.color_tex,
- mip_level: 0,
- origin: wgpu::Origin3d {
- x: 0,
- y: 0,
- z: slot,
+ wgpu::TexelCopyTextureInfo {
+ texture: &self.color_tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d {
+ x: 0,
+ y: 0,
+ z: op.dst_slot,
+ },
+ aspect: wgpu::TextureAspect::All,
},
- aspect: wgpu::TextureAspect::All,
- },
- wgpu::Extent3d {
- width: TILE_SIZE as u32,
- height: TILE_SIZE as u32,
- depth_or_array_layers: 1,
- },
- );
- } else {
- let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
- label: Some("ink-np-clear-color-slot"),
- color_attachments: &[Some(wgpu::RenderPassColorAttachment {
- view: &self.color_slice_views[slot as usize],
- depth_slice: None,
- resolve_target: None,
- ops: wgpu::Operations {
- load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
- store: wgpu::StoreOp::Store,
+ wgpu::Extent3d {
+ width: TILE_SIZE as u32,
+ height: TILE_SIZE as u32,
+ depth_or_array_layers: 1,
},
- })],
- depth_stencil_attachment: None,
- timestamp_writes: None,
- occlusion_query_set: None,
- multiview_mask: None,
- });
+ );
+ } else {
+ let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("ink-np-clear-color-slot"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &self.color_slice_views[op.dst_slot as usize],
+ depth_slice: None,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ multiview_mask: None,
+ });
+ }
+
+ if self.use_cmix_display {
+ if let (Some(ref base), Some(ref disp)) =
+ (self.cmix_base.as_ref(), self.cmix_display.as_ref())
+ {
+ if let Some(src_slot) = op.color_src_slot {
+ for dst_tex in [&base.tex, &disp.tex] {
+ encoder.copy_texture_to_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: tile_pool.atlas_texture(),
+ mip_level: 0,
+ origin: wgpu::Origin3d {
+ x: 0,
+ y: 0,
+ z: src_slot,
+ },
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::TexelCopyTextureInfo {
+ texture: dst_tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d {
+ x: 0,
+ y: 0,
+ z: op.dst_slot,
+ },
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::Extent3d {
+ width: TILE_SIZE as u32,
+ height: TILE_SIZE as u32,
+ depth_or_array_layers: 1,
+ },
+ );
+ }
+ } else {
+ for slice_view in [
+ &base.slice_views[op.dst_slot as usize],
+ &disp.slice_views[op.dst_slot as usize],
+ ] {
+ let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("ink-np-clear-cmix-post-slot"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: slice_view,
+ depth_slice: None,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ multiview_mask: None,
+ });
+ }
+ }
+ }
+ }
+
+ if self.use_cmix_cov {
+ if let Some(ref cov) = self.cmix_cov {
+ let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("ink-np-clear-cmix-cov-slot"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &cov.slice_views[op.dst_slot as usize],
+ depth_slice: None,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ multiview_mask: None,
+ });
+ }
+ }
+
+ if let Some(h_slot) = op.height_src_slot {
+ let imp_tex = tile_pool.ensure_impasto_atlas_texture(device);
+ encoder.copy_texture_to_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: imp_tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d {
+ x: 0,
+ y: 0,
+ z: h_slot,
+ },
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::TexelCopyTextureInfo {
+ texture: &self.height_tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d {
+ x: 0,
+ y: 0,
+ z: op.dst_slot,
+ },
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::Extent3d {
+ width: TILE_SIZE as u32,
+ height: TILE_SIZE as u32,
+ depth_or_array_layers: 1,
+ },
+ );
+ } else {
+ let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("ink-np-clear-height-slot"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &self.height_slice_views[op.dst_slot as usize],
+ depth_slice: None,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ multiview_mask: None,
+ });
+ }
+ }
+
+ if plan.ground_inits.is_empty() {
+ return;
}
- if let Some(h_slot) = height_src_slot {
- let imp_tex = tile_pool.ensure_impasto_atlas_texture(device);
+ let needs_compute = plan.ground_inits.iter().any(|g| g.layer_count > 0);
+ let (bg_b_to_a, bg_a_to_b) = if needs_compute {
+ let mk_bg = |read_view: &wgpu::TextureView, write_view: &wgpu::TextureView| {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-np-ground-bg"),
+ layout: &self.ground_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.ground_uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(
+ std::mem::size_of::<GroundLayerUniforms>() as u64,
+ ),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(tile_pool.atlas_view()),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(read_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::TextureView(write_view),
+ },
+ ],
+ })
+ };
+ (
+ Some(mk_bg(&self.ground_scratch_b_view, &self.ground_scratch_a_view)),
+ Some(mk_bg(&self.ground_scratch_a_view, &self.ground_scratch_b_view)),
+ )
+ } else {
+ (None, None)
+ };
+
+ for gop in &plan.ground_inits {
+ if gop.layer_count == 0 {
+ let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("ink-np-ground-clear-pass"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &self.ground_slice_views[gop.dst_slot as usize],
+ depth_slice: None,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ multiview_mask: None,
+ });
+ continue;
+ }
+
+ let mut ping = false;
+ for idx in 0..gop.layer_count {
+ let dyn_off = ((gop.start_uniform_idx + idx) as u32) * (NP_UNIFORM_STRIDE as u32);
+ let bg = if !ping {
+ bg_b_to_a.as_ref().expect("bg_b_to_a")
+ } else {
+ bg_a_to_b.as_ref().expect("bg_a_to_b")
+ };
+ {
+ let mut cpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("ink-np-ground-comp-pass"),
+ timestamp_writes: None,
+ });
+ cpass.set_pipeline(&self.ground_pipe);
+ cpass.set_bind_group(0, bg, &[dyn_off]);
+ cpass.dispatch_workgroups(16, 16, 1);
+ }
+ ping = !ping;
+ }
+
+ let final_tex = if ping {
+ &self.ground_scratch_a_tex
+ } else {
+ &self.ground_scratch_b_tex
+ };
encoder.copy_texture_to_texture(
wgpu::TexelCopyTextureInfo {
- texture: imp_tex,
+ texture: final_tex,
mip_level: 0,
- origin: wgpu::Origin3d {
- x: 0,
- y: 0,
- z: h_slot,
- },
+ origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
wgpu::TexelCopyTextureInfo {
- texture: &self.height_tex,
+ texture: &self.ground_tex,
mip_level: 0,
origin: wgpu::Origin3d {
x: 0,
y: 0,
- z: slot,
+ z: gop.dst_slot,
},
aspect: wgpu::TextureAspect::All,
},
@@ -668,214 +1405,208 @@ impl NaturalPaintTilePools {
depth_or_array_layers: 1,
},
);
- } else {
- let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
- label: Some("ink-np-clear-height-slot"),
- color_attachments: &[Some(wgpu::RenderPassColorAttachment {
- view: &self.height_slice_views[slot as usize],
- depth_slice: None,
- resolve_target: None,
- ops: wgpu::Operations {
- load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
- store: wgpu::StoreOp::Store,
- },
- })],
- depth_stencil_attachment: None,
- timestamp_writes: None,
- occlusion_query_set: None,
- multiview_mask: None,
- });
}
+ }
- queue.submit(Some(encoder.finish()));
-
- if mix_ground_color {
- self.build_ground_tile_gpu(
- device,
- queue,
- tile_pool,
- doc,
- &active_layer.meta.id,
- coord,
- slot,
- scratch,
- );
- self.ground_populated.insert(coord, true);
+ /// Unpins all source `GpuTilePool` slots pinned during [`Self::prepare_init_tiles_batch`].
+ pub fn unpin_init_plan(&self, tile_pool: &mut GpuTilePool, plan: InitTilesPlan) {
+ for s in plan.pinned_color_slots {
+ tile_pool.unpin_slot(s);
+ }
+ for s in plan.pinned_impasto_slots {
+ tile_pool.unpin_impasto_slot(s);
}
-
- slot
}
- /// Composites visible layers strictly below `active_layer_id` at `coord` directly on GPU
- /// into `self.ground_tex[slot]` (exact 1:1 doc-space ground pickup with zero CPU readback!).
+ /// Ensures `coord` has an allocated slot in `color_pool` & `height_pool`, initializing it
+ /// purely on GPU from the active layer's resident `GpuTilePool` tiles (ZERO CPU `readPixels`!).
+ /// If `mix_ground_color` is true, also composites visible lower layers into `ground_pool[slot]` on GPU.
#[allow(clippy::too_many_arguments)]
- fn build_ground_tile_gpu(
- &self,
+ pub fn ensure_tile_initialized(
+ &mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
tile_pool: &mut GpuTilePool,
doc: &Document,
- active_layer_id: &str,
+ active_layer: &LayerNode,
coord: TileCoord,
- dst_slot: u32,
+ mix_ground_color: bool,
scratch: Option<&dyn ScratchBackend>,
- ) {
- // Document layers are stored top-to-bottom (`layers[0]` = top, `layers[last]` = bottom).
- // Collect visible tile layers strictly BELOW `active_layer_id` in bottom-to-top order.
- let Some(active_idx) = doc.layers.iter().position(|l| l.meta.id == active_layer_id) else {
- return;
- };
- let mut lower_slots: Vec<(u32, f32)> = Vec::new();
- for layer in doc.layers[active_idx + 1..].iter().rev() {
- if !doc.is_layer_effectively_visible(&layer.meta.id)
- || !layer.meta.layer_type.has_tiles()
- {
- continue;
- }
- let eff_op = doc.effective_opacity(&layer.meta.id);
- if eff_op <= 0.001 {
- continue;
- }
- if let Some(tile) = layer.grid.get_tile(coord) {
- let key = GpuTileKey {
- doc_id: doc.id.clone(),
- layer_id: layer.meta.id.clone(),
- lod: 0,
- coord,
- };
- if let Ok(src_slot) = tile_pool.ensure_tile_uploaded(queue, key, tile, scratch) {
- lower_slots.push((src_slot, eff_op));
- }
- }
- }
-
- if lower_slots.is_empty() {
- // Clear ground slot to transparent (no underlying pixels at this tile)
+ ) -> u32 {
+ let plan = self.prepare_init_tiles_batch(
+ device,
+ queue,
+ tile_pool,
+ doc,
+ active_layer,
+ &[coord],
+ mix_ground_color,
+ scratch,
+ );
+ if !plan.tile_inits.is_empty() || !plan.ground_inits.is_empty() {
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-np-ground-clear-enc"),
- });
- let g_view = self.ground_tex.create_view(&wgpu::TextureViewDescriptor {
- dimension: Some(wgpu::TextureViewDimension::D2),
- base_array_layer: dst_slot,
- array_layer_count: Some(1),
- ..Default::default()
+ label: Some("ink-np-init-tile-enc"),
});
- {
- let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
- label: Some("ink-np-ground-clear-pass"),
- color_attachments: &[Some(wgpu::RenderPassColorAttachment {
- view: &g_view,
- depth_slice: None,
- resolve_target: None,
- ops: wgpu::Operations {
- load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
- store: wgpu::StoreOp::Store,
- },
- })],
- depth_stencil_attachment: None,
- timestamp_writes: None,
- occlusion_query_set: None,
- multiview_mask: None,
- });
- }
+ self.encode_init_tiles_plan(device, tile_pool, &mut encoder, &plan);
queue.submit(Some(encoder.finish()));
- return;
}
+ self.unpin_init_plan(tile_pool, plan);
+ *self.coord_to_slot.get(&coord).expect("slot initialized")
+ }
- // Ping-pong composite every lower layer tile on GPU
- let mut ping = false;
- for (idx, &(src_slot, opacity)) in lower_slots.iter().enumerate() {
- let (read_view, write_view) = if !ping {
- (&self.ground_scratch_b_view, &self.ground_scratch_a_view)
- } else {
- (&self.ground_scratch_a_view, &self.ground_scratch_b_view)
- };
- let u = GroundLayerUniforms {
- src_slot: src_slot as i32,
- opacity,
- is_first: u32::from(idx == 0),
- _pad: 0,
- };
- queue.write_buffer(&self.ground_uniform_buf, 0, bytemuck::bytes_of(&u));
-
- let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-np-ground-bg"),
- layout: &self.ground_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: self.ground_uniform_buf.as_entire_binding(),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(tile_pool.atlas_view()),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::TextureView(read_view),
- },
- wgpu::BindGroupEntry {
- binding: 3,
- resource: wgpu::BindingResource::TextureView(write_view),
- },
- ],
- });
-
- let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-np-ground-comp-enc"),
- });
- {
- let mut cpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
- label: Some("ink-np-ground-comp-pass"),
- timestamp_writes: None,
- });
- cpass.set_pipeline(&self.ground_pipe);
- cpass.set_bind_group(0, &bg, &[]);
- cpass.dispatch_workgroups(16, 16, 1);
- }
- queue.submit(Some(encoder.finish()));
- ping = !ping;
+ /// Copies ONLY the tight dab sub-rectangle `(x, y, width, height)` from `color_scratch_tex`
+ /// back to `color_tex[slot]` instead of the full 512 KB `256×256` tile!
+ pub fn flush_color_scratch_subrect_to_slot(
+ &self,
+ encoder: &mut wgpu::CommandEncoder,
+ slot: u32,
+ x: u32,
+ y: u32,
+ width: u32,
+ height: u32,
+ ) {
+ if width == 0 || height == 0 {
+ return;
}
-
- let final_tex = if ping {
- &self.ground_scratch_a_tex
- } else {
- &self.ground_scratch_b_tex
- };
- let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-np-ground-copy-enc"),
- });
encoder.copy_texture_to_texture(
wgpu::TexelCopyTextureInfo {
- texture: final_tex,
+ texture: &self.color_scratch_tex,
mip_level: 0,
- origin: wgpu::Origin3d::ZERO,
+ origin: wgpu::Origin3d { x, y, z: 0 },
aspect: wgpu::TextureAspect::All,
},
wgpu::TexelCopyTextureInfo {
- texture: &self.ground_tex,
+ texture: &self.color_tex,
mip_level: 0,
- origin: wgpu::Origin3d {
- x: 0,
- y: 0,
- z: dst_slot,
- },
+ origin: wgpu::Origin3d { x, y, z: slot },
aspect: wgpu::TextureAspect::All,
},
wgpu::Extent3d {
- width: TILE_SIZE as u32,
- height: TILE_SIZE as u32,
+ width,
+ height,
depth_or_array_layers: 1,
},
);
- queue.submit(Some(encoder.finish()));
+ }
+
+ /// Copies ONLY the tight dab sub-rectangle `(x, y, width, height)` from `cmix_cov_scratch_tex`
+ /// back to `cmix_cov[slot]` when wet-edge coverage accumulation is active.
+ pub fn flush_cov_scratch_subrect_to_slot(
+ &self,
+ encoder: &mut wgpu::CommandEncoder,
+ slot: u32,
+ x: u32,
+ y: u32,
+ width: u32,
+ height: u32,
+ ) {
+ if width == 0 || height == 0 {
+ return;
+ }
+ if let Some(ref cov) = self.cmix_cov {
+ encoder.copy_texture_to_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: &self.cmix_cov_scratch_tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d { x, y, z: 0 },
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::TexelCopyTextureInfo {
+ texture: &cov.tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d { x, y, z: slot },
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ );
+ }
+ }
+
+ /// Copies full resolved `color_scratch_tex` -> `cmix_display[slot]` after opacity/wet-edge resolve.
+ pub fn flush_color_scratch_to_display_slot(
+ &self,
+ encoder: &mut wgpu::CommandEncoder,
+ slot: u32,
+ ) {
+ if let Some(ref disp) = self.cmix_display {
+ encoder.copy_texture_to_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: &self.color_scratch_tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::TexelCopyTextureInfo {
+ texture: &disp.tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d {
+ x: 0,
+ y: 0,
+ z: slot,
+ },
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::Extent3d {
+ width: TILE_SIZE as u32,
+ height: TILE_SIZE as u32,
+ depth_or_array_layers: 1,
+ },
+ );
+ }
+ }
+
+ /// Copies ONLY the tight touched sub-rectangle `(x, y, width, height)` from `color_scratch_tex`
+ /// -> `color_tex[slot]` and hardware-blits strictly that scissored sub-rect from
+ /// `height_scratch_r32f_tex` -> `height_tex[slot]` (`LoadOp::Load` preserves untouched pixels!).
+ #[allow(clippy::too_many_arguments)]
+ pub fn flush_scratch_subrect_to_slot(
+ &self,
+ encoder: &mut wgpu::CommandEncoder,
+ slot: u32,
+ x: u32,
+ y: u32,
+ width: u32,
+ height: u32,
+ write_height: bool,
+ ) {
+ if width == 0 || height == 0 {
+ return;
+ }
+ self.flush_color_scratch_subrect_to_slot(encoder, slot, x, y, width, height);
+
+ if write_height {
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("ink-np-r32-to-r16-subrect-pass"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &self.height_slice_views[slot as usize],
+ depth_slice: None,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Load,
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ multiview_mask: None,
+ });
+ pass.set_scissor_rect(x, y, width, height);
+ pass.set_pipeline(&self.r32_to_r16_pipe);
+ pass.set_bind_group(0, &self.r32_to_r16_bg, &[]);
+ pass.draw(0..3, 0..1);
+ }
}
/// Copies `color_scratch_tex` -> `color_tex[slot]` and hardware-blits `height_scratch_r32f_tex`
/// -> `height_tex[slot]` (`R16Float`) inside the supplied command encoder!
pub fn flush_scratch_to_slot(
&self,
- device: &wgpu::Device,
+ _device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
slot: u32,
write_height: bool,
@@ -905,14 +1636,6 @@ impl NaturalPaintTilePools {
);
if write_height {
- let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-np-r32-to-r16-bg"),
- layout: &self.r32_to_r16_bgl,
- entries: &[wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::TextureView(&self.height_scratch_r32f_view),
- }],
- });
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("ink-np-r32-to-r16-pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
@@ -930,13 +1653,75 @@ impl NaturalPaintTilePools {
multiview_mask: None,
});
pass.set_pipeline(&self.r32_to_r16_pipe);
- pass.set_bind_group(0, &bg, &[]);
+ pass.set_bind_group(0, &self.r32_to_r16_bg, &[]);
pass.draw(0..3, 0..1);
}
}
- /// Commits all touched color & impasto heightfield tiles into `GpuTilePool` directly on GPU
- /// and reads back ONLY the touched tiles once at stroke-end for CPU CoW storage + Undo/Redo!
+ fn ensure_commit_staging_buffers(
+ &mut self,
+ device: &wgpu::Device,
+ needed_tiles: usize,
+ need_height: bool,
+ ) {
+ if needed_tiles > self.pack_uniform_cap {
+ let new_cap = needed_tiles.next_power_of_two().max(64);
+ self.pack_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-np-pack-uniforms-dyn"),
+ size: new_cap as u64 * NP_UNIFORM_STRIDE,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ self.pack_uniform_cap = new_cap;
+ self.pack_uniform_gen = self.pack_uniform_gen.saturating_add(1);
+ }
+ if needed_tiles > self.commit_color_staging_cap
+ || self.commit_color_staging[0].is_none()
+ || self.commit_rgba8_storage.is_none()
+ {
+ let cap = needed_tiles.next_power_of_two().max(16);
+ // Packed RGBA8 (256 KB/tile — HALF the bandwidth of raw Rgba16Float!)
+ let bytes = (cap * BYTES_32BIT) as u64;
+ self.commit_rgba8_storage = Some(device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-np-commit-rgba8-storage"),
+ size: bytes,
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
+ mapped_at_creation: false,
+ }));
+ self.commit_rgba8_storage_gen = self.commit_rgba8_storage_gen.saturating_add(1);
+ for i in 0..2 {
+ self.commit_color_staging[i] = Some(device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-np-commit-rgba8-staging"),
+ size: bytes,
+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
+ mapped_at_creation: false,
+ }));
+ }
+ self.commit_color_staging_cap = cap;
+ }
+ if need_height
+ && (needed_tiles > self.commit_height_staging_cap
+ || self.commit_height_staging[0].is_none())
+ {
+ let cap = needed_tiles.next_power_of_two().max(16);
+ let bytes = (cap * BYTES_R16F) as u64;
+ for i in 0..2 {
+ self.commit_height_staging[i] =
+ Some(device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-np-commit-height-staging"),
+ size: bytes,
+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
+ mapped_at_creation: false,
+ }));
+ }
+ self.commit_height_staging_cap = cap;
+ }
+ }
+
+ /// Commits all touched color & impasto heightfield tiles into `GpuTilePool` directly on GPU,
+ /// packs `Rgba16Float -> Bayer-dithered RGBA8` on GPU (cutting readback bandwidth in half and
+ /// removing 100% of CPU conversion work!), and pipelines double-buffered staging readbacks
+ /// using submission-targeted waits for CPU CoW storage + Undo/Redo!
pub fn commit_to_layer_pool(
&mut self,
device: &wgpu::Device,
@@ -952,125 +1737,181 @@ impl NaturalPaintTilePools {
});
}
- let coords_slots: Vec<(TileCoord, u32)> =
+ let mut coords_slots: Vec<(TileCoord, u32)> =
self.coord_to_slot.iter().map(|(&c, &s)| (c, s)).collect();
+ coords_slots.sort_by_key(|(c, _)| (c.ty, c.tx));
let n = coords_slots.len();
let commit_impasto = self.impasto_dirty;
- let color_staging = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("ink-np-commit-color-staging"),
- size: (n * BYTES_16F) as u64,
- usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
- mapped_at_creation: false,
- });
- let height_staging = if commit_impasto {
- Some(device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("ink-np-commit-height-staging"),
- size: (n * BYTES_R16F) as u64,
- usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
- mapped_at_creation: false,
- }))
+ let max_color_chunk = (tile_pool.capacity() as usize / 2).max(1);
+ let max_single_chunk = if commit_impasto {
+ max_color_chunk.min((tile_pool.impasto_capacity() as usize / 2).max(1))
} else {
- None
+ max_color_chunk
+ };
+ // When spanning multiple chunks, halve chunk size so 2 double-buffered chunks can be
+ // pinned & in-flight simultaneously without colliding on GpuTilePool atlas slots!
+ let chunk_size = if n > max_single_chunk {
+ (max_single_chunk / 2).max(1)
+ } else {
+ max_single_chunk
};
- let mut color_versions = Vec::with_capacity(n);
- let mut height_versions = Vec::with_capacity(n);
-
- // Acquire destination slots in GpuTilePool first
- let mut dst_color_slots = Vec::with_capacity(n);
- let mut dst_height_slots = Vec::with_capacity(n);
- for &(coord, _) in &coords_slots {
- let c_ver = allocate_tile_version();
- let c_key = GpuTileKey {
- doc_id: doc_id.to_string(),
- layer_id: layer_id.to_string(),
- lod: 0,
- coord,
+ let max_req = n.min(chunk_size);
+ self.ensure_commit_staging_buffers(device, max_req, commit_impasto);
+
+ let use_disp = self.use_cmix_display && self.cmix_display.is_some();
+ let pack_key = (
+ self.atlas_gen,
+ self.pack_uniform_gen,
+ self.commit_rgba8_storage_gen,
+ use_disp,
+ );
+ if self
+ .cached_pack_bg
+ .as_ref()
+ .map(|(k, _)| *k != pack_key)
+ .unwrap_or(true)
+ {
+ let src_view = if use_disp {
+ &self.cmix_display.as_ref().expect("cmix_display").array_view
+ } else {
+ &self.color_array_view
};
- dst_color_slots.push(tile_pool.acquire_slot(c_key, c_ver));
- color_versions.push(c_ver);
-
- if commit_impasto {
- let h_ver = allocate_tile_version();
- let h_key = GpuTileKey {
- doc_id: doc_id.to_string(),
- layer_id: layer_id.to_string(),
+ let storage = self
+ .commit_rgba8_storage
+ .as_ref()
+ .expect("commit_rgba8_storage allocated");
+ let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-np-pack-rgba8-bg"),
+ layout: &self.pack_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.pack_uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(std::mem::size_of::<NpPackUniforms>() as u64),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(src_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: storage.as_entire_binding(),
+ },
+ ],
+ });
+ self.cached_pack_bg = Some((pack_key, bg));
+ }
+
+ struct InFlightCommitChunk {
+ rb_idx: usize,
+ sub_idx: wgpu::SubmissionIndex,
+ color_read_bytes: u64,
+ height_read_bytes: u64,
+ rx_c: std::sync::mpsc::Receiver<Result<(), wgpu::BufferAsyncError>>,
+ rx_h: Option<std::sync::mpsc::Receiver<Result<(), wgpu::BufferAsyncError>>>,
+ coords: Vec<TileCoord>,
+ color_versions: Vec<u64>,
+ height_versions: Vec<u64>,
+ dst_color_slots: Vec<u32>,
+ dst_height_slots: Vec<u32>,
+ }
+
+ let mut color_tiles = Vec::with_capacity(n);
+ let mut impasto_tiles = Vec::new();
+ let stride = NP_UNIFORM_STRIDE as usize;
+
+ let submit_chunk = |pools: &mut NaturalPaintTilePools,
+ tile_pool: &mut GpuTilePool,
+ chunk: &[(TileCoord, u32)]|
+ -> InFlightCommitChunk {
+ let cn = chunk.len();
+ let rb_idx = pools.commit_rb_idx;
+ pools.commit_rb_idx ^= 1;
+
+ let color_read_bytes = (cn * BYTES_32BIT) as u64;
+ let height_read_bytes = (cn * BYTES_R16F) as u64;
+
+ let mut coords = Vec::with_capacity(cn);
+ let mut color_versions = Vec::with_capacity(cn);
+ let mut height_versions = Vec::with_capacity(cn);
+ let mut dst_color_slots = Vec::with_capacity(cn);
+ let mut dst_height_slots = Vec::with_capacity(cn);
+
+ // Acquire & pin destination slots so committed tiles are IMMEDIATELY resident in GpuTilePool!
+ let doc_key = tile_pool.intern_doc(doc_id);
+ let layer_key = tile_pool.intern_layer(layer_id);
+ for &(coord, _) in chunk {
+ coords.push(coord);
+ let c_ver = allocate_tile_version();
+ let c_key = GpuTileKey {
+ doc_id: doc_key,
+ layer_id: layer_key,
lod: 0,
coord,
};
- dst_height_slots.push(tile_pool.acquire_impasto_slot(device, h_key, h_ver));
- height_versions.push(h_ver);
+ let c_slot = tile_pool.acquire_slot(c_key, c_ver);
+ tile_pool.pin_slot(c_slot);
+ dst_color_slots.push(c_slot);
+ color_versions.push(c_ver);
+
+ if commit_impasto {
+ let h_ver = allocate_tile_version();
+ let h_key = GpuTileKey {
+ doc_id: doc_key,
+ layer_id: layer_key,
+ lod: 0,
+ coord,
+ };
+ let h_slot = tile_pool.acquire_impasto_slot(device, h_key, h_ver);
+ tile_pool.pin_impasto_slot(h_slot);
+ dst_height_slots.push(h_slot);
+ height_versions.push(h_ver);
+ }
}
- }
- let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-np-commit-enc"),
- });
+ // Upload dynamic uniforms for GPU Bayer-dithered RGBA8 packing
+ pools.pack_uniform_staging.clear();
+ pools.pack_uniform_staging.resize(cn * stride, 0u8);
+ for (i, &(_coord, src_slot)) in chunk.iter().enumerate() {
+ let pu = NpPackUniforms {
+ src_slot: src_slot as i32,
+ out_tile_idx: i as u32,
+ _pad0: 0,
+ _pad1: 0,
+ };
+ let src = bytemuck::bytes_of(&pu);
+ pools.pack_uniform_staging[i * stride..i * stride + src.len()].copy_from_slice(src);
+ }
+ queue.write_buffer(&pools.pack_uniform_buf, 0, &pools.pack_uniform_staging);
- for (i, &(_coord, src_slot)) in coords_slots.iter().enumerate() {
- // GPU->GPU copy color into GpuTilePool
- encoder.copy_texture_to_texture(
- wgpu::TexelCopyTextureInfo {
- texture: &self.color_tex,
- mip_level: 0,
- origin: wgpu::Origin3d {
- x: 0,
- y: 0,
- z: src_slot,
- },
- aspect: wgpu::TextureAspect::All,
- },
- wgpu::TexelCopyTextureInfo {
- texture: tile_pool.atlas_texture(),
- mip_level: 0,
- origin: wgpu::Origin3d {
- x: 0,
- y: 0,
- z: dst_color_slots[i],
- },
- aspect: wgpu::TextureAspect::All,
- },
- wgpu::Extent3d {
- width: TILE_SIZE as u32,
- height: TILE_SIZE as u32,
- depth_or_array_layers: 1,
- },
- );
- // Copy to stroke-end readback staging buffer
- encoder.copy_texture_to_buffer(
- wgpu::TexelCopyTextureInfo {
- texture: &self.color_tex,
- mip_level: 0,
- origin: wgpu::Origin3d {
- x: 0,
- y: 0,
- z: src_slot,
- },
- aspect: wgpu::TextureAspect::All,
- },
- wgpu::TexelCopyBufferInfo {
- buffer: &color_staging,
- layout: wgpu::TexelCopyBufferLayout {
- offset: (i * BYTES_16F) as u64,
- bytes_per_row: Some((TILE_SIZE * 8) as u32), // 2048
- rows_per_image: Some(TILE_SIZE as u32),
- },
- },
- wgpu::Extent3d {
- width: TILE_SIZE as u32,
- height: TILE_SIZE as u32,
- depth_or_array_layers: 1,
- },
- );
- }
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-np-commit-pack-enc"),
+ });
- if let Some(ref h_staging) = height_staging {
- let imp_tex = tile_pool.ensure_impasto_atlas_texture(device);
- for (i, &(_coord, src_slot)) in coords_slots.iter().enumerate() {
+ let src_color_tex = if use_disp {
+ &pools.cmix_display.as_ref().expect("cmix_display").tex
+ } else {
+ &pools.color_tex
+ };
+ let pack_bg = &pools.cached_pack_bg.as_ref().expect("pack_bg cached").1;
+ let rgba8_storage = pools
+ .commit_rgba8_storage
+ .as_ref()
+ .expect("commit_rgba8_storage");
+ let color_staging = pools.commit_color_staging[rb_idx]
+ .as_ref()
+ .expect("commit_color_staging allocated");
+
+ for (i, &(_coord, src_slot)) in chunk.iter().enumerate() {
+ // 1. GPU->GPU copy color into GpuTilePool (immediately resident for next frame!)
encoder.copy_texture_to_texture(
wgpu::TexelCopyTextureInfo {
- texture: &self.height_tex,
+ texture: src_color_tex,
mip_level: 0,
origin: wgpu::Origin3d {
x: 0,
@@ -1080,12 +1921,12 @@ impl NaturalPaintTilePools {
aspect: wgpu::TextureAspect::All,
},
wgpu::TexelCopyTextureInfo {
- texture: imp_tex,
+ texture: tile_pool.atlas_texture(),
mip_level: 0,
origin: wgpu::Origin3d {
x: 0,
y: 0,
- z: dst_height_slots[i],
+ z: dst_color_slots[i],
},
aspect: wgpu::TextureAspect::All,
},
@@ -1095,85 +1936,221 @@ impl NaturalPaintTilePools {
depth_or_array_layers: 1,
},
);
- encoder.copy_texture_to_buffer(
- wgpu::TexelCopyTextureInfo {
- texture: &self.height_tex,
- mip_level: 0,
- origin: wgpu::Origin3d {
- x: 0,
- y: 0,
- z: src_slot,
+ // 2. GPU Bayer-dithered Rgba16Float -> packed RGBA8 compute pass
+ let dyn_off = (i as u32) * (NP_UNIFORM_STRIDE as u32);
+ let mut cpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("ink-np-pack-rgba8-pass"),
+ timestamp_writes: None,
+ });
+ cpass.set_pipeline(&pools.pack_pipe);
+ cpass.set_bind_group(0, pack_bg, &[dyn_off]);
+ cpass.dispatch_workgroups(16, 16, 1);
+ }
+
+ // 3. Single packed buffer copy (256 KB/tile instead of 512 KB/tile!)
+ encoder.copy_buffer_to_buffer(
+ rgba8_storage,
+ 0,
+ color_staging,
+ 0,
+ color_read_bytes,
+ );
+
+ let height_staging = if commit_impasto {
+ pools.commit_height_staging[rb_idx].as_ref()
+ } else {
+ None
+ };
+ if let Some(h_staging) = height_staging {
+ let imp_tex = tile_pool.ensure_impasto_atlas_texture(device);
+ for (i, &(_coord, src_slot)) in chunk.iter().enumerate() {
+ encoder.copy_texture_to_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: &pools.height_tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d {
+ x: 0,
+ y: 0,
+ z: src_slot,
+ },
+ aspect: wgpu::TextureAspect::All,
},
- aspect: wgpu::TextureAspect::All,
- },
- wgpu::TexelCopyBufferInfo {
- buffer: h_staging,
- layout: wgpu::TexelCopyBufferLayout {
- offset: (i * BYTES_R16F) as u64,
- bytes_per_row: Some((TILE_SIZE * 2) as u32), // 512 (multiple of 256!)
- rows_per_image: Some(TILE_SIZE as u32),
+ wgpu::TexelCopyTextureInfo {
+ texture: imp_tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d {
+ x: 0,
+ y: 0,
+ z: dst_height_slots[i],
+ },
+ aspect: wgpu::TextureAspect::All,
},
- },
- wgpu::Extent3d {
- width: TILE_SIZE as u32,
- height: TILE_SIZE as u32,
- depth_or_array_layers: 1,
- },
- );
+ wgpu::Extent3d {
+ width: TILE_SIZE as u32,
+ height: TILE_SIZE as u32,
+ depth_or_array_layers: 1,
+ },
+ );
+ encoder.copy_texture_to_buffer(
+ wgpu::TexelCopyTextureInfo {
+ texture: &pools.height_tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d {
+ x: 0,
+ y: 0,
+ z: src_slot,
+ },
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::TexelCopyBufferInfo {
+ buffer: h_staging,
+ layout: wgpu::TexelCopyBufferLayout {
+ offset: (i * BYTES_R16F) as u64,
+ bytes_per_row: Some((TILE_SIZE * 2) as u32), // 512 (multiple of 256!)
+ rows_per_image: Some(TILE_SIZE as u32),
+ },
+ },
+ wgpu::Extent3d {
+ width: TILE_SIZE as u32,
+ height: TILE_SIZE as u32,
+ depth_or_array_layers: 1,
+ },
+ );
+ }
}
- }
- queue.submit(Some(encoder.finish()));
+ let sub_idx = queue.submit(Some(encoder.finish()));
- // Map color staging buffer
- let c_slice = color_staging.slice(..);
- let (tx_c, rx_c) = std::sync::mpsc::channel();
- c_slice.map_async(wgpu::MapMode::Read, move |res| {
- let _ = tx_c.send(res);
- });
+ // Kick off async mapping immediately so GPU work overlaps with next chunk!
+ let c_slice = color_staging.slice(0..color_read_bytes);
+ let (tx_c, rx_c) = std::sync::mpsc::channel();
+ c_slice.map_async(wgpu::MapMode::Read, move |res| {
+ let _ = tx_c.send(res);
+ });
- let rx_h = height_staging.as_ref().map(|hs| {
- let h_slice = hs.slice(..);
- let (tx_h, rx_h) = std::sync::mpsc::channel();
- h_slice.map_async(wgpu::MapMode::Read, move |res| {
- let _ = tx_h.send(res);
+ let rx_h = height_staging.map(|hs| {
+ let h_slice = hs.slice(0..height_read_bytes);
+ let (tx_h, rx_h) = std::sync::mpsc::channel();
+ h_slice.map_async(wgpu::MapMode::Read, move |res| {
+ let _ = tx_h.send(res);
+ });
+ rx_h
});
- rx_h
- });
- let _ = device.poll(wgpu::PollType::wait_indefinitely());
- rx_c.recv()
- .map_err(|_| "NaturalPaint color commit channel closed".to_string())?
- .map_err(|e| format!("NaturalPaint color commit map failed: {e}"))?;
+ InFlightCommitChunk {
+ rb_idx,
+ sub_idx,
+ color_read_bytes,
+ height_read_bytes,
+ rx_c,
+ rx_h,
+ coords,
+ color_versions,
+ height_versions,
+ dst_color_slots,
+ dst_height_slots,
+ }
+ };
- let c_mapped = c_slice
- .get_mapped_range()
- .map_err(|e| format!("NaturalPaint color get_mapped_range failed: {e}"))?;
- let mut color_tiles = Vec::with_capacity(n);
- for (i, &(coord, _)) in coords_slots.iter().enumerate() {
- let raw_16f = &c_mapped[i * BYTES_16F..(i + 1) * BYTES_16F];
- let mut rgba8 = vec![0u8; BYTES_32BIT];
- rgba16f_to_rgba8_dithered(raw_16f, &mut rgba8);
- color_tiles.push((coord, rgba8, color_versions[i]));
- }
- drop(c_mapped);
- color_staging.unmap();
+ let drain_chunk = |pools: &NaturalPaintTilePools,
+ tile_pool: &mut GpuTilePool,
+ fl: InFlightCommitChunk,
+ color_tiles: &mut Vec<(TileCoord, Vec<u8>, u64)>,
+ impasto_tiles: &mut Vec<(TileCoord, Vec<u8>, u64)>|
+ -> Result<(), String> {
+ let unpin_chunk = |pool: &mut GpuTilePool| {
+ for &s in &fl.dst_color_slots {
+ pool.unpin_slot(s);
+ }
+ for &s in &fl.dst_height_slots {
+ pool.unpin_impasto_slot(s);
+ }
+ };
- let mut impasto_tiles = Vec::new();
- if let (Some(hs), Some(rx_h)) = (height_staging, rx_h) {
- rx_h.recv()
- .map_err(|_| "NaturalPaint impasto commit channel closed".to_string())?
- .map_err(|e| format!("NaturalPaint impasto commit map failed: {e}"))?;
- let h_mapped = hs
- .slice(..)
- .get_mapped_range()
- .map_err(|e| format!("NaturalPaint impasto get_mapped_range failed: {e}"))?;
- for (i, &(coord, _)) in coords_slots.iter().enumerate() {
- let raw_r16f = h_mapped[i * BYTES_R16F..(i + 1) * BYTES_R16F].to_vec();
- impasto_tiles.push((coord, raw_r16f, height_versions[i]));
+ let _ = device.poll(wgpu::PollType::Wait {
+ submission_index: Some(fl.sub_idx),
+ timeout: None,
+ });
+
+ let color_staging = pools.commit_color_staging[fl.rb_idx]
+ .as_ref()
+ .expect("commit_color_staging allocated");
+ let c_recv = fl
+ .rx_c
+ .recv()
+ .map_err(|_| "NaturalPaint color commit channel closed".to_string())
+ .and_then(|r| r.map_err(|e| format!("NaturalPaint color commit map failed: {e}")));
+ if let Err(err) = c_recv {
+ unpin_chunk(tile_pool);
+ return Err(err);
}
- drop(h_mapped);
- hs.unmap();
+
+ let c_slice = color_staging.slice(0..fl.color_read_bytes);
+ let c_mapped = match c_slice.get_mapped_range() {
+ Ok(m) => m,
+ Err(e) => {
+ color_staging.unmap();
+ unpin_chunk(tile_pool);
+ return Err(format!("NaturalPaint color get_mapped_range failed: {e}"));
+ }
+ };
+ // Direct memcpy of GPU-packed Bayer-dithered RGBA8 (ZERO CPU f16 conversion!)
+ for (i, &coord) in fl.coords.iter().enumerate() {
+ let rgba8 = c_mapped[i * BYTES_32BIT..(i + 1) * BYTES_32BIT].to_vec();
+ color_tiles.push((coord, rgba8, fl.color_versions[i]));
+ }
+ drop(c_mapped);
+ color_staging.unmap();
+
+ if let Some(rx_h) = fl.rx_h {
+ let hs = pools.commit_height_staging[fl.rb_idx]
+ .as_ref()
+ .expect("commit_height_staging allocated");
+ let h_recv = rx_h
+ .recv()
+ .map_err(|_| "NaturalPaint impasto commit channel closed".to_string())
+ .and_then(|r| {
+ r.map_err(|e| format!("NaturalPaint impasto commit map failed: {e}"))
+ });
+ if let Err(err) = h_recv {
+ unpin_chunk(tile_pool);
+ return Err(err);
+ }
+ let h_mapped = match hs.slice(0..fl.height_read_bytes).get_mapped_range() {
+ Ok(m) => m,
+ Err(e) => {
+ hs.unmap();
+ unpin_chunk(tile_pool);
+ return Err(format!("NaturalPaint impasto get_mapped_range failed: {e}"));
+ }
+ };
+ for (i, &coord) in fl.coords.iter().enumerate() {
+ let raw_r16f = h_mapped[i * BYTES_R16F..(i + 1) * BYTES_R16F].to_vec();
+ impasto_tiles.push((coord, raw_r16f, fl.height_versions[i]));
+ }
+ drop(h_mapped);
+ hs.unmap();
+ }
+
+ unpin_chunk(tile_pool);
+ Ok(())
+ };
+
+ let mut prev_in_flight: Option<InFlightCommitChunk> = None;
+ for chunk in coords_slots.chunks(chunk_size) {
+ let cur = submit_chunk(self, tile_pool, chunk);
+ if let Some(prev) = prev_in_flight.take() {
+ if let Err(err) =
+ drain_chunk(self, tile_pool, prev, &mut color_tiles, &mut impasto_tiles)
+ {
+ let _ = drain_chunk(self, tile_pool, cur, &mut color_tiles, &mut impasto_tiles);
+ return Err(err);
+ }
+ }
+ prev_in_flight = Some(cur);
+ }
+ if let Some(last) = prev_in_flight {
+ drain_chunk(self, tile_pool, last, &mut color_tiles, &mut impasto_tiles)?;
}
self.reset_for_stroke();
diff --git a/crates/ink-engine/src/natural_paint/mod.rs b/crates/ink-engine/src/natural_paint/mod.rs
index 7ba226c..c86e52d 100644
--- a/crates/ink-engine/src/natural_paint/mod.rs
+++ b/crates/ink-engine/src/natural_paint/mod.rs
@@ -26,7 +26,8 @@ pub use pigment::{
composite_pigment_over_pixel, encode_pigment_over_white, linear_rgb_to_oklab, linear_to_srgb,
mix_oklab_srgb, mix_pigments_srgb, oklab_to_linear_rgb, spectral_state_to_srgb,
srgb_to_linear, srgb_to_spectral_state, DirtyBrushGpuBank, GpuBristleSlot, GpuSpatialTipCell,
- MAX_BRISTLES, PIGMENT_WGSL, SPECTRAL_STATE_SIZE,
+ MAX_BRISTLES, PIGMENT_WGSL, SPECTRAL_STATE_SIZE, TOTAL_BRISTLE_SLOTS, UNDERBED_BANDS,
+ UNDERBED_SLOT_BASE,
};
pub use ribbon::{
collect_ribbon_touched_tiles, compute_ribbon_metrics, GpuRibbonPipeline, RibbonMeshBuilder,
diff --git a/crates/ink-engine/src/natural_paint/natural_paint.rs b/crates/ink-engine/src/natural_paint/natural_paint.rs
index 9fcb671..15e3dc9 100644
--- a/crates/ink-engine/src/natural_paint/natural_paint.rs
+++ b/crates/ink-engine/src/natural_paint/natural_paint.rs
@@ -14,9 +14,10 @@
//! - Pass 3 (`cs_color_mix_pickup` + `cs_color_mix_stamp`): Zero-readback GPU 16×16 oriented
//! `SpatialTipMixer` for non-bristle CSP `colorMixing` / blender / blur brushes.
+use crate::brush::shaders::{DUAL_BRUSH_COMBINE_WGSL, PAPER_GRAIN_WGSL};
use crate::brush::{
- evaluate_csp_sensor, CompiledSensorLuts, GpuBrushDab, GpuPaperTexture, GpuTipArray,
- NativeBrushConfig, NaturalMixingMode, NaturalPaintSettings,
+ evaluate_csp_sensor, CompiledSensorLuts, DualBrushCompositeMode, GpuBrushDab, GpuPaperTexture,
+ GpuTipArray, NativeBrushConfig, NaturalPaintSettings,
};
use crate::document::{Document, LayerNode};
use crate::memory::{GpuTilePool, ScratchBackend};
@@ -24,23 +25,15 @@ use crate::natural_paint::bristle_ribbon::GpuBristleCapsule;
use crate::natural_paint::impasto::{CommittedNaturalPaintBatch, NaturalPaintTilePools};
use crate::natural_paint::pigment::{
DirtyBrushGpuBank, GpuBristleSlot, MAX_BRISTLES, PIGMENT_WGSL, SPATIAL_TIP_GRID,
+ TOTAL_BRISTLE_SLOTS,
};
use crate::tiles::{TileCoord, TILE_SIZE};
use bytemuck::{Pod, Zeroable};
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
+use std::num::NonZeroU64;
-const MAX_LOOKUP_TILES: usize = 256;
-
-/// GPU tile lookup entry mapping `(tx, ty) -> pool_slot` for O(1) multi-tile GPU pickup.
-#[repr(C)]
-#[derive(Debug, Clone, Copy, Pod, Zeroable)]
-struct TileLookupEntry {
- tx: i32,
- ty: i32,
- slot: i32,
- _pad: i32,
-}
+const NP_UNIFORM_STRIDE: u64 = 256;
/// Output of `cs_update_bristle_load` consumed by `cs_raster_natural_paint` (`96` bytes).
#[repr(C)]
@@ -67,16 +60,18 @@ struct PickupUniforms {
paint1: [f32; 4],
/// `[mixing_mode_u, spatial_mixing_u, mix_ground_u, capsule_count_u]`
counts0: [u32; 4],
- /// `[tile_lookup_count_u, bristle_count_u, use_blur_u, perceptual_u]`
+ /// `[total_slots_u, bristle_count_u, use_blur_u, perceptual_u]`
counts1: [u32; 4],
/// `[blur_strength, brush_size, auto_clean_u_f, 0.0]`
extra: [f32; 4],
+ /// `[grid_ox, grid_oy, grid_w, grid_h]` — O(1) dense bounding-box tile lookup grid
+ grid_info: [i32; 4],
}
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct RasterTileUniforms {
- /// `[tile_origin_x, tile_origin_y, tile_slot_f, capsule_count_f]`
+ /// `[tile_origin_x, tile_origin_y, tile_slot_f, 0.0]`
tile_info: [f32; 4],
/// `[dry_brush, granulation, penetration_curve, grain_strength]`
surface0: [f32; 4],
@@ -92,6 +87,10 @@ struct RasterTileUniforms {
extra: [f32; 4],
/// `[sel_slot_f (-2=none, -1=default, >=0=tile slot), sel_default_f, 0.0, 0.0]`
sel_info: [f32; 4],
+ /// `[x0, y0, x1, y1]` — tight tile-local clipped pixel sub-rect in `[0..256]`
+ rect: [u32; 4],
+ /// `[bin_start, bin_count, track_cov_u, 0]` — per-tile binned capsule slice
+ bin_info: [u32; 4],
}
#[repr(C)]
@@ -116,12 +115,14 @@ struct ColorMixPickupUniforms {
params0: [f32; 4],
/// `[fg_r, fg_g, fg_b, pigment_strength]`
fg_pigment: [f32; 4],
- /// `[wetness, blur_strength, pressure, brush_opacity]`
+ /// `[wetness, blur_strength, pressure, step_norm]`
params1: [f32; 4],
- /// `[mixing_mode_u, mix_ground_u, tile_lookup_count_u, use_blur_u]`
+ /// `[mixing_mode_u, mix_ground_u, _unused, use_blur_u]`
flags0: [u32; 4],
/// `[perceptual_u, has_tip_tex_u, sub_tip_slice_u, 0]`
flags1: [u32; 4],
+ /// `[grid_ox, grid_oy, grid_w, grid_h]` — O(1) dense bounding-box tile lookup grid
+ grid_info: [i32; 4],
}
#[repr(C)]
@@ -131,16 +132,45 @@ struct ColorMixTileUniforms {
tile_info: [f32; 4],
/// `[stamp_x, stamp_y, rx, ry]`
stamp_pos: [f32; 4],
- /// `[angle_rad, hardness, opacity, density_of_paint]`
+ /// `[angle_rad, hardness, opacity_dab, density_of_paint]`
geom: [f32; 4],
/// `[pigment_strength, blur_strength, grain_strength, paper_scale]`
fx0: [f32; 4],
- /// `[paper_rot_rad, sub_tip_slice_f, anti_alias_f, is_smear_f]`
+ /// `[paper_rot_rad, sub_tip_slice_f, pressure, stroke_angle_rad]`
fx1: [f32; 4],
- /// `[has_tip_tex_u, has_paper_tex_u, use_blur_u, mixing_mode_u]`
- flags: [u32; 4],
- /// `[sel_slot_f (-2=none, -1=default, >=0=tile slot), sel_default_f, 0.0, 0.0]`
- sel_info: [f32; 4],
+ /// `[paper_size_x, paper_size_y, paper_offset_norm_x, paper_offset_norm_y]`
+ paper0: [f32; 4],
+ /// `[stroke_rand_off_x, stroke_rand_off_y, paper_brightness, paper_contrast]`
+ paper1: [f32; 4],
+ /// `[bg_r, bg_g, bg_b, amount_of_paint]`
+ bg_amount: [f32; 4],
+ /// `[flip_x, flip_y, sel_slot_f (-2=none, -1=default, >=0=tile slot), sel_default_f]`
+ flip_sel: [f32; 4],
+ /// `[x0, y0, x1, y1]` — tight tile-local clipped pixel sub-rect in `[0..256]`
+ rect: [u32; 4],
+ /// `[has_tip_tex_u, has_paper_tex_u, use_blur_u, anti_alias_u]`
+ flags0: [u32; 4],
+ /// `[paper_mode_u, grain_mapping_mode_u, paper_invert_u, emphasize_density_u]`
+ flags1: [u32; 4],
+ /// `[is_color_tip_u, is_dual_tone_tip_u, tip_layer_count_u, track_cov_u]`
+ flags2: [u32; 4],
+ /// `[dual_enabled_i, dual_slot_i, dual_mode_i, mixing_mode_i]`
+ dual_info: [i32; 4],
+ /// `[step_norm, 0.0, 0.0, 0.0]` — spacing-normalized deposition factor (`1.0` at ref spacing 0.25)
+ step_info: [f32; 4],
+}
+
+#[repr(C)]
+#[derive(Debug, Clone, Copy, Pod, Zeroable)]
+struct CmixResolveUniforms {
+ /// `[TL, T, TR, L]` 3×3 neighbor slots in `cmix_cov`
+ n0: [i32; 4],
+ /// `[C, R, BL, B]` (`C` is the tile's own slot)
+ n1: [i32; 4],
+ /// `[BR, radius_px, alpha_lock_i, wet_active_i]`
+ n2: [i32; 4],
+ /// `[wet_edge, opacity_cap, alpha_power, value_power]`
+ params: [f32; 4],
}
fn build_bristle_pickup_wgsl() -> String {
@@ -148,13 +178,6 @@ fn build_bristle_pickup_wgsl() -> String {
r#"
{PIGMENT_WGSL}
-struct TileLookupEntry {{
- tx: i32,
- ty: i32,
- slot: i32,
- _pad: i32,
-}};
-
struct BristleSlot {{
color_load: vec4<f32>,
dirty_wet: vec4<f32>,
@@ -185,25 +208,25 @@ struct PickupUniforms {{
counts0: vec4<u32>,
counts1: vec4<u32>,
extra: vec4<f32>,
+ grid_info: vec4<i32>,
}};
@group(0) @binding(0) var<uniform> u: PickupUniforms;
@group(0) @binding(1) var color_pool: texture_2d_array<f32>;
@group(0) @binding(2) var ground_pool: texture_2d_array<f32>;
-@group(0) @binding(3) var<storage, read> tile_lookup: array<TileLookupEntry>;
+@group(0) @binding(3) var<storage, read> tile_grid: array<i32>;
@group(0) @binding(4) var<storage, read> capsules_in: array<RawCapsule>;
@group(0) @binding(5) var<storage, read_write> bristle_load: array<BristleSlot>;
@group(0) @binding(6) var<storage, read_write> capsules_out: array<ResolvedCapsule>;
+// O(1) dense bounding-box tile slot lookup (1 array load, ZERO O(T) linear scan!)
fn find_tile_slot(tx: i32, ty: i32) -> i32 {{
- let n = u.counts1.x;
- for (var i: u32 = 0u; i < n; i = i + 1u) {{
- let e = tile_lookup[i];
- if (e.tx == tx && e.ty == ty) {{
- return e.slot;
- }}
+ let gx = tx - u.grid_info.x;
+ let gy = ty - u.grid_info.y;
+ if (gx < 0 || gy < 0 || gx >= u.grid_info.z || gy >= u.grid_info.w) {{
+ return -1;
}}
- return -1;
+ return tile_grid[u32(gy * u.grid_info.z + gx)];
}}
fn div_floor_256(v: i32) -> i32 {{
@@ -263,14 +286,15 @@ fn mix_paint_color(c1: vec3<f32>, c2: vec3<f32>, t: f32) -> vec3<f32> {{
return lin_to_srgb(mix(srgb_to_lin(c1), srgb_to_lin(c2), clamp(t, 0.0, 1.0)));
}}
-@compute @workgroup_size(64, 1, 1)
+@compute @workgroup_size(128, 1, 1)
fn cs_update_bristle_load(@builtin(global_invocation_id) gid: vec3<u32>) {{
let tid = gid.x;
let is_spatial = (u.counts0.y != 0u);
+ let total_slots = max(u.counts1.x, 69u);
if (!is_spatial && tid != 0u) {{
return;
}}
- if (tid >= 64u) {{
+ if (tid >= total_slots) {{
return;
}}
@@ -284,81 +308,99 @@ fn cs_update_bristle_load(@builtin(global_invocation_id) gid: vec3<u32>) {{
let viscosity = clamp(u.paint1.y, 0.0, 1.0);
let charge_p = clamp(u.paint1.z, 0.0, 1.0);
let fg = u.fg_pigment.xyz;
+ let max_slot_f = f32(total_slots - 1u);
var slot = bristle_load[tid];
+ var prev_step_dist = -1e9;
+ var prev_step_pos = vec2<f32>(-1e9, -1e9);
for (var i: u32 = 0u; i < cap_count; i = i + 1u) {{
let cap = capsules_in[i];
- let b_idx = u32(clamp(cap.strand.x + 0.5, 0.0, 63.0));
+ let b_idx = u32(clamp(cap.strand.x + 0.5, 0.0, max_slot_f));
if (is_spatial && b_idx != tid) {{
continue;
}}
- let pressure = clamp(cap.geom.z, 0.02, 1.0);
- let ds = max(cap.motion.y, 0.25);
- let r = max(cap.geom.x, cap.geom.y);
- let canvas = sample_canvas_footprint(cap.p0_p1.x, cap.p0_p1.y, r);
-
var cur_rgb = slot.color_load.rgb;
var cur_load = clamp(slot.color_load.w, 0.0, 1.0);
var carry_a = clamp(slot.state_carry.x, 0.0, 1.0);
var has_canvas = slot.state_carry.y;
- // Pickup strength scaled by mixing mode, step distance, wetness, pressure, and canvas alpha.
- // Simultaneously feed fresh paint from the loaded belly according to amount_of_paint * cur_load
- // (except in pure Smear mode) so long strokes over wet ground converge to a rich physical mix
- // instead of decaying 100% into the canvas color.
- let step_scale = clamp(ds / 18.0, 0.14, 1.0);
- if (canvas.a > 0.015) {{
- var pickup_rate = 0.0;
- if (mode == 2u) {{
- // Smear: strong immediate canvas pickup, zero fresh fg
- pickup_rate = clamp(0.45 + wetness * 0.45 + (1.0 - stretch) * 0.25, 0.2, 0.92);
- if (has_canvas < 0.5) {{
- cur_rgb = canvas.rgb;
+ // When spatial_mixing == false, all strands emitted at the exact same stroke substep share
+ // the single unified reservoir — evaluate pickup & KM once per substep instead of 35x!
+ let same_nonspatial_substep = (!is_spatial)
+ && (i > 0u)
+ && (cap_count > 8u)
+ && (abs(cap.motion.x - prev_step_dist) <= 0.01)
+ && (length(cap.p0_p1.xy - prev_step_pos) <= max(u.extra.y * 1.6, 12.0));
+
+ if (!same_nonspatial_substep) {{
+ prev_step_dist = cap.motion.x;
+ prev_step_pos = cap.p0_p1.xy;
+
+ let pressure = clamp(cap.geom.z, 0.02, 1.0);
+ let ds = max(cap.motion.y, 0.25);
+ let r = max(cap.geom.x, cap.geom.y);
+ let canvas = sample_canvas_footprint(cap.p0_p1.x, cap.p0_p1.y, r);
+
+ let step_scale = clamp(ds / 18.0, 0.14, 1.0);
+ if (canvas.a > 0.015) {{
+ var pickup_rate = 0.0;
+ if (mode == 2u) {{
+ // Smear: strong immediate canvas pickup, zero fresh fg
+ pickup_rate = clamp(0.45 + wetness * 0.45 + (1.0 - stretch) * 0.25, 0.2, 0.92);
+ if (has_canvas < 0.5) {{
+ cur_rgb = canvas.rgb;
+ has_canvas = 1.0;
+ }} else {{
+ cur_rgb = mix_paint_color(cur_rgb, canvas.rgb, pickup_rate * canvas.a * step_scale);
+ }}
+ carry_a = max(carry_a, canvas.a * (0.65 + 0.35 * stretch));
+ }} else if (mode == 1u) {{
+ // Running Color: fluid high-pickup wet bleeding
+ pickup_rate = clamp((wetness * 0.65 + (1.0 - amount) * 0.45) * (0.45 + 0.55 * pressure), 0.1, 0.88);
+ cur_rgb = mix_paint_color(cur_rgb, canvas.rgb, pickup_rate * canvas.a * step_scale * 0.82);
+ carry_a = max(carry_a, canvas.a * (0.5 + 0.45 * stretch));
+ has_canvas = 1.0;
+ }} else if (mode == 3u) {{
+ // Impasto Mix: viscous heavy-body oil swirl
+ pickup_rate = clamp((wetness * 0.52 + (1.0 - amount) * 0.38) * (1.0 - viscosity * 0.28) * (0.4 + 0.6 * pressure), 0.08, 0.82);
+ cur_rgb = mix_paint_color(cur_rgb, canvas.rgb, pickup_rate * canvas.a * step_scale * 0.80);
+ carry_a = max(carry_a, canvas.a * (0.55 + 0.4 * stretch));
has_canvas = 1.0;
}} else {{
- cur_rgb = mix_paint_color(cur_rgb, canvas.rgb, pickup_rate * canvas.a * step_scale);
+ // Blend: balanced painterly mixing
+ pickup_rate = clamp((wetness * 0.48 + (1.0 - amount) * 0.42) * (0.45 + 0.55 * pressure), 0.05, 0.80);
+ cur_rgb = mix_paint_color(cur_rgb, canvas.rgb, pickup_rate * canvas.a * step_scale * 0.80);
+ carry_a = max(carry_a, canvas.a * (0.45 + 0.45 * stretch));
+ has_canvas = 1.0;
+ }}
+ // Fresh pigment recharge from the loaded brush belly during wet mixing
+ if (mode != 2u && cur_load > 0.02 && amount > 0.01) {{
+ let fg_feed = clamp(amount * cur_load * step_scale * 0.88, 0.0, 0.55);
+ cur_rgb = mix_paint_color(cur_rgb, fg, fg_feed);
}}
- carry_a = max(carry_a, canvas.a * (0.65 + 0.35 * stretch));
- }} else if (mode == 1u) {{
- // Running Color: fluid high-pickup wet bleeding
- pickup_rate = clamp((wetness * 0.65 + (1.0 - amount) * 0.45) * (0.45 + 0.55 * pressure), 0.1, 0.88);
- cur_rgb = mix_paint_color(cur_rgb, canvas.rgb, pickup_rate * canvas.a * step_scale * 0.82);
- carry_a = max(carry_a, canvas.a * (0.5 + 0.45 * stretch));
- has_canvas = 1.0;
- }} else if (mode == 3u) {{
- // Impasto Mix: viscous heavy-body oil swirl
- pickup_rate = clamp((wetness * 0.52 + (1.0 - amount) * 0.38) * (1.0 - viscosity * 0.28) * (0.4 + 0.6 * pressure), 0.08, 0.82);
- cur_rgb = mix_paint_color(cur_rgb, canvas.rgb, pickup_rate * canvas.a * step_scale * 0.80);
- carry_a = max(carry_a, canvas.a * (0.55 + 0.4 * stretch));
- has_canvas = 1.0;
}} else {{
- // Blend: balanced painterly mixing
- pickup_rate = clamp((wetness * 0.48 + (1.0 - amount) * 0.42) * (0.45 + 0.55 * pressure), 0.05, 0.80);
- cur_rgb = mix_paint_color(cur_rgb, canvas.rgb, pickup_rate * canvas.a * step_scale * 0.80);
- carry_a = max(carry_a, canvas.a * (0.45 + 0.45 * stretch));
- has_canvas = 1.0;
- }}
- // Fresh pigment recharge from the loaded brush belly during wet mixing
- if (mode != 2u && cur_load > 0.02 && amount > 0.01) {{
- let fg_feed = clamp(amount * cur_load * step_scale * 0.88, 0.0, 0.55);
- cur_rgb = mix_paint_color(cur_rgb, fg, fg_feed);
- }}
- }} else {{
- // Over empty canvas: carry decays smoothly according to color_stretch
- let decay = clamp(ds / max(18.0 + stretch * 180.0, 12.0), 0.005, 0.35);
- carry_a = max(0.0, carry_a * (1.0 - decay));
- // Loaded brushes slowly pull back toward fresh fg paint along empty strokes if amount is high
- if (mode != 2u && cur_load > 0.08 && amount > 0.2) {{
- let recharge = clamp(amount * cur_load * step_scale * 0.06, 0.0, 0.08);
- cur_rgb = mix_paint_color(cur_rgb, fg, recharge);
+ // Over empty canvas: carry decays smoothly according to color_stretch
+ let decay = clamp(ds / max(18.0 + stretch * 180.0, 12.0), 0.005, 0.35);
+ carry_a = max(0.0, carry_a * (1.0 - decay));
+ // Loaded brushes slowly pull back toward fresh fg paint along empty strokes if amount is high
+ if (mode != 2u && cur_load > 0.08 && amount > 0.2) {{
+ let recharge = clamp(amount * cur_load * step_scale * 0.06, 0.0, 0.08);
+ cur_rgb = mix_paint_color(cur_rgb, fg, recharge);
+ }}
}}
- }}
- // Paint load depletion along stroke distance (reduced by chargePerPressure when pressing hard!)
- let dep_step = ds * depletion * 0.0018 * (1.0 - charge_p * pressure * 0.45);
- cur_load = max(0.0, cur_load - dep_step);
+ // Paint load depletion along stroke distance (reduced by chargePerPressure when pressing hard!)
+ let dep_step = ds * depletion * 0.0018 * (1.0 - charge_p * pressure * 0.45);
+ cur_load = max(0.0, cur_load - dep_step);
+
+ slot.color_load = vec4<f32>(cur_rgb, cur_load);
+ slot.dirty_wet = vec4<f32>(cur_rgb, wetness);
+ slot.state_carry = vec4<f32>(carry_a, has_canvas, fg.r, fg.g);
+ slot.fg_meta.x = fg.b;
+ slot.fg_meta.w = 1.0;
+ }}
// Compute effective deposit opacity for this capsule
var dep_a = cap.geom.w * density;
@@ -370,12 +412,6 @@ fn cs_update_bristle_load(@builtin(global_invocation_id) gid: vec3<u32>) {{
dep_a = dep_a * load_vis * clamp(0.25 + amount * 0.75 + carry_a * 0.45, 0.0, 1.0);
}}
- slot.color_load = vec4<f32>(cur_rgb, cur_load);
- slot.dirty_wet = vec4<f32>(cur_rgb, wetness);
- slot.state_carry = vec4<f32>(carry_a, has_canvas, fg.r, fg.g);
- slot.fg_meta.x = fg.b;
- slot.fg_meta.w = 1.0;
-
var out_cap: ResolvedCapsule;
out_cap.p0_p1 = cap.p0_p1;
out_cap.geom = cap.geom;
@@ -415,6 +451,8 @@ struct RasterTileUniforms {{
flags1: vec4<u32>,
extra: vec4<f32>,
sel_info: vec4<f32>,
+ rect: vec4<u32>,
+ bin_info: vec4<u32>,
}};
@group(0) @binding(0) var<uniform> u: RasterTileUniforms;
@@ -427,6 +465,9 @@ struct RasterTileUniforms {{
@group(0) @binding(7) var dst_color: texture_storage_2d<rgba16float, write>;
@group(0) @binding(8) var dst_height: texture_storage_2d<r32float, write>;
@group(0) @binding(9) var sel_mask_atlas: texture_2d_array<f32>;
+@group(0) @binding(10) var<storage, read> binned_indices: array<u32>;
+@group(0) @binding(11) var cov_pool: texture_2d_array<f32>;
+@group(0) @binding(12) var dst_cov: texture_storage_2d<rgba16float, write>;
fn sample_surface_height(doc_px: vec2<f32>, stroke_dist: f32, tangent_ang: f32) -> f32 {{
if (u.flags1.x == 0u) {{
@@ -469,17 +510,22 @@ fn sample_surface_height(doc_px: vec2<f32>, stroke_dist: f32, tangent_ang: f32)
return clamp(h, 0.0, 1.0);
}}
-@compute @workgroup_size(16, 16, 1)
+@compute @workgroup_size(8, 8, 1)
fn cs_raster_natural_paint(@builtin(global_invocation_id) gid: vec3<u32>) {{
- if (gid.x >= 256u || gid.y >= 256u) {{
+ let lx = u.rect.x + gid.x;
+ let ly = u.rect.y + gid.y;
+ if (lx >= u.rect.z || ly >= u.rect.w) {{
return;
}}
- let lp = vec2<i32>(i32(gid.x), i32(gid.y));
+ let lp = vec2<i32>(i32(lx), i32(ly));
let slot = i32(u.tile_info.z + 0.5);
var cur_col = textureLoad(color_pool, lp, slot, 0);
var cur_h = max(textureLoad(height_pool, lp, slot, 0).r, 0.0);
+ let track_cov = (u.bin_info.z != 0u);
+ var cur_cov = select(0.0, textureLoad(cov_pool, lp, slot, 0).r, track_cov);
- let cap_count = u32(u.tile_info.w + 0.5);
+ let bin_start = u.bin_info.x;
+ let bin_count = u.bin_info.y;
var sel_a = 1.0;
let sel_slot = i32(round(u.sel_info.x));
if (sel_slot >= 0) {{
@@ -487,17 +533,22 @@ fn cs_raster_natural_paint(@builtin(global_invocation_id) gid: vec3<u32>) {{
}} else if (sel_slot == -1) {{
sel_a = u.sel_info.y;
}}
- if (cap_count == 0u || sel_a <= 0.001) {{
+ if (bin_count == 0u || sel_a <= 0.001) {{
textureStore(dst_color, lp, cur_col);
textureStore(dst_height, lp, vec4<f32>(cur_h, 0.0, 0.0, 0.0));
+ if (track_cov) {{
+ textureStore(dst_cov, lp, vec4<f32>(cur_cov, 0.0, 0.0, 1.0));
+ }}
return;
}}
- let doc_pos = vec2<f32>(u.tile_info.x + f32(gid.x) + 0.5, u.tile_info.y + f32(gid.y) + 0.5);
+ let doc_pos = vec2<f32>(u.tile_info.x + f32(lx) + 0.5, u.tile_info.y + f32(ly) + 0.5);
let dry_brush = clamp(u.surface0.x, 0.0, 1.0);
let granulation = clamp(u.surface0.y, 0.0, 1.0);
let pen_curve = clamp(u.surface0.z, 0.25, 3.0);
+ let pen_is_linear = abs(pen_curve - 1.0) < 0.005;
let grain_strength = clamp(u.surface0.w, 0.0, 1.0);
+ let need_surf = (dry_brush > 0.005) || (granulation > 0.005) || (grain_strength > 0.005);
let impasto_enabled = (u.flags0.y != 0u);
let impasto_depth = clamp(u.impasto0.x, 0.0, 2.5);
@@ -509,27 +560,29 @@ fn cs_raster_natural_paint(@builtin(global_invocation_id) gid: vec3<u32>) {{
let use_blur = (u.flags1.w != 0u) && (u.extra.x > 0.01);
let blur_str = clamp(u.extra.x, 0.0, 1.0);
let pigment_str = clamp(u.extra.y, 0.0, 1.0);
-
- // Precompute 3x3 blurred neighborhood once if CSP useBlur is active
- var blur_col = cur_col;
- if (use_blur) {{
- var sum_rgb = vec3<f32>(0.0);
- var sum_a = 0.0;
- for (var oy: i32 = -1; oy <= 1; oy = oy + 1) {{
- for (var ox: i32 = -1; ox <= 1; ox = ox + 1) {{
- let sp = clamp(lp + vec2<i32>(ox * 2, oy * 2), vec2<i32>(0), vec2<i32>(255));
- let c = textureLoad(color_pool, sp, slot, 0);
- sum_rgb = sum_rgb + c.rgb * c.a;
- sum_a = sum_a + c.a;
- }}
- }}
- if (sum_a > 1e-4) {{
- blur_col = vec4<f32>(sum_rgb / sum_a, sum_a / 9.0);
- }}
- }}
-
- for (var i: u32 = 0u; i < cap_count; i = i + 1u) {{
- let cap = capsules[i];
+ let soft_edge = mix(0.55, 0.14, hardness);
+ let soft_inner = max(0.0, 1.0 - soft_edge);
+
+ // Lazy ONCE-per-pixel surface heightfield cache (ZERO redundant cos/sin/textureLoad per capsule!)
+ var has_surf_h = false;
+ var surf_h = 0.5;
+ var surf_tooth = 1.0;
+
+ // Linear premultiplied accumulator for all overlapping capsules at this pixel,
+ // allowing ONE single perceptual/Kubelka-Munk composite against `cur_col` after the loop!
+ var acc_premul = vec3<f32>(0.0);
+ var acc_a = 0.0;
+ var max_blur_f = 0.0;
+
+ // Accumulated 3D impasto sculpt state
+ var imp_hit = false;
+ var imp_max_target = 0.0;
+ var imp_blend_acc = 0.0;
+ var imp_build_acc = 0.0;
+ var imp_smear_cov = 0.0;
+
+ for (var bi: u32 = 0u; bi < bin_count; bi = bi + 1u) {{
+ let cap = capsules[binned_indices[bin_start + bi]];
let a = cap.p0_p1.xy;
let b = cap.p0_p1.zw;
let r_max = max(cap.geom.x, cap.geom.y) + 1.5;
@@ -547,15 +600,16 @@ fn cs_raster_natural_paint(@builtin(global_invocation_id) gid: vec3<u32>) {{
t = clamp(dot(doc_pos - a, ab) / ab2, 0.0, 1.0);
}}
let closest = a + ab * t;
- let d = length(doc_pos - closest);
+ let diff = doc_pos - closest;
let r = max(mix(cap.geom.x, cap.geom.y, t), 0.5);
- if (d >= r) {{
+ let d2 = dot(diff, diff);
+ if (d2 >= r * r) {{
continue;
}}
+ let d = sqrt(d2);
let lat = d / r; // 0 at strand core, 1 at outer edge
- let soft_edge = mix(0.55, 0.14, hardness);
- var cov = 1.0 - smoothstep(max(0.0, 1.0 - soft_edge), 1.0, lat);
+ var cov = 1.0 - smoothstep(soft_inner, 1.0, lat);
let flags_bits = u32(cap.strand.w + 0.5);
let is_underbed = ((flags_bits & 1u) != 0u);
@@ -583,17 +637,20 @@ fn cs_raster_natural_paint(@builtin(global_invocation_id) gid: vec3<u32>) {{
continue;
}}
- // Surface heightfield evaluation for dry-brush valley skipping, paper grain & granulation
+ // Evaluate surface heightfield AT MOST ONCE per hit pixel
let pressure = clamp(cap.geom.z, 0.02, 1.0);
let load = clamp(cap.resolved_state.y, 0.0, 1.0);
- var surf_h = 0.5;
- if (dry_brush > 0.005 || granulation > 0.005 || grain_strength > 0.005) {{
+ if (need_surf && !has_surf_h) {{
surf_h = sample_surface_height(doc_pos, cap.motion.x, cap.motion.w);
+ if (grain_strength > 0.005) {{
+ surf_tooth = mix(1.0, clamp(0.18 + surf_h * 0.95, 0.0, 1.0), grain_strength);
+ }}
+ has_surf_h = true;
}}
if (dry_brush > 0.005) {{
- // High pressure + heavy load penetrates deeper into valleys; light/dry brush catches peaks only!
- let penetration = clamp(pow(pressure, pen_curve) * (0.30 + 0.70 * load), 0.0, 1.0);
+ let p_pow = select(pow(pressure, pen_curve), pressure, pen_is_linear);
+ let penetration = clamp(p_pow * (0.30 + 0.70 * load), 0.0, 1.0);
let valley_thr = clamp(dry_brush * (1.0 - penetration * 0.72), 0.0, 0.96);
let contact = smoothstep(valley_thr - 0.08, valley_thr + 0.14, surf_h);
cov = cov * contact;
@@ -602,44 +659,33 @@ fn cs_raster_natural_paint(@builtin(global_invocation_id) gid: vec3<u32>) {{
}}
}}
- if (grain_strength > 0.005) {{
- let tooth = mix(1.0, clamp(0.18 + surf_h * 0.95, 0.0, 1.0), grain_strength);
- cov = cov * tooth;
- }}
- cov = cov * sel_a;
+ cov = cov * surf_tooth * sel_a;
var paint_rgb = cap.resolved_rgba.rgb;
var dep_a = clamp(cap.resolved_rgba.a * cov, 0.0, 1.0);
if (granulation > 0.005) {{
- // Watercolor pigment settles & concentrates inside paper valleys (low surf_h)
let valley = 1.0 - surf_h;
- let gran_boost = clamp(1.0 + granulation * (valley * 1.55 - 0.42), 0.22, 1.85);
+ let gran_boost = clamp(1.0 + granulation * (valley * 1.75 - 0.45), 0.18, 2.0);
dep_a = clamp(dep_a * gran_boost, 0.0, 1.0);
- // Slight flocculation darkening in deepest pockets
paint_rgb = clamp(paint_rgb * (1.0 - granulation * valley * 0.14), vec3<f32>(0.0), vec3<f32>(1.0));
}}
- // Optional GPU blur mixing pass (CSP useBlur)
if (use_blur && dep_a > 1e-4) {{
- let bf = clamp(blur_str * cov * 0.55, 0.0, 0.85);
- cur_col = mix(cur_col, blur_col, bf);
+ max_blur_f = max(max_blur_f, clamp(blur_str * cov * 0.55, 0.0, 0.85));
}}
if (dep_a > 1e-4) {{
- let next_col = composite_pigment_over(cur_col, vec4<f32>(paint_rgb, dep_a), pigment_str);
- if (alpha_lock) {{
- cur_col = vec4<f32>(next_col.rgb, base_alpha_lock);
- }} else {{
- cur_col = next_col;
- }}
+ let c_lin = srgb_to_lin_fast(paint_rgb);
+ let inv_d = 1.0 - dep_a;
+ acc_premul = c_lin * dep_a + acc_premul * inv_d;
+ acc_a = dep_a + acc_a * inv_d;
}}
- // Persistent 3D Impasto Heightfield Accumulation in the EXACT same compute pass!
+ // Accumulate 3D Impasto Heightfield target in the same pass
if (impasto_enabled && impasto_depth > 0.005) {{
let edge_w = cap.strand.y;
let groove_s = cap.strand.z;
- // Macro arched cross-section across brush width (tallest at center, sloped flanks) + crisp bristle grooves + outer bead
let macro_arch = clamp(1.0 - edge_w * edge_w * 0.82, 0.14, 1.0);
let crown = (1.0 - lat * lat) * (0.55 + 0.45 * bristle_relief * groove_s);
let trough = smoothstep(0.55, 0.92, lat) * (1.0 - smoothstep(0.92, 1.0, lat)) * bristle_relief * 0.22;
@@ -655,19 +701,52 @@ fn cs_raster_natural_paint(@builtin(global_invocation_id) gid: vec3<u32>) {{
* (0.30 + 0.70 * load)
* (0.45 + 0.55 * pressure),
);
+ imp_hit = true;
+ imp_max_target = max(imp_max_target, target_h);
+ let blend_h = clamp(cov * underbed_scale * 0.42, 0.0, 0.72);
+ imp_blend_acc = 1.0 - (1.0 - imp_blend_acc) * (1.0 - blend_h);
+ imp_build_acc = imp_build_acc + target_h * cov * underbed_scale * 0.025;
+ imp_smear_cov = 1.0 - (1.0 - imp_smear_cov) * (1.0 - cov * 0.45);
+ }}
+ }}
- let mode = u.flags0.w;
- if (mode == 2u) {{
- // Smear plows & slightly softens existing wet impasto ridges
- cur_h = mix(cur_h, max(cur_h * 0.88, target_h * 0.55), cov * 0.45);
- }} else {{
- let max_h = 3.0 * impasto_depth;
- let blend_h = clamp(cov * underbed_scale * 0.42, 0.0, 0.72);
- // Smoothly sculpt toward the arched target height (preserving sloped flanks without mesa clipping)
- let sculpted = mix(cur_h, max(cur_h, target_h), blend_h);
- cur_h = clamp(sculpted + target_h * cov * underbed_scale * 0.025, 0.0, max_h);
+ // Perform optional 3x3 blur + ONE perceptual/subtractive Kubelka-Munk composite per hit pixel!
+ if (acc_a > 1e-4) {{
+ if (use_blur && max_blur_f > 1e-4) {{
+ var sum_rgb = vec3<f32>(0.0);
+ var sum_a = 0.0;
+ for (var oy: i32 = -1; oy <= 1; oy = oy + 1) {{
+ for (var ox: i32 = -1; ox <= 1; ox = ox + 1) {{
+ let sp = clamp(lp + vec2<i32>(ox * 2, oy * 2), vec2<i32>(0), vec2<i32>(255));
+ let c = textureLoad(color_pool, sp, slot, 0);
+ sum_rgb = sum_rgb + c.rgb * c.a;
+ sum_a = sum_a + c.a;
+ }}
+ }}
+ if (sum_a > 1e-4) {{
+ let blur_col = vec4<f32>(sum_rgb / sum_a, sum_a / 9.0);
+ cur_col = mix(cur_col, blur_col, max_blur_f);
}}
}}
+
+ let eff_a = clamp(acc_a, 0.0, 1.0);
+ let batch_rgb = lin_to_srgb_fast(clamp(acc_premul / max(acc_a, 1e-5), vec3<f32>(0.0), vec3<f32>(1.0)));
+ let next_col = composite_pigment_over(cur_col, vec4<f32>(batch_rgb, eff_a), pigment_str);
+ cur_col = select(next_col, vec4<f32>(next_col.rgb, base_alpha_lock), alpha_lock);
+ if (track_cov) {{
+ cur_cov = clamp(cur_cov + eff_a * (1.0 - cur_cov), 0.0, 1.0);
+ }}
+ }}
+
+ if (imp_hit) {{
+ let mode = u.flags0.w;
+ if (mode == 2u) {{
+ cur_h = mix(cur_h, max(cur_h * 0.88, imp_max_target * 0.55), imp_smear_cov);
+ }} else {{
+ let max_h = 3.0 * impasto_depth;
+ let sculpted = mix(cur_h, max(cur_h, imp_max_target), clamp(imp_blend_acc, 0.0, 0.88));
+ cur_h = clamp(sculpted + imp_build_acc, 0.0, max_h);
+ }}
}}
if (u.extra.z < 0.5) {{
@@ -675,6 +754,9 @@ fn cs_raster_natural_paint(@builtin(global_invocation_id) gid: vec3<u32>) {{
}}
textureStore(dst_color, lp, cur_col);
textureStore(dst_height, lp, vec4<f32>(cur_h, 0.0, 0.0, 0.0));
+ if (track_cov) {{
+ textureStore(dst_cov, lp, vec4<f32>(cur_cov, 0.0, 0.0, 1.0));
+ }}
}}
"#
)
@@ -685,13 +767,6 @@ fn build_color_mix_pickup_wgsl() -> String {
r#"
{PIGMENT_WGSL}
-struct TileLookupEntry {{
- tx: i32,
- ty: i32,
- slot: i32,
- _pad: i32,
-}};
-
struct SpatialTipCell {{
rgba: vec4<f32>,
state: vec4<f32>,
@@ -704,23 +779,23 @@ struct ColorMixPickupUniforms {{
params1: vec4<f32>,
flags0: vec4<u32>,
flags1: vec4<u32>,
+ grid_info: vec4<i32>,
}};
@group(0) @binding(0) var<uniform> u: ColorMixPickupUniforms;
@group(0) @binding(1) var color_pool: texture_2d_array<f32>;
@group(0) @binding(2) var ground_pool: texture_2d_array<f32>;
-@group(0) @binding(3) var<storage, read> tile_lookup: array<TileLookupEntry>;
+@group(0) @binding(3) var<storage, read> tile_grid: array<i32>;
@group(0) @binding(4) var<storage, read_write> tip_cells: array<SpatialTipCell>;
+// O(1) dense bounding-box tile slot lookup (1 array read, zero linear scan!)
fn find_tile_slot(tx: i32, ty: i32) -> i32 {{
- let n = u.flags0.z;
- for (var i: u32 = 0u; i < n; i = i + 1u) {{
- let e = tile_lookup[i];
- if (e.tx == tx && e.ty == ty) {{
- return e.slot;
- }}
+ let gx = tx - u.grid_info.x;
+ let gy = ty - u.grid_info.y;
+ if (gx < 0 || gy < 0 || gx >= u.grid_info.z || gy >= u.grid_info.w) {{
+ return -1;
}}
- return -1;
+ return tile_grid[u32(gy * u.grid_info.z + gx)];
}}
fn div_floor_256(v: i32) -> i32 {{
@@ -779,6 +854,9 @@ fn cs_color_mix_pickup(@builtin(global_invocation_id) gid: vec3<u32>) {{
let p_str = clamp(u.fg_pigment.w, 0.0, 1.0);
let wetness = clamp(u.params1.x, 0.0, 1.0);
let pressure = clamp(u.params1.z, 0.02, 1.0);
+ // Step-distance normalization calibrated at reference spacing = 0.25 so spacing 0.04 and 0.25
+ // produce identical lush mixing without over-compounding / muddying!
+ let step_norm = clamp(u.params1.w, 0.08, 2.5);
var cell = tip_cells[idx];
var cur_rgb = cell.rgba.rgb;
@@ -786,29 +864,33 @@ fn cs_color_mix_pickup(@builtin(global_invocation_id) gid: vec3<u32>) {{
var has_p = cell.state.x;
if (canvas.a > 0.015) {{
- let pick = select(
+ let base_pick = select(
clamp((1.0 - amount) * 0.55 + wetness * 0.35, 0.08, 0.85),
clamp(0.55 + (1.0 - stretch) * 0.35, 0.25, 0.92),
mode == 2u
);
+ let raw_pick = clamp(base_pick * canvas.a, 0.0, 0.96);
+ let eff_pick = clamp(1.0 - pow(1.0 - raw_pick, step_norm), 0.0, 0.96);
if (has_p < 0.5 && mode == 2u) {{
cur_rgb = canvas.rgb;
}} else if (p_str > 0.01) {{
- cur_rgb = mix_pigments_srgb(cur_rgb, canvas.rgb, pick * canvas.a, p_str);
+ cur_rgb = mix_pigments_srgb(cur_rgb, canvas.rgb, eff_pick, p_str);
}} else if (u.flags1.x != 0u) {{
- cur_rgb = mix_oklab_srgb(cur_rgb, canvas.rgb, pick * canvas.a);
+ cur_rgb = mix_oklab_srgb(cur_rgb, canvas.rgb, eff_pick);
}} else {{
- cur_rgb = lin_to_srgb(mix(srgb_to_lin(cur_rgb), srgb_to_lin(canvas.rgb), pick * canvas.a));
+ cur_rgb = lin_to_srgb(mix(srgb_to_lin(cur_rgb), srgb_to_lin(canvas.rgb), eff_pick));
}}
cur_a = max(cur_a, canvas.a * (0.45 + 0.55 * stretch));
has_p = 1.0;
}} else {{
- cur_a = cur_a * clamp(0.6 + 0.38 * stretch, 0.0, 0.98);
+ let decay_ref = clamp(0.6 + 0.38 * stretch, 0.0, 0.98);
+ cur_a = cur_a * pow(decay_ref, step_norm);
}}
// Blend in fresh foreground paint according to amountOfPaint (zero for pure Smear!)
if (mode != 2u && amount > 0.005) {{
- let fresh_w = clamp(amount * (0.28 + 0.45 * pressure), 0.0, 0.95);
+ let base_fresh = clamp(amount * (0.28 + 0.45 * pressure), 0.0, 0.95);
+ let fresh_w = clamp(1.0 - pow(1.0 - base_fresh, step_norm), 0.0, 0.95);
if (p_str > 0.01) {{
cur_rgb = mix_pigments_srgb(cur_rgb, fg, fresh_w, p_str);
}} else if (u.flags1.x != 0u) {{
@@ -832,6 +914,10 @@ fn build_color_mix_stamp_wgsl() -> String {
r#"
{PIGMENT_WGSL}
+{PAPER_GRAIN_WGSL}
+
+{DUAL_BRUSH_COMBINE_WGSL}
+
struct SpatialTipCell {{
rgba: vec4<f32>,
state: vec4<f32>,
@@ -843,17 +929,30 @@ struct ColorMixTileUniforms {{
geom: vec4<f32>,
fx0: vec4<f32>,
fx1: vec4<f32>,
- flags: vec4<u32>,
- sel_info: vec4<f32>,
+ paper0: vec4<f32>,
+ paper1: vec4<f32>,
+ bg_amount: vec4<f32>,
+ flip_sel: vec4<f32>,
+ rect: vec4<u32>,
+ flags0: vec4<u32>,
+ flags1: vec4<u32>,
+ flags2: vec4<u32>,
+ dual_info: vec4<i32>,
+ step_info: vec4<f32>,
}};
@group(0) @binding(0) var<uniform> u: ColorMixTileUniforms;
@group(0) @binding(1) var color_pool: texture_2d_array<f32>;
@group(0) @binding(2) var tip_array: texture_2d_array<f32>;
-@group(0) @binding(3) var paper_tex: texture_2d<f32>;
-@group(0) @binding(4) var<storage, read> tip_cells: array<SpatialTipCell>;
-@group(0) @binding(5) var dst_color: texture_storage_2d<rgba16float, write>;
-@group(0) @binding(6) var sel_mask_atlas: texture_2d_array<f32>;
+@group(0) @binding(3) var tip_sampler: sampler;
+@group(0) @binding(4) var paper_tex: texture_2d<f32>;
+@group(0) @binding(5) var paper_sampler: sampler;
+@group(0) @binding(6) var<storage, read> tip_cells: array<SpatialTipCell>;
+@group(0) @binding(7) var dst_color: texture_storage_2d<rgba16float, write>;
+@group(0) @binding(8) var sel_mask_atlas: texture_2d_array<f32>;
+@group(0) @binding(9) var dual_pool: texture_2d_array<f32>;
+@group(0) @binding(10) var cov_pool: texture_2d_array<f32>;
+@group(0) @binding(11) var dst_cov: texture_storage_2d<rgba16float, write>;
fn sample_tip_grid_bilinear(uv: vec2<f32>) -> vec4<f32> {{
let gx = clamp(uv.x * 16.0 - 0.5, 0.0, 15.0);
@@ -873,142 +972,449 @@ fn sample_tip_grid_bilinear(uv: vec2<f32>) -> vec4<f32> {{
return mix(a, b, fy);
}}
-@compute @workgroup_size(16, 16, 1)
+@compute @workgroup_size(8, 8, 1)
fn cs_color_mix_stamp(@builtin(global_invocation_id) gid: vec3<u32>) {{
- if (gid.x >= 256u || gid.y >= 256u) {{
+ let lx = u.rect.x + gid.x;
+ let ly = u.rect.y + gid.y;
+ if (lx >= u.rect.z || ly >= u.rect.w) {{
return;
}}
- let lp = vec2<i32>(i32(gid.x), i32(gid.y));
+ let lp = vec2<i32>(i32(lx), i32(ly));
let slot = i32(u.tile_info.z + 0.5);
var cur_col = textureLoad(color_pool, lp, slot, 0);
+ let track_cov = (u.flags2.w != 0u);
+ var cur_cov = select(0.0, textureLoad(cov_pool, lp, slot, 0).r, track_cov);
var sel_a = 1.0;
- let sel_slot = i32(round(u.sel_info.x));
+ let sel_slot = i32(round(u.flip_sel.z));
if (sel_slot >= 0) {{
sel_a = textureLoad(sel_mask_atlas, lp, sel_slot, 0).r;
}} else if (sel_slot == -1) {{
- sel_a = u.sel_info.y;
- }}
- if (sel_a <= 0.001) {{
- textureStore(dst_color, lp, cur_col);
- return;
+ sel_a = u.flip_sel.w;
}}
- let doc_pos = vec2<f32>(u.tile_info.x + f32(gid.x) + 0.5, u.tile_info.y + f32(gid.y) + 0.5);
- let rel = doc_pos - u.stamp_pos.xy;
- let ang = u.geom.x;
- let ca = cos(-ang);
- let sa = sin(-ang);
- let local = vec2<f32>(rel.x * ca - rel.y * sa, rel.x * sa + rel.y * ca);
- let norm = vec2<f32>(local.x / max(u.stamp_pos.z, 0.5), local.y / max(u.stamp_pos.w, 0.5));
- let dist = length(norm);
- if (dist >= 1.0) {{
- textureStore(dst_color, lp, cur_col);
- return;
- }}
+ if (sel_a > 0.001) {{
+ let doc_pos = vec2<f32>(u.tile_info.x + f32(lx) + 0.5, u.tile_info.y + f32(ly) + 0.5);
+ let rel = doc_pos - u.stamp_pos.xy;
+ let ang = u.geom.x;
+ let ca = cos(-ang);
+ let sa = sin(-ang);
+ let local = vec2<f32>(rel.x * ca - rel.y * sa, rel.x * sa + rel.y * ca);
+ let norm = vec2<f32>(local.x / max(u.stamp_pos.z, 0.5), local.y / max(u.stamp_pos.w, 0.5));
+ let has_tip = (u.flags0.x != 0u);
+ let dist = length(norm);
+ let aa_level = u.flags0.w;
+ let min_half = max(0.35, min(u.stamp_pos.z, u.stamp_pos.w));
+ let aa_pad = select(1.5 / min_half, 0.0, aa_level == 0u);
+ let inside = select(
+ dist < 1.0 + aa_pad,
+ abs(norm.x) <= 1.0 && abs(norm.y) <= 1.0,
+ has_tip
+ );
- let tip_uv = norm * 0.5 + vec2<f32>(0.5);
- var mask_a = 1.0;
- if (u.flags.x != 0u) {{
- let tdims = vec2<f32>(textureDimensions(tip_array, 0));
- let tc = vec2<i32>(clamp(tip_uv * tdims, vec2<f32>(0.0), tdims - vec2<f32>(1.0)));
- mask_a = textureLoad(tip_array, tc, i32(u.fx1.y + 0.5), 0).a;
- }} else {{
- let hardness = clamp(u.geom.y, 0.0, 1.0);
- let inner = hardness * 0.88;
- mask_a = 1.0 - smoothstep(inner, 1.0, dist);
- }}
+ if (inside) {{
+ let grid_uv = clamp(norm * 0.5 + vec2<f32>(0.5), vec2<f32>(0.0), vec2<f32>(1.0));
+ let tip_uv = vec2<f32>(
+ norm.x * u.flip_sel.x * 0.5 + 0.5,
+ norm.y * u.flip_sel.y * 0.5 + 0.5,
+ );
- if (u.flags.y != 0u && u.fx0.z > 0.005) {{
- let pdims = vec2<f32>(textureDimensions(paper_tex, 0));
- let sc = max(u.fx0.w, 0.05);
- let rc = cos(u.fx1.x);
- let rs = sin(u.fx1.x);
- let rp = vec2<f32>(doc_pos.x * rc - doc_pos.y * rs, doc_pos.x * rs + doc_pos.y * rc) / sc;
- let puv = fract(rp / max(pdims, vec2<f32>(1.0)));
- let ptc = vec2<i32>(clamp(puv * pdims, vec2<f32>(0.0), pdims - vec2<f32>(1.0)));
- let g = textureLoad(paper_tex, ptc, 0).r;
- mask_a = mask_a * mix(1.0, g, clamp(u.fx0.z, 0.0, 1.0));
- }}
+ var mask_a = 1.0;
+ var tip_tex_rgb = vec3<f32>(1.0);
+ if (has_tip) {{
+ let max_layer = max(1u, u.flags2.z) - 1u;
+ let layer_i = i32(clamp(u32(round(u.fx1.y)), 0u, max_layer));
+ let tex = textureSampleLevel(tip_array, tip_sampler, tip_uv, layer_i, 0.0);
+ mask_a = tex.a;
+ tip_tex_rgb = tex.rgb;
+ if (aa_level == 0u) {{
+ mask_a = step(0.5, mask_a);
+ }} else if (aa_level == 1u) {{
+ mask_a = smoothstep(0.28, 0.72, mask_a);
+ }}
+ }} else {{
+ let hardness = clamp(u.geom.y, 0.0, 1.0);
+ if (aa_level == 0u) {{
+ mask_a = select(0.0, 1.0, dist <= 1.0);
+ }} else {{
+ let aa_width_px = select(select(0.85, 1.35, aa_level == 2u), 2.1, aa_level >= 3u);
+ let aa_unit = aa_width_px / min_half;
+ let inner = min(1.0 - aa_unit, hardness * 0.92);
+ if (hardness >= 0.98) {{
+ mask_a = 1.0 - smoothstep(max(0.0, 1.0 - aa_unit), 1.0 + aa_unit * 0.35, dist);
+ }} else {{
+ let edge_falloff = 1.0 - smoothstep(max(0.0, inner), 1.0 + aa_unit * 0.25, dist);
+ let softness = 1.0 - hardness;
+ mask_a = edge_falloff * mix(1.0, edge_falloff, softness * 0.65);
+ }}
+ }}
+ }}
- mask_a = mask_a * sel_a;
- if (mask_a <= 1e-4) {{
- textureStore(dst_color, lp, cur_col);
- return;
- }}
+ // All 9 CSP Paper Texture Modes + all 4 GrainMappingModes + brightness/contrast/invert/offset
+ if (u.flags0.y != 0u && u.fx0.z > 0.005 && mask_a > 1e-4) {{
+ let grain_h = sample_paper_grain_height(
+ paper_tex,
+ paper_sampler,
+ doc_pos,
+ tip_uv,
+ u.fx1.w,
+ u.paper0.xy,
+ u.flags1.y,
+ u.fx0.w,
+ u.fx1.x,
+ u.paper0.zw,
+ u.paper1.xy,
+ u.paper1.z,
+ u.paper1.w,
+ u.flags1.z,
+ );
+ mask_a = apply_csp_paper_texture_mode(
+ mask_a,
+ grain_h,
+ u.fx0.z,
+ u.flags1.x,
+ u.flags1.w,
+ u.fx1.z,
+ );
+ }}
- // Optional CSP useBlur local kernel softening
- if (u.flags.z != 0u && u.fx0.y > 0.01) {{
- let rad = i32(clamp(1.0 + u.fx0.y * 3.0, 1.0, 4.0));
- var s_rgb = vec3<f32>(0.0);
- var s_a = 0.0;
- for (var oy: i32 = -1; oy <= 1; oy = oy + 1) {{
- for (var ox: i32 = -1; ox <= 1; ox = ox + 1) {{
- let sp = clamp(lp + vec2<i32>(ox * rad, oy * rad), vec2<i32>(0), vec2<i32>(255));
- let c = textureLoad(color_pool, sp, slot, 0);
- s_rgb = s_rgb + c.rgb * c.a;
- s_a = s_a + c.a;
+ // Dual Brush secondary mask modulation (all 12 CSP DualBrushCompositeModes)
+ if (u.dual_info.x != 0) {{
+ let s_a = select(0.0, textureLoad(dual_pool, lp, u.dual_info.y, 0).a, u.dual_info.y >= 0);
+ mask_a = combine_dual_alpha(mask_a, s_a, u32(max(0, u.dual_info.z)));
+ }}
+
+ if (aa_level == 0u) {{
+ mask_a = step(0.5, mask_a);
+ }}
+ mask_a = mask_a * sel_a;
+
+ if (mask_a > 1e-4) {{
+ // Optional CSP useBlur local kernel softening
+ if (u.flags0.z != 0u && u.fx0.y > 0.01) {{
+ let rad = i32(clamp(1.0 + u.fx0.y * 3.0, 1.0, 4.0));
+ var s_rgb = vec3<f32>(0.0);
+ var s_a = 0.0;
+ for (var oy: i32 = -1; oy <= 1; oy = oy + 1) {{
+ for (var ox: i32 = -1; ox <= 1; ox = ox + 1) {{
+ let sp = clamp(lp + vec2<i32>(ox * rad, oy * rad), vec2<i32>(0), vec2<i32>(255));
+ let c = textureLoad(color_pool, sp, slot, 0);
+ s_rgb = s_rgb + c.rgb * c.a;
+ s_a = s_a + c.a;
+ }}
+ }}
+ if (s_a > 1e-4) {{
+ let blurred = vec4<f32>(s_rgb / s_a, s_a / 9.0);
+ let bf = clamp(u.fx0.y * mask_a * u.geom.z * 0.65, 0.0, 0.88);
+ cur_col = mix(cur_col, blurred, bf);
+ }}
+ }}
+
+ let mixed = sample_tip_grid_bilinear(grid_uv);
+ var dep_rgb = mixed.rgb;
+ if (has_tip) {{
+ if (u.flags2.x != 0u) {{
+ // isColorTip: preserve embedded RGB blended with wet pickup
+ let amt = clamp(u.bg_amount.w, 0.25, 1.0);
+ dep_rgb = mix(mixed.rgb, tip_tex_rgb, amt);
+ }} else if (u.flags2.y != 0u) {{
+ // isDualToneTip: luminance 0 -> mixed/fg, 1 -> bg_color
+ let lum = dot(tip_tex_rgb, vec3<f32>(0.299, 0.587, 0.114));
+ dep_rgb = mix(mixed.rgb, u.bg_amount.rgb, lum);
+ }}
+ }}
+
+ let raw_dep = clamp(mask_a * u.geom.z * u.geom.w * mixed.a, 0.0, 1.0);
+ // Step-distance normalized deposition (calibrated at ref spacing 0.25, zero pow()!)
+ // prevents tight spacing (0.04..0.08) from overwriting the wet canvas 10x faster than pickup.
+ let s_dep = clamp(u.step_info.x, 0.14, 1.5);
+ let dep_a = clamp(raw_dep * s_dep / (1.0 - raw_dep * (1.0 - s_dep) * 0.62), 0.0, 1.0);
+ if (dep_a > 1e-4) {{
+ let alpha_lock = (u.tile_info.w > 0.5);
+ let old_a = cur_col.a;
+ let next = composite_pigment_over_fast(
+ cur_col,
+ vec4<f32>(dep_rgb, dep_a),
+ clamp(u.fx0.x, 0.0, 1.0),
+ );
+ cur_col = select(next, vec4<f32>(next.rgb, old_a), alpha_lock);
+ if (track_cov) {{
+ cur_cov = clamp(cur_cov + dep_a * (1.0 - cur_cov), 0.0, 1.0);
+ }}
+ }}
}}
- }}
- if (s_a > 1e-4) {{
- let blurred = vec4<f32>(s_rgb / s_a, s_a / 9.0);
- let bf = clamp(u.fx0.y * mask_a * u.geom.z * 0.65, 0.0, 0.88);
- cur_col = mix(cur_col, blurred, bf);
}}
}}
- let mixed = sample_tip_grid_bilinear(tip_uv);
- let dep_a = clamp(mask_a * u.geom.z * u.geom.w * mixed.a, 0.0, 1.0);
- if (dep_a > 1e-4) {{
- let alpha_lock = (u.tile_info.w > 0.5);
- let old_a = cur_col.a;
- let next = composite_pigment_over(cur_col, vec4<f32>(mixed.rgb, dep_a), clamp(u.fx0.x, 0.0, 1.0));
- cur_col = select(next, vec4<f32>(next.rgb, old_a), alpha_lock);
+ if (track_cov) {{
+ textureStore(dst_cov, lp, vec4<f32>(cur_cov, 0.0, 0.0, 1.0));
}}
-
textureStore(dst_color, lp, cur_col);
}}
"#
)
}
+/// Seamless 2-pass ColorMixing post-resolve compute shader (runs ONCE per frame ONLY when
+/// `config.opacity < 0.999` or `config.wet_edge > 0.01`):
+/// - `cs_cmix_wet_horiz`: 3×3 neighbor-aware horizontal Gaussian blur of `cov_pool` into `288×288` scratch
+/// - `cs_cmix_resolve`: vertical wet-edge inner-rim pigment pooling + stroke-level `config.opacity` capping
+/// against `base_pool`, writing straight RGBA16F into `dst_color` (`cmix_display_tex`).
+const CMIX_RESOLVE_WGSL: &str = r#"
+struct CmixResolveUniforms {
+ // 3x3 neighbor slots in cov_pool: n0=[TL,T,TR,L], n1=[C,R,BL,B], n2=[BR, radius_px, alpha_lock, wet_active]
+ n0: vec4<i32>,
+ n1: vec4<i32>,
+ n2: vec4<i32>,
+ // params = [wet_edge, opacity_cap, alpha_power, value_power]
+ params: vec4<f32>,
+};
+
+@group(0) @binding(0) var<uniform> u: CmixResolveUniforms;
+@group(0) @binding(1) var color_pool: texture_2d_array<f32>;
+@group(0) @binding(2) var base_pool: texture_2d_array<f32>;
+@group(0) @binding(3) var cov_pool: texture_2d_array<f32>;
+@group(0) @binding(4) var padded_in: texture_2d<f32>;
+@group(0) @binding(5) var out_tex: texture_storage_2d<rgba16float, write>;
+
+fn neighbor_slot(ox: i32, oy: i32) -> i32 {
+ let idx = (oy + 1) * 3 + (ox + 1);
+ switch (idx) {
+ case 0: { return u.n0.x; }
+ case 1: { return u.n0.y; }
+ case 2: { return u.n0.z; }
+ case 3: { return u.n0.w; }
+ case 4: { return u.n1.x; }
+ case 5: { return u.n1.y; }
+ case 6: { return u.n1.z; }
+ case 7: { return u.n1.w; }
+ default: { return u.n2.x; }
+ }
+}
+
+fn load_cov_with_neighbors(px: i32, py: i32) -> f32 {
+ var ox = 0;
+ var lx = px;
+ if (lx < 0) {
+ ox = -1;
+ lx += 256;
+ } else if (lx >= 256) {
+ ox = 1;
+ lx -= 256;
+ }
+ var oy = 0;
+ var ly = py;
+ if (ly < 0) {
+ oy = -1;
+ ly += 256;
+ } else if (ly >= 256) {
+ oy = 1;
+ ly -= 256;
+ }
+ let slot = neighbor_slot(ox, oy);
+ if (slot < 0) {
+ return 0.0;
+ }
+ return textureLoad(cov_pool, vec2<i32>(clamp(lx, 0, 255), clamp(ly, 0, 255)), slot, 0).r;
+}
+
+@compute @workgroup_size(16, 16, 1)
+fn cs_cmix_wet_horiz(@builtin(global_invocation_id) gid: vec3<u32>) {
+ if (gid.x >= 288u || gid.y >= 288u) {
+ return;
+ }
+ let px = i32(gid.x) - 16;
+ let py = i32(gid.y) - 16;
+ let r = clamp(u.n2.y, 1, 14);
+ let sigma = max(0.8, f32(r) * 0.5);
+ let inv_2s2 = 1.0 / (2.0 * sigma * sigma);
+
+ var sum_a = 0.0;
+ var sum_w = 0.0;
+ for (var dx = -r; dx <= r; dx += 1) {
+ let w = exp(-f32(dx * dx) * inv_2s2);
+ sum_a += load_cov_with_neighbors(px + dx, py) * w;
+ sum_w += w;
+ }
+ let blur_a = sum_a / max(1e-5, sum_w);
+ textureStore(out_tex, vec2<i32>(i32(gid.x), i32(gid.y)), vec4<f32>(blur_a, 0.0, 0.0, 1.0));
+}
+
+@compute @workgroup_size(16, 16, 1)
+fn cs_cmix_resolve(@builtin(global_invocation_id) gid: vec3<u32>) {
+ if (gid.x >= 256u || gid.y >= 256u) {
+ return;
+ }
+ let xy = vec2<i32>(i32(gid.x), i32(gid.y));
+ let slot = u.n1.x;
+ if (slot < 0) {
+ textureStore(out_tex, xy, vec4<f32>(0.0));
+ return;
+ }
+ let base_col = textureLoad(base_pool, xy, slot, 0);
+ var mix_col = textureLoad(color_pool, xy, slot, 0);
+
+ // 1. Watercolor inner-rim wet-edge darkening & alpha boost along stroke coverage edge
+ var rim = 0.0;
+ let wet = clamp(u.params.x, 0.0, 1.0);
+ let alpha_pow = max(0.0, u.params.z);
+ let value_pow = max(0.0, u.params.w);
+ if (u.n2.w != 0) {
+ let cov = textureLoad(cov_pool, xy, slot, 0).r;
+ if (cov > 0.001) {
+ let r = clamp(u.n2.y, 1, 14);
+ let sigma = max(0.8, f32(r) * 0.5);
+ let inv_2s2 = 1.0 / (2.0 * sigma * sigma);
+ let cx = i32(gid.x) + 16;
+ let cy = i32(gid.y) + 16;
+ var sum_a = 0.0;
+ var sum_w = 0.0;
+ for (var dy = -r; dy <= r; dy += 1) {
+ let w = exp(-f32(dy * dy) * inv_2s2);
+ let h_val = textureLoad(padded_in, vec2<i32>(cx, cy + dy), 0).r;
+ sum_a += h_val * w;
+ sum_w += w;
+ }
+ let blur_cov = sum_a / max(1e-5, sum_w);
+ rim = clamp((cov - blur_cov) * 2.6, 0.0, 1.0);
+ let dark_factor = clamp(1.0 - wet * value_pow * rim * 0.44, 0.25, 1.0);
+ mix_col = vec4<f32>(
+ clamp(mix_col.rgb * dark_factor, vec3<f32>(0.0), vec3<f32>(1.0)),
+ clamp(mix_col.a + wet * alpha_pow * rim * 0.42 * (1.0 - mix_col.a * 0.35), 0.0, 1.0),
+ );
+ }
+ }
+
+ // 2. Stroke-level config.opacity cap against pre-stroke base tile (preserving wet-edge rim pooling)
+ let op = clamp(u.params.y, 0.0, 1.0);
+ let eff_op = select(
+ op,
+ clamp(op + wet * alpha_pow * rim * 0.42 * op * (1.0 - op * 0.35), 0.0, 1.0),
+ u.n2.w != 0 && rim > 0.001
+ );
+ var out_col = mix_col;
+ if (eff_op < 0.999) {
+ let ba = clamp(base_col.a, 0.0, 1.0);
+ let ma = clamp(mix_col.a, 0.0, 1.0);
+ let base_p = vec4<f32>(base_col.rgb * ba, ba);
+ let mix_p = vec4<f32>(mix_col.rgb * ma, ma);
+ let out_p = mix(base_p, mix_p, eff_op);
+ if (out_p.a <= 1e-5) {
+ out_col = vec4<f32>(0.0);
+ } else {
+ out_col = vec4<f32>(
+ clamp(out_p.rgb / out_p.a, vec3<f32>(0.0), vec3<f32>(1.0)),
+ clamp(out_p.a, 0.0, 1.0),
+ );
+ }
+ }
+
+ if (u.n2.z != 0) {
+ out_col.a = base_col.a;
+ }
+ textureStore(out_tex, xy, out_col);
+}
+"#;
+
/// Complete GPU Compute Natural Paint & Color Mixing Engine (`GpuNaturalPaintEngine`).
pub struct GpuNaturalPaintEngine {
pub pools: NaturalPaintTilePools,
pub dirty_bank: DirtyBrushGpuBank,
- // Pass 1: Bristle GPU pickup & load update
+ // Pass 1: Bristle GPU pickup & load update (O(1) dense tile grid + 69 reservoir slots)
pickup_bgl: wgpu::BindGroupLayout,
pickup_pipe: wgpu::ComputePipeline,
pickup_uniform_buf: wgpu::Buffer,
- tile_lookup_buf: wgpu::Buffer,
+ np_tile_grid_buf: wgpu::Buffer,
+ np_tile_grid_cap: usize,
+ np_tile_grid_gen: u64,
caps_in_buf: wgpu::Buffer,
caps_in_cap: usize,
+ caps_in_gen: u64,
caps_out_buf: wgpu::Buffer,
caps_out_cap: usize,
+ caps_out_gen: u64,
- // Pass 2: Natural paint multi-bristle capsule + impasto compute rasterizer
+ // Pass 2: Natural paint multi-bristle per-tile binned capsule + impasto compute rasterizer
raster_bgl: wgpu::BindGroupLayout,
raster_pipe: wgpu::ComputePipeline,
raster_uniform_buf: wgpu::Buffer,
-
- // Pass 3: Standard CSP Color-Mixing 16×16 SpatialTipMixer pickup + stamp compute
+ raster_uniform_cap: usize,
+ raster_uniform_gen: u64,
+ binned_caps_buf: wgpu::Buffer,
+ binned_caps_cap: usize,
+ binned_caps_gen: u64,
+
+ // Pass 3: Standard CSP Color-Mixing 16×16 SpatialTipMixer pickup + sub-rect stamp + post-resolve
+ cmix_tip_sampler: wgpu::Sampler,
+ cmix_paper_sampler: wgpu::Sampler,
+ cmix_tile_grid_buf: wgpu::Buffer,
+ cmix_tile_grid_cap: usize,
+ cmix_tile_grid_gen: u64,
cmix_pickup_bgl: wgpu::BindGroupLayout,
cmix_pickup_pipe: wgpu::ComputePipeline,
cmix_pickup_uniform_buf: wgpu::Buffer,
+ cmix_pickup_uniform_cap: usize,
+ cmix_pickup_uniform_gen: u64,
cmix_stamp_bgl: wgpu::BindGroupLayout,
cmix_stamp_pipe: wgpu::ComputePipeline,
cmix_stamp_uniform_buf: wgpu::Buffer,
+ cmix_stamp_uniform_cap: usize,
+ cmix_stamp_uniform_gen: u64,
+ cmix_resolve_bgl: wgpu::BindGroupLayout,
+ cmix_wet_horiz_pipe: wgpu::ComputePipeline,
+ cmix_resolve_pipe: wgpu::ComputePipeline,
+ cmix_resolve_uniform_buf: wgpu::Buffer,
+ cmix_resolve_uniform_cap: usize,
+ cmix_resolve_uniform_gen: u64,
+ _cmix_wet_padded_tex: wgpu::Texture,
+ cmix_wet_padded_view: wgpu::TextureView,
+ _dummy_2d_tex: wgpu::Texture,
+ dummy_2d_view: wgpu::TextureView,
_dummy_sel_tex: wgpu::Texture,
dummy_sel_view: wgpu::TextureView,
+ // Persistent scratch CPU staging buffers & cached BindGroups (ZERO per-frame allocations!)
+ np_tile_grid_staging: Vec<i32>,
+ np_binned_indices_staging: Vec<u32>,
+ np_raster_staging: Vec<u8>,
+ cmix_pick_staging: Vec<u8>,
+ cmix_stamp_staging: Vec<u8>,
+ cmix_tile_grid_staging: Vec<i32>,
+ cmix_resolve_staging: Vec<u8>,
+ cached_np_pickup_bg: Option<((u64, u64, u64, u64, u64), wgpu::BindGroup)>,
+ cached_np_raster_bg: Option<((u64, u64, u64, u64, u64, u64, u64, u64), wgpu::BindGroup)>,
+ cached_cmix_pick_bg: Option<((u64, u64, u64, u64), wgpu::BindGroup)>,
+ cached_cmix_stamp_bg: Option<((u64, u64, u64, u64, u64, u64, u64), wgpu::BindGroup)>,
+ cached_cmix_wet_h_bg: Option<((u64, u64), wgpu::BindGroup)>,
+ cached_cmix_resolve_bg: Option<((u64, u64), wgpu::BindGroup)>,
+
+ // Pre-compiled per-stroke CSP sensor LUTs (compiled ONCE in begin_stroke!)
+ cached_amount_luts: Option<CompiledSensorLuts>,
+ cached_density_luts: Option<CompiledSensorLuts>,
+ cached_stretch_luts: Option<CompiledSensorLuts>,
+ cached_paint_load_luts: Option<CompiledSensorLuts>,
+ cached_grain_pen_luts: Option<CompiledSensorLuts>,
+
// Active stroke metadata
active_preset_key: String,
active_doc_id: String,
active_layer_id: String,
active: bool,
active_has_impasto: bool,
+ stroke_rand_offset: [f32; 2],
+ last_cmix_dab_pos: Option<[f32; 2]>,
pub total_compute_dispatches: u64,
+ pub np_last_batch_binned_checks: usize,
+ pub np_last_batch_unbinned_checks: usize,
+ pub np_last_batch_subrect_pixels: u64,
+ pub np_bind_group_rebuilds: u64,
+ pub cmix_last_batch_subrect_pixels: u64,
+ pub cmix_last_batch_full_tile_pixels: u64,
+ pub cmix_total_subrect_pixels: u64,
+ pub cmix_total_full_tile_pixels: u64,
+ pub cmix_last_batch_dispatched_dabs: usize,
+ pub cmix_bind_group_rebuilds: u64,
}
impl GpuNaturalPaintEngine {
@@ -1054,9 +1460,10 @@ impl GpuNaturalPaintEngine {
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
- let tile_lookup_buf = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("ink-np-tile-lookup"),
- size: (MAX_LOOKUP_TILES * std::mem::size_of::<TileLookupEntry>()) as u64,
+ let np_tile_grid_cap = 1024usize;
+ let np_tile_grid_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-np-tile-grid"),
+ size: (np_tile_grid_cap * std::mem::size_of::<i32>()) as u64,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
@@ -1076,11 +1483,11 @@ impl GpuNaturalPaintEngine {
mapped_at_creation: false,
});
- // 2. Natural paint capsule + impasto compute rasterizer
+ // 2. Natural paint per-tile binned capsule + impasto + wet-edge compute rasterizer
let raster_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("ink-np-raster-bgl"),
entries: &[
- uniform_compute_entry(0),
+ dyn_uniform_compute_entry(0, std::mem::size_of::<RasterTileUniforms>()),
tex_array_compute_entry(1),
tex_array_compute_entry(2),
tex_2d_compute_entry(3),
@@ -1090,6 +1497,9 @@ impl GpuNaturalPaintEngine {
storage_tex_compute_entry(7, wgpu::TextureFormat::Rgba16Float),
storage_tex_compute_entry(8, wgpu::TextureFormat::R32Float),
tex_array_compute_entry(9),
+ storage_compute_entry(10, true),
+ tex_array_compute_entry(11),
+ storage_tex_compute_entry(12, wgpu::TextureFormat::Rgba16Float),
],
});
let raster_src = build_natural_paint_raster_wgsl();
@@ -1110,18 +1520,50 @@ impl GpuNaturalPaintEngine {
compilation_options: Default::default(),
cache: None,
});
+ let raster_uniform_cap = 64usize;
let raster_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("ink-np-raster-uniforms"),
- size: std::mem::size_of::<RasterTileUniforms>() as u64,
+ label: Some("ink-np-raster-uniforms-dyn"),
+ size: raster_uniform_cap as u64 * NP_UNIFORM_STRIDE,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
+ let binned_caps_cap = 4096usize;
+ let binned_caps_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-np-binned-caps"),
+ size: (binned_caps_cap * std::mem::size_of::<u32>()) as u64,
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+
+ // 3. Standard CSP Color-Mixing 16×16 SpatialTipMixer + sub-rect stamp + post-resolve pipelines
+ let cmix_tip_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
+ label: Some("ink-np-cmix-tip-sampler"),
+ address_mode_u: wgpu::AddressMode::ClampToEdge,
+ address_mode_v: wgpu::AddressMode::ClampToEdge,
+ mag_filter: wgpu::FilterMode::Linear,
+ min_filter: wgpu::FilterMode::Linear,
+ ..Default::default()
+ });
+ let cmix_paper_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
+ label: Some("ink-np-cmix-paper-sampler"),
+ address_mode_u: wgpu::AddressMode::Repeat,
+ address_mode_v: wgpu::AddressMode::Repeat,
+ mag_filter: wgpu::FilterMode::Linear,
+ min_filter: wgpu::FilterMode::Linear,
+ ..Default::default()
+ });
+ let cmix_tile_grid_cap = 1024usize;
+ let cmix_tile_grid_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-np-cmix-tile-grid"),
+ size: (cmix_tile_grid_cap * std::mem::size_of::<i32>()) as u64,
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
- // 3. Standard CSP Color-Mixing 16×16 SpatialTipMixer compute pipelines
let cmix_pickup_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("ink-np-cmix-pickup-bgl"),
entries: &[
- uniform_compute_entry(0),
+ dyn_uniform_compute_entry(0, std::mem::size_of::<ColorMixPickupUniforms>()),
tex_array_compute_entry(1),
tex_array_compute_entry(2),
storage_compute_entry(3, true),
@@ -1146,9 +1588,10 @@ impl GpuNaturalPaintEngine {
compilation_options: Default::default(),
cache: None,
});
+ let cmix_pickup_uniform_cap = 64usize;
let cmix_pickup_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("ink-np-cmix-pickup-uniforms"),
- size: std::mem::size_of::<ColorMixPickupUniforms>() as u64,
+ label: Some("ink-np-cmix-pickup-uniforms-dyn"),
+ size: cmix_pickup_uniform_cap as u64 * NP_UNIFORM_STRIDE,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
@@ -1156,13 +1599,18 @@ impl GpuNaturalPaintEngine {
let cmix_stamp_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("ink-np-cmix-stamp-bgl"),
entries: &[
- uniform_compute_entry(0),
+ dyn_uniform_compute_entry(0, std::mem::size_of::<ColorMixTileUniforms>()),
tex_array_compute_entry(1),
- tex_array_compute_entry(2),
- tex_2d_compute_entry(3),
- storage_compute_entry(4, true),
- storage_tex_compute_entry(5, wgpu::TextureFormat::Rgba16Float),
- tex_array_compute_entry(6),
+ tex_array_filterable_compute_entry(2),
+ sampler_compute_entry(3),
+ tex_2d_filterable_compute_entry(4),
+ sampler_compute_entry(5),
+ storage_compute_entry(6, true),
+ storage_tex_compute_entry(7, wgpu::TextureFormat::Rgba16Float),
+ tex_array_compute_entry(8),
+ tex_array_compute_entry(9),
+ tex_array_compute_entry(10),
+ storage_tex_compute_entry(11, wgpu::TextureFormat::Rgba16Float),
],
});
let cmix_stamp_src = build_color_mix_stamp_wgsl();
@@ -1183,12 +1631,89 @@ impl GpuNaturalPaintEngine {
compilation_options: Default::default(),
cache: None,
});
+ let cmix_stamp_uniform_cap = 128usize;
let cmix_stamp_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("ink-np-cmix-stamp-uniforms"),
- size: std::mem::size_of::<ColorMixTileUniforms>() as u64,
+ label: Some("ink-np-cmix-stamp-uniforms-dyn"),
+ size: cmix_stamp_uniform_cap as u64 * NP_UNIFORM_STRIDE,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+
+ let cmix_resolve_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("ink-np-cmix-resolve-bgl"),
+ entries: &[
+ dyn_uniform_compute_entry(0, std::mem::size_of::<CmixResolveUniforms>()),
+ tex_array_compute_entry(1),
+ tex_array_compute_entry(2),
+ tex_array_compute_entry(3),
+ tex_2d_compute_entry(4),
+ storage_tex_compute_entry(5, wgpu::TextureFormat::Rgba16Float),
+ ],
+ });
+ let cmix_resolve_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("ink-np-cmix-resolve-wgsl"),
+ source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(CMIX_RESOLVE_WGSL)),
+ });
+ let cmix_resolve_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("ink-np-cmix-resolve-pl"),
+ bind_group_layouts: &[Some(&cmix_resolve_bgl)],
+ immediate_size: 0,
+ });
+ let cmix_wet_horiz_pipe = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: Some("ink-np-cmix-wet-horiz-pipe"),
+ layout: Some(&cmix_resolve_pl),
+ module: &cmix_resolve_shader,
+ entry_point: Some("cs_cmix_wet_horiz"),
+ compilation_options: Default::default(),
+ cache: None,
+ });
+ let cmix_resolve_pipe = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: Some("ink-np-cmix-resolve-pipe"),
+ layout: Some(&cmix_resolve_pl),
+ module: &cmix_resolve_shader,
+ entry_point: Some("cs_cmix_resolve"),
+ compilation_options: Default::default(),
+ cache: None,
+ });
+ let cmix_resolve_uniform_cap = 64usize;
+ let cmix_resolve_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-np-cmix-resolve-uniforms-dyn"),
+ size: cmix_resolve_uniform_cap as u64 * NP_UNIFORM_STRIDE,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
+ let cmix_wet_padded_tex = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("ink-np-cmix-wet-padded"),
+ size: wgpu::Extent3d {
+ width: 288,
+ height: 288,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba16Float,
+ usage: wgpu::TextureUsages::STORAGE_BINDING | wgpu::TextureUsages::TEXTURE_BINDING,
+ view_formats: &[],
+ });
+ let cmix_wet_padded_view =
+ cmix_wet_padded_tex.create_view(&wgpu::TextureViewDescriptor::default());
+ let dummy_2d_tex = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("ink-np-dummy-2d-rgba16f"),
+ size: wgpu::Extent3d {
+ width: 1,
+ height: 1,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba16Float,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
+ view_formats: &[],
+ });
+ let dummy_2d_view = dummy_2d_tex.create_view(&wgpu::TextureViewDescriptor::default());
+
let dummy_sel_tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("ink-np-dummy-sel-r8-array"),
size: wgpu::Extent3d {
@@ -1216,28 +1741,86 @@ impl GpuNaturalPaintEngine {
pickup_bgl,
pickup_pipe,
pickup_uniform_buf,
- tile_lookup_buf,
+ np_tile_grid_buf,
+ np_tile_grid_cap,
+ np_tile_grid_gen: 1,
caps_in_buf,
caps_in_cap: init_caps,
+ caps_in_gen: 1,
caps_out_buf,
caps_out_cap: init_caps,
+ caps_out_gen: 1,
raster_bgl,
raster_pipe,
raster_uniform_buf,
+ raster_uniform_cap,
+ raster_uniform_gen: 1,
+ binned_caps_buf,
+ binned_caps_cap,
+ binned_caps_gen: 1,
+ cmix_tip_sampler,
+ cmix_paper_sampler,
+ cmix_tile_grid_buf,
+ cmix_tile_grid_cap,
+ cmix_tile_grid_gen: 1,
cmix_pickup_bgl,
cmix_pickup_pipe,
cmix_pickup_uniform_buf,
+ cmix_pickup_uniform_cap,
+ cmix_pickup_uniform_gen: 1,
cmix_stamp_bgl,
cmix_stamp_pipe,
cmix_stamp_uniform_buf,
+ cmix_stamp_uniform_cap,
+ cmix_stamp_uniform_gen: 1,
+ cmix_resolve_bgl,
+ cmix_wet_horiz_pipe,
+ cmix_resolve_pipe,
+ cmix_resolve_uniform_buf,
+ cmix_resolve_uniform_cap,
+ cmix_resolve_uniform_gen: 1,
+ _cmix_wet_padded_tex: cmix_wet_padded_tex,
+ cmix_wet_padded_view,
+ _dummy_2d_tex: dummy_2d_tex,
+ dummy_2d_view,
_dummy_sel_tex: dummy_sel_tex,
dummy_sel_view,
+ np_tile_grid_staging: Vec::with_capacity(256),
+ np_binned_indices_staging: Vec::with_capacity(2048),
+ np_raster_staging: Vec::with_capacity(64 * NP_UNIFORM_STRIDE as usize),
+ cmix_pick_staging: Vec::with_capacity(64 * NP_UNIFORM_STRIDE as usize),
+ cmix_stamp_staging: Vec::with_capacity(128 * NP_UNIFORM_STRIDE as usize),
+ cmix_tile_grid_staging: Vec::with_capacity(256),
+ cmix_resolve_staging: Vec::with_capacity(64 * NP_UNIFORM_STRIDE as usize),
+ cached_np_pickup_bg: None,
+ cached_np_raster_bg: None,
+ cached_cmix_pick_bg: None,
+ cached_cmix_stamp_bg: None,
+ cached_cmix_wet_h_bg: None,
+ cached_cmix_resolve_bg: None,
+ cached_amount_luts: None,
+ cached_density_luts: None,
+ cached_stretch_luts: None,
+ cached_paint_load_luts: None,
+ cached_grain_pen_luts: None,
active_preset_key: String::new(),
active_doc_id: String::new(),
active_layer_id: String::new(),
active: false,
active_has_impasto: false,
+ stroke_rand_offset: [0.0, 0.0],
+ last_cmix_dab_pos: None,
total_compute_dispatches: 0,
+ np_last_batch_binned_checks: 0,
+ np_last_batch_unbinned_checks: 0,
+ np_last_batch_subrect_pixels: 0,
+ np_bind_group_rebuilds: 0,
+ cmix_last_batch_subrect_pixels: 0,
+ cmix_last_batch_full_tile_pixels: 0,
+ cmix_total_subrect_pixels: 0,
+ cmix_total_full_tile_pixels: 0,
+ cmix_last_batch_dispatched_dabs: 0,
+ cmix_bind_group_rebuilds: 0,
}
}
@@ -1266,6 +1849,35 @@ impl GpuNaturalPaintEngine {
self.active_doc_id = doc_id.to_string();
self.active_layer_id = layer_id.to_string();
self.active_has_impasto = config.impasto.is_some_and(|i| i.enabled && i.depth > 0.001);
+ self.last_cmix_dab_pos = None;
+ self.np_last_batch_binned_checks = 0;
+ self.np_last_batch_unbinned_checks = 0;
+ self.np_last_batch_subrect_pixels = 0;
+ self.cmix_last_batch_subrect_pixels = 0;
+ self.cmix_last_batch_full_tile_pixels = 0;
+ self.cmix_last_batch_dispatched_dabs = 0;
+
+ // Pre-compile all CSP sensor LUTs ONCE on pen-down (ZERO per-frame LUT rebuilds!)
+ self.cached_amount_luts = config
+ .amount_of_paint_sensor
+ .as_ref()
+ .map(|s| CompiledSensorLuts::from_sensor(Some(s)));
+ self.cached_density_luts = config
+ .density_of_paint_sensor
+ .as_ref()
+ .map(|s| CompiledSensorLuts::from_sensor(Some(s)));
+ self.cached_stretch_luts = config
+ .color_stretch_sensor
+ .as_ref()
+ .map(|s| CompiledSensorLuts::from_sensor(Some(s)));
+ self.cached_paint_load_luts = config
+ .paint_load_sensor
+ .as_ref()
+ .map(|s| CompiledSensorLuts::from_sensor(Some(s)));
+ self.cached_grain_pen_luts = config
+ .grain_penetration_sensor
+ .as_ref()
+ .map(|s| CompiledSensorLuts::from_sensor(Some(s)));
let preset_key = config
.preset_key
@@ -1287,7 +1899,10 @@ impl GpuNaturalPaintEngine {
let auto_clean = if np.enabled { np.auto_clean } else { true };
if config.is_natural_paint_brush() {
- let _ = self.dirty_bank.acquire_bristle_buffer(
+ let need_wet = config.wet_edge > 0.01;
+ self.pools
+ .configure_cmix_post_pools(device, need_wet, need_wet);
+ let _ = self.dirty_bank.acquire_bristle_buffer_with_id(
device,
queue,
&preset_key,
@@ -1297,7 +1912,11 @@ impl GpuNaturalPaintEngine {
auto_clean,
);
} else {
- let _ = self.dirty_bank.acquire_tip_mixer_buffer(
+ let need_cov = config.wet_edge > 0.01;
+ let need_display = need_cov || config.opacity < 0.999;
+ self.pools
+ .configure_cmix_post_pools(device, need_display, need_cov);
+ let _ = self.dirty_bank.acquire_tip_mixer_buffer_with_id(
device,
queue,
&preset_key,
@@ -1309,15 +1928,23 @@ impl GpuNaturalPaintEngine {
}
}
+ #[inline]
+ pub fn set_stroke_rand_offset(&mut self, offset: [f32; 2]) {
+ self.stroke_rand_offset = offset;
+ }
+
/// Cancels an active stroke without committing to the layer.
pub fn cancel_stroke(&mut self) {
self.active = false;
self.active_has_impasto = false;
+ self.last_cmix_dab_pos = None;
self.pools.reset_for_stroke();
}
- /// Dispatches GPU zero-readback canvas pickup + multi-bristle capsule rasterization +
- /// simultaneous `R16Float` impasto heightfield accumulation for a batch of [`GpuBristleCapsule`]s!
+ /// Dispatches GPU zero-readback canvas pickup (O(1) tile grid, 69 slots) + per-tile binned
+ /// tight sub-rect `@workgroup_size(8,8,1)` multi-bristle capsule rasterization +
+ /// simultaneous `R16Float` impasto heightfield accumulation + optional watercolor wet-edge
+ /// resolve in **ONE `CommandEncoder` + ONE `queue.submit`**!
///
/// Returns the newly dirtied document-space AABB `(min_x, min_y, max_x, max_y)` for tight scissor updates.
#[allow(clippy::too_many_arguments)]
@@ -1342,14 +1969,14 @@ impl GpuNaturalPaintEngine {
return None;
}
- // 1. Collect all touched 256×256 tiles & compute dirty AABB
- let mut touched_tiles: HashSet<TileCoord> = HashSet::new();
+ // 1. Per-tile CPU capsule binning + tight tile-local sub-rect `[x0, y0, x1, y1]`
+ let mut tile_bins: HashMap<TileCoord, ([u32; 4], Vec<u32>)> = HashMap::new();
let mut min_x = f32::INFINITY;
let mut min_y = f32::INFINITY;
let mut max_x = f32::NEG_INFINITY;
let mut max_y = f32::NEG_INFINITY;
- for cap in capsules {
+ for (cap_idx, cap) in capsules.iter().enumerate() {
let (x0, y0, x1, y1) = cap.doc_bounds();
min_x = min_x.min(x0);
min_y = min_y.min(y0);
@@ -1362,39 +1989,87 @@ impl GpuNaturalPaintEngine {
let ty1 = (y1.ceil() as i32).div_euclid(TILE_SIZE as i32);
for ty in ty0..=ty1 {
for tx in tx0..=tx1 {
- touched_tiles.insert(TileCoord::new(tx, ty));
+ let tile_ox = tx * TILE_SIZE as i32;
+ let tile_oy = ty * TILE_SIZE as i32;
+ let lx0 = ((x0.floor() as i32) - tile_ox).clamp(0, TILE_SIZE as i32) as u32;
+ let ly0 = ((y0.floor() as i32) - tile_oy).clamp(0, TILE_SIZE as i32) as u32;
+ let lx1 = ((x1.ceil() as i32) - tile_ox).clamp(0, TILE_SIZE as i32) as u32;
+ let ly1 = ((y1.ceil() as i32) - tile_oy).clamp(0, TILE_SIZE as i32) as u32;
+ if lx0 >= lx1 || ly0 >= ly1 {
+ continue;
+ }
+ let coord = TileCoord::new(tx, ty);
+ let entry = tile_bins
+ .entry(coord)
+ .or_insert_with(|| ([TILE_SIZE as u32, TILE_SIZE as u32, 0, 0], Vec::with_capacity(32)));
+ entry.0[0] = entry.0[0].min(lx0);
+ entry.0[1] = entry.0[1].min(ly0);
+ entry.0[2] = entry.0[2].max(lx1);
+ entry.0[3] = entry.0[3].max(ly1);
+ entry.1.push(cap_idx as u32);
}
}
}
- if touched_tiles.is_empty() {
+ if tile_bins.is_empty() {
return None;
}
- // 2. Lazily initialize every newly touched tile purely on GPU (ZERO CPU readPixels!)
- for &coord in &touched_tiles {
- self.pools.ensure_tile_initialized(
- device,
- queue,
- tile_pool,
- doc,
- active_layer,
- coord,
- config.mix_ground_color,
- scratch,
- );
- }
+ // 2. Prepare batched GPU tile initialization (ZERO per-tile queue.submit!)
+ let mut touched_vec: Vec<TileCoord> = tile_bins.keys().copied().collect();
+ touched_vec.sort_by_key(|c| (c.ty, c.tx));
+ let init_plan = self.pools.prepare_init_tiles_batch(
+ device,
+ queue,
+ tile_pool,
+ doc,
+ active_layer,
+ &touched_vec,
+ config.mix_ground_color,
+ scratch,
+ );
- // 3. Upload active tile lookup table for O(1) GPU pickup sampling
- let mut lookup: Vec<TileLookupEntry> = Vec::with_capacity(self.pools.coord_to_slot.len().min(MAX_LOOKUP_TILES));
- for (&coord, &slot) in self.pools.coord_to_slot.iter().take(MAX_LOOKUP_TILES) {
- lookup.push(TileLookupEntry {
- tx: coord.tx,
- ty: coord.ty,
- slot: slot as i32,
- _pad: 0,
+ // 3. Build O(1) dense bounding-box tile lookup grid for ALL active stroke tiles
+ let mut grid_min_tx = i32::MAX;
+ let mut grid_min_ty = i32::MAX;
+ let mut grid_max_tx = i32::MIN;
+ let mut grid_max_ty = i32::MIN;
+ for &coord in self.pools.coord_to_slot.keys() {
+ grid_min_tx = grid_min_tx.min(coord.tx);
+ grid_min_ty = grid_min_ty.min(coord.ty);
+ grid_max_tx = grid_max_tx.max(coord.tx);
+ grid_max_ty = grid_max_ty.max(coord.ty);
+ }
+ if grid_min_tx > grid_max_tx || grid_min_ty > grid_max_ty {
+ self.pools.unpin_init_plan(tile_pool, init_plan);
+ return None;
+ }
+ let grid_w = (grid_max_tx - grid_min_tx + 1).max(1);
+ let grid_h = (grid_max_ty - grid_min_ty + 1).max(1);
+ let grid_len = (grid_w as usize).saturating_mul(grid_h as usize);
+ if grid_len > self.np_tile_grid_cap {
+ let new_cap = grid_len.next_power_of_two().max(1024);
+ self.np_tile_grid_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-np-tile-grid"),
+ size: (new_cap * std::mem::size_of::<i32>()) as u64,
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
});
+ self.np_tile_grid_cap = new_cap;
+ self.np_tile_grid_gen = self.np_tile_grid_gen.saturating_add(1);
+ }
+ self.np_tile_grid_staging.clear();
+ self.np_tile_grid_staging.resize(grid_len, -1i32);
+ for (&coord, &slot) in &self.pools.coord_to_slot {
+ let gx = (coord.tx - grid_min_tx) as usize;
+ let gy = (coord.ty - grid_min_ty) as usize;
+ self.np_tile_grid_staging[gy * (grid_w as usize) + gx] = slot as i32;
}
- queue.write_buffer(&self.tile_lookup_buf, 0, bytemuck::cast_slice(&lookup));
+ queue.write_buffer(
+ &self.np_tile_grid_buf,
+ 0,
+ bytemuck::cast_slice(&self.np_tile_grid_staging),
+ );
+ let grid_info = [grid_min_tx, grid_min_ty, grid_w, grid_h];
// 4. Grow & upload capsule buffers if needed
if capsules.len() > self.caps_in_cap {
@@ -1405,6 +2080,7 @@ impl GpuNaturalPaintEngine {
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
+ self.caps_in_gen = self.caps_in_gen.saturating_add(1);
}
if capsules.len() > self.caps_out_cap {
self.caps_out_cap = capsules.len().next_power_of_two();
@@ -1416,10 +2092,11 @@ impl GpuNaturalPaintEngine {
| wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
+ self.caps_out_gen = self.caps_out_gen.saturating_add(1);
}
queue.write_buffer(&self.caps_in_buf, 0, bytemuck::cast_slice(capsules));
- // Evaluate CSP paint sensors using batch average pressure/tilt
+ // Evaluate CSP paint sensors using cached pre-compiled LUTs (ZERO per-frame LUT rebuilds!)
let avg_p = capsules.iter().map(|c| c.geom[2]).sum::<f32>() / capsules.len() as f32;
let avg_tilt = capsules.iter().map(|c| c.motion[2]).sum::<f32>() / capsules.len() as f32;
let avg_dist = capsules.last().map(|c| c.motion[0]).unwrap_or(0.0);
@@ -1427,9 +2104,16 @@ impl GpuNaturalPaintEngine {
.amount_of_paint_sensor
.as_ref()
.map(|s| {
- let luts = CompiledSensorLuts::from_sensor(Some(s));
config.amount_of_paint
- * evaluate_csp_sensor(s, Some(&luts), avg_p, avg_tilt, 0.0, avg_dist, 0.5)
+ * evaluate_csp_sensor(
+ s,
+ self.cached_amount_luts.as_ref(),
+ avg_p,
+ avg_tilt,
+ 0.0,
+ avg_dist,
+ 0.5,
+ )
})
.unwrap_or(config.amount_of_paint)
.clamp(0.0, 1.0);
@@ -1437,9 +2121,16 @@ impl GpuNaturalPaintEngine {
.density_of_paint_sensor
.as_ref()
.map(|s| {
- let luts = CompiledSensorLuts::from_sensor(Some(s));
config.density_of_paint
- * evaluate_csp_sensor(s, Some(&luts), avg_p, avg_tilt, 0.0, avg_dist, 0.5)
+ * evaluate_csp_sensor(
+ s,
+ self.cached_density_luts.as_ref(),
+ avg_p,
+ avg_tilt,
+ 0.0,
+ avg_dist,
+ 0.5,
+ )
})
.unwrap_or(config.density_of_paint)
.clamp(0.01, 1.0);
@@ -1447,9 +2138,16 @@ impl GpuNaturalPaintEngine {
.color_stretch_sensor
.as_ref()
.map(|s| {
- let luts = CompiledSensorLuts::from_sensor(Some(s));
config.color_stretch
- * evaluate_csp_sensor(s, Some(&luts), avg_p, avg_tilt, 0.0, avg_dist, 0.5)
+ * evaluate_csp_sensor(
+ s,
+ self.cached_stretch_luts.as_ref(),
+ avg_p,
+ avg_tilt,
+ 0.0,
+ avg_dist,
+ 0.5,
+ )
})
.unwrap_or(config.color_stretch)
.clamp(0.0, 1.0);
@@ -1469,16 +2167,30 @@ impl GpuNaturalPaintEngine {
.paint_load_sensor
.as_ref()
.map(|s| {
- let luts = CompiledSensorLuts::from_sensor(Some(s));
- evaluate_csp_sensor(s, Some(&luts), avg_p, avg_tilt, 0.0, avg_dist, 0.5)
+ evaluate_csp_sensor(
+ s,
+ self.cached_paint_load_luts.as_ref(),
+ avg_p,
+ avg_tilt,
+ 0.0,
+ avg_dist,
+ 0.5,
+ )
})
.unwrap_or(1.0);
let eff_dry_brush = config
.grain_penetration_sensor
.as_ref()
.map(|s| {
- let luts = CompiledSensorLuts::from_sensor(Some(s));
- let pen = evaluate_csp_sensor(s, Some(&luts), avg_p, avg_tilt, 0.0, avg_dist, 0.5);
+ let pen = evaluate_csp_sensor(
+ s,
+ self.cached_grain_pen_luts.as_ref(),
+ avg_p,
+ avg_tilt,
+ 0.0,
+ avg_dist,
+ 0.5,
+ );
(np.dry_brush * (1.25 - 0.5 * pen)).clamp(0.0, 1.0)
})
.unwrap_or(np.dry_brush);
@@ -1505,7 +2217,7 @@ impl GpuNaturalPaintEngine {
capsules.len() as u32,
],
counts1: [
- lookup.len() as u32,
+ TOTAL_BRISTLE_SLOTS as u32,
bs.count.clamp(4, MAX_BRISTLES as u32),
u32::from(config.use_blur),
u32::from(config.perceptual_mixing),
@@ -1520,105 +2232,67 @@ impl GpuNaturalPaintEngine {
if np.auto_clean { 1.0 } else { 0.0 },
0.0,
],
+ grid_info,
};
queue.write_buffer(&self.pickup_uniform_buf, 0, bytemuck::bytes_of(&pickup_u));
- // 5. Acquire persistent GPU bristle buffer and dispatch Pass 1 (Pickup + Mixing)
- let (bristle_buf, _) = self.dirty_bank.acquire_bristle_buffer(
- device,
- queue,
- &self.active_preset_key,
- config.fg_color,
- np.paint_load,
- np.wetness,
- false, // never wipe mid-stroke!
- );
+ // 5. Flatten per-tile binned capsule indices & pack Pass 2 dynamic uniforms
+ let (surf_view, surf_id, has_surf) = match surface_tex {
+ Some(s) => (&s.view, s.id, 1u32),
+ None => (dummy_paper_view, 0u64, 0u32),
+ };
+ let (dual_surf_view, dual_surf_id, has_dual_surf) = match dual_surface_tex {
+ Some(s) if config.dual_grain_depth > 0.005 => (&s.view, s.id, 1u32),
+ _ => (dummy_paper_view, 0u64, 0u32),
+ };
+ let (tip_view, tip_id, has_tip) = match tip_arr {
+ Some(t) => (&t.view, t.id, 1u32),
+ None => (dummy_tip_view, 0u64, 0u32),
+ };
+ let grain_mode_u = config.grain_mapping_mode.as_u32();
+ let alpha_lock = active_layer.meta.alpha_locked.unwrap_or(false);
+ let active_sel = selection.filter(|s| s.is_active());
+ let (sel_atlas_view, sel_gen) = match active_sel {
+ Some(s) => (s.atlas_view(), s.atlas_gen()),
+ None => (&self.dummy_sel_view, 0u64),
+ };
+ let sel_default_f = active_sel.map(|s| s.default_alpha_f32()).unwrap_or(1.0);
+ let track_cov = self.pools.use_cmix_cov;
+ let need_wet_resolve = self.pools.use_cmix_display && track_cov;
- let pickup_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-np-pickup-bg"),
- layout: &self.pickup_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: self.pickup_uniform_buf.as_entire_binding(),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(&self.pools.color_array_view),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::TextureView(&self.pools.ground_array_view),
- },
- wgpu::BindGroupEntry {
- binding: 3,
- resource: self.tile_lookup_buf.as_entire_binding(),
- },
- wgpu::BindGroupEntry {
- binding: 4,
- resource: self.caps_in_buf.as_entire_binding(),
- },
- wgpu::BindGroupEntry {
- binding: 5,
- resource: bristle_buf.as_entire_binding(),
- },
- wgpu::BindGroupEntry {
- binding: 6,
- resource: self.caps_out_buf.as_entire_binding(),
- },
- ],
- });
+ self.np_binned_indices_staging.clear();
+ let mut raster_jobs: Vec<(u32, [u32; 4])> = Vec::with_capacity(touched_vec.len());
+ let mut raster_uniforms: Vec<RasterTileUniforms> = Vec::with_capacity(touched_vec.len());
+ let mut total_binned_checks = 0usize;
+ let mut total_subrect_pixels = 0u64;
- let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-np-pickup-and-raster-enc"),
- });
- {
- let mut cpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
- label: Some("ink-np-pickup-pass"),
- timestamp_writes: None,
- });
- cpass.set_pipeline(&self.pickup_pipe);
- cpass.set_bind_group(0, &pickup_bg, &[]);
- cpass.dispatch_workgroups(1, 1, 1); // 64 threads = all 64 bristle reservoirs in parallel!
- }
- queue.submit(Some(encoder.finish()));
- self.total_compute_dispatches += 1;
-
- // 6. Dispatch Pass 2 per touched 256×256 tile (Color + Simultaneous R16F Impasto Heightfield!)
- let (surf_view, has_surf) = match surface_tex {
- Some(s) => (&s.view, 1u32),
- None => (dummy_paper_view, 0u32),
- };
- let (dual_surf_view, has_dual_surf) = match dual_surface_tex {
- Some(s) if config.dual_grain_depth > 0.005 => (&s.view, 1u32),
- _ => (dummy_paper_view, 0u32),
- };
- let (tip_view, has_tip) = match tip_arr {
- Some(t) => (&t.view, 1u32),
- None => (dummy_tip_view, 0u32),
- };
- let grain_mode_u = config.grain_mapping_mode.as_u32();
- let alpha_lock = active_layer.meta.alpha_locked.unwrap_or(false);
- let active_sel = selection.filter(|s| s.is_active());
- let sel_atlas_view = active_sel
- .map(|s| s.atlas_view())
- .unwrap_or(&self.dummy_sel_view);
- let sel_default_f = active_sel.map(|s| s.default_alpha_f32()).unwrap_or(1.0);
-
- for coord in touched_tiles {
+ for &coord in &touched_vec {
let Some(&slot) = self.pools.coord_to_slot.get(&coord) else {
continue;
};
+ let Some((rect, indices)) = tile_bins.get(&coord) else {
+ continue;
+ };
+ if indices.is_empty() || rect[0] >= rect[2] || rect[1] >= rect[3] {
+ continue;
+ }
+ let bin_start = self.np_binned_indices_staging.len() as u32;
+ let bin_count = indices.len() as u32;
+ self.np_binned_indices_staging.extend_from_slice(indices);
+ total_binned_checks += indices.len();
+ total_subrect_pixels += (rect[2] - rect[0]) as u64 * (rect[3] - rect[1]) as u64;
+
let sel_slot_f = match active_sel {
Some(s) => s.tile_slot(&coord).map(|v| v as f32).unwrap_or(-1.0),
None => -2.0,
};
- let raster_u = RasterTileUniforms {
+ raster_jobs.push((slot, *rect));
+ raster_uniforms.push(RasterTileUniforms {
tile_info: [
(coord.tx * TILE_SIZE as i32) as f32,
(coord.ty * TILE_SIZE as i32) as f32,
slot as f32,
- capsules.len() as f32,
+ 0.0,
],
surface0: [
eff_dry_brush,
@@ -1661,16 +2335,85 @@ impl GpuNaturalPaintEngine {
config.opacity.clamp(0.01, 1.0),
],
sel_info: [sel_slot_f, sel_default_f, 0.0, 0.0],
- };
- queue.write_buffer(&self.raster_uniform_buf, 0, bytemuck::bytes_of(&raster_u));
+ rect: *rect,
+ bin_info: [bin_start, bin_count, u32::from(track_cov), 0],
+ });
+ }
+
+ self.np_last_batch_binned_checks = total_binned_checks;
+ self.np_last_batch_unbinned_checks = raster_jobs.len() * capsules.len();
+ self.np_last_batch_subrect_pixels = total_subrect_pixels;
+
+ if !self.np_binned_indices_staging.is_empty() {
+ if self.np_binned_indices_staging.len() > self.binned_caps_cap {
+ self.binned_caps_cap = self.np_binned_indices_staging.len().next_power_of_two().max(4096);
+ self.binned_caps_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-np-binned-caps"),
+ size: (self.binned_caps_cap * std::mem::size_of::<u32>()) as u64,
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ self.binned_caps_gen = self.binned_caps_gen.saturating_add(1);
+ }
+ queue.write_buffer(
+ &self.binned_caps_buf,
+ 0,
+ bytemuck::cast_slice(&self.np_binned_indices_staging),
+ );
+ }
- let raster_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-np-raster-bg"),
- layout: &self.raster_bgl,
+ let stride = NP_UNIFORM_STRIDE as usize;
+ if !raster_uniforms.is_empty() {
+ if ensure_dyn_uniform_buf(
+ device,
+ &mut self.raster_uniform_buf,
+ &mut self.raster_uniform_cap,
+ raster_uniforms.len(),
+ "ink-np-raster-uniforms-dyn",
+ ) {
+ self.raster_uniform_gen = self.raster_uniform_gen.saturating_add(1);
+ }
+ let rlen = raster_uniforms.len() * stride;
+ self.np_raster_staging.clear();
+ self.np_raster_staging.resize(rlen, 0u8);
+ for (i, u) in raster_uniforms.iter().enumerate() {
+ let src = bytemuck::bytes_of(u);
+ self.np_raster_staging[i * stride..i * stride + src.len()].copy_from_slice(src);
+ }
+ queue.write_buffer(&self.raster_uniform_buf, 0, &self.np_raster_staging);
+ }
+
+ // 6. Acquire persistent GPU bristle buffer + cached BindGroups (ZERO per-frame BG churn!)
+ let (bristle_buf, bristle_buf_id, _) = self.dirty_bank.acquire_bristle_buffer_with_id(
+ device,
+ queue,
+ &self.active_preset_key,
+ config.fg_color,
+ np.paint_load,
+ np.wetness,
+ false, // never wipe mid-stroke!
+ );
+
+ let pick_key = (
+ self.pools.atlas_gen,
+ self.np_tile_grid_gen,
+ self.caps_in_gen,
+ self.caps_out_gen,
+ bristle_buf_id,
+ );
+ if self
+ .cached_np_pickup_bg
+ .as_ref()
+ .map(|(k, _)| *k != pick_key)
+ .unwrap_or(true)
+ {
+ let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-np-pickup-bg"),
+ layout: &self.pickup_bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
- resource: self.raster_uniform_buf.as_entire_binding(),
+ resource: self.pickup_uniform_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
@@ -1678,66 +2421,410 @@ impl GpuNaturalPaintEngine {
},
wgpu::BindGroupEntry {
binding: 2,
- resource: wgpu::BindingResource::TextureView(&self.pools.height_array_view),
+ resource: wgpu::BindingResource::TextureView(&self.pools.ground_array_view),
},
wgpu::BindGroupEntry {
binding: 3,
- resource: wgpu::BindingResource::TextureView(surf_view),
+ resource: self.np_tile_grid_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 4,
- resource: wgpu::BindingResource::TextureView(dual_surf_view),
+ resource: self.caps_in_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 5,
- resource: wgpu::BindingResource::TextureView(tip_view),
+ resource: bristle_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 6,
resource: self.caps_out_buf.as_entire_binding(),
},
- wgpu::BindGroupEntry {
- binding: 7,
- resource: wgpu::BindingResource::TextureView(
- &self.pools.color_scratch_view,
- ),
- },
- wgpu::BindGroupEntry {
- binding: 8,
- resource: wgpu::BindingResource::TextureView(
- &self.pools.height_scratch_r32f_view,
- ),
- },
- wgpu::BindGroupEntry {
- binding: 9,
- resource: wgpu::BindingResource::TextureView(sel_atlas_view),
- },
],
});
+ self.cached_np_pickup_bg = Some((pick_key, bg));
+ self.np_bind_group_rebuilds += 1;
+ }
- let mut tile_enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-np-tile-raster-enc"),
- });
+ if !raster_jobs.is_empty() {
+ let raster_key = (
+ self.pools.atlas_gen,
+ self.raster_uniform_gen,
+ surf_id,
+ dual_surf_id,
+ tip_id,
+ self.caps_out_gen,
+ self.binned_caps_gen,
+ sel_gen,
+ );
+ if self
+ .cached_np_raster_bg
+ .as_ref()
+ .map(|(k, _)| *k != raster_key)
+ .unwrap_or(true)
{
- let mut cpass = tile_enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
- label: Some("ink-np-tile-raster-pass"),
- timestamp_writes: None,
+ let cov_view = self.pools.cmix_cov_array_view();
+ let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-np-raster-bg"),
+ layout: &self.raster_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.raster_uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(
+ std::mem::size_of::<RasterTileUniforms>() as u64,
+ ),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(
+ &self.pools.color_array_view,
+ ),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(
+ &self.pools.height_array_view,
+ ),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::TextureView(surf_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 4,
+ resource: wgpu::BindingResource::TextureView(dual_surf_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 5,
+ resource: wgpu::BindingResource::TextureView(tip_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 6,
+ resource: self.caps_out_buf.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 7,
+ resource: wgpu::BindingResource::TextureView(
+ &self.pools.color_scratch_view,
+ ),
+ },
+ wgpu::BindGroupEntry {
+ binding: 8,
+ resource: wgpu::BindingResource::TextureView(
+ &self.pools.height_scratch_r32f_view,
+ ),
+ },
+ wgpu::BindGroupEntry {
+ binding: 9,
+ resource: wgpu::BindingResource::TextureView(sel_atlas_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 10,
+ resource: self.binned_caps_buf.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 11,
+ resource: wgpu::BindingResource::TextureView(cov_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 12,
+ resource: wgpu::BindingResource::TextureView(
+ &self.pools.cmix_cov_scratch_view,
+ ),
+ },
+ ],
});
- cpass.set_pipeline(&self.raster_pipe);
- cpass.set_bind_group(0, &raster_bg, &[]);
- cpass.dispatch_workgroups(16, 16, 1);
+ self.cached_np_raster_bg = Some((raster_key, bg));
+ self.np_bind_group_rebuilds += 1;
+ }
+ }
+
+ // Optional once-per-frame watercolor wet-edge resolve for NaturalPaint presets (e.g. granulating-watercolor)
+ let mut resolve_slots: Vec<u32> = Vec::new();
+ if need_wet_resolve {
+ let mut post_set: HashSet<TileCoord> = HashSet::with_capacity(touched_vec.len() * 2);
+ for &c in &touched_vec {
+ for dy in -1..=1 {
+ for dx in -1..=1 {
+ let nb = TileCoord::new(c.tx + dx, c.ty + dy);
+ if self.pools.coord_to_slot.contains_key(&nb) {
+ post_set.insert(nb);
+ }
+ }
+ }
+ }
+ let mut post_coords: Vec<TileCoord> = post_set.into_iter().collect();
+ post_coords.sort_by_key(|c| (c.ty, c.tx));
+ let radius_px = (config.wet_edge_radius.round() as i32).clamp(1, 14);
+ let mut resolve_uniforms: Vec<CmixResolveUniforms> =
+ Vec::with_capacity(post_coords.len());
+ for &coord in &post_coords {
+ let Some(&center_slot) = self.pools.coord_to_slot.get(&coord) else {
+ continue;
+ };
+ let mut nb = [-1i32; 9];
+ for oy in -1..=1 {
+ for ox in -1..=1 {
+ let nc = TileCoord::new(coord.tx + ox, coord.ty + oy);
+ nb[((oy + 1) * 3 + (ox + 1)) as usize] = self
+ .pools
+ .coord_to_slot
+ .get(&nc)
+ .map(|&s| s as i32)
+ .unwrap_or(-1);
+ }
+ }
+ resolve_slots.push(center_slot);
+ resolve_uniforms.push(CmixResolveUniforms {
+ n0: [nb[0], nb[1], nb[2], nb[3]],
+ n1: [nb[4], nb[5], nb[6], nb[7]],
+ n2: [nb[8], radius_px, i32::from(alpha_lock), 1],
+ params: [
+ config.wet_edge.clamp(0.0, 1.0),
+ 1.0, // NaturalPaint already modulates capsule deposit alpha by config.opacity
+ config.wet_edge_alpha_power.clamp(0.0, 4.0),
+ config.wet_edge_value_power.clamp(0.0, 4.0),
+ ],
+ });
+ }
+ if !resolve_uniforms.is_empty() {
+ if ensure_dyn_uniform_buf(
+ device,
+ &mut self.cmix_resolve_uniform_buf,
+ &mut self.cmix_resolve_uniform_cap,
+ resolve_uniforms.len(),
+ "ink-np-cmix-resolve-uniforms-dyn",
+ ) {
+ self.cmix_resolve_uniform_gen = self.cmix_resolve_uniform_gen.saturating_add(1);
+ }
+ let rlen = resolve_uniforms.len() * stride;
+ self.cmix_resolve_staging.clear();
+ self.cmix_resolve_staging.resize(rlen, 0u8);
+ for (i, u) in resolve_uniforms.iter().enumerate() {
+ let src = bytemuck::bytes_of(u);
+ self.cmix_resolve_staging[i * stride..i * stride + src.len()]
+ .copy_from_slice(src);
+ }
+ queue.write_buffer(&self.cmix_resolve_uniform_buf, 0, &self.cmix_resolve_staging);
+
+ let rkey = (self.pools.atlas_gen, self.cmix_resolve_uniform_gen);
+ let base_view = self
+ .pools
+ .cmix_base
+ .as_ref()
+ .map(|b| &b.array_view)
+ .unwrap_or(&self.pools.dummy_rgba16f_array_view);
+ let cov_view = self.pools.cmix_cov_array_view();
+ if self
+ .cached_cmix_wet_h_bg
+ .as_ref()
+ .map(|(k, _)| *k != rkey)
+ .unwrap_or(true)
+ {
+ let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-np-cmix-wet-h-bg"),
+ layout: &self.cmix_resolve_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.cmix_resolve_uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(
+ std::mem::size_of::<CmixResolveUniforms>() as u64,
+ ),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(
+ &self.pools.color_array_view,
+ ),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(base_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::TextureView(cov_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 4,
+ resource: wgpu::BindingResource::TextureView(&self.dummy_2d_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 5,
+ resource: wgpu::BindingResource::TextureView(
+ &self.cmix_wet_padded_view,
+ ),
+ },
+ ],
+ });
+ self.cached_cmix_wet_h_bg = Some((rkey, bg));
+ }
+ if self
+ .cached_cmix_resolve_bg
+ .as_ref()
+ .map(|(k, _)| *k != rkey)
+ .unwrap_or(true)
+ {
+ let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-np-cmix-resolve-bg"),
+ layout: &self.cmix_resolve_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.cmix_resolve_uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(
+ std::mem::size_of::<CmixResolveUniforms>() as u64,
+ ),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(
+ &self.pools.color_array_view,
+ ),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(base_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::TextureView(cov_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 4,
+ resource: wgpu::BindingResource::TextureView(
+ &self.cmix_wet_padded_view,
+ ),
+ },
+ wgpu::BindGroupEntry {
+ binding: 5,
+ resource: wgpu::BindingResource::TextureView(
+ &self.pools.color_scratch_view,
+ ),
+ },
+ ],
+ });
+ self.cached_cmix_resolve_bg = Some((rkey, bg));
+ }
+ }
+ }
+
+ // 7. Encode Tile Inits + Pass 1 (Pickup) + ALL tiles' binned sub-rect Pass 2 (Raster + Impasto)
+ // + optional wet-edge resolve into ONE CommandEncoder + ONE queue.submit!
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-np-pickup-and-raster-batch-enc"),
+ });
+
+ self.pools
+ .encode_init_tiles_plan(device, tile_pool, &mut encoder, &init_plan);
+
+ let pickup_bg = &self
+ .cached_np_pickup_bg
+ .as_ref()
+ .expect("pickup_bg cached")
+ .1;
+ {
+ let mut cpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("ink-np-pickup-pass"),
+ timestamp_writes: None,
+ });
+ cpass.set_pipeline(&self.pickup_pipe);
+ cpass.set_bind_group(0, pickup_bg, &[]);
+ cpass.dispatch_workgroups(1, 1, 1); // 128 threads = all 64 bristles + 5 underbed slots in parallel!
+ }
+ self.total_compute_dispatches += 1;
+
+ if !raster_jobs.is_empty() {
+ if let Some((_, ref rbg)) = self.cached_np_raster_bg {
+ for (i, &(slot, rect)) in raster_jobs.iter().enumerate() {
+ let rw = rect[2] - rect[0];
+ let rh = rect[3] - rect[1];
+ let wg_x = rw.div_ceil(8);
+ let wg_y = rh.div_ceil(8);
+ let dyn_off = (i as u32) * (NP_UNIFORM_STRIDE as u32);
+ {
+ let mut cpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("ink-np-tile-raster-subrect-pass"),
+ timestamp_writes: None,
+ });
+ cpass.set_pipeline(&self.raster_pipe);
+ cpass.set_bind_group(0, rbg, &[dyn_off]);
+ cpass.dispatch_workgroups(wg_x, wg_y, 1);
+ }
+ self.pools.flush_scratch_subrect_to_slot(
+ &mut encoder,
+ slot,
+ rect[0],
+ rect[1],
+ rw,
+ rh,
+ impasto_enabled,
+ );
+ if track_cov {
+ self.pools.flush_cov_scratch_subrect_to_slot(
+ &mut encoder,
+ slot,
+ rect[0],
+ rect[1],
+ rw,
+ rh,
+ );
+ }
+ self.total_compute_dispatches += 1;
+ }
}
- self.pools
- .flush_scratch_to_slot(device, &mut tile_enc, slot, impasto_enabled);
- queue.submit(Some(tile_enc.finish()));
- self.total_compute_dispatches += 1;
}
+ if need_wet_resolve && !resolve_slots.is_empty() {
+ if let (Some((_, ref wh_bg)), Some((_, ref res_bg))) =
+ (self.cached_cmix_wet_h_bg.as_ref(), self.cached_cmix_resolve_bg.as_ref())
+ {
+ for (i, &slot) in resolve_slots.iter().enumerate() {
+ let dyn_off = (i as u32) * (NP_UNIFORM_STRIDE as u32);
+ {
+ let mut cpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("ink-np-wet-horiz"),
+ timestamp_writes: None,
+ });
+ cpass.set_pipeline(&self.cmix_wet_horiz_pipe);
+ cpass.set_bind_group(0, wh_bg, &[dyn_off]);
+ cpass.dispatch_workgroups(18, 18, 1);
+ }
+ {
+ let mut cpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("ink-np-wet-resolve"),
+ timestamp_writes: None,
+ });
+ cpass.set_pipeline(&self.cmix_resolve_pipe);
+ cpass.set_bind_group(0, res_bg, &[dyn_off]);
+ cpass.dispatch_workgroups(16, 16, 1);
+ }
+ self.pools
+ .flush_color_scratch_to_display_slot(&mut encoder, slot);
+ self.total_compute_dispatches += 1;
+ }
+ }
+ }
+
+ queue.submit(Some(encoder.finish()));
+ self.pools.unpin_init_plan(tile_pool, init_plan);
+
Some((min_x, min_y, max_x, max_y))
}
- /// Dispatches zero-readback GPU 16×16 `SpatialTipMixer` pickup + stamp deposition for
- /// non-bristle CSP `colorMixing` / watercolor / oil-blender / blur brushes!
+ /// Dispatches zero-readback GPU 16×16 `SpatialTipMixer` pickup + tight sub-rect `@workgroup_size(8,8,1)`
+ /// stamp deposition + optional single-pass opacity/wet-edge post-resolve for non-bristle CSP
+ /// `colorMixing` / watercolor / oil-blender / blur brushes in **ONE `CommandEncoder` + ONE `queue.submit`**!
#[allow(clippy::too_many_arguments)]
pub fn dispatch_color_mixing_dabs(
&mut self,
@@ -1754,6 +2841,12 @@ impl GpuNaturalPaintEngine {
dummy_paper_view: &wgpu::TextureView,
scratch: Option<&dyn ScratchBackend>,
selection: Option<&crate::selection::GpuSelectionOverlay>,
+ dual_secondary: Option<(
+ &wgpu::TextureView,
+ u64,
+ &HashMap<TileCoord, u32>,
+ DualBrushCompositeMode,
+ )>,
) -> Option<(f32, f32, f32, f32)> {
if !self.active || dabs.is_empty() {
return None;
@@ -1763,79 +2856,208 @@ impl GpuNaturalPaintEngine {
let mut max_x = f32::NEG_INFINITY;
let mut max_y = f32::NEG_INFINITY;
- let (tip_view, has_tip) = match tip_arr {
- Some(t) => (&t.view, 1u32),
- None => (dummy_tip_view, 0u32),
+ // 0. Adaptive micro-step coalescing when a fast frame emits >32 dabs so dense spacing
+ // never explodes into 250 serialized passes/frame while preserving smooth coverage & step_dist.
+ let mut active_dabs: Vec<(GpuBrushDab, f32)> = Vec::with_capacity(dabs.len().min(128));
+ let coalesce = dabs.len() > 32;
+ let extra_scale = if coalesce {
+ (dabs.len() as f32 / 48.0).clamp(1.0, 2.25)
+ } else {
+ 1.0
+ };
+ let mut prev_pos = self.last_cmix_dab_pos;
+ let last_idx = dabs.len() - 1;
+ for (i, &orig_dab) in dabs.iter().enumerate() {
+ let cx = orig_dab.pos_size[0];
+ let cy = orig_dab.pos_size[1];
+ let radius = orig_dab.pos_size[2].max(orig_dab.pos_size[3]).max(0.5);
+ let diam = (radius * 2.0).max(2.0);
+
+ if coalesce && i > 0 && i < last_idx {
+ if let Some([px, py]) = prev_pos {
+ let dist = (cx - px).hypot(cy - py);
+ let min_step = (radius * 0.08 * extra_scale).max(1.0);
+ if dist < min_step {
+ continue;
+ }
+ }
+ }
+
+ let step_dist = match prev_pos {
+ Some([px, py]) => (cx - px).hypot(cy - py),
+ None => diam * 0.25, // Initial dab calibrated at reference spacing 0.25
+ };
+ active_dabs.push((orig_dab, step_dist));
+ prev_pos = Some([cx, cy]);
+ }
+ self.last_cmix_dab_pos = prev_pos;
+ if active_dabs.is_empty() {
+ return None;
+ }
+
+ // 1. Collect all touched tiles & exact per-(dab, tile) clipped pixel sub-rects `[x0, y0, x1, y1]`
+ let mut all_touched: HashSet<TileCoord> = HashSet::new();
+ let mut dab_tile_rects: Vec<Vec<(TileCoord, [u32; 4])>> =
+ Vec::with_capacity(active_dabs.len());
+ for &(dab, _) in &active_dabs {
+ let (dx0, dy0, dx1, dy1) = dab.doc_bounds();
+ min_x = min_x.min(dx0);
+ min_y = min_y.min(dy0);
+ max_x = max_x.max(dx1);
+ max_y = max_y.max(dy1);
+
+ let tx0 = (dx0.floor() as i32).div_euclid(TILE_SIZE as i32);
+ let ty0 = (dy0.floor() as i32).div_euclid(TILE_SIZE as i32);
+ let tx1 = (dx1.ceil() as i32).div_euclid(TILE_SIZE as i32);
+ let ty1 = (dy1.ceil() as i32).div_euclid(TILE_SIZE as i32);
+ let mut rects = Vec::with_capacity(((tx1 - tx0 + 1) * (ty1 - ty0 + 1)).max(1) as usize);
+ for ty in ty0..=ty1 {
+ for tx in tx0..=tx1 {
+ let tile_ox = tx * TILE_SIZE as i32;
+ let tile_oy = ty * TILE_SIZE as i32;
+ let x0 = ((dx0.floor() as i32) - tile_ox).clamp(0, TILE_SIZE as i32) as u32;
+ let y0 = ((dy0.floor() as i32) - tile_oy).clamp(0, TILE_SIZE as i32) as u32;
+ let x1 = ((dx1.ceil() as i32) - tile_ox).clamp(0, TILE_SIZE as i32) as u32;
+ let y1 = ((dy1.ceil() as i32) - tile_oy).clamp(0, TILE_SIZE as i32) as u32;
+ if x0 >= x1 || y0 >= y1 {
+ continue;
+ }
+ let c = TileCoord::new(tx, ty);
+ all_touched.insert(c);
+ rects.push((c, [x0, y0, x1, y1]));
+ }
+ }
+ dab_tile_rects.push(rects);
+ }
+ if all_touched.is_empty() {
+ return None;
+ }
+
+ // 2. Prepare batched GPU tile initialization for all touched tiles ONCE
+ let mut touched_vec: Vec<TileCoord> = all_touched.into_iter().collect();
+ touched_vec.sort_by_key(|c| (c.ty, c.tx));
+ let init_plan = self.pools.prepare_init_tiles_batch(
+ device,
+ queue,
+ tile_pool,
+ doc,
+ active_layer,
+ &touched_vec,
+ config.mix_ground_color,
+ scratch,
+ );
+
+ // 3. Build O(1) dense bounding-box tile lookup grid for ALL active stroke tiles
+ // (1 indexed array load in WGSL, zero linear scan!)
+ let mut grid_min_tx = i32::MAX;
+ let mut grid_min_ty = i32::MAX;
+ let mut grid_max_tx = i32::MIN;
+ let mut grid_max_ty = i32::MIN;
+ for &coord in self.pools.coord_to_slot.keys() {
+ grid_min_tx = grid_min_tx.min(coord.tx);
+ grid_min_ty = grid_min_ty.min(coord.ty);
+ grid_max_tx = grid_max_tx.max(coord.tx);
+ grid_max_ty = grid_max_ty.max(coord.ty);
+ }
+ if grid_min_tx > grid_max_tx || grid_min_ty > grid_max_ty {
+ self.pools.unpin_init_plan(tile_pool, init_plan);
+ return None;
+ }
+ let grid_w = (grid_max_tx - grid_min_tx + 1).max(1);
+ let grid_h = (grid_max_ty - grid_min_ty + 1).max(1);
+ let grid_len = (grid_w as usize).saturating_mul(grid_h as usize);
+ if grid_len > self.cmix_tile_grid_cap {
+ let new_cap = grid_len.next_power_of_two().max(1024);
+ self.cmix_tile_grid_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-np-cmix-tile-grid"),
+ size: (new_cap * std::mem::size_of::<i32>()) as u64,
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ self.cmix_tile_grid_cap = new_cap;
+ self.cmix_tile_grid_gen = self.cmix_tile_grid_gen.saturating_add(1);
+ }
+ self.cmix_tile_grid_staging.clear();
+ self.cmix_tile_grid_staging.resize(grid_len, -1i32);
+ for (&coord, &slot) in &self.pools.coord_to_slot {
+ let gx = (coord.tx - grid_min_tx) as usize;
+ let gy = (coord.ty - grid_min_ty) as usize;
+ self.cmix_tile_grid_staging[gy * (grid_w as usize) + gx] = slot as i32;
+ }
+ queue.write_buffer(
+ &self.cmix_tile_grid_buf,
+ 0,
+ bytemuck::cast_slice(&self.cmix_tile_grid_staging),
+ );
+ let grid_info = [grid_min_tx, grid_min_ty, grid_w, grid_h];
+
+ let (tip_view, tip_id, has_tip, tip_layers) = match tip_arr {
+ Some(t) => (&t.view, t.id, 1u32, t.layer_count.max(1)),
+ None => (dummy_tip_view, 0u64, 0u32, 1u32),
};
- let (paper_view, has_paper) = match paper_tex {
- Some(p) if config.effective_grain_strength() > 0.005 => (&p.view, 1u32),
- _ => (dummy_paper_view, 0u32),
+ let (paper_view, paper_id, paper_size, has_paper) = match paper_tex {
+ Some(p) if config.effective_grain_strength() > 0.005 => (
+ &p.view,
+ p.id,
+ [p.width.max(1) as f32, p.height.max(1) as f32],
+ 1u32,
+ ),
+ _ => (dummy_paper_view, 0u64, [512.0, 512.0], 0u32),
};
let alpha_lock = active_layer.meta.alpha_locked.unwrap_or(false);
let active_sel = selection.filter(|s| s.is_active());
- let sel_atlas_view = active_sel
- .map(|s| s.atlas_view())
- .unwrap_or(&self.dummy_sel_view);
+ let (sel_atlas_view, sel_gen) = match active_sel {
+ Some(s) => (s.atlas_view(), s.atlas_gen()),
+ None => (&self.dummy_sel_view, 0u64),
+ };
let sel_default_f = active_sel.map(|s| s.default_alpha_f32()).unwrap_or(1.0);
+ let (dual_view, dual_gen, dual_map, dual_enabled, dual_mode_i) = match dual_secondary {
+ Some((v, g, map, mode)) => (v, g, Some(map), 1i32, mode.as_u32() as i32),
+ None => (&self.pools.dummy_rgba16f_array_view, 0u64, None, 0i32, 0i32),
+ };
let pigment_str = config.effective_pigment_strength();
let wetness = config
.natural_paint
.map(|n| n.wetness)
.unwrap_or((1.0 - config.amount_of_paint * 0.5).clamp(0.2, 0.95));
-
- for dab in dabs {
- let (x0, y0, x1, y1) = dab.doc_bounds();
- min_x = min_x.min(x0);
- min_y = min_y.min(y0);
- max_x = max_x.max(x1);
- max_y = max_y.max(y1);
-
- let tx0 = (x0.floor() as i32).div_euclid(TILE_SIZE as i32);
- let ty0 = (y0.floor() as i32).div_euclid(TILE_SIZE as i32);
- let tx1 = (x1.ceil() as i32).div_euclid(TILE_SIZE as i32);
- let ty1 = (y1.ceil() as i32).div_euclid(TILE_SIZE as i32);
-
- let mut dab_tiles = Vec::new();
- for ty in ty0..=ty1 {
- for tx in tx0..=tx1 {
- let coord = TileCoord::new(tx, ty);
- let slot = self.pools.ensure_tile_initialized(
- device,
- queue,
- tile_pool,
- doc,
- active_layer,
- coord,
- config.mix_ground_color,
- scratch,
- );
- dab_tiles.push((coord, slot));
- }
- }
- if dab_tiles.is_empty() {
+ let track_cov = self.pools.use_cmix_cov;
+ let need_post = self.pools.use_cmix_display;
+ let paper_offset_norm = [
+ config.paper_texture_offset_x / paper_size[0].max(1.0),
+ config.paper_texture_offset_y / paper_size[1].max(1.0),
+ ];
+
+ // Reuse pre-compiled sensor LUTs cached in `begin_stroke` (ZERO per-frame LUT rebuilds!)
+ let amount_luts = self.cached_amount_luts.as_ref();
+ let density_luts = self.cached_density_luts.as_ref();
+ let stretch_luts = self.cached_stretch_luts.as_ref();
+
+ // 4. Pack ALL dabs' pickup uniforms & tight sub-rect per-tile stamp uniforms
+ let mut pickup_uniforms: Vec<ColorMixPickupUniforms> =
+ Vec::with_capacity(active_dabs.len());
+ let mut stamp_uniforms: Vec<ColorMixTileUniforms> =
+ Vec::with_capacity(active_dabs.len() * 2);
+ let mut stamp_jobs: Vec<(u32, [u32; 4])> = Vec::with_capacity(active_dabs.len() * 2);
+ let mut dab_stamp_ranges: Vec<(usize, usize)> = Vec::with_capacity(active_dabs.len());
+ let mut batch_subrect_pixels: u64 = 0;
+ let mut batch_full_tile_pixels: u64 = 0;
+
+ for (&(dab, step_dist), rects) in active_dabs.iter().zip(dab_tile_rects.iter()) {
+ if rects.is_empty() {
continue;
}
-
- let lookup: Vec<TileLookupEntry> = dab_tiles
- .iter()
- .map(|&(coord, slot)| TileLookupEntry {
- tx: coord.tx,
- ty: coord.ty,
- slot: slot as i32,
- _pad: 0,
- })
- .collect();
- queue.write_buffer(&self.tile_lookup_buf, 0, bytemuck::cast_slice(&lookup));
-
let pressure = dab.extra[2].clamp(0.05, 1.0);
let angle_rad = dab.rot_tip[1].atan2(dab.rot_tip[0]);
+ let diam = (dab.pos_size[2].max(dab.pos_size[3]) * 2.0).max(2.0);
+ let step_ratio = (step_dist / diam).clamp(0.02, 1.0);
+ let step_norm = (step_ratio / 0.25).clamp(0.08, 2.5);
+
let eff_amount = config
.amount_of_paint_sensor
.as_ref()
.map(|s| {
- let luts = CompiledSensorLuts::from_sensor(Some(s));
config.amount_of_paint
- * evaluate_csp_sensor(s, Some(&luts), pressure, 0.0, 0.0, 0.0, 0.5)
+ * evaluate_csp_sensor(s, amount_luts, pressure, 0.0, 0.0, 0.0, 0.5)
})
.unwrap_or(config.amount_of_paint)
.clamp(0.0, 1.0);
@@ -1843,9 +3065,16 @@ impl GpuNaturalPaintEngine {
.density_of_paint_sensor
.as_ref()
.map(|s| {
- let luts = CompiledSensorLuts::from_sensor(Some(s));
config.density_of_paint
- * evaluate_csp_sensor(s, Some(&luts), pressure, 0.0, 0.0, 0.0, 0.5)
+ * evaluate_csp_sensor(
+ s,
+ density_luts,
+ pressure,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.5,
+ )
})
.unwrap_or(config.density_of_paint)
.clamp(0.01, 1.0);
@@ -1853,14 +3082,142 @@ impl GpuNaturalPaintEngine {
.color_stretch_sensor
.as_ref()
.map(|s| {
- let luts = CompiledSensorLuts::from_sensor(Some(s));
config.color_stretch
- * evaluate_csp_sensor(s, Some(&luts), pressure, 0.0, 0.0, 0.0, 0.5)
+ * evaluate_csp_sensor(
+ s,
+ stretch_luts,
+ pressure,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.5,
+ )
})
.unwrap_or(config.color_stretch)
.clamp(0.0, 1.0);
- let pick_u = ColorMixPickupUniforms {
+ let dab_grain = if dab.bg_grain[3] > 0.001 {
+ dab.bg_grain[3]
+ } else {
+ config.effective_grain_strength()
+ };
+ let flip_x = if dab.extra[0].abs() > 0.5 {
+ dab.extra[0]
+ } else {
+ 1.0
+ };
+ let flip_y = if dab.extra[1].abs() > 0.5 {
+ dab.extra[1]
+ } else {
+ 1.0
+ };
+
+ let stamp_start = stamp_uniforms.len();
+ for &(coord, rect) in rects {
+ let Some(&slot) = self.pools.coord_to_slot.get(&coord) else {
+ continue;
+ };
+ let sel_slot_f = match active_sel {
+ Some(s) => s.tile_slot(&coord).map(|v| v as f32).unwrap_or(-1.0),
+ None => -2.0,
+ };
+ let dual_slot_i = dual_map
+ .and_then(|m| m.get(&coord).copied())
+ .map(|s| s as i32)
+ .unwrap_or(-1);
+ let rw = rect[2] - rect[0];
+ let rh = rect[3] - rect[1];
+ batch_subrect_pixels += (rw as u64) * (rh as u64);
+ batch_full_tile_pixels += (TILE_SIZE as u64) * (TILE_SIZE as u64);
+
+ stamp_jobs.push((slot, rect));
+ stamp_uniforms.push(ColorMixTileUniforms {
+ tile_info: [
+ (coord.tx * TILE_SIZE as i32) as f32,
+ (coord.ty * TILE_SIZE as i32) as f32,
+ slot as f32,
+ if alpha_lock { 1.0 } else { 0.0 },
+ ],
+ stamp_pos: [
+ dab.pos_size[0],
+ dab.pos_size[1],
+ dab.pos_size[2].max(0.5),
+ dab.pos_size[3].max(0.5),
+ ],
+ geom: [
+ angle_rad,
+ dab.rot_tip[3].clamp(0.0, 1.0),
+ dab.color_rgba[3].clamp(0.01, 1.0),
+ eff_density,
+ ],
+ fx0: [
+ pigment_str,
+ if config.use_blur {
+ config.blur_strength.clamp(0.0, 1.0)
+ } else {
+ 0.0
+ },
+ dab_grain,
+ config.paper_texture_scale.clamp(0.05, 10.0),
+ ],
+ fx1: [
+ config.paper_texture_rotate.to_radians(),
+ dab.rot_tip[2],
+ pressure,
+ dab.extra[3],
+ ],
+ paper0: [
+ paper_size[0],
+ paper_size[1],
+ paper_offset_norm[0],
+ paper_offset_norm[1],
+ ],
+ paper1: [
+ self.stroke_rand_offset[0],
+ self.stroke_rand_offset[1],
+ config.paper_texture_brightness,
+ config.paper_texture_contrast,
+ ],
+ bg_amount: [
+ dab.bg_grain[0],
+ dab.bg_grain[1],
+ dab.bg_grain[2],
+ eff_amount,
+ ],
+ flip_sel: [flip_x, flip_y, sel_slot_f, sel_default_f],
+ rect,
+ flags0: [
+ has_tip,
+ has_paper,
+ u32::from(config.use_blur),
+ config.anti_alias.min(3) as u32,
+ ],
+ flags1: [
+ config.paper_texture_mode.as_u32(),
+ config.grain_mapping_mode.as_u32(),
+ u32::from(config.paper_texture_invert),
+ u32::from(config.emphasize_density),
+ ],
+ flags2: [
+ u32::from(config.is_color_tip),
+ u32::from(config.is_dual_tone_tip),
+ tip_layers,
+ u32::from(track_cov),
+ ],
+ dual_info: [
+ dual_enabled,
+ dual_slot_i,
+ dual_mode_i,
+ config.mixing_mode.as_u32() as i32,
+ ],
+ step_info: [step_norm, 0.0, 0.0, 0.0],
+ });
+ }
+ let stamp_count = stamp_uniforms.len() - stamp_start;
+ if stamp_count == 0 {
+ continue;
+ }
+ pickup_uniforms.push(ColorMixPickupUniforms {
stamp_pos: [
dab.pos_size[0],
dab.pos_size[1],
@@ -1882,12 +3239,12 @@ impl GpuNaturalPaintEngine {
0.0
},
pressure,
- dab.color_rgba[3].clamp(0.01, 1.0),
+ step_norm,
],
flags0: [
config.mixing_mode.as_u32(),
u32::from(config.mix_ground_color),
- lookup.len() as u32,
+ 0,
u32::from(config.use_blur),
],
flags1: [
@@ -1896,26 +3253,97 @@ impl GpuNaturalPaintEngine {
dab.rot_tip[2].max(0.0) as u32,
0,
],
- };
- queue.write_buffer(&self.cmix_pickup_uniform_buf, 0, bytemuck::bytes_of(&pick_u));
+ grid_info,
+ });
+ dab_stamp_ranges.push((stamp_start, stamp_count));
+ }
- let (tip_buf, _) = self.dirty_bank.acquire_tip_mixer_buffer(
- device,
- queue,
- &self.active_preset_key,
- config.fg_color,
- eff_amount,
- wetness,
- false,
- );
+ if pickup_uniforms.is_empty() {
+ self.pools.unpin_init_plan(tile_pool, init_plan);
+ return None;
+ }
+
+ self.cmix_last_batch_subrect_pixels = batch_subrect_pixels;
+ self.cmix_last_batch_full_tile_pixels = batch_full_tile_pixels;
+ self.cmix_total_subrect_pixels += batch_subrect_pixels;
+ self.cmix_total_full_tile_pixels += batch_full_tile_pixels;
+ self.cmix_last_batch_dispatched_dabs = pickup_uniforms.len();
- let pick_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ if ensure_dyn_uniform_buf(
+ device,
+ &mut self.cmix_pickup_uniform_buf,
+ &mut self.cmix_pickup_uniform_cap,
+ pickup_uniforms.len(),
+ "ink-np-cmix-pickup-uniforms-dyn",
+ ) {
+ self.cmix_pickup_uniform_gen = self.cmix_pickup_uniform_gen.saturating_add(1);
+ }
+ if ensure_dyn_uniform_buf(
+ device,
+ &mut self.cmix_stamp_uniform_buf,
+ &mut self.cmix_stamp_uniform_cap,
+ stamp_uniforms.len(),
+ "ink-np-cmix-stamp-uniforms-dyn",
+ ) {
+ self.cmix_stamp_uniform_gen = self.cmix_stamp_uniform_gen.saturating_add(1);
+ }
+
+ // Pack into persistent scratch Vec<u8> buffers (ZERO per-frame heap allocations!)
+ let stride = NP_UNIFORM_STRIDE as usize;
+ let pick_len = pickup_uniforms.len() * stride;
+ self.cmix_pick_staging.clear();
+ self.cmix_pick_staging.resize(pick_len, 0u8);
+ for (i, u) in pickup_uniforms.iter().enumerate() {
+ let src = bytemuck::bytes_of(u);
+ self.cmix_pick_staging[i * stride..i * stride + src.len()].copy_from_slice(src);
+ }
+ queue.write_buffer(&self.cmix_pickup_uniform_buf, 0, &self.cmix_pick_staging);
+
+ let stamp_len = stamp_uniforms.len() * stride;
+ self.cmix_stamp_staging.clear();
+ self.cmix_stamp_staging.resize(stamp_len, 0u8);
+ for (i, u) in stamp_uniforms.iter().enumerate() {
+ let src = bytemuck::bytes_of(u);
+ self.cmix_stamp_staging[i * stride..i * stride + src.len()].copy_from_slice(src);
+ }
+ queue.write_buffer(&self.cmix_stamp_uniform_buf, 0, &self.cmix_stamp_staging);
+
+ let (tip_buf, tip_buf_id, _) = self.dirty_bank.acquire_tip_mixer_buffer_with_id(
+ device,
+ queue,
+ &self.active_preset_key,
+ config.fg_color,
+ config.amount_of_paint,
+ wetness,
+ false,
+ );
+
+ // Cached BindGroups keyed by resource generations/IDs (ZERO BindGroup churn on consecutive frames!)
+ let pick_key = (
+ self.pools.atlas_gen,
+ self.cmix_pickup_uniform_gen,
+ self.cmix_tile_grid_gen,
+ tip_buf_id,
+ );
+ let rebuild_pick = self
+ .cached_cmix_pick_bg
+ .as_ref()
+ .map(|(k, _)| *k != pick_key)
+ .unwrap_or(true);
+ if rebuild_pick {
+ let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("ink-np-cmix-pickup-bg"),
layout: &self.cmix_pickup_bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
- resource: self.cmix_pickup_uniform_buf.as_entire_binding(),
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.cmix_pickup_uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(
+ std::mem::size_of::<ColorMixPickupUniforms>() as u64,
+ ),
+ }),
},
wgpu::BindGroupEntry {
binding: 1,
@@ -1927,7 +3355,7 @@ impl GpuNaturalPaintEngine {
},
wgpu::BindGroupEntry {
binding: 3,
- resource: self.tile_lookup_buf.as_entire_binding(),
+ resource: self.cmix_tile_grid_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 4,
@@ -1935,134 +3363,387 @@ impl GpuNaturalPaintEngine {
},
],
});
+ self.cached_cmix_pick_bg = Some((pick_key, bg));
+ self.cmix_bind_group_rebuilds += 1;
+ }
- let mut pick_enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-np-cmix-pickup-enc"),
+ let stamp_key = (
+ self.pools.atlas_gen,
+ self.cmix_stamp_uniform_gen,
+ tip_id,
+ paper_id,
+ tip_buf_id,
+ sel_gen,
+ dual_gen,
+ );
+ let rebuild_stamp = self
+ .cached_cmix_stamp_bg
+ .as_ref()
+ .map(|(k, _)| *k != stamp_key)
+ .unwrap_or(true);
+ if rebuild_stamp {
+ let cov_view = self.pools.cmix_cov_array_view();
+ let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-np-cmix-stamp-bg"),
+ layout: &self.cmix_stamp_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.cmix_stamp_uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(
+ std::mem::size_of::<ColorMixTileUniforms>() as u64,
+ ),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(&self.pools.color_array_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(tip_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::Sampler(&self.cmix_tip_sampler),
+ },
+ wgpu::BindGroupEntry {
+ binding: 4,
+ resource: wgpu::BindingResource::TextureView(paper_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 5,
+ resource: wgpu::BindingResource::Sampler(&self.cmix_paper_sampler),
+ },
+ wgpu::BindGroupEntry {
+ binding: 6,
+ resource: tip_buf.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 7,
+ resource: wgpu::BindingResource::TextureView(&self.pools.color_scratch_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 8,
+ resource: wgpu::BindingResource::TextureView(sel_atlas_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 9,
+ resource: wgpu::BindingResource::TextureView(dual_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 10,
+ resource: wgpu::BindingResource::TextureView(cov_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 11,
+ resource: wgpu::BindingResource::TextureView(
+ &self.pools.cmix_cov_scratch_view,
+ ),
+ },
+ ],
});
+ self.cached_cmix_stamp_bg = Some((stamp_key, bg));
+ self.cmix_bind_group_rebuilds += 1;
+ }
+
+ // Prepare optional once-per-frame post-resolve (opacity cap + watercolor wet edge)
+ let mut resolve_slots: Vec<u32> = Vec::new();
+ if need_post {
+ let mut post_set: HashSet<TileCoord> = HashSet::with_capacity(touched_vec.len() * 2);
+ if track_cov {
+ for &c in &touched_vec {
+ for dy in -1..=1 {
+ for dx in -1..=1 {
+ let nb = TileCoord::new(c.tx + dx, c.ty + dy);
+ if self.pools.coord_to_slot.contains_key(&nb) {
+ post_set.insert(nb);
+ }
+ }
+ }
+ }
+ } else {
+ for &c in &touched_vec {
+ if self.pools.coord_to_slot.contains_key(&c) {
+ post_set.insert(c);
+ }
+ }
+ }
+
+ let mut post_coords: Vec<TileCoord> = post_set.into_iter().collect();
+ post_coords.sort_by_key(|c| (c.ty, c.tx));
+ let radius_px = (config.wet_edge_radius.round() as i32).clamp(1, 14);
+ let mut resolve_uniforms: Vec<CmixResolveUniforms> =
+ Vec::with_capacity(post_coords.len());
+ for &coord in &post_coords {
+ let Some(&center_slot) = self.pools.coord_to_slot.get(&coord) else {
+ continue;
+ };
+ let mut nb = [-1i32; 9];
+ if track_cov {
+ for oy in -1..=1 {
+ for ox in -1..=1 {
+ let nc = TileCoord::new(coord.tx + ox, coord.ty + oy);
+ nb[((oy + 1) * 3 + (ox + 1)) as usize] = self
+ .pools
+ .coord_to_slot
+ .get(&nc)
+ .map(|&s| s as i32)
+ .unwrap_or(-1);
+ }
+ }
+ } else {
+ nb[4] = center_slot as i32;
+ }
+ resolve_slots.push(center_slot);
+ resolve_uniforms.push(CmixResolveUniforms {
+ n0: [nb[0], nb[1], nb[2], nb[3]],
+ n1: [nb[4], nb[5], nb[6], nb[7]],
+ n2: [nb[8], radius_px, i32::from(alpha_lock), i32::from(track_cov)],
+ params: [
+ config.wet_edge.clamp(0.0, 1.0),
+ config.opacity.clamp(0.0, 1.0),
+ config.wet_edge_alpha_power.clamp(0.0, 4.0),
+ config.wet_edge_value_power.clamp(0.0, 4.0),
+ ],
+ });
+ }
+
+ if !resolve_uniforms.is_empty() {
+ if ensure_dyn_uniform_buf(
+ device,
+ &mut self.cmix_resolve_uniform_buf,
+ &mut self.cmix_resolve_uniform_cap,
+ resolve_uniforms.len(),
+ "ink-np-cmix-resolve-uniforms-dyn",
+ ) {
+ self.cmix_resolve_uniform_gen = self.cmix_resolve_uniform_gen.saturating_add(1);
+ }
+ let rlen = resolve_uniforms.len() * stride;
+ self.cmix_resolve_staging.clear();
+ self.cmix_resolve_staging.resize(rlen, 0u8);
+ for (i, u) in resolve_uniforms.iter().enumerate() {
+ let src = bytemuck::bytes_of(u);
+ self.cmix_resolve_staging[i * stride..i * stride + src.len()]
+ .copy_from_slice(src);
+ }
+ queue.write_buffer(&self.cmix_resolve_uniform_buf, 0, &self.cmix_resolve_staging);
+
+ let rkey = (self.pools.atlas_gen, self.cmix_resolve_uniform_gen);
+ let base_view = self
+ .pools
+ .cmix_base
+ .as_ref()
+ .map(|b| &b.array_view)
+ .unwrap_or(&self.pools.dummy_rgba16f_array_view);
+ let cov_view = self.pools.cmix_cov_array_view();
+ if track_cov
+ && self
+ .cached_cmix_wet_h_bg
+ .as_ref()
+ .map(|(k, _)| *k != rkey)
+ .unwrap_or(true)
+ {
+ let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-np-cmix-wet-h-bg"),
+ layout: &self.cmix_resolve_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.cmix_resolve_uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(
+ std::mem::size_of::<CmixResolveUniforms>() as u64,
+ ),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(
+ &self.pools.color_array_view,
+ ),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(base_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::TextureView(cov_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 4,
+ resource: wgpu::BindingResource::TextureView(&self.dummy_2d_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 5,
+ resource: wgpu::BindingResource::TextureView(
+ &self.cmix_wet_padded_view,
+ ),
+ },
+ ],
+ });
+ self.cached_cmix_wet_h_bg = Some((rkey, bg));
+ }
+ if self
+ .cached_cmix_resolve_bg
+ .as_ref()
+ .map(|(k, _)| *k != rkey)
+ .unwrap_or(true)
+ {
+ let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-np-cmix-resolve-bg"),
+ layout: &self.cmix_resolve_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.cmix_resolve_uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(
+ std::mem::size_of::<CmixResolveUniforms>() as u64,
+ ),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(
+ &self.pools.color_array_view,
+ ),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(base_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::TextureView(cov_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 4,
+ resource: wgpu::BindingResource::TextureView(
+ &self.cmix_wet_padded_view,
+ ),
+ },
+ wgpu::BindGroupEntry {
+ binding: 5,
+ resource: wgpu::BindingResource::TextureView(
+ &self.pools.color_scratch_view,
+ ),
+ },
+ ],
+ });
+ self.cached_cmix_resolve_bg = Some((rkey, bg));
+ }
+ }
+ }
+
+ // 5. Encode Tile Inits + ALL dabs' Pickup & Tight Sub-Rect Stamp passes (+ optional Post-Resolve)
+ // into ONE CommandEncoder + ONE queue.submit!
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-np-cmix-batch-enc"),
+ });
+
+ self.pools
+ .encode_init_tiles_plan(device, tile_pool, &mut encoder, &init_plan);
+
+ let pick_bg = &self.cached_cmix_pick_bg.as_ref().expect("pick_bg cached").1;
+ let stamp_bg = &self
+ .cached_cmix_stamp_bg
+ .as_ref()
+ .expect("stamp_bg cached")
+ .1;
+
+ for (dab_idx, &(stamp_start, stamp_count)) in dab_stamp_ranges.iter().enumerate() {
+ let pick_off = (dab_idx as u32) * (NP_UNIFORM_STRIDE as u32);
{
- let mut cpass = pick_enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ let mut cpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("ink-np-cmix-pickup-pass"),
timestamp_writes: None,
});
cpass.set_pipeline(&self.cmix_pickup_pipe);
- cpass.set_bind_group(0, &pick_bg, &[]);
+ cpass.set_bind_group(0, pick_bg, &[pick_off]);
cpass.dispatch_workgroups(1, 1, 1); // 16×16 spatial tip cells!
}
- queue.submit(Some(pick_enc.finish()));
self.total_compute_dispatches += 1;
- for &(coord, slot) in &dab_tiles {
- let sel_slot_f = match active_sel {
- Some(s) => s.tile_slot(&coord).map(|v| v as f32).unwrap_or(-1.0),
- None => -2.0,
- };
- let stamp_u = ColorMixTileUniforms {
- tile_info: [
- (coord.tx * TILE_SIZE as i32) as f32,
- (coord.ty * TILE_SIZE as i32) as f32,
- slot as f32,
- if alpha_lock { 1.0 } else { 0.0 },
- ],
- stamp_pos: [
- dab.pos_size[0],
- dab.pos_size[1],
- dab.pos_size[2].max(0.5),
- dab.pos_size[3].max(0.5),
- ],
- geom: [
- angle_rad,
- dab.rot_tip[3].clamp(0.0, 1.0),
- dab.color_rgba[3].clamp(0.01, 1.0),
- eff_density,
- ],
- fx0: [
- pigment_str,
- if config.use_blur {
- config.blur_strength.clamp(0.0, 1.0)
- } else {
- 0.0
- },
- config.effective_grain_strength(),
- config.paper_texture_scale.max(0.05),
- ],
- fx1: [
- config.paper_texture_rotate.to_radians(),
- dab.rot_tip[2],
- config.anti_alias as f32,
- if config.mixing_mode == NaturalMixingMode::Smear {
- 1.0
- } else {
- 0.0
- },
- ],
- flags: [
- has_tip,
- has_paper,
- u32::from(config.use_blur),
- config.mixing_mode.as_u32(),
- ],
- sel_info: [sel_slot_f, sel_default_f, 0.0, 0.0],
- };
- queue.write_buffer(&self.cmix_stamp_uniform_buf, 0, bytemuck::bytes_of(&stamp_u));
-
- let stamp_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-np-cmix-stamp-bg"),
- layout: &self.cmix_stamp_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: self.cmix_stamp_uniform_buf.as_entire_binding(),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(
- &self.pools.color_array_view,
- ),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::TextureView(tip_view),
- },
- wgpu::BindGroupEntry {
- binding: 3,
- resource: wgpu::BindingResource::TextureView(paper_view),
- },
- wgpu::BindGroupEntry {
- binding: 4,
- resource: tip_buf.as_entire_binding(),
- },
- wgpu::BindGroupEntry {
- binding: 5,
- resource: wgpu::BindingResource::TextureView(
- &self.pools.color_scratch_view,
- ),
- },
- wgpu::BindGroupEntry {
- binding: 6,
- resource: wgpu::BindingResource::TextureView(sel_atlas_view),
- },
- ],
- });
-
- let mut st_enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-np-cmix-stamp-enc"),
- });
+ for s_idx in stamp_start..(stamp_start + stamp_count) {
+ let (slot, rect) = stamp_jobs[s_idx];
+ let rw = rect[2] - rect[0];
+ let rh = rect[3] - rect[1];
+ let wg_x = rw.div_ceil(8);
+ let wg_y = rh.div_ceil(8);
+ let st_off = (s_idx as u32) * (NP_UNIFORM_STRIDE as u32);
{
- let mut cpass = st_enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
- label: Some("ink-np-cmix-stamp-pass"),
+ let mut cpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("ink-np-cmix-stamp-subrect-pass"),
timestamp_writes: None,
});
cpass.set_pipeline(&self.cmix_stamp_pipe);
- cpass.set_bind_group(0, &stamp_bg, &[]);
- cpass.dispatch_workgroups(16, 16, 1);
+ cpass.set_bind_group(0, stamp_bg, &[st_off]);
+ cpass.dispatch_workgroups(wg_x, wg_y, 1);
+ }
+ self.pools.flush_color_scratch_subrect_to_slot(
+ &mut encoder,
+ slot,
+ rect[0],
+ rect[1],
+ rw,
+ rh,
+ );
+ if track_cov {
+ self.pools.flush_cov_scratch_subrect_to_slot(
+ &mut encoder,
+ slot,
+ rect[0],
+ rect[1],
+ rw,
+ rh,
+ );
}
- self.pools
- .flush_scratch_to_slot(device, &mut st_enc, slot, false);
- queue.submit(Some(st_enc.finish()));
self.total_compute_dispatches += 1;
}
}
+ // Optional once-per-frame opacity-cap / watercolor wet-edge post-resolve into cmix_display
+ if need_post && !resolve_slots.is_empty() {
+ if let Some((_, ref res_bg)) = self.cached_cmix_resolve_bg {
+ for (i, &slot) in resolve_slots.iter().enumerate() {
+ let dyn_off = (i as u32) * (NP_UNIFORM_STRIDE as u32);
+ if track_cov {
+ if let Some((_, ref wh_bg)) = self.cached_cmix_wet_h_bg {
+ let mut cpass =
+ encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("ink-np-cmix-wet-horiz"),
+ timestamp_writes: None,
+ });
+ cpass.set_pipeline(&self.cmix_wet_horiz_pipe);
+ cpass.set_bind_group(0, wh_bg, &[dyn_off]);
+ cpass.dispatch_workgroups(18, 18, 1);
+ }
+ }
+ {
+ let mut cpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("ink-np-cmix-resolve"),
+ timestamp_writes: None,
+ });
+ cpass.set_pipeline(&self.cmix_resolve_pipe);
+ cpass.set_bind_group(0, res_bg, &[dyn_off]);
+ cpass.dispatch_workgroups(16, 16, 1);
+ }
+ self.pools
+ .flush_color_scratch_to_display_slot(&mut encoder, slot);
+ self.total_compute_dispatches += 1;
+ }
+ }
+ }
+
+ queue.submit(Some(encoder.finish()));
+ self.pools.unpin_init_plan(tile_pool, init_plan);
+
if min_x.is_finite() {
Some((min_x, min_y, max_x, max_y))
} else {
@@ -2080,6 +3761,7 @@ impl GpuNaturalPaintEngine {
) -> Result<CommittedNaturalPaintBatch, String> {
self.active = false;
self.active_has_impasto = false;
+ self.last_cmix_dab_pos = None;
let doc_id = self.active_doc_id.clone();
let layer_id = self.active_layer_id.clone();
self.pools
@@ -2089,7 +3771,10 @@ impl GpuNaturalPaintEngine {
/// Returns `(color_array_view, coord_to_slot)` for live viewport overlay projection!
#[inline]
pub fn active_color_atlas(&self) -> (&wgpu::TextureView, &HashMap<TileCoord, u32>) {
- (&self.pools.color_array_view, &self.pools.coord_to_slot)
+ (
+ self.pools.active_display_color_view(),
+ &self.pools.coord_to_slot,
+ )
}
/// Returns `(height_array_view, coord_to_slot)` for live 120 FPS impasto relief lighting!
@@ -2101,6 +3786,9 @@ impl GpuNaturalPaintEngine {
/// Explicitly cleans one preset's or all presets' persistent dirty GPU brush reservoirs.
pub fn clean_dirty_brush(&mut self, preset_key: Option<&str>) {
self.dirty_bank.clean(preset_key);
+ self.cached_np_pickup_bg = None;
+ self.cached_cmix_pick_bg = None;
+ self.cached_cmix_stamp_bg = None;
}
/// Test helper: reads back the 64 GPU bristle slots for `preset_key`.
@@ -2128,6 +3816,40 @@ fn uniform_compute_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
}
}
+fn dyn_uniform_compute_entry(binding: u32, size_bytes: usize) -> wgpu::BindGroupLayoutEntry {
+ wgpu::BindGroupLayoutEntry {
+ binding,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: true,
+ min_binding_size: NonZeroU64::new(size_bytes as u64),
+ },
+ count: None,
+ }
+}
+
+fn ensure_dyn_uniform_buf(
+ device: &wgpu::Device,
+ buf: &mut wgpu::Buffer,
+ cap: &mut usize,
+ needed: usize,
+ label: &str,
+) -> bool {
+ if needed <= *cap {
+ return false;
+ }
+ let new_cap = needed.next_power_of_two().max(64);
+ *buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some(label),
+ size: new_cap as u64 * NP_UNIFORM_STRIDE,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ *cap = new_cap;
+ true
+}
+
fn storage_compute_entry(binding: u32, read_only: bool) -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry {
binding,
@@ -2141,6 +3863,15 @@ fn storage_compute_entry(binding: u32, read_only: bool) -> wgpu::BindGroupLayout
}
}
+fn sampler_compute_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
+ wgpu::BindGroupLayoutEntry {
+ binding,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
+ count: None,
+ }
+}
+
fn tex_2d_compute_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry {
binding,
@@ -2154,6 +3885,19 @@ fn tex_2d_compute_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
}
}
+fn tex_2d_filterable_compute_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
+ wgpu::BindGroupLayoutEntry {
+ binding,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Texture {
+ sample_type: wgpu::TextureSampleType::Float { filterable: true },
+ view_dimension: wgpu::TextureViewDimension::D2,
+ multisampled: false,
+ },
+ count: None,
+ }
+}
+
fn tex_array_compute_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry {
binding,
@@ -2167,6 +3911,19 @@ fn tex_array_compute_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
}
}
+fn tex_array_filterable_compute_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
+ wgpu::BindGroupLayoutEntry {
+ binding,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Texture {
+ sample_type: wgpu::TextureSampleType::Float { filterable: true },
+ view_dimension: wgpu::TextureViewDimension::D2Array,
+ multisampled: false,
+ },
+ count: None,
+ }
+}
+
fn storage_tex_compute_entry(
binding: u32,
format: wgpu::TextureFormat,
diff --git a/crates/ink-engine/src/natural_paint/pigment.rs b/crates/ink-engine/src/natural_paint/pigment.rs
index d211c79..ab66b58 100644
--- a/crates/ink-engine/src/natural_paint/pigment.rs
+++ b/crates/ink-engine/src/natural_paint/pigment.rs
@@ -18,6 +18,9 @@ use std::collections::HashMap;
pub const SPECTRAL_BANDS: usize = 8;
pub const SPECTRAL_STATE_SIZE: usize = 12;
pub const MAX_BRISTLES: usize = 64;
+pub const UNDERBED_BANDS: usize = 5;
+pub const UNDERBED_SLOT_BASE: usize = MAX_BRISTLES;
+pub const TOTAL_BRISTLE_SLOTS: usize = MAX_BRISTLES + UNDERBED_BANDS;
pub const SPATIAL_TIP_GRID: usize = 16;
pub const SPATIAL_TIP_CELLS: usize = SPATIAL_TIP_GRID * SPATIAL_TIP_GRID;
@@ -506,6 +509,94 @@ fn composite_pigment_over(dst_rgba: vec4<f32>, src_rgba: vec4<f32>, strength: f3
let mixed = mix_pigments_srgb(dst_rgba.rgb, src_rgba.rgb, t, strength);
return vec4<f32>(mixed, out_a);
}
+
+/// Fast vectorized 4-band Kubelka-Munk subtractive pigment blend (ZERO `pow()` calls per pixel!).
+/// Uses hardware `sqrt`/`inverseSqrt` with a 4th blue-green spectral overlap band + exact residual
+/// cancellation, preserving vivid Blue+Yellow -> Green, luminous Dark Blue+White -> Cerulean,
+/// self-mix invariance, and strict Black+White achromatic neutrality at ~10x the throughput of
+/// full 8-band `mix_pigments_srgb` in per-pixel stamp deposition loops.
+fn srgb_to_lin_fast(c: vec3<f32>) -> vec3<f32> {
+ let v = clamp(c, vec3<f32>(0.0), vec3<f32>(1.0));
+ return v * (v * (v * 0.305306011 + 0.682171111) + 0.012522878);
+}
+
+fn lin_to_srgb_fast(x: vec3<f32>) -> vec3<f32> {
+ let c = clamp(x, vec3<f32>(0.0), vec3<f32>(1.0));
+ let s1 = sqrt(c);
+ let s2 = sqrt(s1);
+ let s3 = sqrt(s2);
+ return clamp(0.585122381 * s1 + 0.783140355 * s2 - 0.368262736 * s3, vec3<f32>(0.0), vec3<f32>(1.0));
+}
+
+fn mix_pigments_fast_srgb(c1: vec3<f32>, c2: vec3<f32>, t: f32, strength: f32) -> vec3<f32> {
+ let ct = clamp(t, 0.0, 1.0);
+ let lin = mix(c1, c2, ct);
+ let s = clamp(strength, 0.0, 1.0);
+ if (s <= 0.005 || ct <= 0.0001 || ct >= 0.9999) {
+ return lin;
+ }
+ let ch1 = max(max(c1.r, c1.g), c1.b) - min(min(c1.r, c1.g), c1.b);
+ let ch2 = max(max(c2.r, c2.g), c2.b) - min(min(c2.r, c2.g), c2.b);
+ let max_ch = max(ch1, ch2);
+ if (max_ch <= 0.004) {
+ return lin;
+ }
+
+ let l1 = srgb_to_lin_fast(c1);
+ let l2 = srgb_to_lin_fast(c2);
+ let r1 = clamp(l1, vec3<f32>(0.003), vec3<f32>(0.999));
+ let r2 = clamp(l2, vec3<f32>(0.003), vec3<f32>(0.999));
+
+ // 4th spectral band models blue-green reflectance overlap (matching 8-band KM's B_B[3]/B_Y[3])
+ let bg1 = clamp(r1.g * 0.62 + r1.b * 0.38, 0.003, 0.999);
+ let bg2 = clamp(r2.g * 0.62 + r2.b * 0.38, 0.003, 0.999);
+ let v1 = vec4<f32>(r1, bg1);
+ let v2 = vec4<f32>(r2, bg2);
+
+ // Two-constant bulk scattering estimate (sqrt only, zero cbrt/pow)
+ let lum1 = dot(l1, vec3<f32>(0.2126, 0.7152, 0.0722));
+ let lum2 = dot(l2, vec3<f32>(0.2126, 0.7152, 0.0722));
+ let min1 = min(min(l1.r, l1.g), l1.b);
+ let min2 = min(min(l2.r, l2.g), l2.b);
+ let max1 = max(max(l1.r, l1.g), l1.b);
+ let max2 = max(max(l2.r, l2.g), l2.b);
+ let sc1 = 0.04 + 0.14 * sqrt(max(lum1, 0.0)) + 0.64 * sqrt(max(max1, 0.0)) + 0.18 * sqrt(max(min1, 0.0));
+ let sc2 = 0.04 + 0.14 * sqrt(max(lum2, 0.0)) + 0.64 * sqrt(max(max2, 0.0)) + 0.18 * sqrt(max(min2, 0.0));
+ let inv_t = 1.0 - ct;
+ let w1 = (inv_t * sc1) / max(1e-6, inv_t * sc1 + ct * sc2);
+ let w2 = 1.0 - w1;
+
+ // Vectorized 4-band Kubelka-Munk via sqrt(K/S) = (1 - R) / sqrt(2R)
+ let u1 = (vec4<f32>(1.0) - v1) * inverseSqrt(2.0 * v1);
+ let u2 = (vec4<f32>(1.0) - v2) * inverseSqrt(2.0 * v2);
+ let um = max(vec4<f32>(0.0), u1 * w1 + u2 * w2);
+ let ks = um * um;
+ let vm = vec4<f32>(1.0) + ks - sqrt(ks * ks + 2.0 * ks);
+
+ // Exact residual reconstruction on green so self-mix is identity and neutral grays stay neutral
+ let res_g1 = r1.g - (r1.g * 0.72 + bg1 * 0.28);
+ let res_g2 = r2.g - (r2.g * 0.72 + bg2 * 0.28);
+ let out_lin = vec3<f32>(
+ vm.x + (l1.r - r1.r) * inv_t + (l2.r - r2.r) * ct,
+ vm.y * 0.72 + vm.w * 0.28 + res_g1 * inv_t + res_g2 * ct + (l1.g - r1.g) * inv_t + (l2.g - r2.g) * ct,
+ vm.z + (l1.b - r1.b) * inv_t + (l2.b - r2.b) * ct,
+ );
+ let pig = lin_to_srgb_fast(out_lin);
+ let eff_s = s * smoothstep(0.004, 0.032, max_ch);
+ return mix(lin, pig, eff_s);
+}
+
+fn composite_pigment_over_fast(dst_rgba: vec4<f32>, src_rgba: vec4<f32>, strength: f32) -> vec4<f32> {
+ let sa = clamp(src_rgba.a, 0.0, 1.0);
+ if (sa <= 1e-5) { return dst_rgba; }
+ let da = clamp(dst_rgba.a, 0.0, 1.0);
+ if (da <= 1e-5) { return vec4<f32>(src_rgba.rgb, sa); }
+ let out_a = sa + da * (1.0 - sa);
+ if (out_a <= 1e-5) { return vec4<f32>(0.0); }
+ let t = clamp(sa / out_a, 0.0, 1.0);
+ let mixed = mix_pigments_fast_srgb(dst_rgba.rgb, src_rgba.rgb, t, strength);
+ return vec4<f32>(mixed, out_a);
+}
"#;
// ============================================================================
@@ -550,10 +641,12 @@ pub struct GpuSpatialTipCell {
/// Persistent GPU VRAM bank storing per-preset `BrushLoadBuffer`s so `autoClean: false`
/// preserves dirty multi-bristle pigment across strokes with ZERO CPU `readPixels`!
pub struct DirtyBrushGpuBank {
- /// Per-preset GPU bristle buffers (`MAX_BRISTLES * 64` bytes = 4,096 bytes each).
- bristle_buffers: HashMap<String, wgpu::Buffer>,
- /// Per-preset GPU spatial tip mixer buffers (`256 * 32` bytes = 8,192 bytes each).
- tip_mixer_buffers: HashMap<String, wgpu::Buffer>,
+ /// Per-preset GPU bristle + dedicated underbed buffers (`TOTAL_BRISTLE_SLOTS * 64` bytes), with unique IDs.
+ bristle_buffers: HashMap<String, (u64, wgpu::Buffer)>,
+ /// Per-preset GPU spatial tip mixer buffers (`256 * 32` bytes = 8,192 bytes each), with unique IDs.
+ tip_mixer_buffers: HashMap<String, (u64, wgpu::Buffer)>,
+ next_bristle_buf_id: u64,
+ next_tip_buf_id: u64,
}
impl Default for DirtyBrushGpuBank {
@@ -567,15 +660,16 @@ impl DirtyBrushGpuBank {
Self {
bristle_buffers: HashMap::new(),
tip_mixer_buffers: HashMap::new(),
+ next_bristle_buf_id: 1,
+ next_tip_buf_id: 1,
}
}
- /// Returns (or creates) the persistent GPU bristle `BrushLoadBuffer` for `preset_key`.
- /// When `auto_clean` is `true` OR the buffer was just created, initializes all 64 slots
- /// to clean foreground paint on GPU (`queue.write_buffer`). When `auto_clean` is `false`
- /// and a dirty buffer already exists for `preset_key`, preserves its exact GPU VRAM state!
+ /// Returns (or creates) the persistent GPU bristle `BrushLoadBuffer` + unique buffer ID for `preset_key`.
+ /// Allocates `TOTAL_BRISTLE_SLOTS` (`0..64` real bristles + `64..69` dedicated underbed bands)
+ /// so underbed bands NEVER collide with real bristle reservoirs!
#[allow(clippy::too_many_arguments)]
- pub fn acquire_bristle_buffer(
+ pub fn acquire_bristle_buffer_with_id(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
@@ -584,38 +678,51 @@ impl DirtyBrushGpuBank {
paint_load: f32,
wetness: f32,
auto_clean: bool,
- ) -> (&wgpu::Buffer, bool) {
+ ) -> (&wgpu::Buffer, u64, bool) {
let existed = self.bristle_buffers.contains_key(preset_key);
- let buf = self
+ let next_id = &mut self.next_bristle_buf_id;
+ let (id, buf) = self
.bristle_buffers
.entry(preset_key.to_string())
.or_insert_with(|| {
- device.create_buffer(&wgpu::BufferDescriptor {
+ let id = *next_id;
+ *next_id = next_id.saturating_add(1);
+ let b = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("ink-np-bristle-load-buf"),
- size: (MAX_BRISTLES * std::mem::size_of::<GpuBristleSlot>()) as u64,
+ size: (TOTAL_BRISTLE_SLOTS * std::mem::size_of::<GpuBristleSlot>()) as u64,
usage: wgpu::BufferUsages::STORAGE
| wgpu::BufferUsages::COPY_DST
| wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
- })
+ });
+ (id, b)
});
let needs_reset = auto_clean || !existed;
if needs_reset {
- let mut init = [GpuBristleSlot::zeroed(); MAX_BRISTLES];
+ let mut init = [GpuBristleSlot::zeroed(); TOTAL_BRISTLE_SLOTS];
for (i, slot) in init.iter_mut().enumerate() {
- let u = (i as f32 + 0.5) / MAX_BRISTLES as f32 * 2.0 - 1.0;
+ let u = if i < MAX_BRISTLES {
+ (i as f32 + 0.5) / MAX_BRISTLES as f32 * 2.0 - 1.0
+ } else {
+ ((i - UNDERBED_SLOT_BASE) as f32 / (UNDERBED_BANDS.saturating_sub(1).max(1) as f32))
+ * 1.44
+ - 0.72
+ };
let groove = 0.75 + 0.25 * (1.0 - u * u);
*slot = GpuBristleSlot::fresh(fg_color, paint_load, wetness, groove);
}
queue.write_buffer(buf, 0, bytemuck::cast_slice(&init));
}
- (buf, !needs_reset)
+ (buf, *id, !needs_reset)
}
- /// Returns (or creates) the GPU 16×16 `SpatialTipMixer` buffer for `preset_key`.
+ /// Returns (or creates) the persistent GPU bristle `BrushLoadBuffer` for `preset_key`.
+ /// When `auto_clean` is `true` OR the buffer was just created, initializes all slots
+ /// to clean foreground paint on GPU (`queue.write_buffer`). When `auto_clean` is `false`
+ /// and a dirty buffer already exists for `preset_key`, preserves its exact GPU VRAM state!
#[allow(clippy::too_many_arguments)]
- pub fn acquire_tip_mixer_buffer(
+ pub fn acquire_bristle_buffer(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
@@ -625,19 +732,47 @@ impl DirtyBrushGpuBank {
wetness: f32,
auto_clean: bool,
) -> (&wgpu::Buffer, bool) {
+ let (buf, _, preserved) = self.acquire_bristle_buffer_with_id(
+ device,
+ queue,
+ preset_key,
+ fg_color,
+ paint_load,
+ wetness,
+ auto_clean,
+ );
+ (buf, preserved)
+ }
+
+ /// Returns (or creates) the GPU 16×16 `SpatialTipMixer` buffer + its unique ID for `preset_key`.
+ #[allow(clippy::too_many_arguments)]
+ pub fn acquire_tip_mixer_buffer_with_id(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ preset_key: &str,
+ fg_color: [f32; 3],
+ paint_load: f32,
+ wetness: f32,
+ auto_clean: bool,
+ ) -> (&wgpu::Buffer, u64, bool) {
let existed = self.tip_mixer_buffers.contains_key(preset_key);
- let buf = self
+ let next_id = &mut self.next_tip_buf_id;
+ let (id, buf) = self
.tip_mixer_buffers
.entry(preset_key.to_string())
.or_insert_with(|| {
- device.create_buffer(&wgpu::BufferDescriptor {
+ let id = *next_id;
+ *next_id = next_id.saturating_add(1);
+ let b = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("ink-np-spatial-tip-mixer-buf"),
size: (SPATIAL_TIP_CELLS * std::mem::size_of::<GpuSpatialTipCell>()) as u64,
usage: wgpu::BufferUsages::STORAGE
| wgpu::BufferUsages::COPY_DST
| wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
- })
+ });
+ (id, b)
});
let needs_reset = auto_clean || !existed;
@@ -651,7 +786,31 @@ impl DirtyBrushGpuBank {
];
queue.write_buffer(buf, 0, bytemuck::cast_slice(&init));
}
- (buf, !needs_reset)
+ (buf, *id, !needs_reset)
+ }
+
+ /// Returns (or creates) the GPU 16×16 `SpatialTipMixer` buffer for `preset_key`.
+ #[allow(clippy::too_many_arguments)]
+ pub fn acquire_tip_mixer_buffer(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ preset_key: &str,
+ fg_color: [f32; 3],
+ paint_load: f32,
+ wetness: f32,
+ auto_clean: bool,
+ ) -> (&wgpu::Buffer, bool) {
+ let (buf, _, preserved) = self.acquire_tip_mixer_buffer_with_id(
+ device,
+ queue,
+ preset_key,
+ fg_color,
+ paint_load,
+ wetness,
+ auto_clean,
+ );
+ (buf, preserved)
}
/// Explicitly washes/cleans one preset's dirty brush buffer or all dirty brush buffers (`None`).
@@ -674,15 +833,16 @@ impl DirtyBrushGpuBank {
|| self.tip_mixer_buffers.contains_key(preset_key)
}
- /// Reads back the 64 `GpuBristleSlot`s for a preset (strictly for headless Rust unit tests!).
+ /// Reads back all `TOTAL_BRISTLE_SLOTS` (`0..64` real bristles + `64..69` underbed bands)
+ /// for a preset (strictly for headless Rust unit tests!).
pub fn readback_bristle_slots(
&self,
device: &wgpu::Device,
queue: &wgpu::Queue,
preset_key: &str,
) -> Option<Vec<GpuBristleSlot>> {
- let buf = self.bristle_buffers.get(preset_key)?;
- let size = (MAX_BRISTLES * std::mem::size_of::<GpuBristleSlot>()) as u64;
+ let (_, buf) = self.bristle_buffers.get(preset_key)?;
+ let size = (TOTAL_BRISTLE_SLOTS * std::mem::size_of::<GpuBristleSlot>()) as u64;
let staging = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("ink-np-bristle-readback"),
size,
diff --git a/crates/ink-engine/src/natural_paint/ribbon.rs b/crates/ink-engine/src/natural_paint/ribbon.rs
index 1d88b1d..52a3174 100644
--- a/crates/ink-engine/src/natural_paint/ribbon.rs
+++ b/crates/ink-engine/src/natural_paint/ribbon.rs
@@ -19,8 +19,11 @@ use crate::stroke::StrokePoint;
use crate::tiles::{TileCoord, TILE_SIZE};
use bytemuck::{Pod, Zeroable};
use std::borrow::Cow;
-use std::collections::HashSet;
+use std::collections::{HashMap, HashSet};
use std::f32::consts::PI;
+use std::num::NonZeroU64;
+
+const RIBBON_UNIFORM_STRIDE: u64 = 256;
pub const MAX_MITER_RATIO: f32 = 1.45;
pub const BEVEL_ANGLE_THRESHOLD_RAD: f32 = 0.22;
@@ -112,11 +115,13 @@ fn eval_paper_grain(doc_pos: vec2<f32>, base_alpha: f32) -> f32 {
let ry = (shifted.x * s + shifted.y * c) / (512.0 * scale);
let p_uv = fract(vec2<f32>(rx, ry));
var g = textureSampleLevel(paper_tex, paper_sampler, p_uv, 0.0).r;
+ let b_norm = clamp(u.paper1.z * 0.01, -1.0, 1.0);
+ let c_norm = clamp(u.paper1.w * 0.01, -0.95, 0.99);
+ let contrast = clamp((1.0 + c_norm) / max(0.05, 1.0 - c_norm * 0.85), 0.1, 3.0);
+ g = clamp((g - 0.5) * contrast + 0.5 + b_norm * 0.5, 0.0, 1.0);
if (u.paper2.x > 0.5) {
g = 1.0 - g;
}
- let contrast = clamp(1.0 + u.paper1.w, 0.1, 3.0);
- g = clamp((g - 0.5) * contrast + 0.5 + u.paper1.z, 0.0, 1.0);
let density = clamp(u.paper0.x, 0.0, 1.0);
let mode = u32(u.paper0.y + 0.5);
@@ -146,13 +151,14 @@ fn eval_paper_grain(doc_pos: vec2<f32>, base_alpha: f32) -> f32 {
let ov = select(1.0 - 2.0 * (1.0 - base_alpha) * (1.0 - g), 2.0 * base_alpha * g, base_alpha < 0.5);
out_a = mix(base_alpha, ov, density);
} else if (mode == 7u) {
- // ColorDodge
- let cd = clamp(base_alpha / max(1.0 - g * 0.92, 0.08), 0.0, 1.0);
- out_a = mix(base_alpha, cd, density);
- } else {
+ // Normal (linear mix toward paper texture density)
+ out_a = mix(base_alpha, base_alpha * g, density * 0.85);
+ } else if (mode == 8u) {
// ColorBurn
let cb = clamp(1.0 - (1.0 - base_alpha) / max(g, 0.08), 0.0, 1.0);
out_a = mix(base_alpha, cb, density);
+ } else {
+ out_a = base_alpha * mix(1.0, g, density);
}
return clamp(out_a, 0.0, 1.0);
}
@@ -271,6 +277,9 @@ struct SpineNode {
/// bevel corner subdivision, and anti-bowtie guard.
pub struct RibbonMeshBuilder {
nodes: Vec<SpineNode>,
+ /// Incremental unit segment tangent directions (`dirs[i]` = unit vector from `nodes[i]` to `nodes[i+1]`).
+ /// Maintained in O(1) per pushed node so `triangulate_range` is strictly `O(new_nodes)`!
+ dirs: Vec<(f32, f32)>,
emitted_seg_count: usize,
tip_w: u32,
tip_h: u32,
@@ -280,12 +289,23 @@ pub struct RibbonMeshBuilder {
total_arc_len: f32,
accum_u: f32,
tile_meta_cache: Vec<(usize, bool, bool)>, // (sub_tip_idx, flip_h, flip_v) per integer tile index
+ /// Pre-compiled CSP sensor LUTs (compiled ONCE on first `push_points`, ZERO per-frame rebuilds!).
+ cached_size_luts: Option<CompiledSensorLuts>,
+ cached_op_luts: Option<CompiledSensorLuts>,
+ luts_initialized: bool,
+ /// Incremental geometry + arc-length cache for `RibbonRepeatMode::Once` so UV re-normalization
+ /// never recomputes finalized segments' miters, bevels, or positions!
+ once_cached_verts: Vec<RibbonVertex>,
+ once_vert_arcs: Vec<f32>,
+ once_finalized_seg_count: usize,
+ once_finalized_vert_count: usize,
}
impl RibbonMeshBuilder {
pub fn new(tip_w: u32, tip_h: u32, sub_tip_count: usize, seed: u64) -> Self {
Self {
nodes: Vec::with_capacity(256),
+ dirs: Vec::with_capacity(256),
emitted_seg_count: 0,
tip_w: tip_w.max(1),
tip_h: tip_h.max(1),
@@ -295,6 +315,13 @@ impl RibbonMeshBuilder {
total_arc_len: 0.0,
accum_u: 0.0,
tile_meta_cache: Vec::new(),
+ cached_size_luts: None,
+ cached_op_luts: None,
+ luts_initialized: false,
+ once_cached_verts: Vec::new(),
+ once_vert_arcs: Vec::new(),
+ once_finalized_seg_count: 0,
+ once_finalized_vert_count: 0,
}
}
@@ -317,8 +344,17 @@ impl RibbonMeshBuilder {
self.tip_w,
self.tip_h,
);
- let size_luts = CompiledSensorLuts::from_sensor(config.size_sensor.as_ref());
- let op_luts = CompiledSensorLuts::from_sensor(config.opacity_sensor.as_ref());
+ if !self.luts_initialized {
+ self.cached_size_luts = config
+ .size_sensor
+ .as_ref()
+ .map(|s| CompiledSensorLuts::from_sensor(Some(s)));
+ self.cached_op_luts = config
+ .opacity_sensor
+ .as_ref()
+ .map(|s| CompiledSensorLuts::from_sensor(Some(s)));
+ self.luts_initialized = true;
+ }
for &pt in points {
let px = pt.x as f32;
@@ -335,14 +371,14 @@ impl RibbonMeshBuilder {
let size_f = if let Some(ref s) = config.size_sensor {
evaluate_csp_sensor(
s,
- Some(&size_luts),
+ self.cached_size_luts.as_ref(),
pressure,
tilt_mag,
vel,
self.total_arc_len,
self.rng.next_f32(),
)
- .clamp(config.min_size_factor.max(0.04), 1.5)
+ .clamp(config.min_size_factor.max(0.04), 4.0)
} else if config.use_pressure {
let min_f = config.min_size_factor.clamp(0.04, 1.0);
min_f + (1.0 - min_f) * pressure
@@ -353,7 +389,7 @@ impl RibbonMeshBuilder {
let op_f = if let Some(ref s) = config.opacity_sensor {
evaluate_csp_sensor(
s,
- Some(&op_luts),
+ self.cached_op_luts.as_ref(),
pressure,
tilt_mag,
vel,
@@ -386,6 +422,7 @@ impl RibbonMeshBuilder {
if d < 0.4 {
continue;
}
+ self.dirs.push((dx / d.max(1e-5), dy / d.max(1e-5)));
self.total_arc_len += d;
// Keep UV aspect ratio locked locally even as pressure changes brush width!
let avg_period = ((last.half_width * 2.0 / metrics_unit.ribbon_width.max(0.05))
@@ -406,17 +443,16 @@ impl RibbonMeshBuilder {
});
}
- // For Repeat & Reverse modes we can incrementally emit finalized segments up to `len - 1`
+ // For Repeat & Reverse modes we incrementally emit finalized segments up to `len - 2`
// (leaving 1 lookahead segment so miter joints stay exact as the next point arrives!).
if self.nodes.len() < 2 {
return None;
}
- let target_seg_end = if config.ribbon_repeat_mode == RibbonRepeatMode::Once {
- // Once mode stretches U from 0..1 across full stroke; emit live preview from 0
- out_verts.clear();
- self.emitted_seg_count = 0;
- self.nodes.len() - 1
- } else if self.nodes.len() >= 3 {
+ if config.ribbon_repeat_mode == RibbonRepeatMode::Once {
+ return self.emit_once_incremental(config, metrics_unit.swap_uv_axes, false, out_verts);
+ }
+
+ let target_seg_end = if self.nodes.len() >= 3 {
self.nodes.len() - 2
} else {
0
@@ -433,11 +469,86 @@ impl RibbonMeshBuilder {
config,
metrics_unit.swap_uv_axes,
out_verts,
+ None,
);
self.emitted_seg_count = target_seg_end;
compute_verts_bounds(&out_verts[start_vert..])
}
+ /// Incrementally updates geometry for `RibbonRepeatMode::Once` (triangulating ONLY newly
+ /// appended segments + the 1 lookahead tail segment) and re-normalizes ONLY the U coordinate
+ /// across cached vertices in O(V) without recomputing any finalized miters or bevels!
+ fn emit_once_incremental(
+ &mut self,
+ config: &NativeBrushConfig,
+ swap_uv: bool,
+ is_finish: bool,
+ out_verts: &mut Vec<RibbonVertex>,
+ ) -> Option<(f32, f32, f32, f32)> {
+ let total_segs = self.nodes.len().saturating_sub(1);
+ if total_segs == 0 {
+ return None;
+ }
+ // Discard only the previous transient tail segment (keeping all finalized segments intact!)
+ self.once_cached_verts.truncate(self.once_finalized_vert_count);
+ self.once_vert_arcs.truncate(self.once_finalized_vert_count);
+
+ let finalize_end = if is_finish {
+ total_segs
+ } else {
+ total_segs.saturating_sub(1)
+ };
+
+ let mut cached_verts = std::mem::take(&mut self.once_cached_verts);
+ let mut cached_arcs = std::mem::take(&mut self.once_vert_arcs);
+
+ if finalize_end > self.once_finalized_seg_count {
+ self.triangulate_range(
+ self.once_finalized_seg_count,
+ finalize_end,
+ config,
+ swap_uv,
+ &mut cached_verts,
+ Some(&mut cached_arcs),
+ );
+ self.once_finalized_seg_count = finalize_end;
+ self.once_finalized_vert_count = cached_verts.len();
+ }
+ if total_segs > finalize_end {
+ self.triangulate_range(
+ finalize_end,
+ total_segs,
+ config,
+ swap_uv,
+ &mut cached_verts,
+ Some(&mut cached_arcs),
+ );
+ }
+
+ // Fast O(V) UV-only re-normalization across the full stroke (`u = arc_len / total_arc`)
+ let inv_total_arc = 1.0 / self.total_arc_len.max(1e-4);
+ let (_, flip_h, _) = self.tile_meta_for(0, config);
+ for (v, &arc) in cached_verts.iter_mut().zip(cached_arcs.iter()) {
+ let mut lu = (arc * inv_total_arc).clamp(0.0, 1.0);
+ if flip_h {
+ lu = 1.0 - lu;
+ }
+ if swap_uv {
+ v.uv[1] = lu;
+ } else {
+ v.uv[0] = lu;
+ }
+ }
+
+ out_verts.clear();
+ out_verts.extend_from_slice(&cached_verts);
+
+ self.once_cached_verts = cached_verts;
+ self.once_vert_arcs = cached_arcs;
+ self.emitted_seg_count = total_segs;
+ compute_verts_bounds(out_verts)
+ }
+
/// Flushes the final lookahead segment on pointer-up (or full stretch for `Once`).
pub fn finish(
&mut self,
@@ -456,8 +567,7 @@ impl RibbonMeshBuilder {
self.tip_h,
);
if config.ribbon_repeat_mode == RibbonRepeatMode::Once {
- out_verts.clear();
- self.emitted_seg_count = 0;
+ return self.emit_once_incremental(config, metrics_unit.swap_uv_axes, true, out_verts);
}
let seg_end = self.nodes.len() - 1;
if seg_end <= self.emitted_seg_count {
@@ -470,6 +580,7 @@ impl RibbonMeshBuilder {
config,
metrics_unit.swap_uv_axes,
out_verts,
+ None,
);
self.emitted_seg_count = seg_end;
compute_verts_bounds(&out_verts[start_vert..])
@@ -550,6 +661,7 @@ impl RibbonMeshBuilder {
config: &NativeBrushConfig,
swap_uv: bool,
out_verts: &mut Vec<RibbonVertex>,
+ mut out_arcs: Option<&mut Vec<f32>>,
) {
let n = self.nodes.len();
if n < 2 || seg_start >= seg_end {
@@ -557,21 +669,14 @@ impl RibbonMeshBuilder {
}
let total_arc = self.total_arc_len.max(1e-4);
- let mut dirs: Vec<(f32, f32)> = Vec::with_capacity(n - 1);
- for i in 0..(n - 1) {
- let dx = self.nodes[i + 1].x - self.nodes[i].x;
- let dy = self.nodes[i + 1].y - self.nodes[i].y;
- let len = (dx * dx + dy * dy).sqrt().max(1e-5);
- dirs.push((dx / len, dy / len));
- }
-
for seg in seg_start..seg_end {
let a = self.nodes[seg];
let b = self.nodes[seg + 1];
- let d = dirs[seg];
- let (mut l0, mut r0, _bev0, _) = Self::compute_node_edges(&self.nodes, &dirs, seg, d);
+ let d = self.dirs[seg];
+ let (mut l0, mut r0, _bev0, _) =
+ Self::compute_node_edges(&self.nodes, &self.dirs, seg, d);
let (mut l1, mut r1, bev1, _) =
- Self::compute_node_edges(&self.nodes, &dirs, seg + 1, d);
+ Self::compute_node_edges(&self.nodes, &self.dirs, seg + 1, d);
// Anti-bowtie winding guard: if left or right edge crosses backward along segment tangent,
// clamp the offending inner corner cleanly to prevent self-intersecting bowtie quads!
@@ -676,12 +781,17 @@ impl RibbonMeshBuilder {
RibbonVertex { doc_pos: [pl1.0, pl1.1], uv: uv_l1, fg_alpha: c1, sub_bg },
RibbonVertex { doc_pos: [pr1.0, pr1.1], uv: uv_r1, fg_alpha: c1, sub_bg },
);
+ if let Some(arcs) = out_arcs.as_deref_mut() {
+ let arc0 = a.arc_len + (b.arc_len - a.arc_len) * t0;
+ let arc1 = a.arc_len + (b.arc_len - a.arc_len) * t1;
+ arcs.extend_from_slice(&[arc0, arc0, arc1, arc0, arc1, arc1]);
+ }
}
// Emit bevel fan bridge on sharp corners (`seg + 1` joining `dirs[seg]` -> `dirs[seg + 1]`)
- if bev1 && seg + 1 < dirs.len() {
- let d0 = dirs[seg];
- let d1 = dirs[seg + 1];
+ if bev1 && seg + 1 < self.dirs.len() {
+ let d0 = self.dirs[seg];
+ let d1 = self.dirs[seg + 1];
let cross = d0.0 * d1.1 - d0.1 * d1.0;
if cross.abs() > 1e-4 {
let n0 = (-d0.1, d0.0);
@@ -742,6 +852,9 @@ impl RibbonMeshBuilder {
fg_alpha: col,
sub_bg,
});
+ if let Some(arcs) = out_arcs.as_deref_mut() {
+ arcs.extend_from_slice(&[b.arc_len, b.arc_len, b.arc_len]);
+ }
}
}
}
@@ -819,7 +932,8 @@ pub fn collect_ribbon_touched_tiles(verts: &[RibbonVertex]) -> HashSet<TileCoord
}
/// Compiled `wgpu` render pipeline rendering [`RibbonVertex`] meshes directly into sparse
-/// `256×256` `Rgba16Float` stroke tiles (supporting both primary ribbons and Dual Brush ribbons!).
+/// `256×256` `Rgba16Float` stroke tiles (supporting both primary ribbons and Dual Brush ribbons!)
+/// with per-tile triangle index binning and cached `BindGroup`s.
pub struct GpuRibbonPipeline {
bgl: wgpu::BindGroupLayout,
pipeline_alpha_over: wgpu::RenderPipeline,
@@ -827,8 +941,18 @@ pub struct GpuRibbonPipeline {
linear_sampler: wgpu::Sampler,
repeat_sampler: wgpu::Sampler,
uniform_buf: wgpu::Buffer,
+ uniform_cap: usize,
+ uniform_buf_gen: u64,
vert_buf: wgpu::Buffer,
vert_capacity: usize,
+ index_buf: wgpu::Buffer,
+ index_capacity: usize,
+ uniform_staging: Vec<u8>,
+ index_staging: Vec<u32>,
+ cached_bg: Option<((u64, u64, u64), wgpu::BindGroup)>,
+ pub last_batch_binned_indices: usize,
+ pub last_batch_unbinned_indices: usize,
+ pub bind_group_rebuilds: u64,
}
impl GpuRibbonPipeline {
@@ -841,8 +965,10 @@ impl GpuRibbonPipeline {
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
- has_dynamic_offset: false,
- min_binding_size: None,
+ has_dynamic_offset: true,
+ min_binding_size: NonZeroU64::new(
+ std::mem::size_of::<RibbonTileUniforms>() as u64,
+ ),
},
count: None,
},
@@ -983,9 +1109,10 @@ impl GpuRibbonPipeline {
..Default::default()
});
+ let uniform_cap = 64usize;
let uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("ink-ribbon-uniforms"),
- size: std::mem::size_of::<RibbonTileUniforms>() as u64,
+ label: Some("ink-ribbon-uniforms-dyn"),
+ size: uniform_cap as u64 * RIBBON_UNIFORM_STRIDE,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
@@ -996,6 +1123,13 @@ impl GpuRibbonPipeline {
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
+ let index_capacity = 8192usize;
+ let index_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-ribbon-binned-indices"),
+ size: (index_capacity * std::mem::size_of::<u32>()) as u64,
+ usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
Self {
bgl,
@@ -1004,29 +1138,39 @@ impl GpuRibbonPipeline {
linear_sampler,
repeat_sampler,
uniform_buf,
+ uniform_cap,
+ uniform_buf_gen: 1,
vert_buf,
vert_capacity,
+ index_buf,
+ index_capacity,
+ uniform_staging: Vec::with_capacity(64 * RIBBON_UNIFORM_STRIDE as usize),
+ index_staging: Vec::with_capacity(4096),
+ cached_bg: None,
+ last_batch_binned_indices: 0,
+ last_batch_unbinned_indices: 0,
+ bind_group_rebuilds: 0,
}
}
- /// Renders `verts` into a single `256×256` `Rgba16Float` target tile view at `coord`.
+ /// Renders `verts` into a batch of `256×256` `Rgba16Float` target tile views with per-tile
+ /// triangle index binning, cached `BindGroup`, and **ONE vertex upload + ONE index upload +
+ /// ONE dynamic uniform upload + ONE `CommandEncoder` + ONE `queue.submit`**!
#[allow(clippy::too_many_arguments)]
- pub fn render_into_tile(
+ pub fn render_into_tiles_batch(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
- target_view: &wgpu::TextureView,
- coord: TileCoord,
+ targets: &[(TileCoord, &wgpu::TextureView, bool)],
verts: &[RibbonVertex],
config: &NativeBrushConfig,
tip_arr: Option<&GpuTipArray>,
dummy_tip_view: &wgpu::TextureView,
paper_tex: Option<&GpuPaperTexture>,
dummy_paper_view: &wgpu::TextureView,
- clear_first: bool,
use_max_blend: bool,
) {
- if verts.is_empty() {
+ if verts.is_empty() || targets.is_empty() {
return;
}
if verts.len() > self.vert_capacity {
@@ -1040,6 +1184,66 @@ impl GpuRibbonPipeline {
}
queue.write_buffer(&self.vert_buf, 0, bytemuck::cast_slice(verts));
+ // 1. Bin triangles strictly into the tiles they overlap (ZERO full-mesh redraw per tile!)
+ let mut target_map: HashMap<TileCoord, usize> = HashMap::with_capacity(targets.len());
+ for (i, &(coord, _, _)) in targets.iter().enumerate() {
+ target_map.insert(coord, i);
+ }
+ let mut tile_bins: Vec<Vec<u32>> = vec![Vec::new(); targets.len()];
+ for (tri_idx, tri) in verts.as_chunks::<3>().0.iter().enumerate() {
+ let min_x = tri[0].doc_pos[0].min(tri[1].doc_pos[0]).min(tri[2].doc_pos[0]) - 1.0;
+ let min_y = tri[0].doc_pos[1].min(tri[1].doc_pos[1]).min(tri[2].doc_pos[1]) - 1.0;
+ let max_x = tri[0].doc_pos[0].max(tri[1].doc_pos[0]).max(tri[2].doc_pos[0]) + 1.0;
+ let max_y = tri[0].doc_pos[1].max(tri[1].doc_pos[1]).max(tri[2].doc_pos[1]) + 1.0;
+ let tx0 = (min_x.floor() as i32).div_euclid(TILE_SIZE as i32);
+ let ty0 = (min_y.floor() as i32).div_euclid(TILE_SIZE as i32);
+ let tx1 = (max_x.ceil() as i32).div_euclid(TILE_SIZE as i32);
+ let ty1 = (max_y.ceil() as i32).div_euclid(TILE_SIZE as i32);
+ let base = (tri_idx * 3) as u32;
+ for ty in ty0..=ty1 {
+ for tx in tx0..=tx1 {
+ if let Some(&t_idx) = target_map.get(&TileCoord::new(tx, ty)) {
+ tile_bins[t_idx].extend_from_slice(&[base, base + 1, base + 2]);
+ }
+ }
+ }
+ }
+
+ self.index_staging.clear();
+ let mut tile_ranges: Vec<(u32, u32)> = Vec::with_capacity(targets.len());
+ for bin in &tile_bins {
+ let start = self.index_staging.len() as u32;
+ let count = bin.len() as u32;
+ self.index_staging.extend_from_slice(bin);
+ tile_ranges.push((start, count));
+ }
+ self.last_batch_binned_indices = self.index_staging.len();
+ self.last_batch_unbinned_indices = targets.len() * verts.len();
+
+ if !self.index_staging.is_empty() {
+ if self.index_staging.len() > self.index_capacity {
+ self.index_capacity = self.index_staging.len().next_power_of_two().max(8192);
+ self.index_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-ribbon-binned-indices"),
+ size: (self.index_capacity * std::mem::size_of::<u32>()) as u64,
+ usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ }
+ queue.write_buffer(&self.index_buf, 0, bytemuck::cast_slice(&self.index_staging));
+ }
+
+ if targets.len() > self.uniform_cap {
+ self.uniform_cap = targets.len().next_power_of_two().max(64);
+ self.uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-ribbon-uniforms-dyn"),
+ size: self.uniform_cap as u64 * RIBBON_UNIFORM_STRIDE,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ self.uniform_buf_gen = self.uniform_buf_gen.saturating_add(1);
+ }
+
let paper_mode_u = match config.paper_texture_mode {
CspPaperTextureMode::Multiply => 0.0,
CspPaperTextureMode::Subtract => 1.0,
@@ -1051,80 +1255,116 @@ impl GpuRibbonPipeline {
CspPaperTextureMode::Normal => 7.0,
CspPaperTextureMode::ColorBurn => 8.0,
};
- let (tip_view, has_tip, tip_w, tip_h) = match tip_arr {
- Some(t) => (&t.view, 1u32, t.width as f32, t.height as f32),
- None => (dummy_tip_view, 0u32, 64.0, 64.0),
+ let (tip_view, tip_id, has_tip, tip_w, tip_h) = match tip_arr {
+ Some(t) => (&t.view, t.id, 1u32, t.width as f32, t.height as f32),
+ None => (dummy_tip_view, 0u64, 0u32, 64.0, 64.0),
};
- let (paper_view, has_paper) = match paper_tex {
- Some(p) if config.effective_grain_strength() > 1e-4 => (&p.view, 1u32),
- _ => (dummy_paper_view, 0u32),
+ let (paper_view, paper_id, has_paper) = match paper_tex {
+ Some(p) if config.effective_grain_strength() > 1e-4 => (&p.view, p.id, 1u32),
+ _ => (dummy_paper_view, 0u64, 0u32),
};
- let uniforms = RibbonTileUniforms {
- tile_rect: [
- (coord.tx * TILE_SIZE as i32) as f32,
- (coord.ty * TILE_SIZE as i32) as f32,
- TILE_SIZE as f32,
- config.anti_alias as f32,
- ],
- flags: [
- u32::from(config.is_color_tip),
- u32::from(config.is_dual_tone_tip),
- has_tip,
- has_paper,
- ],
- paper0: [
- config.effective_grain_strength(),
- paper_mode_u,
- config.paper_texture_scale.max(0.05),
- config.paper_texture_rotate.to_radians(),
- ],
- paper1: [
- config.paper_texture_offset_x,
- config.paper_texture_offset_y,
- config.paper_texture_brightness,
- config.paper_texture_contrast,
- ],
- paper2: [
- if config.paper_texture_invert { 1.0 } else { 0.0 },
- if config.emphasize_density { 1.0 } else { 0.0 },
- tip_w,
- tip_h,
- ],
- };
- queue.write_buffer(&self.uniform_buf, 0, bytemuck::bytes_of(&uniforms));
+ let stride = RIBBON_UNIFORM_STRIDE as usize;
+ self.uniform_staging.clear();
+ self.uniform_staging.resize(targets.len() * stride, 0u8);
+ for (i, &(coord, _, _)) in targets.iter().enumerate() {
+ let uniforms = RibbonTileUniforms {
+ tile_rect: [
+ (coord.tx * TILE_SIZE as i32) as f32,
+ (coord.ty * TILE_SIZE as i32) as f32,
+ TILE_SIZE as f32,
+ config.anti_alias as f32,
+ ],
+ flags: [
+ u32::from(config.is_color_tip),
+ u32::from(config.is_dual_tone_tip),
+ has_tip,
+ has_paper,
+ ],
+ paper0: [
+ config.effective_grain_strength(),
+ paper_mode_u,
+ config.paper_texture_scale.max(0.05),
+ config.paper_texture_rotate.to_radians(),
+ ],
+ paper1: [
+ config.paper_texture_offset_x,
+ config.paper_texture_offset_y,
+ config.paper_texture_brightness,
+ config.paper_texture_contrast,
+ ],
+ paper2: [
+ if config.paper_texture_invert { 1.0 } else { 0.0 },
+ if config.emphasize_density { 1.0 } else { 0.0 },
+ tip_w,
+ tip_h,
+ ],
+ };
+ let src = bytemuck::bytes_of(&uniforms);
+ self.uniform_staging[i * stride..i * stride + src.len()].copy_from_slice(src);
+ }
+ queue.write_buffer(&self.uniform_buf, 0, &self.uniform_staging);
+
+ // Cached BindGroup keyed by (uniform_buf_gen, tip_id, paper_id) — ZERO per-frame churn!
+ let bg_key = (self.uniform_buf_gen, tip_id, paper_id);
+ if self
+ .cached_bg
+ .as_ref()
+ .map(|(k, _)| *k != bg_key)
+ .unwrap_or(true)
+ {
+ let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-ribbon-bg"),
+ layout: &self.bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(std::mem::size_of::<RibbonTileUniforms>() as u64),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(tip_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(paper_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::Sampler(&self.linear_sampler),
+ },
+ wgpu::BindGroupEntry {
+ binding: 4,
+ resource: wgpu::BindingResource::Sampler(&self.repeat_sampler),
+ },
+ ],
+ });
+ self.cached_bg = Some((bg_key, bg));
+ self.bind_group_rebuilds += 1;
+ }
+ let bg = &self.cached_bg.as_ref().expect("ribbon bg cached").1;
- let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-ribbon-bg"),
- layout: &self.bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: self.uniform_buf.as_entire_binding(),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(tip_view),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::TextureView(paper_view),
- },
- wgpu::BindGroupEntry {
- binding: 3,
- resource: wgpu::BindingResource::Sampler(&self.linear_sampler),
- },
- wgpu::BindGroupEntry {
- binding: 4,
- resource: wgpu::BindingResource::Sampler(&self.repeat_sampler),
- },
- ],
- });
+ let pipeline = if use_max_blend {
+ &self.pipeline_max
+ } else {
+ &self.pipeline_alpha_over
+ };
+ let vert_bytes = std::mem::size_of_val(verts) as u64;
+ let idx_bytes = (self.index_staging.len() * std::mem::size_of::<u32>()) as u64;
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-ribbon-tile-enc"),
+ label: Some("ink-ribbon-batch-enc"),
});
- {
+ for (i, &(_, target_view, clear_first)) in targets.iter().enumerate() {
+ let (start_idx, count) = tile_ranges[i];
+ if count == 0 && !clear_first {
+ continue;
+ }
+ let dyn_off = (i as u32) * (RIBBON_UNIFORM_STRIDE as u32);
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("ink-ribbon-tile-pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
@@ -1145,15 +1385,45 @@ impl GpuRibbonPipeline {
occlusion_query_set: None,
multiview_mask: None,
});
- pass.set_pipeline(if use_max_blend {
- &self.pipeline_max
- } else {
- &self.pipeline_alpha_over
- });
- pass.set_bind_group(0, &bg, &[]);
- pass.set_vertex_buffer(0, self.vert_buf.slice(0..std::mem::size_of_val(verts) as u64));
- pass.draw(0..verts.len() as u32, 0..1);
+ if count > 0 {
+ pass.set_pipeline(pipeline);
+ pass.set_bind_group(0, bg, &[dyn_off]);
+ pass.set_vertex_buffer(0, self.vert_buf.slice(0..vert_bytes));
+ pass.set_index_buffer(self.index_buf.slice(0..idx_bytes), wgpu::IndexFormat::Uint32);
+ pass.draw_indexed(start_idx..(start_idx + count), 0, 0..1);
+ }
}
queue.submit(Some(encoder.finish()));
}
+
+ /// Renders `verts` into a single `256×256` `Rgba16Float` target tile view at `coord`.
+ #[allow(clippy::too_many_arguments)]
+ pub fn render_into_tile(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ target_view: &wgpu::TextureView,
+ coord: TileCoord,
+ verts: &[RibbonVertex],
+ config: &NativeBrushConfig,
+ tip_arr: Option<&GpuTipArray>,
+ dummy_tip_view: &wgpu::TextureView,
+ paper_tex: Option<&GpuPaperTexture>,
+ dummy_paper_view: &wgpu::TextureView,
+ clear_first: bool,
+ use_max_blend: bool,
+ ) {
+ self.render_into_tiles_batch(
+ device,
+ queue,
+ &[(coord, target_view, clear_first)],
+ verts,
+ config,
+ tip_arr,
+ dummy_tip_view,
+ paper_tex,
+ dummy_paper_view,
+ use_max_blend,
+ );
+ }
}
diff --git a/crates/ink-engine/src/phase2_tests.rs b/crates/ink-engine/src/phase2_tests.rs
index 4d1c64b..63bc8f0 100644
--- a/crates/ink-engine/src/phase2_tests.rs
+++ b/crates/ink-engine/src/phase2_tests.rs
@@ -630,6 +630,7 @@ fn test_tiered_memory_lru_to_lz4_ram_to_scratch_disk_roundtrip() {
#[test]
fn test_headless_dx12_gpu_tile_pool_lru_and_compute_mipmap_pyramid() {
+ let _dx12_guard = crate::lock_dx12_test();
let mut renderer = match GpuRenderer::new_with_vram(
SurfaceTarget::Headless {
width: 256,
@@ -658,12 +659,14 @@ fn test_headless_dx12_gpu_tile_pool_lru_and_compute_mipmap_pyramid() {
assert_eq!(pool.capacity(), 16);
pool.begin_frame();
+ let d1 = pool.intern_doc("d1");
+ let l1 = pool.intern_layer("l1");
let s_tl = pool
.ensure_tile_uploaded(
&queue,
GpuTileKey {
- doc_id: "d1".into(),
- layer_id: "l1".into(),
+ doc_id: d1,
+ layer_id: l1,
lod: 0,
coord: TileCoord::new(0, 0),
},
@@ -675,8 +678,8 @@ fn test_headless_dx12_gpu_tile_pool_lru_and_compute_mipmap_pyramid() {
.ensure_tile_uploaded(
&queue,
GpuTileKey {
- doc_id: "d1".into(),
- layer_id: "l1".into(),
+ doc_id: d1,
+ layer_id: l1,
lod: 0,
coord: TileCoord::new(1, 0),
},
@@ -688,8 +691,8 @@ fn test_headless_dx12_gpu_tile_pool_lru_and_compute_mipmap_pyramid() {
.ensure_tile_uploaded(
&queue,
GpuTileKey {
- doc_id: "d1".into(),
- layer_id: "l1".into(),
+ doc_id: d1,
+ layer_id: l1,
lod: 0,
coord: TileCoord::new(0, 1),
},
@@ -701,8 +704,8 @@ fn test_headless_dx12_gpu_tile_pool_lru_and_compute_mipmap_pyramid() {
.ensure_tile_uploaded(
&queue,
GpuTileKey {
- doc_id: "d1".into(),
- layer_id: "l1".into(),
+ doc_id: d1,
+ layer_id: l1,
lod: 0,
coord: TileCoord::new(1, 1),
},
@@ -716,8 +719,8 @@ fn test_headless_dx12_gpu_tile_pool_lru_and_compute_mipmap_pyramid() {
&device,
&queue,
GpuTileKey {
- doc_id: "d1".into(),
- layer_id: "l1".into(),
+ doc_id: d1,
+ layer_id: l1,
lod: 1,
coord: TileCoord::new(0, 0),
},
@@ -742,15 +745,15 @@ fn test_headless_dx12_gpu_tile_pool_lru_and_compute_mipmap_pyramid() {
assert_eq!(px_at(32, 192), [0, 0, 255, 255], "LOD 1 BL quadrant must be Blue");
assert_eq!(px_at(192, 192), [255, 255, 255, 255], "LOD 1 BR quadrant must be White");
- // Verify LRU eviction triggers cleanly when exceeding the 16-slot VRAM capacity
+ // Verify SolidColor deduplication collapses 20 identical solid-red tiles onto the existing shared slot
+ let l_solid = pool.intern_layer("l_solid");
for i in 0..20i32 {
- pool.begin_frame();
let _ = pool
.ensure_tile_uploaded(
&queue,
GpuTileKey {
- doc_id: "d1".into(),
- layer_id: "l_evict".into(),
+ doc_id: d1,
+ layer_id: l_solid,
lod: 0,
coord: TileCoord::new(i, 0),
},
@@ -759,6 +762,34 @@ fn test_headless_dx12_gpu_tile_pool_lru_and_compute_mipmap_pyramid() {
)
.unwrap();
}
+ assert_eq!(
+ pool.stats().slots_used,
+ 5,
+ "20 identical SolidColor tiles must share 1 VRAM slot (4 solid + 1 LOD1 = 5)"
+ );
+
+ // Verify LRU eviction triggers cleanly when exceeding the 16-slot VRAM capacity with non-solid tiles
+ let mut non_solid_raw = vec![0u8; BYTES_32BIT];
+ non_solid_raw[0..4].copy_from_slice(&[255, 0, 0, 255]);
+ non_solid_raw[4..8].copy_from_slice(&[0, 255, 0, 255]);
+ let non_solid_tile = TileData::from_raw(TileFormat::Color32Bit, TileKind::Raster, non_solid_raw);
+ let l_evict = pool.intern_layer("l_evict");
+ for i in 0..20i32 {
+ pool.begin_frame();
+ let _ = pool
+ .ensure_tile_uploaded(
+ &queue,
+ GpuTileKey {
+ doc_id: d1,
+ layer_id: l_evict,
+ lod: 0,
+ coord: TileCoord::new(i, 0),
+ },
+ &non_solid_tile,
+ None,
+ )
+ .unwrap();
+ }
let st = pool.stats();
assert_eq!(st.slots_used, 16);
assert!(st.evictions >= 9, "Expected LRU evictions when exceeding 16 slots, got {}", st.evictions);
diff --git a/crates/ink-engine/src/phase4_tests.rs b/crates/ink-engine/src/phase4_tests.rs
index a3910c4..e939794 100644
--- a/crates/ink-engine/src/phase4_tests.rs
+++ b/crates/ink-engine/src/phase4_tests.rs
@@ -200,7 +200,7 @@ fn emit_line_stroke_gpu(
&before_map,
128,
);
- renderer.regenerate_layer_mipmaps(&doc_id, layer_id, &mut layer.grid, &cleared);
+ renderer.regenerate_layer_mipmaps(&doc_id, layer_id, &mut layer.grid, &cleared, None);
}
renderer.clear_live_stroke();
ret_tiles
@@ -839,6 +839,7 @@ fn test_p4_procedural_tips_seamless_surfaces_and_png_roundtrip() {
#[test]
fn test_p4_gpu_binary_manga_inking_and_dualtone_compare_tips() {
+ let _dx12_guard = crate::lock_dx12_test();
let Some(mut renderer) = make_headless_renderer(256, 256, 256, 256) else {
return;
};
@@ -975,6 +976,7 @@ fn test_p4_gpu_binary_manga_inking_and_dualtone_compare_tips() {
#[test]
fn test_p4_gpu_all_9_paper_modes_and_12_dual_brush_modes() {
+ let _dx12_guard = crate::lock_dx12_test();
let Some(mut renderer) = make_headless_renderer(256, 256, 256, 256) else {
return;
};
@@ -1130,6 +1132,7 @@ fn test_p4_gpu_all_9_paper_modes_and_12_dual_brush_modes() {
#[test]
fn test_p4_gpu_watercolor_wet_edge_seamless_across_tile_boundary() {
+ let _dx12_guard = crate::lock_dx12_test();
let Some(mut renderer) = make_headless_renderer(512, 256, 512, 256) else {
return;
};
@@ -1206,6 +1209,7 @@ fn test_p4_gpu_watercolor_wet_edge_seamless_across_tile_boundary() {
#[test]
fn test_p4_gpu_combine_modes_alpha_lock_and_end_to_end_cow_undo_redo() {
+ let _dx12_guard = crate::lock_dx12_test();
let Some(mut renderer) = make_headless_renderer(256, 256, 256, 256) else {
return;
};
@@ -1356,6 +1360,7 @@ fn test_p4_gpu_combine_modes_alpha_lock_and_end_to_end_cow_undo_redo() {
flip_x: false,
flip_y: false,
}));
+ handle.send_command(EngineCommand::SetCollabPointsEnabled(true));
handle.send_command(EngineCommand::SetFullBrushConfig(Box::new(
NativeBrushConfig {
fg_color: [0.95, 0.15, 0.25],
@@ -1512,6 +1517,7 @@ fn test_p4_gpu_combine_modes_alpha_lock_and_end_to_end_cow_undo_redo() {
#[test]
fn test_phase4_benchmark_4k_300px_textured_dual_brush() {
+ let _dx12_guard = crate::lock_dx12_test();
let Some(mut renderer) = make_headless_renderer(1920, 1080, 4096, 4096) else {
return;
};
@@ -1703,7 +1709,7 @@ fn test_phase4_benchmark_4k_300px_textured_dual_brush() {
&before_map,
128,
);
- renderer.regenerate_layer_mipmaps(&doc_id, &lid, &mut layer.grid, &cleared);
+ renderer.regenerate_layer_mipmaps(&doc_id, &lid, &mut layer.grid, &cleared, None);
}
let total_commit_with_cow_and_mips_ms = t_commit.elapsed().as_secs_f64() * 1000.0;
renderer.clear_live_stroke();
diff --git a/crates/ink-engine/src/phase5_tests.rs b/crates/ink-engine/src/phase5_tests.rs
index d142efa..38c3c17 100644
--- a/crates/ink-engine/src/phase5_tests.rs
+++ b/crates/ink-engine/src/phase5_tests.rs
@@ -24,8 +24,9 @@
use crate::brush::{
BristleProfilePreset, BristleSettings, BrushRenderMode, BrushTextureKind, CspDualBrushConfig,
- CspSensorConfig, CspSubTipOrder, CspTipFlipMode, DualBrushCompositeMode, ImpastoSettings,
- NativeBrushConfig, NaturalMixingMode, NaturalPaintSettings, RibbonRepeatMode, StrokeDabEmitter,
+ CspPaperTextureMode, CspSensorConfig, CspSubTipOrder, CspTipFlipMode, DualBrushCompositeMode,
+ ImpastoSettings, NativeBrushConfig, NaturalMixingMode, NaturalPaintSettings, RibbonRepeatMode,
+ StrokeDabEmitter,
};
use crate::clock;
use crate::compositor::{CompositorDisplayConfig, FlattenOptions};
@@ -419,6 +420,7 @@ fn test_p5_kubelka_munk_and_oklab_pigment_mixing() {
#[test]
fn test_p5_gpu_zero_readback_pickup_ground_mix_and_all_4_modes() {
+ let _dx12_guard = crate::lock_dx12_test();
let Some(mut renderer) = make_headless_renderer(256, 256, 512, 512) else {
return;
};
@@ -547,6 +549,7 @@ fn test_p5_gpu_zero_readback_pickup_ground_mix_and_all_4_modes() {
#[test]
fn test_p5_gpu_spatial_bristle_mixing_depletion_autoclean_and_profiles() {
+ let _dx12_guard = crate::lock_dx12_test();
let profiles = [
BristleProfilePreset::Round,
BristleProfilePreset::Flat,
@@ -662,6 +665,7 @@ fn test_p5_gpu_spatial_bristle_mixing_depletion_autoclean_and_profiles() {
#[test]
fn test_p5_gpu_dry_brush_valley_skipping_and_watercolor_granulation() {
+ let _dx12_guard = crate::lock_dx12_test();
let Some(mut renderer) = make_headless_renderer(256, 256, 512, 512) else {
return;
};
@@ -739,6 +743,7 @@ fn test_p5_gpu_dry_brush_valley_skipping_and_watercolor_granulation() {
#[test]
fn test_p5_ribbon_uv_continuity_anti_bowtie_and_gpu_raster() {
+ let _dx12_guard = crate::lock_dx12_test();
let mut brush = NativeBrushConfig {
fg_color: [0.15, 0.25, 0.85],
bg_color: [0.95, 0.75, 0.15],
@@ -895,6 +900,7 @@ fn test_p5_ribbon_uv_continuity_anti_bowtie_and_gpu_raster() {
#[test]
fn test_p5_gpu_impasto_r16f_cow_undo_ink_roundtrip_and_live_relief_lighting() {
+ let _dx12_guard = crate::lock_dx12_test();
let (handle, mut producers) = match EngineHandle::spawn(
SurfaceTarget::Headless {
width: 512,
@@ -952,7 +958,8 @@ fn test_p5_gpu_impasto_r16f_cow_undo_ink_roundtrip_and_live_relief_lighting() {
handle.send_command(EngineCommand::SetFullBrushConfig(Box::new(oil_brush)));
// Paint a vertical oil impasto ridge down center (x=256, y=90..420) via lock-free SPSC ring!
- let now = clock::now_ms();
+ // Use a fixed base timestamp so `stroke_seed` (and bristle clump geometry) is deterministic.
+ let now = 1000.0;
let steps = 26usize;
let mut samples = Vec::with_capacity(steps + 1);
for i in 0..=steps {
@@ -1123,6 +1130,7 @@ fn test_p5_gpu_impasto_r16f_cow_undo_ink_roundtrip_and_live_relief_lighting() {
#[test]
fn test_p5_native_mask_mode_stroke_and_gpu_brush_preview() {
+ let _dx12_guard = crate::lock_dx12_test();
let (handle, mut producers) = match EngineHandle::spawn(
SurfaceTarget::Headless {
width: 256,
@@ -1300,6 +1308,7 @@ fn test_p5_native_mask_mode_stroke_and_gpu_brush_preview() {
#[test]
fn test_benchmark_4k_250px_impasto_and_wet_filbert() {
+ let _dx12_guard = crate::lock_dx12_test();
let Some(mut renderer) = make_headless_renderer(1280, 720, 4096, 4096) else {
return;
};
@@ -1466,3 +1475,990 @@ fn test_benchmark_4k_250px_impasto_and_wet_filbert() {
1000.0 / avg_filb_ms.max(0.01),
);
}
+
+// ============================================================================
+// 9. ColorMixingStamp Sub-Rect Perf Benchmark & Full CSP/Moko.art Parity Suite
+// ============================================================================
+
+#[test]
+fn test_p5_color_mixing_stamp_subrect_perf_and_csp_parity() {
+ let _dx12_guard = crate::lock_dx12_test();
+ let Some(mut renderer) = make_headless_renderer(512, 512, 512, 512) else {
+ return;
+ };
+
+ // Helper: emit primary (+ optional dual-brush secondary) dabs along a straight line
+ let emit_line_dabs = |renderer: &mut GpuRenderer,
+ brush: &NativeBrushConfig,
+ x0: f64,
+ y0: f64,
+ x1: f64,
+ y1: f64,
+ seed: u64|
+ -> (Vec<crate::brush::GpuBrushDab>, Vec<crate::brush::GpuBrushDab>, [f32; 2]) {
+ let metrics = renderer.resolve_brush_tip_metrics(brush);
+ let mut emitter = StrokeDabEmitter::new(brush.clone(), seed, metrics.0, metrics.1);
+ let mut sec_emitter = brush.build_secondary_brush_config().map(|sc| {
+ let sm = renderer.resolve_brush_tip_metrics(&sc);
+ StrokeDabEmitter::new(sc, seed ^ 0xA5A5_5A5A, sm.0, sm.1)
+ });
+ let pts = make_line_points(x0, y0, x1, y1, 24, brush.size, 0.9);
+ let mut p_dabs = Vec::with_capacity(256);
+ let mut s_dabs = Vec::with_capacity(256);
+ emitter.emit_initial_point(&pts[0], None, 0.0, &mut p_dabs);
+ if let Some(ref mut se) = sec_emitter {
+ se.emit_initial_point(&pts[0], None, 0.0, &mut s_dabs);
+ }
+ for i in 1..pts.len() {
+ let p0 = pts[i.saturating_sub(2)];
+ let p1 = pts[i - 1];
+ let p2 = pts[i];
+ let p3 = pts[(i + 1).min(pts.len() - 1)];
+ let seg = centripetal_catmull_rom_to_bezier(p0, p1, p2, p3, 0.5);
+ emitter.emit_segment(&seg, None, 0.0, &mut p_dabs);
+ if let Some(ref mut se) = sec_emitter {
+ se.emit_segment(&seg, None, 0.0, &mut s_dabs);
+ }
+ }
+ (p_dabs, s_dabs, emitter.stroke_grain_offset)
+ };
+
+ // ------------------------------------------------------------------------
+ // 1 & 2. Fast 300px oil-flat-alla-prima (size=48, spacing=0.05) sub-rect
+ // efficiency + Blue + Yellow subtractive KM Green + zero BG churn
+ // ------------------------------------------------------------------------
+ let mut doc = make_doc("p5-cmix-subrect-bench", 512, 512);
+ let layer_id = doc.layers[0].meta.id.clone();
+ fill_layer_rect(&mut doc, &layer_id, 40, 180, 400, 140, [0, 45, 215, 255]);
+ let _ = renderer.sync_document(&mut doc, None);
+
+ let oil_brush = NativeBrushConfig {
+ fg_color: [1.0, 0.90, 0.0],
+ size: 48.0,
+ min_size_factor: 0.35,
+ opacity: 1.0,
+ flow: 0.95,
+ brush_density: 0.92,
+ hardness: 0.85,
+ spacing: 0.05,
+ preset_key: Some("oil-flat-alla-prima".to_string()),
+ render_mode: BrushRenderMode::Stamp,
+ color_mixing: true,
+ perceptual_mixing: true,
+ amount_of_paint: 0.52,
+ density_of_paint: 0.90,
+ color_stretch: 0.72,
+ mixing_mode: NaturalMixingMode::Blend,
+ ..NativeBrushConfig::default()
+ };
+ assert!(oil_brush.is_color_mixing_stamp_brush());
+
+ let (dabs_300, _, grain_off) = emit_line_dabs(&mut renderer, &oil_brush, 80.0, 250.0, 380.0, 250.0, 1001);
+ assert!(
+ dabs_300.len() >= 100,
+ "300px stroke at size=48, spacing=0.05 should emit >= 100 raw dabs, got {}",
+ dabs_300.len()
+ );
+
+ renderer.begin_natural_paint_stroke(&doc.id, &layer_id, 512, 512, oil_brush.clone());
+ renderer.set_natural_paint_stroke_rand_offset(grain_off);
+ let layer_snap = doc.layer(&layer_id).cloned().unwrap();
+
+ let t0 = Instant::now();
+ let _ = renderer.dispatch_color_mixing_dabs(&doc, &layer_snap, &dabs_300, None);
+ let subrect_px = renderer.brush_engine().natural_paint.cmix_last_batch_subrect_pixels;
+ let full_tile_px = renderer.brush_engine().natural_paint.cmix_last_batch_full_tile_pixels;
+ let dispatched_dabs = renderer.brush_engine().natural_paint.cmix_last_batch_dispatched_dabs;
+ let bg_rebuilds_after_first = renderer.brush_engine().natural_paint.cmix_bind_group_rebuilds;
+
+ // Dispatch a second batch on the same stroke to verify ZERO BindGroup rebuild churn
+ let (dabs_next, _, _) = emit_line_dabs(&mut renderer, &oil_brush, 380.0, 250.0, 420.0, 250.0, 1002);
+ let _ = renderer.dispatch_color_mixing_dabs(&doc, &layer_snap, &dabs_next, None);
+ let bg_rebuilds_after_second = renderer.brush_engine().natural_paint.cmix_bind_group_rebuilds;
+ let batch_ms = t0.elapsed().as_secs_f64() * 1000.0;
+
+ let batch = renderer
+ .commit_natural_paint_to_layer()
+ .expect("commit oil-flat-alla-prima stroke");
+ let empty_snap = HashMap::new();
+ let _ = doc
+ .layer_mut(&layer_id)
+ .unwrap()
+ .grid
+ .apply_gpu_committed_tiles(&layer_id, batch.color_tiles, &empty_snap, 128);
+
+ let area_ratio = subrect_px as f64 / full_tile_px.max(1) as f64;
+ println!(
+ "\n[COLOR-MIXING SUB-RECT BENCHMARK — Adapter: {}]\n\
+ - oil-flat-alla-prima (300px, size=48, spacing=0.05): raw_dabs={}, dispatched_dabs={}, \
+ subrect_ratio={:.2}% ({subrect_px}/{full_tile_px} px), bg_rebuilds={}->{}, elapsed={batch_ms:.2}ms",
+ renderer.adapter_name(),
+ dabs_300.len(),
+ dispatched_dabs,
+ area_ratio * 100.0,
+ bg_rebuilds_after_first,
+ bg_rebuilds_after_second,
+ );
+
+ assert!(
+ area_ratio < 0.15,
+ "Sub-rect dispatch & copy area must be < 15% of full-tile area! got {:.2}% ({subrect_px}/{full_tile_px})",
+ area_ratio * 100.0
+ );
+ assert!(
+ dispatched_dabs < dabs_300.len(),
+ "Adaptive micro-step coalescing must reduce dense >32-dab frame passes ({dispatched_dabs} vs {})",
+ dabs_300.len()
+ );
+ assert_eq!(
+ bg_rebuilds_after_first, bg_rebuilds_after_second,
+ "Consecutive ColorMixingStamp frames must allocate ZERO new BindGroups!"
+ );
+
+ let (rgb_mix, a_mix, _) = sample_region_mean_rgba(&doc, &layer_id, 130, 240, 320, 260);
+ assert!(a_mix > 0.85, "Mixed stroke must be opaque: a={a_mix}");
+ assert!(
+ rgb_mix[1] > rgb_mix[0] + 0.04 && rgb_mix[1] > rgb_mix[2] && rgb_mix[1] > 0.35,
+ "Fast per-pixel KM Blue+Yellow must produce vivid Green! got={rgb_mix:?}"
+ );
+
+ // ------------------------------------------------------------------------
+ // 3. Zero dark-halo artifact on transparent edges during live strokes
+ // (SPARSE_STROKE_PROJECT_WGSL halo-free premultiplied 2x2 bilinear)
+ // ------------------------------------------------------------------------
+ let mut doc_halo = make_doc("p5-cmix-halo", 512, 512);
+ let bg_id = doc_halo.layers[0].meta.id.clone();
+ fill_layer_rect(&mut doc_halo, &bg_id, 0, 0, 512, 512, [255, 255, 255, 255]);
+ let _ = doc_halo.add_layer(LayerNodeMeta::new_raster("top-halo", "Top"), Some(0), true, false);
+ let top_id = "top-halo".to_string();
+ doc_halo.active_layer_id = Some(top_id.clone());
+ let _ = renderer.sync_document(&mut doc_halo, None);
+
+ let mut bright_yellow = oil_brush.clone();
+ bright_yellow.fg_color = [1.0, 0.96, 0.0];
+ bright_yellow.size = 44.0;
+ bright_yellow.spacing = 0.12;
+ bright_yellow.hardness = 0.7;
+ bright_yellow.amount_of_paint = 0.95;
+ let (halo_dabs, _, halo_off) =
+ emit_line_dabs(&mut renderer, &bright_yellow, 140.0, 256.0, 360.0, 256.0, 2001);
+
+ renderer.begin_natural_paint_stroke(&doc_halo.id, &top_id, 512, 512, bright_yellow);
+ renderer.set_natural_paint_stroke_rand_offset(halo_off);
+ let top_snap = doc_halo.layer(&top_id).cloned().unwrap();
+ let _ = renderer.dispatch_color_mixing_dabs(&doc_halo, &top_snap, &halo_dabs, None);
+
+ // Render live viewport at fractional zoom (1.37x) to exercise bilinear sampling across edges!
+ let vp = ViewportRect {
+ x_px: 0,
+ y_px: 0,
+ width_px: 512,
+ height_px: 512,
+ dpr: 1.0,
+ };
+ let cam = CameraState {
+ pan_x: 256.3,
+ pan_y: 256.4,
+ zoom: 1.37,
+ rotation: 0.0,
+ flip_x: false,
+ flip_y: false,
+ };
+ let display = CompositorDisplayConfig::default();
+ let cursor_cfg = CursorConfig::default();
+ renderer.render_document_frame_with_brush(
+ &doc_halo,
+ None,
+ &display,
+ &vp,
+ &cam,
+ &[],
+ false,
+ true,
+ &[],
+ None,
+ &cursor_cfg,
+ None,
+ true,
+ );
+ let (rw, rh, fb_rgba) = renderer
+ .readback_headless_rgba8()
+ .expect("readback live viewport framebuffer");
+ assert_eq!((rw, rh), (512, 512));
+
+ // Every pixel in the live yellow-over-white stroke region must stay bright (ZERO dark edge halo!)
+ let mut min_r = 255u8;
+ let mut min_g = 255u8;
+ let mut yellow_edge_pixels = 0usize;
+ for y in 200..312usize {
+ for x in 140..372usize {
+ let off = (y * 512 + x) * 4;
+ let r = fb_rgba[off];
+ let g = fb_rgba[off + 1];
+ let b = fb_rgba[off + 2];
+ if b < 245 && b > 20 {
+ yellow_edge_pixels += 1;
+ min_r = min_r.min(r);
+ min_g = min_g.min(g);
+ }
+ }
+ }
+ let _ = renderer.commit_natural_paint_to_layer();
+ assert!(
+ yellow_edge_pixels > 50,
+ "Expected anti-aliased edge pixels in live stroke viewport, found {yellow_edge_pixels}"
+ );
+ assert!(
+ min_r >= 230 && min_g >= 220,
+ "Live ColorMixingStamp stroke had dark premultiplied alpha halo on transparent edge! min_r={min_r}, min_g={min_g} (expected >= 230, 220)"
+ );
+
+ // ------------------------------------------------------------------------
+ // 4. Paper Texture Mode = Compare vs Multiply AND Dual Brush = true vs false
+ // ------------------------------------------------------------------------
+ let run_cmix_variant =
+ |renderer: &mut GpuRenderer, name: &str, brush: &NativeBrushConfig| -> Vec<u8> {
+ let mut d = make_doc(name, 512, 512);
+ let lid = d.layers[0].meta.id.clone();
+ let _ = renderer.sync_document(&mut d, None);
+ let (pd, sd, goff) =
+ emit_line_dabs(renderer, brush, 90.0, 256.0, 380.0, 256.0, 3001);
+ renderer.begin_natural_paint_stroke(&d.id, &lid, 512, 512, brush.clone());
+ renderer.set_natural_paint_stroke_rand_offset(goff);
+ let lsnap = d.layer(&lid).cloned().unwrap();
+ let _ = renderer.dispatch_color_mixing_dabs_with_secondary(&d, &lsnap, &pd, &sd, None);
+ let b = renderer
+ .commit_natural_paint_to_layer()
+ .expect("commit variant");
+ let es = HashMap::new();
+ let _ = d
+ .layer_mut(&lid)
+ .unwrap()
+ .grid
+ .apply_gpu_committed_tiles(&lid, b.color_tiles, &es, 128);
+ let layer = d.layer(&lid).unwrap();
+ let mut out = Vec::with_capacity((340 * 100 * 4) as usize);
+ for y in 206..306 {
+ for x in 70..410 {
+ out.extend_from_slice(&layer.grid.get_pixel_rgba8(x, y, None));
+ }
+ }
+ out
+ };
+
+ let mean_abs_diff = |a: &[u8], b: &[u8]| -> f64 {
+ assert_eq!(a.len(), b.len());
+ let sum: u64 = a
+ .iter()
+ .zip(b.iter())
+ .map(|(&x, &y)| x.abs_diff(y) as u64)
+ .sum();
+ sum as f64 / a.len().max(1) as f64
+ };
+
+ // 4a. Paper Texture Mode: Multiply vs Compare
+ let mut paper_mult = oil_brush.clone();
+ paper_mult.fg_color = [0.22, 0.35, 0.78];
+ paper_mult.hardness = 0.45;
+ paper_mult.spacing = 0.16;
+ paper_mult.flow = 0.65;
+ paper_mult.brush_density = 0.65;
+ paper_mult.surface_texture_id = Some("cold-press-watercolor".to_string());
+ paper_mult.grain = 0.85;
+ paper_mult.paper_texture_mode = CspPaperTextureMode::Multiply;
+
+ let mut paper_cmp = paper_mult.clone();
+ paper_cmp.paper_texture_mode = CspPaperTextureMode::Compare;
+
+ let px_mult = run_cmix_variant(&mut renderer, "p5-cmix-paper-mult", &paper_mult);
+ let px_cmp = run_cmix_variant(&mut renderer, "p5-cmix-paper-cmp", &paper_cmp);
+ let paper_diff = mean_abs_diff(&px_mult, &px_cmp);
+ assert!(
+ paper_diff > 2.5,
+ "paper_texture_mode=Compare must produce measurably distinct output from Multiply on ColorMixingStamp! diff={paper_diff:.3}"
+ );
+
+ // 4b. Dual Brush: disabled vs enabled (Multiply with smaller scattered secondary mask)
+ let mut dual_off = oil_brush.clone();
+ dual_off.fg_color = [0.75, 0.22, 0.18];
+ dual_off.spacing = 0.14;
+ dual_off.dual_brush = false;
+ dual_off.dual_brush_config = None;
+
+ let mut dual_on = dual_off.clone();
+ dual_on.dual_brush = true;
+ dual_on.dual_brush_config = Some(CspDualBrushConfig {
+ enabled: true,
+ combine_mode: DualBrushCompositeMode::Multiply,
+ link_size: false,
+ size: 20.0,
+ spacing: 1.4, // wide spacing so secondary leaves clear gaps that carve primary
+ hardness: 0.85,
+ density: 0.85,
+ ..CspDualBrushConfig::default()
+ });
+
+ let px_dual_off = run_cmix_variant(&mut renderer, "p5-cmix-dual-off", &dual_off);
+ let px_dual_on = run_cmix_variant(&mut renderer, "p5-cmix-dual-on", &dual_on);
+ let dual_diff = mean_abs_diff(&px_dual_off, &px_dual_on);
+ assert!(
+ dual_diff > 5.0,
+ "dual_brush=true must produce measurably distinct output on ColorMixingStamp! diff={dual_diff:.3}"
+ );
+
+ // 4c. Stroke-level config.opacity capping & watercolor wet_edge
+ let mut wash_brush = oil_brush.clone();
+ wash_brush.fg_color = [0.15, 0.55, 0.88];
+ wash_brush.opacity = 0.45;
+ wash_brush.spacing = 0.08;
+ wash_brush.wet_edge = 0.0;
+ let px_wash_no_wet = run_cmix_variant(&mut renderer, "p5-cmix-opacity-cap", &wash_brush);
+ let max_alpha = px_wash_no_wet
+ .chunks_exact(4)
+ .map(|c| c[3])
+ .max()
+ .unwrap_or(0);
+ assert!(
+ max_alpha > 80 && max_alpha <= 130,
+ "Stroke-level config.opacity=0.45 must cap overlapping stroke alpha near ~115 (got max_alpha={max_alpha})"
+ );
+
+ let mut wash_wet = wash_brush.clone();
+ wash_wet.wet_edge = 0.48;
+ wash_wet.wet_edge_radius = 4.0;
+ let px_wash_wet = run_cmix_variant(&mut renderer, "p5-cmix-wet-edge", &wash_wet);
+ let wet_diff = mean_abs_diff(&px_wash_no_wet, &px_wash_wet);
+ let max_wet_px_diff = px_wash_no_wet
+ .iter()
+ .zip(px_wash_wet.iter())
+ .map(|(&a, &b)| a.abs_diff(b))
+ .max()
+ .unwrap_or(0);
+ let max_alpha_wet = px_wash_wet
+ .chunks_exact(4)
+ .map(|c| c[3])
+ .max()
+ .unwrap_or(0);
+ assert!(
+ wet_diff > 0.2 && max_wet_px_diff >= 6 && max_alpha_wet > max_alpha,
+ "wet_edge=0.48 must produce measurable watercolor edge darkening/pooling on ColorMixingStamp! diff={wet_diff:.3}, max_px_diff={max_wet_px_diff}, max_alpha={max_alpha}->{max_alpha_wet}"
+ );
+}
+
+// ============================================================================
+// 9. Performance & Parity Regression Tests (Binning, Underbed, TiltMax, Ribbon, GPU Pack)
+// ============================================================================
+
+#[test]
+fn test_p5_natural_paint_per_tile_capsule_binning_and_wet_edge() {
+ let _dx12_guard = crate::lock_dx12_test();
+ let Some(mut renderer) = make_headless_renderer(256, 256, 1024, 256) else {
+ return;
+ };
+
+ // Multi-tile horizontal NaturalPaint stroke spanning 4 tiles (x = 40..980)
+ let mut brush = make_wet_filbert_brush([0.12, 0.42, 0.86], 44.0);
+ brush.preset_key = Some("p5-binning-test".to_string());
+ brush.mix_ground_color = false;
+ brush.natural_paint.as_mut().unwrap().auto_clean = true;
+ brush.natural_paint.as_mut().unwrap().spatial_mixing = true;
+ brush.natural_paint.as_mut().unwrap().depletion_rate = 0.0;
+
+ let pts = make_line_points(40.0, 128.0, 980.0, 128.0, 48, 44.0, 0.85);
+ let mut sim = BristleRibbonSimulator::new(&brush, 777);
+ let mut capsules = Vec::new();
+ sim.step_points(&pts, &brush, &mut capsules);
+ assert!(capsules.len() >= 200, "Expected multi-tile capsule batch, got {}", capsules.len());
+
+ // A) Full 4-tile binned dispatch
+ let mut doc_binned = make_doc("p5-np-binned", 1024, 256);
+ let lid_b = doc_binned.layers[0].meta.id.clone();
+ let _ = renderer.sync_document(&mut doc_binned, None);
+ renderer.begin_natural_paint_stroke(&doc_binned.id, &lid_b, 1024, 256, brush.clone());
+ let lsnap_b = doc_binned.layer(&lid_b).cloned().unwrap();
+ let _ = renderer.dispatch_natural_paint_capsules(&doc_binned, &lsnap_b, &capsules, None);
+
+ let binned_checks = renderer.brush_engine().natural_paint.np_last_batch_binned_checks;
+ let unbinned_checks = renderer.brush_engine().natural_paint.np_last_batch_unbinned_checks;
+ let subrect_px = renderer.brush_engine().natural_paint.np_last_batch_subrect_pixels;
+ let bg_rebuilds_1 = renderer.brush_engine().natural_paint.np_bind_group_rebuilds;
+
+ // Second dispatch on same stroke should NOT rebuild cached pickup/raster BindGroups!
+ let _ = renderer.dispatch_natural_paint_capsules(&doc_binned, &lsnap_b, &capsules[..16], None);
+ let bg_rebuilds_2 = renderer.brush_engine().natural_paint.np_bind_group_rebuilds;
+
+ assert!(
+ binned_checks > 0 && binned_checks * 2 < unbinned_checks,
+ "Per-tile capsule binning must check < 50% of unbinned tile×capsule pairs! binned={binned_checks}, unbinned={unbinned_checks}"
+ );
+ assert!(
+ subrect_px < 4 * 256 * 256 / 2,
+ "Tight tile-local sub-rect must cover < 50% of 4 full tiles! subrect_px={subrect_px}"
+ );
+ assert_eq!(
+ bg_rebuilds_1, bg_rebuilds_2,
+ "Cached pickup_bg/raster_bg must incur 0 BindGroup rebuilds on steady-state follow-up batches!"
+ );
+ let _ = renderer.commit_natural_paint_to_layer();
+
+ // B) Verify binned multi-tile rendering is bit-identical to unbinned single-tile reference
+ let mut doc_all = make_doc("p5-np-bin-all", 1024, 256);
+ let lid_all = doc_all.layers[0].meta.id.clone();
+ let _ = renderer.sync_document(&mut doc_all, None);
+ renderer.begin_natural_paint_stroke(&doc_all.id, &lid_all, 1024, 256, brush.clone());
+ let lsnap_all = doc_all.layer(&lid_all).cloned().unwrap();
+ let _ = renderer.dispatch_natural_paint_capsules(&doc_all, &lsnap_all, &capsules, None);
+ let batch_all = renderer.commit_natural_paint_to_layer().expect("commit all");
+ let empty_snap = HashMap::new();
+ let _ = doc_all
+ .layer_mut(&lid_all)
+ .unwrap()
+ .grid
+ .apply_gpu_committed_tiles(&lid_all, batch_all.color_tiles, &empty_snap, 128);
+
+ // Filter strictly to capsules whose AABB overlaps tile (0, 0) (`x < 256`) and dispatch alone
+ let tile0_caps: Vec<_> = capsules
+ .iter()
+ .copied()
+ .filter(|c| {
+ let (x0, _, x1, _) = c.doc_bounds();
+ x0 < 256.0 && x1 >= 0.0
+ })
+ .collect();
+ assert!(tile0_caps.len() < capsules.len() / 2);
+
+ let mut doc_ref = make_doc("p5-np-bin-ref", 1024, 256);
+ let lid_ref = doc_ref.layers[0].meta.id.clone();
+ let _ = renderer.sync_document(&mut doc_ref, None);
+ renderer.begin_natural_paint_stroke(&doc_ref.id, &lid_ref, 1024, 256, brush.clone());
+ let lsnap_ref = doc_ref.layer(&lid_ref).cloned().unwrap();
+ let _ = renderer.dispatch_natural_paint_capsules(&doc_ref, &lsnap_ref, &tile0_caps, None);
+ let batch_ref = renderer.commit_natural_paint_to_layer().expect("commit ref");
+ let _ = doc_ref
+ .layer_mut(&lid_ref)
+ .unwrap()
+ .grid
+ .apply_gpu_committed_tiles(&lid_ref, batch_ref.color_tiles, &empty_snap, 128);
+
+ let l_all = doc_all.layer(&lid_all).unwrap();
+ let l_ref = doc_ref.layer(&lid_ref).unwrap();
+ let mut max_diff = 0u8;
+ let mut painted_px = 0usize;
+ for y in 64..192 {
+ for x in 16..240 {
+ let pa = l_all.grid.get_pixel_rgba8(x, y, None);
+ let pr = l_ref.grid.get_pixel_rgba8(x, y, None);
+ if pa[3] > 20 {
+ painted_px += 1;
+ }
+ for c in 0..4 {
+ max_diff = max_diff.max(pa[c].abs_diff(pr[c]));
+ }
+ }
+ }
+ assert!(painted_px > 2000, "Expected painted pixels in tile 0, got {painted_px}");
+ assert!(
+ max_diff <= 1,
+ "Per-tile capsule binning must match unbinned tile-local reference (max_diff={max_diff})"
+ );
+
+ // C) Verify wet_edge > 0.01 works on NaturalPaint (e.g. granulating-watercolor)
+ let mut wc_off = make_wet_filbert_brush([0.14, 0.48, 0.85], 40.0);
+ wc_off.preset_key = Some("p5-np-wet-off".to_string());
+ wc_off.mix_ground_color = false;
+ wc_off.opacity = 0.55;
+ wc_off.wet_edge = 0.0;
+
+ let mut wc_on = wc_off.clone();
+ wc_on.preset_key = Some("p5-np-wet-on".to_string());
+ wc_on.wet_edge = 0.65;
+ wc_on.wet_edge_radius = 4.0;
+
+ let wc_pts = make_line_points(60.0, 128.0, 260.0, 128.0, 24, 40.0, 0.8);
+ let mut doc_w0 = make_doc("p5-np-wet0", 512, 256);
+ let lw0 = doc_w0.layers[0].meta.id.clone();
+ run_natural_paint_stroke(&mut renderer, &mut doc_w0, &lw0, wc_off, &wc_pts, 801);
+
+ let mut doc_w1 = make_doc("p5-np-wet1", 512, 256);
+ let lw1 = doc_w1.layers[0].meta.id.clone();
+ run_natural_paint_stroke(&mut renderer, &mut doc_w1, &lw1, wc_on, &wc_pts, 801);
+
+ let l0 = doc_w0.layer(&lw0).unwrap();
+ let l1 = doc_w1.layer(&lw1).unwrap();
+ let mut wet_max_diff = 0u8;
+ for y in 90..166 {
+ for x in 45..275 {
+ let p0 = l0.grid.get_pixel_rgba8(x, y, None);
+ let p1 = l1.grid.get_pixel_rgba8(x, y, None);
+ for c in 0..4 {
+ wet_max_diff = wet_max_diff.max(p0[c].abs_diff(p1[c]));
+ }
+ }
+ }
+ assert!(
+ wet_max_diff >= 8,
+ "NaturalPaint with wet_edge=0.65 must produce measurable rim darkening/pooling! wet_max_diff={wet_max_diff}"
+ );
+}
+
+#[test]
+fn test_p5_underbed_bands_do_not_corrupt_bristles_0_to_4() {
+ let _dx12_guard = crate::lock_dx12_test();
+ use crate::natural_paint::{
+ GpuBristleCapsule, MAX_BRISTLES, TOTAL_BRISTLE_SLOTS, UNDERBED_BANDS, UNDERBED_SLOT_BASE,
+ };
+
+ // 1. CPU BristleRibbonSimulator must assign dedicated reservoir indices `64..69` to underbed bands
+ let brush = make_wet_filbert_brush([1.0, 1.0, 1.0], 48.0);
+ let mut sim = BristleRibbonSimulator::new(&brush, 1234);
+ let pts = make_line_points(40.0, 128.0, 220.0, 128.0, 18, 48.0, 0.85);
+ let mut caps = Vec::new();
+ sim.step_points(&pts, &brush, &mut caps);
+
+ let mut underbed_count = 0usize;
+ let mut bristle_count = 0usize;
+ for cap in &caps {
+ let flags = (cap.strand[3] + 0.5) as u32;
+ let idx = (cap.strand[0] + 0.5) as usize;
+ if (flags & 1) != 0 {
+ underbed_count += 1;
+ assert!(
+ idx >= UNDERBED_SLOT_BASE && idx < TOTAL_BRISTLE_SLOTS,
+ "Underbed band must use dedicated slot in {}..{}, got {}",
+ UNDERBED_SLOT_BASE,
+ TOTAL_BRISTLE_SLOTS,
+ idx
+ );
+ } else {
+ bristle_count += 1;
+ assert!(
+ idx < MAX_BRISTLES,
+ "Real bristle must use slot in 0..{}, got {}",
+ MAX_BRISTLES,
+ idx
+ );
+ }
+ }
+ assert!(underbed_count >= UNDERBED_BANDS && bristle_count > 50);
+
+ // 2. GPU verification: real bristles 0..4 pass over pure BLUE, while underbed bands 64..68
+ // pass over pure RED — assert slots 0..4 stay BLUE and are NEVER corrupted by RED!
+ let Some(mut renderer) = make_headless_renderer(256, 256, 512, 256) else {
+ return;
+ };
+ let mut doc = make_doc("p5-underbed-isolation", 512, 256);
+ let lid = doc.layers[0].meta.id.clone();
+ fill_layer_rect(&mut doc, &lid, 0, 0, 512, 128, [10, 35, 245, 255]); // top half: BLUE
+ fill_layer_rect(&mut doc, &lid, 0, 128, 512, 128, [245, 15, 15, 255]); // bottom half: RED
+ let _ = renderer.sync_document(&mut doc, None);
+
+ let mut iso_brush = make_wet_filbert_brush([1.0, 1.0, 1.0], 32.0);
+ iso_brush.preset_key = Some("p5-underbed-iso-key".to_string());
+ iso_brush.mix_ground_color = false;
+ iso_brush.amount_of_paint = 0.05;
+ iso_brush.natural_paint.as_mut().unwrap().spatial_mixing = true;
+ iso_brush.natural_paint.as_mut().unwrap().auto_clean = true;
+ iso_brush.natural_paint.as_mut().unwrap().wetness = 0.95;
+
+ let mut test_caps = Vec::new();
+ for step in 0..6 {
+ let x0 = 60.0 + step as f32 * 24.0;
+ let x1 = x0 + 24.0;
+ for b in 0..5usize {
+ // Real bristles 0..4 travel across top BLUE half (y = 40..80)
+ let yb = 40.0 + b as f32 * 10.0;
+ test_caps.push(GpuBristleCapsule {
+ p0_p1: [x0, yb, x1, yb],
+ geom: [4.0, 4.0, 0.9, 0.8],
+ strand: [b as f32, 0.1, 0.8, 0.0],
+ motion: [(step as f32 + 1.0) * 24.0, 24.0, 0.0, 0.0],
+ });
+ // Underbed bands 64..68 travel across bottom RED half (y = 160..200)
+ let yu = 160.0 + b as f32 * 10.0;
+ test_caps.push(GpuBristleCapsule {
+ p0_p1: [x0, yu, x1, yu],
+ geom: [8.0, 8.0, 0.9, 0.6],
+ strand: [(UNDERBED_SLOT_BASE + b) as f32, 0.2, 0.45, 1.0],
+ motion: [(step as f32 + 1.0) * 24.0, 24.0, 0.0, 0.0],
+ });
+ }
+ }
+
+ renderer.begin_natural_paint_stroke(&doc.id, &lid, 512, 256, iso_brush);
+ let lsnap = doc.layer(&lid).cloned().unwrap();
+ let _ = renderer.dispatch_natural_paint_capsules(&doc, &lsnap, &test_caps, None);
+ let slots = renderer
+ .brush_engine()
+ .natural_paint
+ .readback_bristle_slots(renderer.device(), renderer.queue(), "p5-underbed-iso-key")
+ .expect("readback bristle + underbed slots");
+ let _ = renderer.commit_natural_paint_to_layer();
+
+ assert_eq!(slots.len(), TOTAL_BRISTLE_SLOTS);
+ for b in 0..5usize {
+ let rgb = slots[b].color_load;
+ assert!(
+ rgb[2] > rgb[0] + 0.20,
+ "Real bristle slot {b} must retain BLUE pickup and NEVER be corrupted by RED underbed! got={rgb:?}"
+ );
+ }
+ for u in 0..UNDERBED_BANDS {
+ let rgb = slots[UNDERBED_SLOT_BASE + u].color_load;
+ assert!(
+ rgb[0] > rgb[2] + 0.20,
+ "Underbed slot {} must independently track RED pickup! got={rgb:?}",
+ UNDERBED_SLOT_BASE + u
+ );
+ }
+}
+
+#[test]
+fn test_p5_size_sensor_tilt_max_grows_brush_size() {
+ use crate::brush::{evaluate_csp_sensor, CompiledSensorLuts};
+
+ // 1. JSON deserialization defaults & explicit tiltMax
+ let explicit: CspSensorConfig =
+ serde_json::from_str(r#"{"useTilt":true,"tiltMin":1.0,"tiltMax":1.5}"#)
+ .expect("deserialize explicit tiltMax");
+ assert!((explicit.tilt_min - 1.0).abs() < 1e-5);
+ assert!((explicit.tilt_max - 1.5).abs() < 1e-5);
+
+ let defaulted: CspSensorConfig =
+ serde_json::from_str(r#"{"useTilt":true,"tiltMin":0.25}"#)
+ .expect("deserialize default tiltMax");
+ assert!((defaulted.tilt_max - 1.0).abs() < 1e-5);
+
+ // 2. Direct evaluate_csp_sensor check
+ let luts = CompiledSensorLuts::from_sensor(Some(&explicit));
+ let upright_mult = evaluate_csp_sensor(&explicit, Some(&luts), 1.0, 0.0, 0.0, 0.0, 0.5);
+ let tilted_mult = evaluate_csp_sensor(&explicit, Some(&luts), 1.0, 1.0, 0.0, 0.0, 0.5);
+ assert!(
+ (upright_mult - 1.0).abs() < 1e-4,
+ "Upright pen must stay 1.0x, got {upright_mult}"
+ );
+ assert!(
+ (tilted_mult - 1.5).abs() < 1e-4,
+ "Full pen tilt with tiltMin=1.0, tiltMax=1.5 must grow size by 1.5x! got {tilted_mult}"
+ );
+
+ // 3. End-to-end StrokeDabEmitter check (G-Pen style brush with sizeSensor tiltMax=1.5)
+ let brush = NativeBrushConfig {
+ size: 20.0,
+ use_pressure: true,
+ use_tilt: true,
+ tilt_scale: 1.0, // Pure sizeSensor tiltMax enlargement
+ size_sensor: Some(explicit),
+ ..NativeBrushConfig::default()
+ };
+ let mut emitter = StrokeDabEmitter::new(brush, 999, 1, 1.0);
+ let mut dabs_upright = Vec::new();
+ let mut dabs_tilted = Vec::new();
+ let pt_up = StrokePoint {
+ x: 100.0,
+ y: 100.0,
+ pressure: 1.0,
+ width: 20.0,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ ..Default::default()
+ };
+ let pt_tilt = StrokePoint {
+ x: 100.0,
+ y: 100.0,
+ pressure: 1.0,
+ width: 20.0,
+ tilt_x: 75.0,
+ tilt_y: 0.0,
+ ..Default::default()
+ };
+ emitter.emit_initial_point(&pt_up, None, 0.0, &mut dabs_upright);
+ emitter.emit_initial_point(&pt_tilt, None, 0.0, &mut dabs_tilted);
+ let hw_up = dabs_upright[0].pos_size[2];
+ let hw_tilt = dabs_tilted[0].pos_size[2];
+ assert!(
+ ((hw_tilt / hw_up) - 1.5).abs() < 1e-3,
+ "StrokeDabEmitter with sizeSensor tiltMin=1.0, tiltMax=1.5 must swell dab width by 1.5x! upright={hw_up}, tilted={hw_tilt}"
+ );
+}
+
+#[test]
+fn test_p5_ribbon_incremental_triangulation_and_paper_contrast() {
+ let _dx12_guard = crate::lock_dx12_test();
+
+ // Build a 40-point curved + sharp-corner stroke
+ let mut pts = Vec::with_capacity(40);
+ for i in 0..40 {
+ let t = i as f64 / 39.0;
+ let (x, y, corner) = if i == 20 {
+ (220.0, 200.0, true)
+ } else if i < 20 {
+ (30.0 + t * 380.0, 90.0 + (t * std::f64::consts::TAU).sin() * 45.0, false)
+ } else {
+ (30.0 + t * 380.0, 170.0 - (t * std::f64::consts::TAU).cos() * 40.0, false)
+ };
+ pts.push(StrokePoint {
+ x,
+ y,
+ pressure: 0.55 + 0.4 * (t as f32),
+ width: 28.0,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ velocity: 0.6,
+ timestamp_ms: i as f64 * 4.0,
+ is_corner: corner,
+ });
+ }
+
+ // 1. Incremental chunked triangulation (3 pts/frame) must match full single-call triangulation
+ // across ALL 3 RibbonRepeatModes (Repeat, Reverse, Once)!
+ for mode in [
+ RibbonRepeatMode::Repeat,
+ RibbonRepeatMode::Reverse,
+ RibbonRepeatMode::Once,
+ ] {
+ let brush = NativeBrushConfig {
+ fg_color: [0.2, 0.35, 0.85],
+ bg_color: [0.9, 0.7, 0.2],
+ size: 32.0,
+ opacity: 0.9,
+ flow: 1.0,
+ is_ribbon: true,
+ ribbon_repeat_mode: mode,
+ sub_tip_order: CspSubTipOrder::Sequential,
+ flip_h: CspTipFlipMode::Alternate,
+ flip_v: CspTipFlipMode::None,
+ ..NativeBrushConfig::default()
+ };
+
+ let mut full_builder = RibbonMeshBuilder::new(64, 64, 3, 424242);
+ let mut full_verts = Vec::new();
+ full_builder.push_points(&pts, &brush, &mut full_verts);
+ full_builder.finish(&brush, &mut full_verts);
+
+ let mut inc_builder = RibbonMeshBuilder::new(64, 64, 3, 424242);
+ let mut inc_verts = Vec::new();
+ for chunk in pts.chunks(3) {
+ inc_builder.push_points(chunk, &brush, &mut inc_verts);
+ }
+ inc_builder.finish(&brush, &mut inc_verts);
+
+ assert_eq!(
+ inc_verts.len(),
+ full_verts.len(),
+ "[{mode:?}] Incremental ribbon vertex count must match full triangulation!"
+ );
+ for (idx, (iv, fv)) in inc_verts.iter().zip(full_verts.iter()).enumerate() {
+ assert!(
+ (iv.doc_pos[0] - fv.doc_pos[0]).abs() < 1e-3
+ && (iv.doc_pos[1] - fv.doc_pos[1]).abs() < 1e-3
+ && (iv.uv[0] - fv.uv[0]).abs() < 1e-3
+ && (iv.uv[1] - fv.uv[1]).abs() < 1e-3
+ && (iv.fg_alpha[3] - fv.fg_alpha[3]).abs() < 1e-3
+ && (iv.sub_bg[0] - fv.sub_bg[0]).abs() < 1e-3,
+ "[{mode:?}] Vertex {idx} mismatch! inc={iv:?}, full={fv:?}"
+ );
+ }
+ }
+
+ // 2. GPU check: RIBBON_MESH_WGSL paper mode Normal (7) + scaled brightness/contrast (-100..100)
+ // must NOT blow out contrast to pure binary black/white, and must differ cleanly from 0 contrast!
+ let Some(mut renderer) = make_headless_renderer(256, 256, 768, 256) else {
+ return;
+ };
+ let line_pts = make_line_points(40.0, 128.0, 700.0, 128.0, 36, 48.0, 1.0);
+
+ let render_ribbon_strip = |renderer: &mut GpuRenderer,
+ doc_id: &str,
+ contrast: f32,
+ brightness: f32|
+ -> (Vec<u8>, usize, usize) {
+ let brush = NativeBrushConfig {
+ fg_color: [0.15, 0.25, 0.75],
+ size: 48.0,
+ opacity: 1.0,
+ flow: 1.0,
+ is_ribbon: true,
+ ribbon_repeat_mode: RibbonRepeatMode::Repeat,
+ surface_texture_id: Some("rough-cold-press".to_string()),
+ grain: 0.75,
+ paper_texture_apply_each_plot: true,
+ paper_texture_mode: CspPaperTextureMode::Normal,
+ paper_texture_contrast: contrast,
+ paper_texture_brightness: brightness,
+ ..NativeBrushConfig::default()
+ };
+ let mut doc = make_doc(doc_id, 768, 256);
+ let lid = doc.layers[0].meta.id.clone();
+ let _ = renderer.sync_document(&mut doc, None);
+ let mut rb = RibbonMeshBuilder::new(64, 64, 1, 5555);
+ let mut verts = Vec::new();
+ rb.push_points(&line_pts, &brush, &mut verts);
+ rb.finish(&brush, &mut verts);
+ renderer.begin_gpu_stroke(768, 256, false, brush, [0.0, 0.0]);
+ let _ = renderer.stamp_gpu_ribbon_vertices(&verts, &[], false);
+ let binned = renderer.brush_engine().ribbon_pipeline.last_batch_binned_indices;
+ let unbinned = renderer.brush_engine().ribbon_pipeline.last_batch_unbinned_indices;
+ let grid = doc.layer(&lid).unwrap().grid.clone();
+ let batch = renderer
+ .commit_gpu_stroke_to_layer(&doc.id, &lid, &grid, None, false, false)
+ .expect("commit ribbon");
+ let es = HashMap::new();
+ let _ = doc
+ .layer_mut(&lid)
+ .unwrap()
+ .grid
+ .apply_gpu_committed_tiles(&lid, batch.tiles, &es, 128);
+ renderer.clear_live_stroke();
+ let layer = doc.layer(&lid).unwrap();
+ let mut alphas = Vec::with_capacity(600 * 30);
+ for y in 113..143 {
+ for x in 60..660 {
+ alphas.push(layer.grid.get_pixel_rgba8(x, y, None)[3]);
+ }
+ }
+ (alphas, binned, unbinned)
+ };
+
+ let (a_base, binned_idx, unbinned_idx) =
+ render_ribbon_strip(&mut renderer, "p5-rib-contrast-0", 0.0, 0.0);
+ let (a_mod, _, _) = render_ribbon_strip(&mut renderer, "p5-rib-contrast-25", 25.0, 10.0);
+
+ // Per-tile triangle binning must dramatically reduce drawn indices across 3 tiles!
+ assert!(
+ binned_idx > 0 && binned_idx < unbinned_idx / 2,
+ "Ribbon per-tile triangle binning must draw < 50% of unbinned indices! binned={binned_idx}, unbinned={unbinned_idx}"
+ );
+ // Mid-tone alpha values must survive (not blown out to 0 or 255 by unscaled contrast!)
+ let mid_tones = a_mod.iter().filter(|&&a| a > 30 && a < 245).count();
+ assert!(
+ mid_tones > 1000,
+ "RIBBON_MESH_WGSL Normal mode + contrast=25, brightness=10 must preserve rich mid-tone paper grain instead of blowing out to pure 0/255! mid_tones={mid_tones}"
+ );
+ let mean_diff: f64 = a_base
+ .iter()
+ .zip(a_mod.iter())
+ .map(|(&x, &y)| x.abs_diff(y) as f64)
+ .sum::<f64>()
+ / a_base.len() as f64;
+ assert!(
+ mean_diff > 1.0 && mean_diff < 60.0,
+ "Scaled brightness/contrast (+10/+25) must gently shift paper grain without clipping! mean_diff={mean_diff:.2}"
+ );
+}
+
+#[test]
+fn test_p5_natural_paint_gpu_rgba8_pack_matches_cpu_dithered() {
+ let _dx12_guard = crate::lock_dx12_test();
+ use crate::natural_paint::NaturalPaintTilePools;
+ use crate::tiles::format::rgba16f_to_rgba8_dithered;
+ use crate::tiles::{TileCoord, BYTES_16F, BYTES_32BIT, TILE_SIZE};
+
+ let Some(renderer) = make_headless_renderer(256, 256, 256, 256) else {
+ return;
+ };
+
+ // Build a deterministic 256×256 Rgba16Float tile covering exact 0.0, exact 1.0, and smooth fractional gradients
+ let mut raw_16f = vec![0u8; BYTES_16F];
+ for y in 0..TILE_SIZE {
+ for x in 0..TILE_SIZE {
+ let (r, g, b, a) = if y == 0 {
+ (0.0f32, 0.0f32, 0.0f32, 0.0f32)
+ } else if y == 1 {
+ (1.0f32, 1.0f32, 1.0f32, 1.0f32)
+ } else {
+ (
+ x as f32 / 255.0,
+ y as f32 / 255.0,
+ ((x + y) as f32 / 510.0) * 0.85 + 0.05,
+ ((x * 3 + y * 5) % 256) as f32 / 255.0,
+ )
+ };
+ let off = (y * TILE_SIZE + x) * 8;
+ raw_16f[off..off + 2].copy_from_slice(&half::f16::from_f32(r).to_bits().to_le_bytes());
+ raw_16f[off + 2..off + 4]
+ .copy_from_slice(&half::f16::from_f32(g).to_bits().to_le_bytes());
+ raw_16f[off + 4..off + 6]
+ .copy_from_slice(&half::f16::from_f32(b).to_bits().to_le_bytes());
+ raw_16f[off + 6..off + 8]
+ .copy_from_slice(&half::f16::from_f32(a).to_bits().to_le_bytes());
+ }
+ }
+
+ // CPU reference Bayer-dithered RGBA8
+ let mut cpu_rgba8 = vec![0u8; BYTES_32BIT];
+ rgba16f_to_rgba8_dithered(&raw_16f, &mut cpu_rgba8);
+
+ // Upload raw_16f directly to NaturalPaintTilePools slot 0 and commit via GPU Bayer-dithered pack
+ let mut pools = NaturalPaintTilePools::new(renderer.device(), 32);
+ let coord = TileCoord::new(0, 0);
+ pools.coord_to_slot.insert(coord, 0);
+ renderer.queue().write_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: &pools.color_tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ &raw_16f,
+ wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some((TILE_SIZE * 8) as u32),
+ rows_per_image: Some(TILE_SIZE as u32),
+ },
+ wgpu::Extent3d {
+ width: TILE_SIZE as u32,
+ height: TILE_SIZE as u32,
+ depth_or_array_layers: 1,
+ },
+ );
+
+ let mut tile_pool = crate::memory::GpuTilePool::new(renderer.device(), 32);
+ let batch = pools
+ .commit_to_layer_pool(
+ renderer.device(),
+ renderer.queue(),
+ &mut tile_pool,
+ "pack-doc",
+ "pack-layer",
+ )
+ .expect("GPU Bayer-dithered RGBA8 commit");
+
+ assert_eq!(batch.color_tiles.len(), 1);
+ let (out_coord, gpu_rgba8, out_ver) = &batch.color_tiles[0];
+ assert_eq!(*out_coord, coord);
+ assert_eq!(gpu_rgba8.len(), BYTES_32BIT);
+
+ // Verify committed tile is immediately resident in GpuTilePool!
+ let resident_key = tile_pool.make_key("pack-doc", "pack-layer", 0, coord);
+ assert!(
+ tile_pool.get_slot_if_version(&resident_key, *out_ver).is_some(),
+ "Committed tile must be immediately resident in GpuTilePool at pen-up!"
+ );
+
+ // Exact 0.0 -> 0 and 1.0 -> 255 endpoints
+ for x in 0..TILE_SIZE {
+ let off0 = x * 4;
+ assert_eq!(&gpu_rgba8[off0..off0 + 4], &[0, 0, 0, 0], "Exact 0.0 endpoint must stay 0");
+ let off1 = (TILE_SIZE + x) * 4;
+ assert_eq!(
+ &gpu_rgba8[off1..off1 + 4],
+ &[255, 255, 255, 255],
+ "Exact 1.0 endpoint must stay 255"
+ );
+ }
+
+ // Compare all 262,144 channels against CPU Bayer-dithered reference
+ let mut max_diff = 0u8;
+ let mut sum_diff = 0u64;
+ for (&g, &c) in gpu_rgba8.iter().zip(cpu_rgba8.iter()) {
+ let d = g.abs_diff(c);
+ max_diff = max_diff.max(d);
+ sum_diff += d as u64;
+ }
+ let mean_diff = sum_diff as f64 / BYTES_32BIT as f64;
+ assert!(
+ max_diff <= 1 && mean_diff < 0.05,
+ "GPU Bayer-dithered RGBA8 pack must match CPU rgba16f_to_rgba8_dithered! max_diff={max_diff}, mean_diff={mean_diff:.5}"
+ );
+}
diff --git a/crates/ink-engine/src/phase6_tests.rs b/crates/ink-engine/src/phase6_tests.rs
index 90982ab..ab72051 100644
--- a/crates/ink-engine/src/phase6_tests.rs
+++ b/crates/ink-engine/src/phase6_tests.rs
@@ -156,6 +156,7 @@ fn make_line_pts(x0: f64, y0: f64, x1: f64, y1: f64, count: usize, width: f32) -
#[test]
fn test_phase6_selection_mask_ops_and_gpu_marching_ants() {
+ let _dx12_guard = crate::lock_dx12_test();
let mut doc = make_doc("sel-doc", 512, 512);
let l1 = active_id(&doc);
@@ -343,6 +344,7 @@ fn test_phase6_selection_mask_ops_and_gpu_marching_ants() {
#[test]
fn test_phase6_brush_commit_clipped_by_selection_mask() {
+ let _dx12_guard = crate::lock_dx12_test();
let Some(mut renderer) = make_headless_renderer(256, 256, 512, 512) else {
return;
};
@@ -406,6 +408,7 @@ fn test_phase6_brush_commit_clipped_by_selection_mask() {
#[test]
fn test_phase6_gpu_liquify_all_8_modes_reconstruct_and_multilayer() {
+ let _dx12_guard = crate::lock_dx12_test();
let Some(mut renderer) = make_headless_renderer(256, 256, 512, 512) else {
return;
};
@@ -667,6 +670,7 @@ fn test_phase6_flood_fill_smart_line_fill_and_eyedropper() {
#[test]
fn test_phase6_gpu_transform_all_5_modes_and_switch_mode() {
+ let _dx12_guard = crate::lock_dx12_test();
let Some(mut renderer) = make_headless_renderer(256, 256, 512, 512) else {
return;
};
@@ -1224,6 +1228,7 @@ fn test_phase6_filters_tonal_corrections_and_histogram() {
#[test]
fn test_phase6_collab_gpu_draft_handoff_wire_codec_and_webp() {
+ let _dx12_guard = crate::lock_dx12_test();
let mut doc_a = make_doc("collab-a", 512, 512);
let mut doc_b = make_doc("collab-b", 512, 512);
let lid = active_id(&doc_a);
@@ -1378,6 +1383,7 @@ fn test_phase6_collab_gpu_draft_handoff_wire_codec_and_webp() {
#[test]
fn test_phase6_4k_8k_performance_and_memory_benchmarks() {
+ let _dx12_guard = crate::lock_dx12_test();
// 1. 4K (3840x2160, 12 layers) & 8K (7680x4320, 8 layers) Rust Sparse + L2 LZ4 Memory Audit
let mut mgr4k = DocumentManager::new(
MemoryBudgetConfig {
diff --git a/crates/ink-engine/src/regression_dx12_tests.rs b/crates/ink-engine/src/regression_dx12_tests.rs
new file mode 100644
index 0000000..0c1ad46
--- /dev/null
+++ b/crates/ink-engine/src/regression_dx12_tests.rs
@@ -0,0 +1,2010 @@
+//! Headless DX12 regression & stress tests for:
+//! 1. 4K (`3840×2160`) & Manga B4 (`6071×8598`) tight `64 MB` VRAM pool stress at `zoom = 0.25`,
+//! solid-color deduplication (`<= 4` slots for 816-tile solid Background), chunked stroke commit,
+//! and pixel-accurate parity against an unconstrained `512 MB` reference.
+//! 2. Mouse 120 Hz input stream (`NativeNavEvent::MouseDraw` spaced `8 ms` apart) proving zero
+//! 250 ms self-throttling and proving active mouse `phase == 3` is never dropped even if a
+//! stylus packet arrives within 250 ms.
+//! 3. Multi-tile `CspBlendTipsMode::Darken` stroke across 4+ tiles in 2 batches proving dynamic
+//! uniform offsets eliminate tile-slot uniform overwrite/duplication.
+//! 4. Evicted-sibling mipmap preservation in `regenerate_layer_mipmaps` + `LiveGpuStrokeOverlay`
+//! dirty-rect scissor & predicted dab clipping at `zoom = 0.25` across `dpr = 1.0, 1.25, 1.5`.
+
+use crate::brush::{CspBlendTipsMode, GpuBrushDab, NativeBrushConfig, StrokeDabEmitter};
+use crate::clock;
+use crate::compositor::{CompositorDisplayConfig, DocBounds};
+use crate::document::{CanvasColorMode, CanvasDimensions, Document, LayerNodeMeta};
+use crate::engine::{EngineConfig, EngineHandle};
+use crate::gpu::GpuRenderer;
+use crate::memory::MemoryBudgetConfig;
+use crate::stroke::{SplineGenerator, StrokePoint};
+use crate::tiles::{RectI32, TileCoord, BYTES_16F, TILE_SIZE};
+use crate::types::{
+ CameraState, CursorConfig, EngineCommand, EngineEvent, NativeInputSample, NativeNavEvent,
+ SurfaceTarget, ViewportRect,
+};
+use std::collections::{HashMap, HashSet};
+use std::time::{Duration, Instant};
+
+fn lock_dx12() -> std::sync::MutexGuard<'static, ()> {
+ crate::lock_dx12_test()
+}
+
+fn make_headless_renderer_vram(
+ vp_w: u32,
+ vp_h: u32,
+ doc_w: u32,
+ doc_h: u32,
+ vram_bytes: u64,
+) -> Option<GpuRenderer> {
+ match GpuRenderer::new_with_vram(
+ SurfaceTarget::Headless {
+ width: vp_w,
+ height: vp_h,
+ },
+ doc_w,
+ doc_h,
+ vram_bytes,
+ ) {
+ Ok(r) => Some(r),
+ Err(err) => {
+ eprintln!("Skipping DX12 regression GPU test (no adapter available): {err}");
+ None
+ }
+ }
+}
+
+fn make_white_doc(id: &str, w: u32, h: u32) -> Document {
+ Document::new_blank(
+ id,
+ "DX12 Regression Doc",
+ CanvasDimensions {
+ width: w,
+ height: h,
+ dpi: 300,
+ },
+ CanvasColorMode::Color,
+ "#ffffff",
+ 60.0,
+ 50,
+ )
+}
+
+fn fnv1a_hash(bytes: &[u8]) -> u64 {
+ let mut h = 0xcbf29ce484222325u64;
+ for &b in bytes {
+ h ^= u64::from(b);
+ h = h.wrapping_mul(0x100000001b3);
+ }
+ h
+}
+
+fn make_curved_stroke_points(
+ x0: f64,
+ y0: f64,
+ x1: f64,
+ y1: f64,
+ amp: f64,
+ freq: f64,
+ count: usize,
+ width: f32,
+) -> Vec<StrokePoint> {
+ let dx = x1 - x0;
+ let dy = y1 - y0;
+ let len = dx.hypot(dy).max(1.0);
+ let nx = -dy / len;
+ let ny = dx / len;
+ let mut pts = Vec::with_capacity(count);
+ for i in 0..count {
+ let t = if count <= 1 {
+ 0.0
+ } else {
+ i as f64 / (count - 1) as f64
+ };
+ let wave = (t * std::f64::consts::TAU * freq).sin() * amp;
+ pts.push(StrokePoint {
+ x: x0 + dx * t + nx * wave,
+ y: y0 + dy * t + ny * wave,
+ pressure: 0.9,
+ width,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ velocity: 0.5,
+ timestamp_ms: i as f64 * 8.0,
+ is_corner: false,
+ });
+ }
+ pts
+}
+
+fn emit_and_commit_stroke(
+ renderer: &mut GpuRenderer,
+ doc: &mut Document,
+ layer_id: &str,
+ brush: NativeBrushConfig,
+ pts: &[StrokePoint],
+ seed: u64,
+) {
+ let (tip_count, tip_aspect) = renderer.resolve_brush_tip_metrics(&brush);
+ let mut emitter = StrokeDabEmitter::new(brush.clone(), seed, tip_count, tip_aspect);
+ let rand_off = emitter.stroke_grain_offset;
+ renderer.begin_gpu_stroke(
+ doc.dimensions.width,
+ doc.dimensions.height,
+ false,
+ brush,
+ rand_off,
+ );
+
+ let mut spline = SplineGenerator::new(0.0);
+ let mut dabs = Vec::new();
+ if let Some(&first) = pts.first() {
+ spline.push_knot(first);
+ emitter.emit_initial_point(&first, None, 0.0, &mut dabs);
+ }
+ for &pt in pts.iter().skip(1) {
+ for seg in spline.push_knot(pt) {
+ emitter.emit_segment(&seg, None, 0.0, &mut dabs);
+ }
+ }
+ for seg in spline.finish() {
+ emitter.emit_segment(&seg, None, 0.0, &mut dabs);
+ }
+
+ renderer.stamp_gpu_stroke_dabs(&dabs, &[]);
+ let doc_id = doc.id.clone();
+ let committed = {
+ let layer = doc.layer(layer_id).expect("layer exists");
+ renderer
+ .commit_gpu_stroke_to_layer(&doc_id, layer_id, &layer.grid, None, false, false)
+ .expect("commit_gpu_stroke_to_layer must succeed")
+ };
+
+ let mut before_map = HashMap::new();
+ {
+ let layer = doc.layer_mut(layer_id).expect("layer exists");
+ for (coord, _, _) in &committed.tiles {
+ before_map.insert(*coord, layer.grid.tiles.get(coord).cloned());
+ }
+ let (_deltas, cleared) =
+ layer
+ .grid
+ .apply_gpu_committed_tiles(layer_id, committed.tiles, &before_map, 128);
+ renderer.regenerate_layer_mipmaps(&doc_id, layer_id, &mut layer.grid, &cleared, None);
+ }
+ renderer.clear_live_stroke();
+}
+
+fn render_viewport_zoom_025(
+ renderer: &mut GpuRenderer,
+ doc: &Document,
+ vp_w: u32,
+ vp_h: u32,
+) -> Vec<u8> {
+ let vp = ViewportRect {
+ x_px: 0,
+ y_px: 0,
+ width_px: vp_w,
+ height_px: vp_h,
+ dpr: 1.0,
+ };
+ let cam = CameraState {
+ pan_x: vp_w as f32 * 0.5,
+ pan_y: vp_h as f32 * 0.5,
+ zoom: 0.25,
+ rotation: 0.0,
+ flip_x: false,
+ flip_y: false,
+ };
+ let display = CompositorDisplayConfig {
+ show_checkerboard: true,
+ matte_color: [0.05, 0.05, 0.05, 1.0],
+ layer_stack_caching: true,
+ ..Default::default()
+ };
+ let cursor = CursorConfig {
+ visible: false,
+ ..Default::default()
+ };
+ let _ = renderer.render_document_frame(
+ doc,
+ None,
+ &display,
+ &vp,
+ &cam,
+ &[],
+ false,
+ false,
+ &cursor,
+ None,
+ true,
+ );
+ let (rw, rh, rgba) = renderer
+ .readback_headless_rgba8()
+ .expect("headless DX12 viewport readback must succeed");
+ assert_eq!((rw, rh), (vp_w, vp_h));
+ rgba
+}
+
+fn run_tight_vram_64mb_stress(label: &str, doc_w: u32, doc_h: u32, vp_w: u32, vp_h: u32) {
+ let w = doc_w as f64;
+ let h = doc_h as f64;
+ let stroke_specs: [([f32; 3], (f64, f64), (f64, f64), f64, f64, f32, u64); 4] = [
+ (
+ [0.88, 0.12, 0.16],
+ (w * 0.08, h * 0.12),
+ (w * 0.92, h * 0.88),
+ 120.0,
+ 1.3,
+ 48.0,
+ 101,
+ ),
+ (
+ [0.10, 0.35, 0.90],
+ (w * 0.90, h * 0.14),
+ (w * 0.10, h * 0.86),
+ 140.0,
+ 1.7,
+ 44.0,
+ 202,
+ ),
+ (
+ [0.12, 0.72, 0.24],
+ (w * 0.12, h * 0.50),
+ (w * 0.88, h * 0.42),
+ 180.0,
+ 2.1,
+ 40.0,
+ 303,
+ ),
+ (
+ [0.45, 0.10, 0.75],
+ (w * 0.46, h * 0.08),
+ (w * 0.56, h * 0.92),
+ 150.0,
+ 1.9,
+ 36.0,
+ 404,
+ ),
+ ];
+
+ // Phase 1: Run on tight 64 MB pool, capture viewport & tiles, then drop DX12 device before Phase 2
+ let mut doc_tight = make_white_doc("stress-tight", doc_w, doc_h);
+ let lid_tight = doc_tight.active_layer_id.clone().unwrap();
+ let tight_vp = {
+ let Some(mut r_tight) =
+ make_headless_renderer_vram(vp_w, vp_h, doc_w, doc_h, 64 * 1024 * 1024)
+ else {
+ return;
+ };
+
+ // First verify solid white Background uses <= 4 VRAM slots (not 135..816!)
+ r_tight
+ .sync_document(&mut doc_tight, None)
+ .expect("sync_document tight");
+ let _ = render_viewport_zoom_025(&mut r_tight, &doc_tight, vp_w, vp_h);
+ let bg_stats = r_tight.gpu_pool_stats();
+ assert!(
+ bg_stats.slots_used <= 4,
+ "[{label}] Solid-color {doc_w}x{doc_h} Background must use <= 4 VRAM slots, got {}",
+ bg_stats.slots_used
+ );
+
+ for &(color, (x0, y0), (x1, y1), amp, freq, size, seed) in &stroke_specs {
+ let brush = NativeBrushConfig {
+ fg_color: color,
+ size,
+ hardness: 0.92,
+ spacing: 0.16,
+ opacity: 1.0,
+ ..Default::default()
+ };
+ let pts = make_curved_stroke_points(x0, y0, x1, y1, amp, freq, 96, size);
+ emit_and_commit_stroke(&mut r_tight, &mut doc_tight, &lid_tight, brush, &pts, seed);
+ let _ = render_viewport_zoom_025(&mut r_tight, &doc_tight, vp_w, vp_h);
+ }
+
+ render_viewport_zoom_025(&mut r_tight, &doc_tight, vp_w, vp_h)
+ };
+
+ // Phase 2: Run identical strokes on unconstrained 512 MB reference pool
+ let mut doc_ref = make_white_doc("stress-ref", doc_w, doc_h);
+ let lid_ref = doc_ref.active_layer_id.clone().unwrap();
+ let ref_vp = {
+ let Some(mut r_ref) =
+ make_headless_renderer_vram(vp_w, vp_h, doc_w, doc_h, 512 * 1024 * 1024)
+ else {
+ return;
+ };
+ r_ref
+ .sync_document(&mut doc_ref, None)
+ .expect("sync_document ref");
+
+ for &(color, (x0, y0), (x1, y1), amp, freq, size, seed) in &stroke_specs {
+ let brush = NativeBrushConfig {
+ fg_color: color,
+ size,
+ hardness: 0.92,
+ spacing: 0.16,
+ opacity: 1.0,
+ ..Default::default()
+ };
+ let pts = make_curved_stroke_points(x0, y0, x1, y1, amp, freq, 96, size);
+ emit_and_commit_stroke(&mut r_ref, &mut doc_ref, &lid_ref, brush, &pts, seed);
+ }
+
+ render_viewport_zoom_025(&mut r_ref, &doc_ref, vp_w, vp_h)
+ };
+
+ // 1. Verify committed tile hashes: 0 unintended duplicate inked tiles AND exact match vs 512 MB ref
+ let tight_layer = doc_tight.layer(&lid_tight).unwrap();
+ let ref_layer = doc_ref.layer(&lid_ref).unwrap();
+ assert_eq!(
+ tight_layer.grid.tiles.len(),
+ ref_layer.grid.tiles.len(),
+ "[{label}] Tight 64 MB pool committed tile count must match 512 MB reference"
+ );
+ assert!(
+ tight_layer.grid.tiles.len() >= 20,
+ "[{label}] 4 canvas-spanning strokes should touch >= 20 tiles, got {}",
+ tight_layer.grid.tiles.len()
+ );
+
+ let mut seen_hashes: HashMap<u64, TileCoord> = HashMap::new();
+ let mut max_tile_premul_diff = 0u8;
+ for (&coord, tight_tile) in &tight_layer.grid.tiles {
+ let tight_rgba = tight_tile.to_rgba8(None, false).unwrap();
+ let ref_tile = ref_layer
+ .grid
+ .tiles
+ .get(&coord)
+ .expect("coord exists in ref");
+ let ref_rgba = ref_tile.to_rgba8(None, false).unwrap();
+
+ let h_tight = fnv1a_hash(&tight_rgba);
+ // Compare premultiplied RGBA (since evicting an Rgba16Float tile to RGBA8 and reloading
+ // before an overlapping stroke only quantizes straight-RGB on near-zero-alpha fringe pixels).
+ let mut tile_max_diff = 0u8;
+ let mut tile_big_diffs = 0usize;
+ for (tp, rp) in tight_rgba.chunks_exact(4).zip(ref_rgba.chunks_exact(4)) {
+ let ta = tp[3] as u32;
+ let ra = rp[3] as u32;
+ let dr = ((tp[0] as u32 * ta + 127) / 255).abs_diff((rp[0] as u32 * ra + 127) / 255) as u8;
+ let dg = ((tp[1] as u32 * ta + 127) / 255).abs_diff((rp[1] as u32 * ra + 127) / 255) as u8;
+ let db = ((tp[2] as u32 * ta + 127) / 255).abs_diff((rp[2] as u32 * ra + 127) / 255) as u8;
+ let da = tp[3].abs_diff(rp[3]);
+ let d = dr.max(dg).max(db).max(da);
+ if d > tile_max_diff {
+ tile_max_diff = d;
+ }
+ if d > 2 {
+ tile_big_diffs += 1;
+ }
+ }
+ max_tile_premul_diff = max_tile_premul_diff.max(tile_max_diff);
+ assert_eq!(
+ tile_big_diffs, 0,
+ "[{label}] Tile {coord:?} had {tile_big_diffs} premultiplied pixel diffs > 2 between 64 MB pool and 512 MB reference (max_diff={tile_max_diff})"
+ );
+
+ // Non-solid inked tiles along distinct curves must never duplicate each other's contents
+ if tight_tile.solid_rgba8().is_none() {
+ if let Some(prev_coord) = seen_hashes.insert(h_tight, coord) {
+ panic!(
+ "[{label}] Duplicate inked tile hash detected! Tile {coord:?} cloned tile {prev_coord:?}"
+ );
+ }
+ }
+ }
+ println!(
+ "[{label}] Committed {} tiles (0 duplicate hashes, max premul diff vs 512 MB ref = {max_tile_premul_diff})",
+ tight_layer.grid.tiles.len()
+ );
+
+ // 2. Compare final rendered viewports at zoom = 0.25 and verify 0 missing background pixels + match vs 512 MB ref
+
+ let doc_half_w_vp = (doc_w as f32 * 0.25 * 0.5) as i32;
+ let doc_half_h_vp = (doc_h as f32 * 0.25 * 0.5) as i32;
+ let cx = vp_w as i32 / 2;
+ let cy = vp_h as i32 / 2;
+ let x_min = (cx - doc_half_w_vp + 2).max(0) as u32;
+ let x_max = (cx + doc_half_w_vp - 2).min(vp_w as i32) as u32;
+ let y_min = (cy - doc_half_h_vp + 2).max(0) as u32;
+ let y_max = (cy + doc_half_h_vp - 2).min(vp_h as i32) as u32;
+
+ let mut mismatched = 0usize;
+ let mut max_diff = 0u8;
+ let mut missing_bg_holes = 0usize;
+ let mut pure_white_bg_pixels = 0usize;
+ let mut inked_pixels = 0usize;
+
+ for y in y_min..y_max {
+ for x in x_min..x_max {
+ let off = ((y * vp_w + x) * 4) as usize;
+ let tp = &tight_vp[off..off + 4];
+ let rp = &ref_vp[off..off + 4];
+
+ let diff = tp[0]
+ .abs_diff(rp[0])
+ .max(tp[1].abs_diff(rp[1]))
+ .max(tp[2].abs_diff(rp[2]))
+ .max(tp[3].abs_diff(rp[3]));
+ max_diff = max_diff.max(diff);
+ if diff > 3 {
+ mismatched += 1;
+ }
+
+ // Detect checkerboard hole where reference is pure white Background (255,255,255)
+ // but tight pool fell back to gray checkerboard (<240)!
+ if rp[0] >= 252 && rp[1] >= 252 && rp[2] >= 252 {
+ if tp[0] < 245 || tp[1] < 245 || tp[2] < 245 {
+ missing_bg_holes += 1;
+ } else {
+ pure_white_bg_pixels += 1;
+ }
+ } else {
+ inked_pixels += 1;
+ }
+ }
+ }
+
+ assert_eq!(
+ missing_bg_holes, 0,
+ "[{label}] Found {missing_bg_holes} missing white background / checkerboard hole pixels!"
+ );
+ assert_eq!(
+ mismatched, 0,
+ "[{label}] Tight 64 MB viewport had {mismatched} pixels differing >3 from 512 MB ref (max_diff={max_diff})"
+ );
+ assert!(
+ pure_white_bg_pixels > 10_000 && inked_pixels > 1_000,
+ "[{label}] Sanity check failed: white_bg={pure_white_bg_pixels}, inked={inked_pixels}"
+ );
+}
+
+#[test]
+fn test_dx12_4k_and_manga_b4_tight_vram_64mb_stress_and_solid_dedup() {
+ let _guard = lock_dx12();
+ // 1. Illustration 4K (3840x2160) on tight 64 MB pool at zoom = 0.25
+ run_tight_vram_64mb_stress("Illustration-4K", 3840, 2160, 1024, 600);
+ // 2. Manga B4 (6071x8598, 816 tiles!) on tight 64 MB pool at zoom = 0.25
+ run_tight_vram_64mb_stress("Manga-B4-6071x8598", 6071, 8598, 1600, 2200);
+}
+
+#[test]
+fn test_dx12_chunked_commit_exceeding_pool_capacity_zero_duplication() {
+ let _guard = lock_dx12();
+ // Force a single stroke touching >24 distinct tiles onto a tiny 16-slot (8 MB) pool
+ // so `commit_to_layer_pool_with_selection` MUST split across multiple sub-batches!
+ let brush = NativeBrushConfig {
+ fg_color: [0.85, 0.20, 0.15],
+ size: 64.0,
+ hardness: 0.9,
+ spacing: 0.15,
+ opacity: 1.0,
+ ..Default::default()
+ };
+ let pts = make_curved_stroke_points(120.0, 180.0, 3920.0, 3840.0, 240.0, 2.3, 140, 64.0);
+
+ let mut doc_tiny = make_white_doc("chunk-tiny", 4096, 4096);
+ let lid_tiny = doc_tiny.active_layer_id.clone().unwrap();
+ {
+ let Some(mut r_tiny) =
+ make_headless_renderer_vram(1024, 1024, 4096, 4096, 16 * BYTES_16F as u64)
+ else {
+ return;
+ };
+ emit_and_commit_stroke(&mut r_tiny, &mut doc_tiny, &lid_tiny, brush.clone(), &pts, 777);
+ }
+
+ let mut doc_ref = make_white_doc("chunk-ref", 4096, 4096);
+ let lid_ref = doc_ref.active_layer_id.clone().unwrap();
+ {
+ let Some(mut r_ref) =
+ make_headless_renderer_vram(1024, 1024, 4096, 4096, 512 * 1024 * 1024)
+ else {
+ return;
+ };
+ emit_and_commit_stroke(&mut r_ref, &mut doc_ref, &lid_ref, brush, &pts, 777);
+ }
+
+ let l_tiny = doc_tiny.layer(&lid_tiny).unwrap();
+ let l_ref = doc_ref.layer(&lid_ref).unwrap();
+ assert!(
+ l_tiny.grid.tiles.len() > 24,
+ "Stroke must exceed 16-slot pool capacity to exercise chunking, got {} tiles",
+ l_tiny.grid.tiles.len()
+ );
+ assert_eq!(l_tiny.grid.tiles.len(), l_ref.grid.tiles.len());
+
+ let mut hashes = HashSet::new();
+ for (&coord, t_tiny) in &l_tiny.grid.tiles {
+ let b_tiny = t_tiny.to_rgba8(None, false).unwrap();
+ let b_ref = l_ref.grid.tiles.get(&coord).unwrap().to_rgba8(None, false).unwrap();
+ assert_eq!(
+ fnv1a_hash(&b_tiny),
+ fnv1a_hash(&b_ref),
+ "Chunked commit tile {coord:?} diverged from 512 MB reference"
+ );
+ assert!(
+ hashes.insert(fnv1a_hash(&b_tiny)),
+ "Chunked commit produced duplicate tile contents at {coord:?}"
+ );
+ }
+}
+
+#[test]
+fn test_dx12_mouse_120hz_stream_and_active_mouse_up_never_dropped() {
+ let _guard = lock_dx12();
+ let (handle, mut producers) = match EngineHandle::spawn(
+ SurfaceTarget::Headless {
+ width: 1024,
+ height: 768,
+ },
+ EngineConfig {
+ doc_width: 1024,
+ doc_height: 768,
+ show_checkerboard: true,
+ matte_color: [0.086, 0.086, 0.086, 1.0],
+ memory_budget: MemoryBudgetConfig {
+ vram_budget_bytes: 64 * 1024 * 1024,
+ ..Default::default()
+ },
+ ..Default::default()
+ },
+ ) {
+ Ok(pair) => pair,
+ Err(err) => {
+ eprintln!("Skipping DX12 mouse 120 Hz stream test (no adapter available): {err}");
+ return;
+ }
+ };
+
+ {
+ let docs = handle.documents();
+ let mut mgr = docs.write();
+ mgr.create_document(
+ "mouse-120hz-doc",
+ "Mouse 120Hz Doc",
+ CanvasDimensions {
+ width: 1024,
+ height: 768,
+ dpi: 300,
+ },
+ CanvasColorMode::Color,
+ "#ffffff",
+ 60.0,
+ );
+ }
+ handle.send_command(EngineCommand::SyncActiveDocument);
+ handle.send_command(EngineCommand::SetVisible(true));
+ handle.send_command(EngineCommand::SetViewport(ViewportRect {
+ x_px: 0,
+ y_px: 0,
+ width_px: 1024,
+ height_px: 768,
+ dpr: 1.0,
+ }));
+ handle.send_command(EngineCommand::SetCamera(CameraState {
+ pan_x: 512.0,
+ pan_y: 384.0,
+ zoom: 1.0,
+ rotation: 0.0,
+ flip_x: false,
+ flip_y: false,
+ }));
+ handle.send_command(EngineCommand::SetCollabPointsEnabled(true));
+ handle.send_command(EngineCommand::SetFullBrushConfig(Box::new(
+ NativeBrushConfig {
+ fg_color: [0.1, 0.1, 0.1],
+ size: 18.0,
+ hardness: 0.95,
+ spacing: 0.15,
+ stabilization: 0.0,
+ smoothing: false,
+ post_correction: 0,
+ ..Default::default()
+ },
+ )));
+ // Wait briefly so initial viewport/camera/brush commands settle before input stream
+ std::thread::sleep(Duration::from_millis(60));
+
+ // Push 60 MouseDraw samples spaced 8 ms apart (125 Hz): phase 1 -> 58x phase 2 -> phase 3
+ // Use low timestamps starting near 10.0 ms as well to verify NEG_INFINITY init never suppresses!
+ let base_ts = 10.0f64;
+ let total_samples = 60usize;
+ for i in 0..total_samples {
+ let t = i as f64 / (total_samples - 1) as f64;
+ let x = 100.0 + 800.0 * t;
+ let y = 140.0 + 480.0 * t + (t * std::f64::consts::TAU * 2.0).sin() * 45.0;
+ let phase = if i == 0 {
+ 1
+ } else if i + 1 == total_samples {
+ 3
+ } else {
+ 2
+ };
+ assert!(producers.nav.push(NativeNavEvent::MouseDraw {
+ phys_x: x as f32,
+ phys_y: y as f32,
+ phase,
+ shift_held: false,
+ timestamp_ms: base_ts + i as f64 * 8.0,
+ }));
+ }
+
+ let mut committed_points = None;
+ let deadline = Instant::now() + Duration::from_secs(4);
+ while Instant::now() < deadline && committed_points.is_none() {
+ for ev in handle.events().try_iter() {
+ if let EngineEvent::StrokeCommitted {
+ dirty_rect, points, ..
+ } = ev
+ {
+ assert!(!dirty_rect.is_empty(), "Committed mouse stroke dirty_rect must be non-empty");
+ committed_points = Some(points);
+ break;
+ }
+ }
+ std::thread::sleep(Duration::from_millis(10));
+ }
+
+ let points = committed_points.expect("StrokeCommitted must fire cleanly on MouseDraw phase 3");
+ // Before our fix, 250ms self-throttling dropped 58 of 60 samples (<= 3 points, dropped phase 3!)
+ assert!(
+ points.len() >= 55,
+ "All 60 120Hz mouse samples must be processed (not throttled to 4 Hz), got {} points",
+ points.len()
+ );
+
+ // Wait for throttled diagnostics tick (250 ms) and assert active_stroke_dabs > 50
+ let mut observed_dabs = handle.diagnostics().active_stroke_dabs;
+ let diag_deadline = Instant::now() + Duration::from_secs(2);
+ while Instant::now() < diag_deadline && observed_dabs <= 50 {
+ std::thread::sleep(Duration::from_millis(40));
+ // Poke hover so engine loop wakes and flushes diagnostics even when idle
+ let _ = producers.nav.push(NativeNavEvent::Hover {
+ phys_x: 512.0,
+ phys_y: 384.0,
+ timestamp_ms: base_ts + 800.0,
+ });
+ observed_dabs = handle.diagnostics().active_stroke_dabs;
+ }
+ assert!(
+ observed_dabs > 50,
+ "Expected active_stroke_dabs > 50 for 60-sample 120 Hz mouse stroke, got {observed_dabs}"
+ );
+
+ // Part 2: Verify an active mouse stroke's phase == 3 mouse-up is NEVER dropped even if a
+ // stylus packet arrives < 250 ms earlier (so mouse strokes can never get stuck!)
+ let t2 = clock::now_ms() + 2000.0;
+ assert!(producers.nav.push(NativeNavEvent::MouseDraw {
+ phys_x: 200.0,
+ phys_y: 500.0,
+ phase: 1,
+ shift_held: false,
+ timestamp_ms: t2,
+ }));
+ for step in 1..=10 {
+ assert!(producers.nav.push(NativeNavEvent::MouseDraw {
+ phys_x: 200.0 + step as f32 * 25.0,
+ phys_y: 500.0,
+ phase: 2,
+ shift_held: false,
+ timestamp_ms: t2 + step as f64 * 8.0,
+ }));
+ }
+ // Wait so engine processes the mouse stroke start + moves first
+ std::thread::sleep(Duration::from_millis(50));
+
+ // Inject a stylus hover packet 5 ms before mouse-up!
+ assert!(producers.wintab.push(NativeInputSample {
+ phys_x: 450.0,
+ phys_y: 500.0,
+ pressure: 0.0,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: t2 + 85.0,
+ buttons: 0,
+ phase: 0,
+ backend: 1,
+ }));
+ assert!(producers.nav.push(NativeNavEvent::MouseDraw {
+ phys_x: 450.0,
+ phys_y: 500.0,
+ phase: 3,
+ shift_held: false,
+ timestamp_ms: t2 + 90.0,
+ }));
+
+ let mut second_committed = false;
+ let deadline2 = Instant::now() + Duration::from_secs(3);
+ while Instant::now() < deadline2 && !second_committed {
+ for ev in handle.events().try_iter() {
+ if matches!(ev, EngineEvent::StrokeCommitted { .. }) {
+ second_committed = true;
+ break;
+ }
+ }
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ assert!(
+ second_committed,
+ "Active mouse stroke phase == 3 must NEVER be dropped even when a stylus packet arrived within 250 ms"
+ );
+
+ handle.shutdown();
+}
+
+#[test]
+fn test_dx12_multi_tile_darken_brush_distinct_tiles() {
+ let _guard = lock_dx12();
+ let Some(mut renderer) =
+ make_headless_renderer_vram(1024, 1024, 1024, 1024, 128 * 1024 * 1024)
+ else {
+ return;
+ };
+
+ let mut doc = Document::new_blank(
+ "darken-doc",
+ "Darken Multi-Tile",
+ CanvasDimensions {
+ width: 1024,
+ height: 1024,
+ dpi: 300,
+ },
+ CanvasColorMode::Color,
+ "transparent",
+ 60.0,
+ 50,
+ );
+ let lid = doc.active_layer_id.clone().unwrap();
+
+ // Non-45° diagonal so every crossed 256x256 tile has a DISTINCT local pixel geometry!
+ // Slope ~0.78 crosses (0,0), (1,0)/(1,1), (2,1)/(2,2), (3,2)/(3,3) cleanly at distinct offsets.
+ let mut brush = NativeBrushConfig {
+ fg_color: [0.85, 0.55, 0.30],
+ size: 36.0,
+ hardness: 0.95,
+ spacing: 0.18,
+ opacity: 1.0,
+ blend_tips_mode: CspBlendTipsMode::Darken,
+ ..Default::default()
+ };
+
+ let (tip_count, tip_aspect) = renderer.resolve_brush_tip_metrics(&brush);
+ let mut emitter1 = StrokeDabEmitter::new(brush.clone(), 4242, tip_count, tip_aspect);
+ let rand_off = emitter1.stroke_grain_offset;
+ renderer.begin_gpu_stroke(1024, 1024, false, brush.clone(), rand_off);
+
+ // Batch 1: stamps warm orange across >= 4 distinct 256x256 tiles (allocating them `is_new = true`)
+ let mut batch1_dabs = Vec::new();
+ let pts1 = make_curved_stroke_points(60.0, 90.0, 960.0, 790.0, 0.0, 0.0, 64, 36.0);
+ let mut sp1 = SplineGenerator::new(0.0);
+ sp1.push_knot(pts1[0]);
+ emitter1.emit_initial_point(&pts1[0], None, 0.0, &mut batch1_dabs);
+ for &p in pts1.iter().skip(1) {
+ for seg in sp1.push_knot(p) {
+ emitter1.emit_segment(&seg, None, 0.0, &mut batch1_dabs);
+ }
+ }
+ for seg in sp1.finish() {
+ emitter1.emit_segment(&seg, None, 0.0, &mut batch1_dabs);
+ }
+ let touched1 = renderer.stamp_gpu_stroke_dabs(&batch1_dabs, &[]);
+ assert!(
+ touched1.len() >= 4,
+ "Batch 1 must touch at least 4 distinct 256x256 tiles, got {}",
+ touched1.len()
+ );
+
+ // Batch 2: stamps darker blue-green over the EXACT SAME 4+ tiles (`is_new = false` -> Darken compute merge!)
+ brush.fg_color = [0.15, 0.30, 0.75];
+ let mut emitter2 = StrokeDabEmitter::new(brush.clone(), 9001, tip_count, tip_aspect);
+ let mut batch2_dabs = Vec::new();
+ let pts2 = make_curved_stroke_points(60.0, 90.0, 960.0, 790.0, 0.0, 0.0, 64, 36.0);
+ let mut sp2 = SplineGenerator::new(0.0);
+ sp2.push_knot(pts2[0]);
+ emitter2.emit_initial_point(&pts2[0], None, 0.0, &mut batch2_dabs);
+ for &p in pts2.iter().skip(1) {
+ for seg in sp2.push_knot(p) {
+ emitter2.emit_segment(&seg, None, 0.0, &mut batch2_dabs);
+ }
+ }
+ for seg in sp2.finish() {
+ emitter2.emit_segment(&seg, None, 0.0, &mut batch2_dabs);
+ }
+ let touched2 = renderer.stamp_gpu_stroke_dabs(&batch2_dabs, &[]);
+ assert!(
+ touched2.is_empty(),
+ "Batch 2 should hit existing tiles (`is_new == false`) to trigger Darken compute merge"
+ );
+
+ let doc_id = doc.id.clone();
+ let committed = {
+ let layer = doc.layer(&lid).unwrap();
+ renderer
+ .commit_gpu_stroke_to_layer(&doc_id, &lid, &layer.grid, None, false, false)
+ .expect("Darken commit must succeed")
+ };
+ {
+ let layer = doc.layer_mut(&lid).unwrap();
+ let empty = HashMap::new();
+ let (_deltas, cleared) =
+ layer
+ .grid
+ .apply_gpu_committed_tiles(&lid, committed.tiles, &empty, 128);
+ renderer.regenerate_layer_mipmaps(&doc_id, &lid, &mut layer.grid, &cleared, None);
+ }
+ renderer.clear_live_stroke();
+
+ let layer = doc.layer(&lid).unwrap();
+ assert!(
+ layer.grid.tiles.len() >= 4,
+ "Committed Darken stroke must span >= 4 tiles, got {}",
+ layer.grid.tiles.len()
+ );
+
+ // 1. Assert every committed tile has a unique hash (zero duplicated tile contents!)
+ let mut tile_hashes: HashMap<u64, TileCoord> = HashMap::new();
+ for (&coord, tile) in &layer.grid.tiles {
+ let rgba = tile.to_rgba8(None, false).unwrap();
+ let h = fnv1a_hash(&rgba);
+ if let Some(prev) = tile_hashes.insert(h, coord) {
+ panic!(
+ "Multi-tile Darken bug: tile {coord:?} duplicated pixels from tile {prev:?}!"
+ );
+ }
+ }
+
+ // 2. Verify document-coordinate accuracy along the diagonal in 4 distinct tiles:
+ // Line equation: x(t) = 60 + 900*t, y(t) = 90 + 700*t.
+ // Darken(rgb1=[0.85, 0.55, 0.30], rgb2=[0.15, 0.30, 0.75]) = [0.15, 0.30, 0.30] -> (~38, ~77, ~77)!
+ let probe_ts = [0.08f64, 0.36, 0.66, 0.94];
+ let mut probed_tiles = HashSet::new();
+ for &t in &probe_ts {
+ let px = (60.0 + 900.0 * t).round() as i32;
+ let py = (90.0 + 700.0 * t).round() as i32;
+ let coord = TileCoord::new(px / TILE_SIZE as i32, py / TILE_SIZE as i32);
+ probed_tiles.insert(coord);
+
+ let rgba = layer.grid.get_pixel_rgba8(px, py, None);
+ assert!(
+ rgba[3] > 220,
+ "Probe at ({px}, {py}) in tile {coord:?} must be inked, got {rgba:?}"
+ );
+ // Darken min([0.85,0.55,0.30], [0.15,0.30,0.75]) = [0.15, 0.30, 0.30] => R~38, G~77, B~77
+ assert!(
+ rgba[0] < 70 && rgba[1] < 105 && rgba[2] < 105,
+ "Darken merge at ({px}, {py}) in tile {coord:?} should preserve min(R,G,B) ~= (38,77,77), got {rgba:?}"
+ );
+
+ // Verify an off-diagonal point in the SAME tile (far from the line) is completely transparent
+ let tile_origin_x = coord.tx * TILE_SIZE as i32;
+ let tile_origin_y = coord.ty * TILE_SIZE as i32;
+ let off_y = if (py - tile_origin_y) < 128 {
+ tile_origin_y + 240
+ } else {
+ tile_origin_y + 12
+ };
+ let off_x = if (px - tile_origin_x) < 128 {
+ tile_origin_x + 240
+ } else {
+ tile_origin_x + 12
+ };
+ let empty_px = layer.grid.get_pixel_rgba8(off_x, off_y, None);
+ assert_eq!(
+ empty_px[3], 0,
+ "Off-diagonal corner ({off_x}, {off_y}) in tile {coord:?} must remain transparent (not polluted by another tile's Darken slot!), got {empty_px:?}"
+ );
+ }
+ assert_eq!(
+ probed_tiles.len(),
+ 4,
+ "Probes must span 4 distinct 256x256 tiles, got {probed_tiles:?}"
+ );
+}
+
+#[test]
+fn test_dx12_mipmap_preserves_evicted_sibling_and_live_scissor_dpr() {
+ let _guard = lock_dx12();
+ // Part A: Evicted sibling quadrant preservation in `regenerate_layer_mipmaps`
+ let Some(mut renderer) =
+ make_headless_renderer_vram(512, 512, 1024, 1024, 16 * BYTES_16F as u64)
+ else {
+ return;
+ };
+ let mut doc = make_white_doc("mip-evict-doc", 1024, 1024);
+ let lid = doc.active_layer_id.clone().unwrap();
+
+ // Stroke 1: bright RED inside tile (0, 0)
+ let red_brush = NativeBrushConfig {
+ fg_color: [0.95, 0.05, 0.05],
+ size: 90.0,
+ hardness: 0.98,
+ spacing: 0.15,
+ opacity: 1.0,
+ ..Default::default()
+ };
+ let pts_red = make_curved_stroke_points(80.0, 128.0, 180.0, 128.0, 0.0, 0.0, 12, 90.0);
+ emit_and_commit_stroke(&mut renderer, &mut doc, &lid, red_brush, &pts_red, 11);
+
+ // Explicitly evict tile (0, 0) from L1 VRAM before committing a stroke in sibling tile (1, 0)!
+ let evict_key = renderer.tile_pool_mut().make_key(&doc.id, &lid, 0, TileCoord::new(0, 0));
+ renderer.tile_pool_mut().evict_key(&evict_key);
+
+ // Stroke 2: bright BLUE inside sibling tile (1, 0) — triggers regenerate_layer_mipmaps for LOD 1 (0, 0)!
+ let blue_brush = NativeBrushConfig {
+ fg_color: [0.05, 0.10, 0.95],
+ size: 90.0,
+ hardness: 0.98,
+ spacing: 0.15,
+ opacity: 1.0,
+ ..Default::default()
+ };
+ let pts_blue = make_curved_stroke_points(320.0, 128.0, 440.0, 128.0, 0.0, 0.0, 12, 90.0);
+ emit_and_commit_stroke(&mut renderer, &mut doc, &lid, blue_brush, &pts_blue, 22);
+
+ // Render at zoom = 0.25 (LOD 2) and verify BOTH red (0,0) AND blue (1,0) quadrants survived!
+ let vp_rgba = render_viewport_zoom_025(&mut renderer, &doc, 512, 512);
+ // Doc (128, 128) maps to vp (256 + (128-512)*0.25, 256 + (128-512)*0.25) = (160, 160)
+ // Doc (380, 128) maps to vp (256 + (380-512)*0.25, 160) = (223, 160)
+ let red_off = ((160 * 512 + 160) * 4) as usize;
+ let blue_off = ((160 * 512 + 223) * 4) as usize;
+ let r_px = &vp_rgba[red_off..red_off + 4];
+ let b_px = &vp_rgba[blue_off..blue_off + 4];
+ assert!(
+ r_px[0] > 180 && r_px[1] < 80 && r_px[2] < 80,
+ "Evicted sibling quadrant (0,0) MUST remain red after mipmap regeneration, got {r_px:?}"
+ );
+ assert!(
+ b_px[2] > 180 && b_px[0] < 80,
+ "Updated sibling quadrant (1,0) MUST be blue after mipmap regeneration, got {b_px:?}"
+ );
+
+ // Part B: LiveGpuStrokeOverlay scissor + predicted dab clipping at zoom = 0.25 across dpr = 1.0, 1.25, 1.5
+ for dpr in [1.0f32, 1.25, 1.5] {
+ let vp_w = (512.0 * dpr).round() as u32;
+ let vp_h = (512.0 * dpr).round() as u32;
+ let Some(mut r_live) =
+ make_headless_renderer_vram(vp_w, vp_h, 1024, 1024, 64 * 1024 * 1024)
+ else {
+ return;
+ };
+ let mut live_doc = make_white_doc("live-scissor-doc", 1024, 1024);
+ r_live.sync_document(&mut live_doc, None).unwrap();
+
+ let vp = ViewportRect {
+ x_px: 0,
+ y_px: 0,
+ width_px: vp_w,
+ height_px: vp_h,
+ dpr,
+ };
+ let cam = CameraState {
+ pan_x: 256.0,
+ pan_y: 256.0,
+ zoom: 0.25,
+ rotation: 0.0,
+ flip_x: false,
+ flip_y: false,
+ };
+ let display = CompositorDisplayConfig {
+ show_checkerboard: true,
+ matte_color: [0.05, 0.05, 0.05, 1.0],
+ layer_stack_caching: true,
+ ..Default::default()
+ };
+ let cursor = CursorConfig {
+ visible: false,
+ ..Default::default()
+ };
+
+ let brush = NativeBrushConfig {
+ fg_color: [0.05, 0.65, 0.15],
+ size: 48.0,
+ hardness: 0.95,
+ spacing: 0.15,
+ opacity: 1.0,
+ ..Default::default()
+ };
+ r_live.begin_gpu_stroke(1024, 1024, false, brush.clone(), [0.0, 0.0]);
+
+ let make_dab = |cx: f32, cy: f32| GpuBrushDab {
+ pos_size: [cx, cy, 24.0, 24.0],
+ rot_tip: [1.0, 0.0, 0.0, 0.95],
+ color_rgba: [0.05, 0.65, 0.15, 1.0],
+ bg_grain: [1.0, 1.0, 1.0, 0.0],
+ extra: [1.0, 1.0, 1.0, 0.0],
+ };
+
+ // Frame 1: stamp first segment left of x=256 + predicted dab far right at (800, 512)
+ let d1 = make_dab(220.0, 512.0);
+ r_live.stamp_gpu_stroke_dabs(&[d1], &[]);
+ let pred_far = make_dab(800.0, 512.0);
+ let _ = r_live.render_document_frame_with_brush(
+ &live_doc,
+ None,
+ &display,
+ &vp,
+ &cam,
+ &[],
+ false,
+ true,
+ &[pred_far],
+ Some(DocBounds {
+ min_x: 190,
+ min_y: 480,
+ max_x: 250,
+ max_y: 544,
+ }),
+ &cursor,
+ None,
+ true,
+ );
+
+ // Frame 2: stroke crosses x=256 boundary (256..300) and predicted dab disappears (empty slice)
+ let d2 = make_dab(260.0, 512.0);
+ r_live.stamp_gpu_stroke_dabs(&[d2], &[]);
+ let _ = r_live.render_document_frame_with_brush(
+ &live_doc,
+ None,
+ &display,
+ &vp,
+ &cam,
+ &[],
+ false,
+ true,
+ &[],
+ Some(DocBounds {
+ min_x: 230,
+ min_y: 480,
+ max_x: 290,
+ max_y: 544,
+ }),
+ &cursor,
+ None,
+ true,
+ );
+
+ let (_, _, rgba2) = r_live.readback_headless_rgba8().unwrap();
+ // Check stroke pixel right on x=256 tile boundary: doc (256, 512) -> css (256 + (256-512)*0.25, 256) = (192, 256)
+ let bx = (192.0 * dpr).round() as u32;
+ let by = (256.0 * dpr).round() as u32;
+ let b_off = ((by * vp_w + bx) * 4) as usize;
+ assert!(
+ rgba2[b_off + 1] > 120 && rgba2[b_off] < 80,
+ "[dpr={dpr}] Live stroke across x=256 boundary must be visibly green, got {:?}",
+ &rgba2[b_off..b_off + 4]
+ );
+
+ // Check former predicted dab location (800, 512) -> css (256 + (800-512)*0.25, 256) = (328, 256)
+ // MUST be cleanly cleared back to pure white (0 ghost trails!)
+ let gx = (328.0 * dpr).round() as u32;
+ let gy = (256.0 * dpr).round() as u32;
+ let g_off = ((gy * vp_w + gx) * 4) as usize;
+ let gp = &rgba2[g_off..g_off + 4];
+ assert!(
+ gp[0] >= 250 && gp[1] >= 250 && gp[2] >= 250,
+ "[dpr={dpr}] Former predicted dab at (800,512) left ghost trail pixels: {gp:?}"
+ );
+ }
+}
+
+/// Headless DX12 benchmark & regression test for the full live-stroke pipeline on a 4K (`3840×2160`) canvas:
+/// 1. Simulates 100 consecutive live-stroke frames with 5 tablet input samples per frame (500 samples total),
+/// proving all 5 samples per frame are batched into ONE GPU stamp dispatch per frame (not 5).
+/// 2. Intentionally inserts a 380 ms idle gap before the stroke to reproduce the historical `3 FPS` HUD bug,
+/// verifying active FPS stays realistic (`>= 30 FPS` when frame time `< 16 ms`, never `3 FPS`).
+/// 3. Commits pen-up cleanly and proves ZERO PNG thumbnails are generated synchronously on the DX12 render
+/// thread (`sync_render_thread_thumbnails == 0`), while `EngineEvent::ThumbnailsUpdated` arrives
+/// asynchronously from the background thumbnail worker.
+#[test]
+fn test_dx12_4k_100frame_batched_live_stroke_benchmark() {
+ let _guard = lock_dx12();
+ let vp_w = 1280u32;
+ let vp_h = 720u32;
+ let doc_w = 3840u32;
+ let doc_h = 2160u32;
+
+ let (handle, mut producers) = match EngineHandle::spawn(
+ SurfaceTarget::Headless {
+ width: vp_w,
+ height: vp_h,
+ },
+ EngineConfig {
+ doc_width: doc_w,
+ doc_height: doc_h,
+ show_checkerboard: true,
+ matte_color: [0.086, 0.086, 0.086, 1.0],
+ memory_budget: MemoryBudgetConfig {
+ vram_budget_bytes: 128 * 1024 * 1024,
+ ..Default::default()
+ },
+ ..Default::default()
+ },
+ ) {
+ Ok(pair) => pair,
+ Err(err) => {
+ eprintln!("Skipping DX12 4K 100-frame benchmark test (no adapter available): {err}");
+ return;
+ }
+ };
+
+ {
+ let docs = handle.documents();
+ let mut mgr = docs.write();
+ mgr.create_document(
+ "bench-4k-doc",
+ "4K Live Stroke Bench",
+ CanvasDimensions {
+ width: doc_w,
+ height: doc_h,
+ dpi: 300,
+ },
+ CanvasColorMode::Color,
+ "#ffffff",
+ 60.0,
+ );
+ }
+ handle.send_command(EngineCommand::SyncActiveDocument);
+ handle.send_command(EngineCommand::SetVisible(true));
+ handle.send_command(EngineCommand::SetViewport(ViewportRect {
+ x_px: 0,
+ y_px: 0,
+ width_px: vp_w,
+ height_px: vp_h,
+ dpr: 1.0,
+ }));
+ handle.send_command(EngineCommand::SetCamera(CameraState {
+ pan_x: vp_w as f32 * 0.5,
+ pan_y: vp_h as f32 * 0.5,
+ zoom: 0.25,
+ rotation: 0.0,
+ flip_x: false,
+ flip_y: false,
+ }));
+ handle.send_command(EngineCommand::SetCollabPointsEnabled(true));
+ handle.send_command(EngineCommand::SetFullBrushConfig(Box::new(
+ NativeBrushConfig {
+ fg_color: [0.12, 0.22, 0.68],
+ size: 32.0,
+ hardness: 0.92,
+ spacing: 0.15,
+ opacity: 1.0,
+ stabilization: 0.0,
+ smoothing: false,
+ post_correction: 0,
+ ..Default::default()
+ },
+ )));
+
+ // Wait for initial viewport frame to render cleanly
+ let init_deadline = Instant::now() + Duration::from_secs(5);
+ while Instant::now() < init_deadline && handle.diagnostics().total_frames_rendered == 0 {
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ assert!(
+ handle.diagnostics().total_frames_rendered >= 1,
+ "Initial 4K viewport frame must render before benchmark begins"
+ );
+
+ // Deliberately sleep > 350 ms to create an idle gap (reproducing the historical "3 FPS" bug!)
+ std::thread::sleep(Duration::from_millis(380));
+
+ let perf_before = handle.perf_snapshot();
+ let mut prev_frames = handle.diagnostics().total_frames_rendered;
+ let total_stroke_frames = 100usize;
+ let samples_per_frame = 5usize;
+ let total_samples = total_stroke_frames * samples_per_frame;
+
+ let bench_start = Instant::now();
+ let mut first_frame_diag = None;
+ let mut frames_rendered = 0u64;
+
+ for frame_idx in 0..total_stroke_frames {
+ let now_ts = clock::now_ms();
+ let mut batch = Vec::with_capacity(samples_per_frame);
+ for k in 0..samples_per_frame {
+ let global_i = frame_idx * samples_per_frame + k;
+ let t = global_i as f64 / (total_samples - 1) as f64;
+ // Sweep smoothly inside the visible 4K artboard (zoom=0.25 => artboard spans x=[160..1120], y=[90..630])
+ let phys_x = (220.0 + 840.0 * t) as f32;
+ let phys_y = (200.0 + 300.0 * t + (t * std::f64::consts::TAU * 3.0).sin() * 65.0) as f32;
+ let phase = if global_i == 0 { 1u8 } else { 2u8 };
+ batch.push(NativeInputSample {
+ phys_x,
+ phys_y,
+ pressure: 0.75 + 0.2 * (t as f32).sin(),
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: now_ts - ((samples_per_frame - 1 - k) as f64 * 0.4),
+ buttons: 1,
+ phase,
+ backend: 1,
+ });
+ }
+
+ let pushed = producers.wintab.push_batch(&batch);
+ assert_eq!(pushed, samples_per_frame, "All 5 frame samples must push cleanly");
+
+ // Wait for the engine to drain all 5 samples and present this frame
+ let frame_deadline = Instant::now() + Duration::from_secs(2);
+ let mut cur_frames = handle.diagnostics().total_frames_rendered;
+ while cur_frames <= prev_frames && Instant::now() < frame_deadline {
+ std::thread::yield_now();
+ cur_frames = handle.diagnostics().total_frames_rendered;
+ }
+ assert!(
+ cur_frames > prev_frames,
+ "Engine did not render frame {frame_idx} within 2s"
+ );
+ frames_rendered += cur_frames - prev_frames;
+ prev_frames = cur_frames;
+
+ if frame_idx == 0 {
+ first_frame_diag = Some(handle.diagnostics());
+ }
+ }
+
+ let stroke_elapsed = bench_start.elapsed();
+ let perf_after_move = handle.perf_snapshot();
+ let diag_after_move = handle.diagnostics();
+ let dispatches_during_move = perf_after_move.stamp_dispatches - perf_before.stamp_dispatches;
+
+ eprintln!(
+ "[4K 100-frame live-stroke bench] elapsed={:.1}ms, frames={}, stamp_dispatches={} (for {} samples), fps={:.1}, frame_ms={:.2}ms, i2p={:.2}ms",
+ stroke_elapsed.as_secs_f64() * 1000.0,
+ frames_rendered,
+ dispatches_during_move,
+ total_samples,
+ diag_after_move.fps,
+ diag_after_move.frame_time_ms,
+ diag_after_move.input_to_present_ms,
+ );
+
+ // 1. Verify all 5 samples per frame are batched into 1 stamp dispatch per frame (NOT 500!)
+ assert!(
+ dispatches_during_move > 0 && dispatches_during_move <= frames_rendered,
+ "Expected <= 1 stamp dispatch per rendered frame (got {dispatches_during_move} dispatches across {frames_rendered} frames for {total_samples} input samples)"
+ );
+ assert!(
+ dispatches_during_move <= total_stroke_frames as u64,
+ "100 live-stroke frames with 5 samples/frame must trigger <= 100 stamp dispatches, got {dispatches_during_move}"
+ );
+
+ // 2. Verify active FPS telemetry never falsely reports "3 FPS" after the prior 380 ms idle gap!
+ let first_diag = first_frame_diag.expect("First frame diagnostics must be captured");
+ assert!(
+ !first_diag.is_idle,
+ "Engine diagnostics must report active (!is_idle) immediately after rendering a frame"
+ );
+ if first_diag.frame_time_ms < 16.0 {
+ assert!(
+ first_diag.fps >= 30.0,
+ "First frame after 380 ms idle gap with frame_time_ms={:.2}ms must report >= 30 FPS (never 3 FPS!), got {:.1} FPS",
+ first_diag.frame_time_ms,
+ first_diag.fps
+ );
+ }
+ assert!(
+ !diag_after_move.is_idle,
+ "Engine diagnostics must report active (!is_idle) after 100 consecutive live-stroke frames"
+ );
+ if diag_after_move.frame_time_ms < 16.0 {
+ assert!(
+ diag_after_move.fps >= 30.0,
+ "100 consecutive live-stroke frames with frame_time_ms={:.2}ms must report >= 30 FPS, got {:.1} FPS",
+ diag_after_move.frame_time_ms,
+ diag_after_move.fps
+ );
+ }
+ assert!(
+ diag_after_move.input_to_present_ms < 120.0,
+ "I2P latency must not be polluted by prior 380 ms idle gap, got {:.2}ms",
+ diag_after_move.input_to_present_ms
+ );
+
+ // 3. Pen-up commit: verify clean commit, ZERO synchronous render-thread PNG thumbnails,
+ // and asynchronous EngineEvent::ThumbnailsUpdated delivery from background worker!
+ assert!(producers.wintab.push(NativeInputSample {
+ phys_x: 1060.0,
+ phys_y: 500.0,
+ pressure: 0.0,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: clock::now_ms(),
+ buttons: 0,
+ phase: 3,
+ backend: 1,
+ }));
+
+ let mut saw_stroke_committed = false;
+ let mut saw_async_thumbnail = false;
+ let commit_deadline = Instant::now() + Duration::from_secs(5);
+ while Instant::now() < commit_deadline && (!saw_stroke_committed || !saw_async_thumbnail) {
+ for ev in handle.events().try_iter() {
+ match ev {
+ EngineEvent::StrokeCommitted { dirty_rect, points, .. } => {
+ assert!(
+ !dirty_rect.is_empty(),
+ "Pen-up StrokeCommitted dirty_rect must be non-empty"
+ );
+ assert!(
+ points.len() >= 100,
+ "Pen-up committed stroke should retain sampled path points, got {}",
+ points.len()
+ );
+ saw_stroke_committed = true;
+ }
+ EngineEvent::ThumbnailsUpdated { updates, .. } => {
+ if updates.iter().any(|u| {
+ u.thumbnail_url
+ .as_deref()
+ .is_some_and(|s| s.starts_with("data:image/png;base64,"))
+ }) {
+ saw_async_thumbnail = true;
+ }
+ }
+ _ => {}
+ }
+ }
+ std::thread::sleep(Duration::from_millis(5));
+ }
+
+ let perf_after_commit = handle.perf_snapshot();
+ assert!(
+ saw_stroke_committed,
+ "Pen-up must emit EngineEvent::StrokeCommitted cleanly"
+ );
+ assert_eq!(
+ perf_after_commit.sync_render_thread_thumbnails, 0,
+ "Render thread must NEVER generate PNG thumbnails synchronously on pen-up!"
+ );
+ assert!(
+ saw_async_thumbnail && perf_after_commit.async_thumbnails_completed >= 1,
+ "Background thumbnail worker must asynchronously emit EngineEvent::ThumbnailsUpdated (saw={saw_async_thumbnail}, completed={})",
+ perf_after_commit.async_thumbnails_completed
+ );
+
+ // Verify committed 4K document layer contains painted tiles cleanly
+ {
+ let docs = handle.documents();
+ let mgr = docs.read();
+ let doc = mgr.active_document().expect("Active 4K doc must exist");
+ let aid = doc.active_layer_id.as_deref().expect("Active layer must exist");
+ let layer = doc.layer(aid).expect("Active layer node must exist");
+ assert!(
+ !layer.grid.tiles.is_empty(),
+ "Committed 4K stroke must populate painted tiles on the active layer"
+ );
+ }
+
+ handle.shutdown();
+}
+
+// ============================================================================
+// Phase 7 Compositor & Latency Audit Regression Tests
+// ============================================================================
+
+/// Regression 1: Pure 240 Hz hover cursor moves & 30 Hz marching-ants ticks must hit the
+/// `final_scene_sig` fast path with ZERO BelowCache/AboveCache/FinalScene recompositing passes,
+/// and `GpuSelectionOverlay::encode_viewport_mask` must NOT re-project when selection & camera
+/// are unchanged.
+#[test]
+fn test_hover_and_marching_ants_perform_zero_recompositing_passes() {
+ let _dx12_guard = lock_dx12();
+ let Some(mut renderer) =
+ make_headless_renderer_vram(512, 512, 512, 512, 128 * 1024 * 1024)
+ else {
+ return;
+ };
+
+ let mut doc = Document::new_blank(
+ "doc-hover-fastpath",
+ "Hover Fast Path",
+ CanvasDimensions {
+ width: 512,
+ height: 512,
+ dpi: 300,
+ },
+ CanvasColorMode::Color,
+ "#ffffff",
+ 60.0,
+ 20,
+ );
+ let below_id = "layer-below".to_string();
+ let active_id = "layer-active".to_string();
+ let above_id = "layer-above".to_string();
+ doc.add_layer(LayerNodeMeta::new_raster(&below_id, "Below"), None, false, false);
+ doc.add_layer(LayerNodeMeta::new_raster(&active_id, "Active"), None, false, false);
+ doc.add_layer(LayerNodeMeta::new_raster(&above_id, "Above"), None, false, false);
+ doc.active_layer_id = Some(active_id.clone());
+
+ // Paint distinct tiles on below, active, and above layers + add an active selection
+ let red_px = vec![220u8, 40, 40, 255].repeat(64 * 64);
+ let blue_px = vec![40u8, 80, 220, 255].repeat(64 * 64);
+ let green_px = vec![40u8, 200, 80, 255].repeat(64 * 64);
+ doc.layer_mut(&below_id)
+ .unwrap()
+ .grid
+ .write_rgba8_rect(&red_px, RectI32::new(32, 32, 64, 64), 128, None)
+ .unwrap();
+ doc.layer_mut(&active_id)
+ .unwrap()
+ .grid
+ .write_rgba8_rect(&blue_px, RectI32::new(128, 128, 64, 64), 128, None)
+ .unwrap();
+ doc.layer_mut(&above_id)
+ .unwrap()
+ .grid
+ .write_rgba8_rect(&green_px, RectI32::new(256, 256, 64, 64), 128, None)
+ .unwrap();
+
+ crate::selection::select_rect(
+ &mut doc,
+ RectI32::new(64, 64, 192, 192),
+ crate::selection::SelectionCombineMode::Replace,
+ );
+
+ let display = CompositorDisplayConfig {
+ layer_stack_caching: true,
+ ..Default::default()
+ };
+ let vp = ViewportRect {
+ x_px: 0,
+ y_px: 0,
+ width_px: 512,
+ height_px: 512,
+ dpr: 1.0,
+ };
+ let cam = CameraState {
+ pan_x: 256.0,
+ pan_y: 256.0,
+ zoom: 1.0,
+ rotation: 0.0,
+ flip_x: false,
+ flip_y: false,
+ };
+ let cursor_cfg = CursorConfig {
+ visible: true,
+ size: 32.0,
+ ..Default::default()
+ };
+
+ // Frame 1: initial full build
+ let _ = renderer.render_document_frame(
+ &doc,
+ None,
+ &display,
+ &vp,
+ &cam,
+ &[],
+ false,
+ false,
+ &cursor_cfg,
+ Some((100.0, 100.0)),
+ false,
+ );
+ let base_stats = renderer.stack_cache_stats();
+ let base_sel_rebuilds = renderer.selection_vp_mask_rebuilds();
+ assert_eq!(base_stats.below_rebuilds, 1);
+ assert_eq!(base_stats.above_rebuilds, 1);
+ assert_eq!(base_stats.final_scene_rebuilds, 1);
+ assert_eq!(base_sel_rebuilds, 1);
+
+ // Frames 2..=25: pure hover cursor movement + marching-ants ticks (unchanged scene & camera)
+ for i in 0..24 {
+ let cx = 120.0 + (i as f32) * 10.0;
+ let cy = 140.0 + (i as f32) * 6.0;
+ let _ = renderer.render_document_frame(
+ &doc,
+ None,
+ &display,
+ &vp,
+ &cam,
+ &[],
+ false,
+ false,
+ &cursor_cfg,
+ Some((cx, cy)),
+ false,
+ );
+ assert!(
+ renderer
+ .last_composite_scissor()
+ .is_some_and(|s| s.is_empty()),
+ "Pure hover frame {i} must perform ZERO FinalScene compositing"
+ );
+ }
+
+ let after_stats = renderer.stack_cache_stats();
+ assert_eq!(
+ after_stats.below_rebuilds, base_stats.below_rebuilds,
+ "Pure hover frames must perform ZERO BelowCache rebuilds"
+ );
+ assert_eq!(
+ after_stats.above_rebuilds, base_stats.above_rebuilds,
+ "Pure hover frames must perform ZERO AboveCache rebuilds"
+ );
+ assert_eq!(
+ after_stats.final_scene_rebuilds, base_stats.final_scene_rebuilds,
+ "Pure hover frames must perform ZERO ActiveUnit/FinalScene recompositing passes"
+ );
+ assert_eq!(
+ after_stats.final_scene_hits, 24,
+ "All 24 hover frames must hit the final_scene_sig fast path"
+ );
+ assert_eq!(
+ renderer.selection_vp_mask_rebuilds(),
+ base_sel_rebuilds,
+ "Selection viewport mask must NOT be re-projected during hover / marching-ants ticks"
+ );
+}
+
+/// Regression 2: A 1-tile stroke on a 4×4-tile layer must regenerate strictly <= 3 LOD tiles
+/// (1 per LOD 1..3) in ONE batched `queue.submit`, with ZERO invalidation of untouched siblings.
+#[test]
+fn test_mipmap_1_tile_stroke_regenerates_at_most_3_lods_in_1_submit() {
+ let _dx12_guard = lock_dx12();
+ let Some(mut renderer) =
+ make_headless_renderer_vram(512, 512, 1024, 1024, 128 * 1024 * 1024)
+ else {
+ return;
+ };
+
+ let mut doc = Document::new_blank(
+ "doc-mip-4x4",
+ "Mipmap 4x4",
+ CanvasDimensions {
+ width: 1024,
+ height: 1024,
+ dpi: 300,
+ },
+ CanvasColorMode::Color,
+ "#ffffff",
+ 60.0,
+ 20,
+ );
+ let lid = "layer-4x4".to_string();
+ doc.add_layer(LayerNodeMeta::new_raster(&lid, "4x4 Grid"), None, false, false);
+ doc.active_layer_id = Some(lid.clone());
+
+ // Populate all 4×4 LOD-0 tiles with non-solid textured pixels (so none take the SolidColor shortcut)
+ {
+ let layer = doc.layer_mut(&lid).unwrap();
+ for ty in 0..4i32 {
+ for tx in 0..4i32 {
+ let mut tile_rgba = vec![0u8; TILE_SIZE * TILE_SIZE * 4];
+ for y in 0..TILE_SIZE {
+ for x in 0..TILE_SIZE {
+ let o = (y * TILE_SIZE + x) * 4;
+ tile_rgba[o] = ((tx * 50 + (x & 31) as i32) & 255) as u8;
+ tile_rgba[o + 1] = ((ty * 50 + (y & 31) as i32) & 255) as u8;
+ tile_rgba[o + 2] = 180;
+ tile_rgba[o + 3] = 255;
+ }
+ }
+ let td = crate::tiles::TileData::from_raw(
+ crate::tiles::TileFormat::Color32Bit,
+ crate::tiles::TileKind::Raster,
+ tile_rgba,
+ );
+ layer.grid.set_tile(TileCoord::new(tx, ty), std::sync::Arc::new(td));
+ }
+ }
+ }
+
+ // Build initial full mipmap pyramid (4 LOD-1 + 1 LOD-2 + 1 LOD-3 = 6 LOD tiles)
+ renderer.sync_document(&mut doc, None).unwrap();
+
+ // Record untouched sibling LOD-1 slots & versions BEFORE 1-tile stroke in (0, 0)
+ let sibling_coords = [
+ TileCoord::new(1, 0),
+ TileCoord::new(0, 1),
+ TileCoord::new(1, 1),
+ ];
+ let sibling_versions_before: Vec<u64> = {
+ let grid = &doc.layer(&lid).unwrap().grid;
+ sibling_coords
+ .iter()
+ .map(|&c| crate::memory::compute_lod_tile_version(grid, 1, c))
+ .collect()
+ };
+ let mipmaps_before = renderer.gpu_pool_stats().mipmaps_generated;
+ let submits_before = renderer.tile_pool().mipmap_submits();
+
+ // Mutate ONLY 1 tile: (0, 0) (simulating a localized 1-tile brush stroke commit)
+ let dirty_lods = {
+ let layer = doc.layer_mut(&lid).unwrap();
+ let mut tile_rgba = vec![0u8; TILE_SIZE * TILE_SIZE * 4];
+ for y in 0..TILE_SIZE {
+ for x in 0..TILE_SIZE {
+ let o = (y * TILE_SIZE + x) * 4;
+ tile_rgba[o] = 255;
+ tile_rgba[o + 1] = (x & 63) as u8;
+ tile_rgba[o + 2] = (y & 63) as u8;
+ tile_rgba[o + 3] = 255;
+ }
+ }
+ let td = crate::tiles::TileData::from_raw(
+ crate::tiles::TileFormat::Color32Bit,
+ crate::tiles::TileKind::Raster,
+ tile_rgba,
+ );
+ layer.grid.set_tile(TileCoord::new(0, 0), std::sync::Arc::new(td));
+ [
+ layer.grid.dirty_lods[0].drain().collect::<Vec<_>>(),
+ layer.grid.dirty_lods[1].drain().collect::<Vec<_>>(),
+ layer.grid.dirty_lods[2].drain().collect::<Vec<_>>(),
+ ]
+ };
+
+ // Regenerate dirty mipmaps for the 1-tile stroke
+ let grid_ref = &doc.layer(&lid).unwrap().grid;
+ renderer.regenerate_layer_mipmaps_from_dirty(&doc.id, &lid, grid_ref, &dirty_lods, &[], None);
+
+ let mipmaps_delta = renderer.gpu_pool_stats().mipmaps_generated - mipmaps_before;
+ let submits_delta = renderer.tile_pool().mipmap_submits() - submits_before;
+ assert!(
+ mipmaps_delta <= 3 && mipmaps_delta > 0,
+ "1-tile stroke on 4x4 layer must regenerate strictly <= 3 LOD tiles (1 per LOD 1..3), got {mipmaps_delta}"
+ );
+ assert_eq!(
+ submits_delta, 1,
+ "1-tile stroke mipmap update must execute in exactly 1 batched queue.submit, got {submits_delta}"
+ );
+
+ // Verify all 3 untouched LOD-1 siblings kept identical versions AND remained resident in VRAM!
+ for (i, &sc) in sibling_coords.iter().enumerate() {
+ let v_after = crate::memory::compute_lod_tile_version(&doc.layer(&lid).unwrap().grid, 1, sc);
+ assert_eq!(
+ v_after, sibling_versions_before[i],
+ "Untouched LOD-1 sibling {sc:?} version must remain unchanged"
+ );
+ let key = renderer.tile_pool_mut().make_key(&doc.id, &lid, 1, sc);
+ assert!(
+ renderer
+ .tile_pool_mut()
+ .get_slot_if_version(&key, v_after)
+ .is_some(),
+ "Untouched LOD-1 sibling {sc:?} must remain resident without invalidation"
+ );
+ }
+
+ // Also verify zoomed-out viewport render at zoom=0.25 (LOD 2) regenerates ZERO extra mipmaps!
+ let mipmaps_before_zoom_render = renderer.gpu_pool_stats().mipmaps_generated;
+ let display = CompositorDisplayConfig::default();
+ let vp = ViewportRect {
+ x_px: 0,
+ y_px: 0,
+ width_px: 512,
+ height_px: 512,
+ dpr: 1.0,
+ };
+ let cam_zoom_out = CameraState {
+ pan_x: 256.0,
+ pan_y: 256.0,
+ zoom: 0.25,
+ rotation: 0.0,
+ flip_x: false,
+ flip_y: false,
+ };
+ let _ = renderer.render_document_frame(
+ &doc,
+ None,
+ &display,
+ &vp,
+ &cam_zoom_out,
+ &[],
+ false,
+ false,
+ &CursorConfig::default(),
+ None,
+ true,
+ );
+ assert_eq!(
+ renderer.gpu_pool_stats().mipmaps_generated,
+ mipmaps_before_zoom_render,
+ "Zoomed-out render after 1-tile stroke must hit cached LOD pyramid with ZERO extra mipmaps"
+ );
+}
+
+/// Regression 3: Raster strokes on a masked layer must NOT bump `grid.mask_version` and must
+/// NOT trigger `DocMaskCache` mask rebuilds!
+#[test]
+fn test_raster_strokes_on_masked_layer_do_not_rebuild_mask() {
+ let _dx12_guard = lock_dx12();
+ let Some(mut renderer) =
+ make_headless_renderer_vram(512, 512, 512, 512, 128 * 1024 * 1024)
+ else {
+ return;
+ };
+
+ let mut doc = Document::new_blank(
+ "doc-mask-version",
+ "Mask Version",
+ CanvasDimensions {
+ width: 512,
+ height: 512,
+ dpi: 300,
+ },
+ CanvasColorMode::Color,
+ "#ffffff",
+ 60.0,
+ 20,
+ );
+ let lid = "layer-masked".to_string();
+ doc.add_layer(LayerNodeMeta::new_raster(&lid, "Masked"), None, false, false);
+ doc.active_layer_id = Some(lid.clone());
+
+ // Attach a non-destructive 8-bit mask with a crisp 128×128 reveal hole
+ doc.add_layer_mask(&lid, 0, false).unwrap();
+ let reveal_box = vec![255u8; 128 * 128];
+ doc.layer_mut(&lid)
+ .unwrap()
+ .grid
+ .write_mask8_rect(&reveal_box, RectI32::new(128, 128, 128, 128), None)
+ .unwrap();
+
+ let mask_ver_initial = doc.layer(&lid).unwrap().grid.mask_version;
+ let display = CompositorDisplayConfig {
+ layer_stack_caching: true,
+ ..Default::default()
+ };
+ let vp = ViewportRect {
+ x_px: 0,
+ y_px: 0,
+ width_px: 512,
+ height_px: 512,
+ dpr: 1.0,
+ };
+ let cam = CameraState {
+ pan_x: 256.0,
+ pan_y: 256.0,
+ zoom: 1.0,
+ rotation: 0.0,
+ flip_x: false,
+ flip_y: false,
+ };
+
+ // Initial render projects the viewport-resolution GPU mask once
+ let _ = renderer.render_document_frame(
+ &doc,
+ None,
+ &display,
+ &vp,
+ &cam,
+ &[],
+ false,
+ false,
+ &CursorConfig::default(),
+ None,
+ true,
+ );
+ let mask_rebuilds_after_init = renderer.doc_mask_rebuilds();
+ assert_eq!(mask_rebuilds_after_init, 1);
+
+ // Commit 3 separate raster strokes on the masked layer & render after each
+ for s in 0..3i32 {
+ let brush = NativeBrushConfig {
+ fg_color: [0.9, 0.1 + s as f32 * 0.2, 0.2],
+ size: 36.0,
+ hardness: 0.95,
+ spacing: 0.2,
+ opacity: 1.0,
+ ..Default::default()
+ };
+ let pts = make_curved_stroke_points(
+ 140.0,
+ 150.0 + s as f64 * 25.0,
+ 230.0,
+ 150.0 + s as f64 * 25.0,
+ 0.0,
+ 0.0,
+ 8,
+ 36.0,
+ );
+ emit_and_commit_stroke(&mut renderer, &mut doc, &lid, brush, &pts, 100 + s as u64);
+
+ assert_eq!(
+ doc.layer(&lid).unwrap().grid.mask_version,
+ mask_ver_initial,
+ "Raster stroke {s} must NEVER bump grid.mask_version"
+ );
+
+ let _ = renderer.render_document_frame(
+ &doc,
+ None,
+ &display,
+ &vp,
+ &cam,
+ &[],
+ false,
+ false,
+ &CursorConfig::default(),
+ None,
+ true,
+ );
+ assert_eq!(
+ renderer.doc_mask_rebuilds(),
+ mask_rebuilds_after_init,
+ "Raster stroke {s} must trigger ZERO DocMaskCache rebuilds!"
+ );
+ }
+
+ // Mutating the mask MUST bump mask_version and rebuild the GPU viewport mask exactly once
+ let extra_reveal = vec![255u8; 32 * 32];
+ doc.layer_mut(&lid)
+ .unwrap()
+ .grid
+ .write_mask8_rect(&extra_reveal, RectI32::new(260, 260, 32, 32), None)
+ .unwrap();
+ assert_ne!(
+ doc.layer(&lid).unwrap().grid.mask_version,
+ mask_ver_initial,
+ "Mask mutation must bump grid.mask_version"
+ );
+ let _ = renderer.render_document_frame(
+ &doc,
+ None,
+ &display,
+ &vp,
+ &cam,
+ &[],
+ false,
+ false,
+ &CursorConfig::default(),
+ None,
+ true,
+ );
+ assert_eq!(
+ renderer.doc_mask_rebuilds(),
+ mask_rebuilds_after_init + 1,
+ "Mask edit must rebuild DocMaskCache exactly once"
+ );
+}
+
+/// Regression 4: Active-stroke frames with NO newly sealed segments (`dirty_doc_bounds == None`)
+/// and NO predicted dabs (`predicted_dabs.is_empty()`) — e.g. during stabilizer hold — must NOT
+/// fall back to `full_scissor`!
+#[test]
+fn test_active_stroke_no_new_segments_does_not_fallback_to_full_scissor() {
+ let _dx12_guard = lock_dx12();
+ let Some(mut renderer) =
+ make_headless_renderer_vram(512, 512, 512, 512, 128 * 1024 * 1024)
+ else {
+ return;
+ };
+
+ let mut doc = Document::new_blank(
+ "doc-live-zero-skip",
+ "Live Stroke Zero Skip",
+ CanvasDimensions {
+ width: 512,
+ height: 512,
+ dpi: 300,
+ },
+ CanvasColorMode::Color,
+ "#ffffff",
+ 60.0,
+ 20,
+ );
+ let lid = "layer-ink".to_string();
+ doc.add_layer(LayerNodeMeta::new_raster(&lid, "Ink"), None, false, false);
+ doc.active_layer_id = Some(lid.clone());
+
+ let display = CompositorDisplayConfig {
+ layer_stack_caching: true,
+ ..Default::default()
+ };
+ let vp = ViewportRect {
+ x_px: 0,
+ y_px: 0,
+ width_px: 512,
+ height_px: 512,
+ dpr: 1.0,
+ };
+ let cam = CameraState {
+ pan_x: 256.0,
+ pan_y: 256.0,
+ zoom: 1.0,
+ rotation: 0.0,
+ flip_x: false,
+ flip_y: false,
+ };
+
+ // Start a live GPU brush stroke and stamp an initial dab at (200, 200)
+ let brush = NativeBrushConfig {
+ fg_color: [0.1, 0.1, 0.1],
+ size: 24.0,
+ hardness: 0.9,
+ spacing: 0.15,
+ opacity: 1.0,
+ ..Default::default()
+ };
+ let mut emitter = StrokeDabEmitter::new(brush.clone(), 1, 777, 1.0);
+ let mut initial_dabs = Vec::new();
+ emitter.emit_initial_point(
+ &StrokePoint {
+ x: 200.0,
+ y: 200.0,
+ pressure: 1.0,
+ width: 24.0,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ velocity: 0.0,
+ timestamp_ms: 0.0,
+ is_corner: false,
+ },
+ None,
+ 0.0,
+ &mut initial_dabs,
+ );
+ renderer.begin_gpu_stroke(512, 512, false, brush, emitter.stroke_grain_offset);
+ let _ = renderer.stamp_gpu_stroke_dabs(&initial_dabs, &[]);
+
+ // Frame 1: stroke init (needs_init == true -> full_scissor expected)
+ let _ = renderer.render_document_frame_with_brush(
+ &doc,
+ None,
+ &display,
+ &vp,
+ &cam,
+ &[],
+ false,
+ true,
+ &[],
+ Some(crate::compositor::DocBounds {
+ min_x: 180,
+ min_y: 180,
+ max_x: 220,
+ max_y: 220,
+ }),
+ &CursorConfig::default(),
+ Some((200.0, 200.0)),
+ false,
+ );
+ assert_eq!(
+ renderer.last_composite_scissor(),
+ Some(crate::compositor::ScissorRect::full(512, 512)),
+ "First live-stroke frame should initialize with full_scissor"
+ );
+
+ // Frame 2: stabilizer hold — stroke is active, pointer moved slightly, ZERO new sealed
+ // segments (`dirty_doc_bounds = None`) and ZERO predicted dabs (`&[]`)!
+ let skips_before = renderer.stack_cache_stats().live_stroke_zero_skips;
+ let _ = renderer.render_document_frame_with_brush(
+ &doc,
+ None,
+ &display,
+ &vp,
+ &cam,
+ &[],
+ false,
+ true,
+ &[],
+ None,
+ &CursorConfig::default(),
+ Some((201.0, 200.0)),
+ false,
+ );
+
+ let sc = renderer
+ .last_composite_scissor()
+ .expect("last_composite_scissor must be recorded");
+ assert!(
+ sc.is_empty(),
+ "Active-stroke frame with no newly sealed segments and no predicted dabs must NOT fall back to full_scissor (got {sc:?})"
+ );
+ assert_eq!(
+ renderer.stack_cache_stats().live_stroke_zero_skips,
+ skips_before + 1,
+ "live_stroke_zero_skips must increment on zero-change active-stroke frame"
+ );
+}
diff --git a/crates/ink-engine/src/selection/gpu_ants.rs b/crates/ink-engine/src/selection/gpu_ants.rs
index ec32e21..891f999 100644
--- a/crates/ink-engine/src/selection/gpu_ants.rs
+++ b/crates/ink-engine/src/selection/gpu_ants.rs
@@ -268,12 +268,44 @@ struct FloatingQuadUniforms {
rect_doc: [f32; 4],
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+struct VpMaskCacheKey {
+ synced_version: u64,
+ atlas_gen: u64,
+ doc_width: u32,
+ doc_height: u32,
+ default_value: u8,
+ vp_w: u32,
+ vp_h: u32,
+ camera_sig: u64,
+ shift_x_bits: u32,
+ shift_y_bits: u32,
+}
+
+#[inline]
+fn hash_sel_camera(camera: &CameraState, dpr: f32) -> u64 {
+ let mut h: u64 = 0xcbf29ce484222325;
+ let mix = |h: &mut u64, v: u32| {
+ *h ^= u64::from(v);
+ *h = h.wrapping_mul(0x100000001b3);
+ };
+ let fbits = |f: f32| if f == 0.0 { 0u32 } else { f.to_bits() };
+ mix(&mut h, fbits(camera.pan_x));
+ mix(&mut h, fbits(camera.pan_y));
+ mix(&mut h, fbits(camera.zoom));
+ mix(&mut h, fbits(camera.rotation));
+ mix(&mut h, u32::from(camera.flip_x) | (u32::from(camera.flip_y) << 1));
+ mix(&mut h, fbits(dpr));
+ h
+}
+
/// Manages sparse `R8Unorm` GPU selection tiles, viewport selection mask projection,
/// floating selection RGBA preview, and animated GPU marching ants rendering.
pub struct GpuSelectionOverlay {
atlas_tex: wgpu::Texture,
atlas_view: wgpu::TextureView,
atlas_capacity: u32,
+ atlas_gen: u64,
coord_to_slot: HashMap<TileCoord, u32>,
synced_version: u64,
active: bool,
@@ -285,19 +317,24 @@ pub struct GpuSelectionOverlay {
vp_view: wgpu::TextureView,
vp_width: u32,
vp_height: u32,
+ vp_mask_cache_key: Option<VpMaskCacheKey>,
+ vp_mask_rebuilds: u64,
project_bgl: wgpu::BindGroupLayout,
project_pipeline: wgpu::RenderPipeline,
project_uniform_buf: wgpu::Buffer,
+ project_bg: Option<wgpu::BindGroup>,
inst_buf: wgpu::Buffer,
inst_cap: usize,
ants_bgl: wgpu::BindGroupLayout,
ants_pipeline: wgpu::RenderPipeline,
ants_uniform_buf: wgpu::Buffer,
+ ants_bg: Option<wgpu::BindGroup>,
// Floating selection GPU texture (allocated strictly while floating move is active)
floating_tex: Option<(wgpu::Texture, wgpu::TextureView, u32, u32, u64)>,
+ floating_bg: Option<wgpu::BindGroup>,
floating_bgl: wgpu::BindGroupLayout,
floating_pipeline: wgpu::RenderPipeline,
floating_uniform_buf: wgpu::Buffer,
@@ -553,6 +590,7 @@ impl GpuSelectionOverlay {
atlas_tex,
atlas_view,
atlas_capacity,
+ atlas_gen: 1,
coord_to_slot: HashMap::new(),
synced_version: 0,
active: false,
@@ -563,15 +601,20 @@ impl GpuSelectionOverlay {
vp_view,
vp_width: 1,
vp_height: 1,
+ vp_mask_cache_key: None,
+ vp_mask_rebuilds: 0,
project_bgl,
project_pipeline,
project_uniform_buf,
+ project_bg: None,
inst_buf,
inst_cap,
ants_bgl,
ants_pipeline,
ants_uniform_buf,
+ ants_bg: None,
floating_tex: None,
+ floating_bg: None,
floating_bgl,
floating_pipeline,
floating_uniform_buf,
@@ -634,6 +677,11 @@ impl GpuSelectionOverlay {
&self.atlas_view
}
+ #[inline]
+ pub fn atlas_gen(&self) -> u64 {
+ self.atlas_gen
+ }
+
#[inline]
pub fn default_alpha_f32(&self) -> f32 {
self.default_value as f32 / 255.0
@@ -650,6 +698,11 @@ impl GpuSelectionOverlay {
&self.vp_view
}
+ #[inline]
+ pub fn vp_mask_rebuilds(&self) -> u64 {
+ self.vp_mask_rebuilds
+ }
+
/// Synchronizes a `Document`'s [`SparseSelectionMask`] into GPU `R8Unorm` sparse tiles (O(1) no-op if unchanged).
pub fn sync_from_mask(
&mut self,
@@ -661,7 +714,9 @@ impl GpuSelectionOverlay {
self.active = false;
self.coord_to_slot.clear();
self.synced_version = 0;
+ self.vp_mask_cache_key = None;
self.floating_tex = None;
+ self.floating_bg = None;
return;
};
@@ -713,9 +768,11 @@ impl GpuSelectionOverlay {
},
);
self.floating_tex = Some((tex, view, fl.width, fl.height, fl.version));
+ self.floating_bg = None;
}
} else {
self.floating_tex = None;
+ self.floating_bg = None;
}
if self.synced_version == mask.version {
@@ -729,6 +786,8 @@ impl GpuSelectionOverlay {
self.atlas_tex = tex;
self.atlas_view = view;
self.atlas_capacity = new_cap;
+ self.atlas_gen = self.atlas_gen.saturating_add(1);
+ self.project_bg = None;
}
self.coord_to_slot.clear();
@@ -763,15 +822,20 @@ impl GpuSelectionOverlay {
self.coord_to_slot.insert(coord, slot_idx as u32);
}
self.synced_version = mask.version;
+ self.vp_mask_cache_key = None;
}
/// Projects sparse `R8Unorm` selection tiles into viewport-resolution `self.vp_view`
- /// so both `WgpuCompositor` (live stroke clipping) and `render_floating_and_ants` can read it.
+ /// by recording the pass directly into a caller-supplied `CommandEncoder` (zero extra submit).
+ ///
+ /// Cached by `(synced_version, atlas_gen, doc_size, default_value, vp_size, camera_sig, floating_shift)`
+ /// so 240 Hz hover cursor moves and 30 Hz marching-ants ticks do ZERO selection re-projection!
#[allow(clippy::too_many_arguments)]
- pub fn project_viewport_mask(
+ pub fn encode_viewport_mask(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
+ encoder: &mut wgpu::CommandEncoder,
mask_opt: Option<&SparseSelectionMask>,
camera: &CameraState,
vp_w: u32,
@@ -786,44 +850,97 @@ impl GpuSelectionOverlay {
return;
};
+ let safe_dpr = dpr.max(0.05);
+ let (shift_x, shift_y) = mask
+ .floating
+ .as_ref()
+ .map(|fl| ((fl.x - fl.orig_x) as f32, (fl.y - fl.orig_y) as f32))
+ .unwrap_or((0.0, 0.0));
+
+ let cache_key = VpMaskCacheKey {
+ synced_version: self.synced_version,
+ atlas_gen: self.atlas_gen,
+ doc_width: self.doc_width,
+ doc_height: self.doc_height,
+ default_value: self.default_value,
+ vp_w,
+ vp_h,
+ camera_sig: hash_sel_camera(camera, safe_dpr),
+ shift_x_bits: if shift_x == 0.0 { 0 } else { shift_x.to_bits() },
+ shift_y_bits: if shift_y == 0.0 { 0 } else { shift_y.to_bits() },
+ };
+
+ if self.vp_width == vp_w
+ && self.vp_height == vp_h
+ && self.vp_mask_cache_key == Some(cache_key)
+ {
+ return;
+ }
+
if self.vp_width != vp_w || self.vp_height != vp_h {
let (t, v) = Self::alloc_vp_mask(device, vp_w, vp_h);
self.vp_tex = t;
self.vp_view = v;
self.vp_width = vp_w;
self.vp_height = vp_h;
+ self.ants_bg = None;
}
- let (shift_x, shift_y) = mask
- .floating
- .as_ref()
- .map(|fl| ((fl.x - fl.orig_x) as f32, (fl.y - fl.orig_y) as f32))
- .unwrap_or((0.0, 0.0));
-
- let mut insts = Vec::with_capacity(self.coord_to_slot.len().max(16));
+ // Frustum-cull emitted selection tile quads against the visible document bounds
+ // (critical for inverted selections on 4K–8K canvases!).
+ let frustum = crate::compositor::calculate_visible_doc_bounds(
+ vp_w as f32 / safe_dpr,
+ vp_h as f32 / safe_dpr,
+ camera,
+ self.doc_width,
+ self.doc_height,
+ );
+ let vis_min_tx =
+ ((frustum.min_x as f32 - shift_x).floor() as i32).div_euclid(TILE_SIZE as i32) - 1;
+ let vis_max_tx =
+ ((frustum.max_x as f32 - shift_x).ceil() as i32).div_euclid(TILE_SIZE as i32) + 1;
+ let vis_min_ty =
+ ((frustum.min_y as f32 - shift_y).floor() as i32).div_euclid(TILE_SIZE as i32) - 1;
+ let vis_max_ty =
+ ((frustum.max_y as f32 - shift_y).ceil() as i32).div_euclid(TILE_SIZE as i32) + 1;
+
+ let mut insts = Vec::with_capacity(self.coord_to_slot.len().min(64).max(16));
if self.default_value > 0 {
let max_tx = (self.doc_width.saturating_sub(1) / TILE_SIZE as u32) as i32;
let max_ty = (self.doc_height.saturating_sub(1) / TILE_SIZE as u32) as i32;
- for ty in 0..=max_ty {
- for tx in 0..=max_tx {
- let coord = TileCoord::new(tx, ty);
- let slot = self
- .coord_to_slot
- .get(&coord)
- .map(|&s| s as f32)
- .unwrap_or(-1.0);
- insts.push(SelTileInst {
- tile_origin_doc: [
- (tx * TILE_SIZE as i32) as f32 + shift_x,
- (ty * TILE_SIZE as i32) as f32 + shift_y,
- ],
- slot_f: slot,
- _pad: 0.0,
- });
+ let tx0 = vis_min_tx.clamp(0, max_tx);
+ let tx1 = vis_max_tx.clamp(0, max_tx);
+ let ty0 = vis_min_ty.clamp(0, max_ty);
+ let ty1 = vis_max_ty.clamp(0, max_ty);
+ if !frustum.is_empty() && tx0 <= tx1 && ty0 <= ty1 {
+ for ty in ty0..=ty1 {
+ for tx in tx0..=tx1 {
+ let coord = TileCoord::new(tx, ty);
+ let slot = self
+ .coord_to_slot
+ .get(&coord)
+ .map(|&s| s as f32)
+ .unwrap_or(-1.0);
+ insts.push(SelTileInst {
+ tile_origin_doc: [
+ (tx * TILE_SIZE as i32) as f32 + shift_x,
+ (ty * TILE_SIZE as i32) as f32 + shift_y,
+ ],
+ slot_f: slot,
+ _pad: 0.0,
+ });
+ }
}
}
- } else {
+ } else if !frustum.is_empty() {
for (&coord, &slot) in &self.coord_to_slot {
+ if coord.tx < vis_min_tx
+ || coord.tx > vis_max_tx
+ || coord.ty < vis_min_ty
+ || coord.ty > vis_max_ty
+ {
+ continue;
+ }
insts.push(SelTileInst {
tile_origin_doc: [
(coord.tx * TILE_SIZE as i32) as f32 + shift_x,
@@ -858,29 +975,31 @@ impl GpuSelectionOverlay {
if camera.flip_x { -1.0 } else { 1.0 },
if camera.flip_y { -1.0 } else { 1.0 },
],
- dpr: dpr.max(0.05),
+ dpr: safe_dpr,
default_val: self.default_value as f32 / 255.0,
};
queue.write_buffer(&self.project_uniform_buf, 0, bytemuck::bytes_of(&proj_u));
- let proj_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-sel-project-bg"),
- layout: &self.project_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: self.project_uniform_buf.as_entire_binding(),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(&self.atlas_view),
- },
- ],
+ let proj_bgl = &self.project_bgl;
+ let project_uniform_buf = &self.project_uniform_buf;
+ let atlas_view = &self.atlas_view;
+ let proj_bg = self.project_bg.get_or_insert_with(|| {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-sel-project-bg"),
+ layout: proj_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: project_uniform_buf.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(atlas_view),
+ },
+ ],
+ })
});
- let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-sel-project-encoder"),
- });
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("ink-sel-project-pass"),
@@ -900,21 +1019,47 @@ impl GpuSelectionOverlay {
});
if !insts.is_empty() {
pass.set_pipeline(&self.project_pipeline);
- pass.set_bind_group(0, &proj_bg, &[]);
+ pass.set_bind_group(0, &*proj_bg, &[]);
pass.set_vertex_buffer(0, self.inst_buf.slice(..));
pass.draw(0..6, 0..insts.len() as u32);
}
}
+ self.vp_mask_cache_key = Some(cache_key);
+ self.vp_mask_rebuilds = self.vp_mask_rebuilds.saturating_add(1);
+ }
+
+ /// Projects sparse `R8Unorm` selection tiles into viewport-resolution `self.vp_view`
+ /// so both `WgpuCompositor` (live stroke clipping) and `render_floating_and_ants` can read it.
+ #[allow(clippy::too_many_arguments)]
+ pub fn project_viewport_mask(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ mask_opt: Option<&SparseSelectionMask>,
+ camera: &CameraState,
+ vp_w: u32,
+ vp_h: u32,
+ dpr: f32,
+ ) {
+ self.sync_from_mask(device, queue, mask_opt);
+ if !self.active || vp_w == 0 || vp_h == 0 {
+ return;
+ }
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-sel-project-encoder"),
+ });
+ self.encode_viewport_mask(device, queue, &mut encoder, mask_opt, camera, vp_w, vp_h, dpr);
queue.submit(Some(encoder.finish()));
}
- /// Renders optional floating selection pixels + animated display-resolution GPU Marching Ants
- /// onto `target_view` using the already-projected `self.vp_view`.
+ /// Encodes optional floating selection pixels + animated display-resolution GPU Marching Ants
+ /// onto `target_view` inside a caller-supplied `CommandEncoder` (zero extra submit).
#[allow(clippy::too_many_arguments)]
- pub fn render_floating_and_ants(
+ pub fn encode_floating_and_ants(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
+ encoder: &mut wgpu::CommandEncoder,
mask_opt: Option<&SparseSelectionMask>,
camera: &CameraState,
vp_w: u32,
@@ -941,23 +1086,24 @@ impl GpuSelectionOverlay {
};
queue.write_buffer(&self.ants_uniform_buf, 0, bytemuck::bytes_of(&ants_u));
- let ants_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-marching-ants-bg"),
- layout: &self.ants_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: self.ants_uniform_buf.as_entire_binding(),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(&self.vp_view),
- },
- ],
- });
-
- let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-sel-ants-encoder"),
+ let ants_bgl = &self.ants_bgl;
+ let ants_uniform_buf = &self.ants_uniform_buf;
+ let vp_view = &self.vp_view;
+ let ants_bg = self.ants_bg.get_or_insert_with(|| {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-marching-ants-bg"),
+ layout: ants_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: ants_uniform_buf.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(vp_view),
+ },
+ ],
+ })
});
// Pass 1: Draw optional floating selection pixels directly onto swapchain target
@@ -978,23 +1124,28 @@ impl GpuSelectionOverlay {
rect_doc: [fl.x as f32, fl.y as f32, fl.width as f32, fl.height as f32],
};
queue.write_buffer(&self.floating_uniform_buf, 0, bytemuck::bytes_of(&fl_u));
- let fl_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-sel-floating-bg"),
- layout: &self.floating_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: self.floating_uniform_buf.as_entire_binding(),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(fl_view),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::Sampler(&self.linear_sampler),
- },
- ],
+ let floating_bgl = &self.floating_bgl;
+ let floating_uniform_buf = &self.floating_uniform_buf;
+ let linear_sampler = &self.linear_sampler;
+ let fl_bg = self.floating_bg.get_or_insert_with(|| {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-sel-floating-bg"),
+ layout: floating_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: floating_uniform_buf.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(fl_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::Sampler(linear_sampler),
+ },
+ ],
+ })
});
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("ink-sel-floating-pass"),
@@ -1013,7 +1164,7 @@ impl GpuSelectionOverlay {
multiview_mask: None,
});
pass.set_pipeline(&self.floating_pipeline);
- pass.set_bind_group(0, &fl_bg, &[]);
+ pass.set_bind_group(0, &*fl_bg, &[]);
pass.draw(0..6, 0..1);
}
@@ -1036,10 +1187,44 @@ impl GpuSelectionOverlay {
multiview_mask: None,
});
pass.set_pipeline(&self.ants_pipeline);
- pass.set_bind_group(0, &ants_bg, &[]);
+ pass.set_bind_group(0, &*ants_bg, &[]);
pass.draw(0..3, 0..1);
}
+ }
+ /// Renders optional floating selection pixels + animated display-resolution GPU Marching Ants
+ /// onto `target_view` using the already-projected `self.vp_view`.
+ #[allow(clippy::too_many_arguments)]
+ pub fn render_floating_and_ants(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ mask_opt: Option<&SparseSelectionMask>,
+ camera: &CameraState,
+ vp_w: u32,
+ vp_h: u32,
+ dpr: f32,
+ time_sec: f32,
+ target_view: &wgpu::TextureView,
+ ) {
+ if !self.active || vp_w == 0 || vp_h == 0 || mask_opt.is_none() {
+ return;
+ }
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-sel-ants-encoder"),
+ });
+ self.encode_floating_and_ants(
+ device,
+ queue,
+ &mut encoder,
+ mask_opt,
+ camera,
+ vp_w,
+ vp_h,
+ dpr,
+ time_sec,
+ target_view,
+ );
queue.submit(Some(encoder.finish()));
}
diff --git a/crates/ink-engine/src/selection/ops.rs b/crates/ink-engine/src/selection/ops.rs
index 2b3d080..6511682 100644
--- a/crates/ink-engine/src/selection/ops.rs
+++ b/crates/ink-engine/src/selection/ops.rs
@@ -97,12 +97,27 @@ pub fn select_lasso(
max_x = max_x.max(px);
max_y = max_y.max(py);
}
+ if !min_x.is_finite() || !min_y.is_finite() || !max_x.is_finite() || !max_y.is_finite() {
+ if mode == SelectionCombineMode::Replace || mode == SelectionCombineMode::Intersect {
+ doc.selection = None;
+ return SelectionMetaSnapshot::empty();
+ }
+ return doc
+ .selection
+ .as_ref()
+ .map(|s| s.snapshot_meta())
+ .unwrap_or_else(SelectionMetaSnapshot::empty);
+ }
let doc_rect = RectI32::new(0, 0, dw, dh);
let raw_rect = RectI32::new(
- min_x.floor() as i32 - 1,
- min_y.floor() as i32 - 1,
- ((max_x.ceil() - min_x.floor()) as i32 + 3).max(0) as u32,
- ((max_y.ceil() - min_y.floor()) as i32 + 3).max(0) as u32,
+ (min_x.floor() as i32).saturating_sub(1),
+ (min_y.floor() as i32).saturating_sub(1),
+ ((max_x.ceil() - min_x.floor()) as i32)
+ .saturating_add(3)
+ .max(0) as u32,
+ ((max_y.ceil() - min_y.floor()) as i32)
+ .saturating_add(3)
+ .max(0) as u32,
);
let clipped = raw_rect.intersect(doc_rect);
if clipped.is_empty() {
@@ -835,6 +850,11 @@ pub fn cut_selection(
layer_id: &str,
scratch: Option<&dyn ScratchBackend>,
) -> Result<Option<SelectionClipboard>, String> {
+ if let Some(node) = doc.layer(layer_id) {
+ if node.meta.locked || !node.meta.layer_type.has_tiles() {
+ return Ok(None);
+ }
+ }
let copied = copy_selection(doc, layer_id, scratch)?;
if copied.is_none() {
return Ok(None);
@@ -847,13 +867,16 @@ pub fn cut_selection(
Ok(copied)
}
-/// Pastes a [`SelectionClipboard`] into a brand-new raster layer above the active layer with CoW Undo.
+/// Pastes a [`SelectionClipboard`] into a brand-new raster layer above the active layer with atomic CoW Undo.
pub fn paste_selection(
doc: &mut Document,
clip: &SelectionClipboard,
new_layer_id: String,
scratch: Option<&dyn ScratchBackend>,
) -> Result<String, String> {
+ let before_layers: Vec<LayerNodeMeta> = doc.layers.iter().map(|l| l.meta.clone()).collect();
+ let before_active = doc.active_layer_id.clone();
+
let name = format!("{} (Pasted)", clip.source_layer_name);
let insert_idx = doc
.active_layer_id
@@ -866,18 +889,27 @@ pub fn paste_selection(
}
doc.add_layer(meta, Some(insert_idx), true, false);
let rect = RectI32::new(clip.x, clip.y, clip.width, clip.height);
- doc.ingest_dirty_rect(
- &new_layer_id,
- rect,
- &clip.rgba,
- false,
- true,
+ if let Some(node) = doc.layer_mut(&new_layer_id) {
+ let thresh = node.meta.mono_threshold.unwrap_or(128);
+ node.grid.write_rgba8_rect(&clip.rgba, rect, thresh, scratch)?;
+ }
+ let after_grid = doc
+ .layer(&new_layer_id)
+ .map(|n| (new_layer_id.clone(), n.grid.clone_cow()))
+ .into_iter()
+ .collect();
+ doc.dirty_for_render = true;
+ doc.record_tree_history(
"layer",
"Paste Selection",
+ Some(new_layer_id.clone()),
+ before_layers,
+ before_active,
+ Vec::new(),
+ after_grid,
+ Vec::new(),
None,
- None,
- scratch,
- )?;
+ );
Ok(new_layer_id)
}
@@ -888,9 +920,41 @@ pub fn move_selection_to_new_layer(
new_layer_id: String,
scratch: Option<&dyn ScratchBackend>,
) -> Result<Option<String>, String> {
- let Some(clip) = cut_selection(doc, src_layer_id, scratch)? else {
+ if let Some(node) = doc.layer(src_layer_id) {
+ if node.meta.locked || !node.meta.layer_type.has_tiles() {
+ return Ok(None);
+ }
+ }
+ let Some(clip) = copy_selection(doc, src_layer_id, scratch)? else {
return Ok(None);
};
+ let before_layers: Vec<LayerNodeMeta> = doc.layers.iter().map(|l| l.meta.clone()).collect();
+ let before_active = doc.active_layer_id.clone();
+ let src_before_grid = doc
+ .layer(src_layer_id)
+ .map(|n| (src_layer_id.to_string(), n.grid.clone_cow()));
+
+ // Clear selected region from source layer without recording a separate undo step
+ let rect = RectI32::new(clip.x, clip.y, clip.width, clip.height);
+ if let Some(sel) = doc.selection.clone() {
+ let mask = sel.read_rect(rect);
+ if let Some(node) = doc.layer_mut(src_layer_id) {
+ let mut rgba = node.grid.read_rgba8_rect(rect, false, scratch)?;
+ for (px, &m) in rgba.as_chunks_mut::<4>().0.iter_mut().zip(mask.iter()) {
+ if m == 255 {
+ px.copy_from_slice(&[0, 0, 0, 0]);
+ } else if m > 0 {
+ let keep = 255u32 - u32::from(m);
+ px[3] = ((u32::from(px[3]) * keep + 127) / 255) as u8;
+ }
+ }
+ let thresh = node.meta.mono_threshold.unwrap_or(128);
+ node.grid.write_rgba8_rect(&rgba, rect, thresh, scratch)?;
+ }
+ } else {
+ doc.clear_layer(src_layer_id, false)?;
+ }
+
let name = format!("{} (Selection)", clip.source_layer_name);
let insert_idx = doc.layer_index(src_layer_id).unwrap_or(0);
let mut meta = LayerNodeMeta::new_raster(new_layer_id.clone(), name);
@@ -898,20 +962,34 @@ pub fn move_selection_to_new_layer(
meta.parent_id = src.meta.parent_id.clone();
}
doc.add_layer(meta, Some(insert_idx), true, false);
- let rect = RectI32::new(clip.x, clip.y, clip.width, clip.height);
- doc.ingest_dirty_rect(
- &new_layer_id,
- rect,
- &clip.rgba,
- false,
- true,
+ if let Some(node) = doc.layer_mut(&new_layer_id) {
+ let thresh = node.meta.mono_threshold.unwrap_or(128);
+ node.grid.write_rgba8_rect(&clip.rgba, rect, thresh, scratch)?;
+ }
+ let mut before_grids = Vec::new();
+ let mut after_grids = Vec::new();
+ if let Some(bg) = src_before_grid {
+ before_grids.push(bg);
+ }
+ if let Some(src) = doc.layer(src_layer_id) {
+ after_grids.push((src_layer_id.to_string(), src.grid.clone_cow()));
+ }
+ if let Some(dst) = doc.layer(&new_layer_id) {
+ after_grids.push((new_layer_id.clone(), dst.grid.clone_cow()));
+ }
+ doc.selection = None;
+ doc.dirty_for_render = true;
+ doc.record_tree_history(
"selection-move",
"Move Selection to New Layer",
+ Some(new_layer_id.clone()),
+ before_layers,
+ before_active,
+ before_grids,
+ after_grids,
+ Vec::new(),
None,
- None,
- scratch,
- )?;
- doc.selection = None;
+ );
Ok(Some(new_layer_id))
}
@@ -927,6 +1005,11 @@ pub fn lift_floating_selection(
if sel.floating.is_some() {
return Ok(sel.snapshot_meta());
}
+ if let Some(node) = doc.layer(layer_id) {
+ if node.meta.locked || !node.meta.layer_type.has_tiles() {
+ return Ok(sel.snapshot_meta());
+ }
+ }
let Some(clip) = copy_selection(doc, layer_id, scratch)? else {
return Ok(sel.snapshot_meta());
};
diff --git a/crates/ink-engine/src/tiles/grid.rs b/crates/ink-engine/src/tiles/grid.rs
index c343f82..e41e663 100644
--- a/crates/ink-engine/src/tiles/grid.rs
+++ b/crates/ink-engine/src/tiles/grid.rs
@@ -53,12 +53,26 @@ impl RectI32 {
#[inline]
pub const fn right(&self) -> i32 {
- self.x + self.width as i32
+ let sum = (self.x as i64) + (self.width as i64);
+ if sum > i32::MAX as i64 {
+ i32::MAX
+ } else if sum < i32::MIN as i64 {
+ i32::MIN
+ } else {
+ sum as i32
+ }
}
#[inline]
pub const fn bottom(&self) -> i32 {
- self.y + self.height as i32
+ let sum = (self.y as i64) + (self.height as i64);
+ if sum > i32::MAX as i64 {
+ i32::MAX
+ } else if sum < i32::MIN as i64 {
+ i32::MIN
+ } else {
+ sum as i32
+ }
}
#[inline]
@@ -73,7 +87,9 @@ impl RectI32 {
let y0 = self.y.min(other.y);
let x1 = self.right().max(other.right());
let y1 = self.bottom().max(other.bottom());
- Self::new(x0, y0, (x1 - x0).max(0) as u32, (y1 - y0).max(0) as u32)
+ let w = (x1 as i64 - x0 as i64).clamp(0, u32::MAX as i64) as u32;
+ let h = (y1 as i64 - y0 as i64).clamp(0, u32::MAX as i64) as u32;
+ Self::new(x0, y0, w, h)
}
#[inline]
@@ -88,7 +104,9 @@ impl RectI32 {
if x1 <= x0 || y1 <= y0 {
Self::empty()
} else {
- Self::new(x0, y0, (x1 - x0) as u32, (y1 - y0) as u32)
+ let w = (x1 as i64 - x0 as i64).clamp(0, u32::MAX as i64) as u32;
+ let h = (y1 as i64 - y0 as i64).clamp(0, u32::MAX as i64) as u32;
+ Self::new(x0, y0, w, h)
}
}
}
@@ -128,6 +146,9 @@ pub struct SparseLayerGrid {
pub dirty_lods: [HashSet<TileCoord>; 3],
/// Monotonic version counter bumped on any raster, mask, or impasto mutation.
pub layer_version: u64,
+ /// Monotonic version counter bumped ONLY when mask tiles, `has_mask`, or `mask_default_value` mutate
+ /// (NEVER bumped by raster or impasto strokes!).
+ pub mask_version: u64,
/// Per-tile remote peer mutation epoch for collaborative conflict-aware selective undo.
pub remote_epochs: HashMap<TileCoord, u64>,
}
@@ -149,6 +170,7 @@ impl SparseLayerGrid {
impasto_tiles: HashMap::new(),
dirty_lods: [HashSet::new(), HashSet::new(), HashSet::new()],
layer_version: allocate_tile_version(),
+ mask_version: allocate_tile_version(),
remote_epochs: HashMap::new(),
}
}
@@ -164,6 +186,7 @@ impl SparseLayerGrid {
impasto_tiles: self.impasto_tiles.clone(),
dirty_lods: self.dirty_lods.clone(),
layer_version: allocate_tile_version(),
+ mask_version: self.mask_version,
remote_epochs: self.remote_epochs.clone(),
}
}
@@ -173,6 +196,11 @@ impl SparseLayerGrid {
self.layer_version = allocate_tile_version();
}
+ #[inline]
+ pub fn bump_mask_version(&mut self) {
+ self.mask_version = allocate_tile_version();
+ }
+
#[inline]
pub fn mark_lod_ancestors_dirty(&mut self, coord: TileCoord) {
let mut c = coord;
@@ -336,8 +364,14 @@ impl SparseLayerGrid {
None
} else {
let mut td = TileData::from_raw_auto_compact(self.format, TileKind::Raster, raw);
- // Preserve exact GPU atlas slot version so WgpuCompositor skips redundant re-upload!
- td.version = gpu_ver;
+ // Only preserve GPU atlas slot version for full-precision color tiles;
+ // quantized Monochrome1Bit / Grayscale8Bit tiles must re-upload their quantized pixels!
+ if matches!(
+ self.format,
+ TileFormat::Color32Bit | TileFormat::Rgba16Float
+ ) {
+ td.version = gpu_ver;
+ }
let arc = Arc::new(td);
self.tiles.insert(coord, Arc::clone(&arc));
Some(arc)
@@ -375,12 +409,14 @@ impl SparseLayerGrid {
pub fn set_mask_tile(&mut self, coord: TileCoord, tile: Arc<TileData>) {
self.has_mask = true;
self.mask_tiles.insert(coord, tile);
+ self.bump_mask_version();
self.bump_version();
}
pub fn remove_mask_tile(&mut self, coord: TileCoord) -> Option<Arc<TileData>> {
let prev = self.mask_tiles.remove(&coord);
if prev.is_some() {
+ self.bump_mask_version();
self.bump_version();
}
prev
@@ -500,6 +536,7 @@ impl SparseLayerGrid {
}
if !deltas.is_empty() {
+ self.bump_mask_version();
self.bump_version();
}
(deltas, cleared_coords)
@@ -538,17 +575,20 @@ impl SparseLayerGrid {
self.has_mask = true;
self.mask_default_value = default_value;
self.mask_tiles.clear();
+ self.bump_mask_version();
self.bump_version();
}
pub fn remove_mask(&mut self) {
self.has_mask = false;
self.mask_tiles.clear();
+ self.bump_mask_version();
self.bump_version();
}
/// Fills `[0..width, 0..height]` with a uniform RGBA8 color using zero-allocation
- /// [`TileStorage::SolidColor`] tiles for full interior tiles and exact clipped tiles at edges.
+ /// [`TileStorage::SolidColor`] tiles shared via `Arc` across the entire canvas
+ /// (both GPU shaders and CPU readers clip strictly to `[0..doc_w, 0..doc_h]`).
pub fn fill_solid_layer(&mut self, width: u32, height: u32, rgba8: [u8; 4]) {
self.clear_raster();
if width == 0 || height == 0 || rgba8[3] == 0 {
@@ -556,43 +596,13 @@ impl SparseLayerGrid {
}
let max_tx = pixel_to_tile_coord(width as i32 - 1, 0);
let max_ty = pixel_to_tile_coord(height as i32 - 1, 0);
- // Share a single Arc<TileData> across EVERY full interior solid tile (O(1) memory!)
+ // Share a single Arc<TileData> across EVERY tile (0 bytes pixel RAM & 1 VRAM slot!)
let shared_solid = Arc::new(TileData::new_solid(self.format, TileKind::Raster, rgba8));
for ty in 0..=max_ty {
- let y0 = ty * TILE_SIZE_I32;
- let valid_h = ((height as i32) - y0).clamp(0, TILE_SIZE_I32) as usize;
for tx in 0..=max_tx {
- let x0 = tx * TILE_SIZE_I32;
- let valid_w = ((width as i32) - x0).clamp(0, TILE_SIZE_I32) as usize;
let coord = TileCoord::new(tx, ty);
- if valid_w == TILE_SIZE && valid_h == TILE_SIZE {
- self.tiles.insert(coord, Arc::clone(&shared_solid));
- } else {
- let mut tile_rgba = vec![0u8; BYTES_32BIT];
- for ly in 0..valid_h {
- let row_start = ly * TILE_SIZE * 4;
- for lx in 0..valid_w {
- let off = row_start + lx * 4;
- tile_rgba[off..off + 4].copy_from_slice(&rgba8);
- }
- }
- let raw = convert_tile_bytes(
- &tile_rgba,
- TileFormat::Color32Bit,
- self.format,
- 128,
- false,
- );
- self.tiles.insert(
- coord,
- Arc::new(TileData::from_raw_auto_compact(
- self.format,
- TileKind::Raster,
- raw,
- )),
- );
- }
+ self.tiles.insert(coord, Arc::clone(&shared_solid));
self.mark_lod_ancestors_dirty(coord);
}
}
@@ -979,6 +989,7 @@ impl SparseLayerGrid {
}
if !touched.is_empty() {
+ self.bump_mask_version();
self.bump_version();
}
Ok(touched)
@@ -1128,6 +1139,7 @@ impl SparseLayerGrid {
} else {
self.mask_tiles.remove(&delta.coord);
}
+ self.bump_mask_version();
}
TileKind::ImpastoHeight => {
if let Some(tile) = target {
@@ -1573,3 +1585,33 @@ fn bilinear_scale_u8(src: &[u8], old_w: u32, old_h: u32, new_w: u32, new_h: u32)
}
dst
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn rect_i32_right_and_bottom_saturate_without_overflow() {
+ let near_max = RectI32::new(i32::MAX - 5, i32::MAX - 10, 100, 200);
+ assert_eq!(near_max.right(), i32::MAX);
+ assert_eq!(near_max.bottom(), i32::MAX);
+
+ let huge_dims = RectI32::new(0, 0, u32::MAX, u32::MAX);
+ assert_eq!(huge_dims.right(), i32::MAX);
+ assert_eq!(huge_dims.bottom(), i32::MAX);
+
+ let neg_origin_huge = RectI32::new(-100, -50, u32::MAX, u32::MAX);
+ assert_eq!(neg_origin_huge.right(), i32::MAX);
+ assert_eq!(neg_origin_huge.bottom(), i32::MAX);
+
+ let normal = RectI32::new(-10, 20, 30, 40);
+ assert_eq!(normal.right(), 20);
+ assert_eq!(normal.bottom(), 60);
+
+ let u = normal.union(near_max);
+ assert_eq!(u.x, -10);
+ assert_eq!(u.y, 20);
+ assert_eq!(u.right(), i32::MAX);
+ assert_eq!(u.bottom(), i32::MAX);
+ }
+}
diff --git a/crates/ink-engine/src/tiles/tile_data.rs b/crates/ink-engine/src/tiles/tile_data.rs
index d313af6..fee5b19 100644
--- a/crates/ink-engine/src/tiles/tile_data.rs
+++ b/crates/ink-engine/src/tiles/tile_data.rs
@@ -139,6 +139,15 @@ impl TileData {
}
}
+ /// Returns the solid `Rgba16Float` half-float bit pattern if this tile is stored as `SolidColor`.
+ #[inline]
+ pub fn solid_rgba16f(&self) -> Option<[u16; 4]> {
+ match self.storage {
+ TileStorage::SolidColor { rgba16f, .. } => Some(rgba16f),
+ _ => None,
+ }
+ }
+
/// Returns true if stored in L2 LZ4-compressed RAM.
#[inline]
pub fn is_compressed_lz4(&self) -> bool {
@@ -283,8 +292,12 @@ impl TileData {
/// Demotes a `Raw` tile in-place to L2 `CompressedLz4` RAM (or `SolidColor` if uniform).
/// Returns bytes freed in CPU RAM.
pub fn demote_to_lz4(&mut self) -> usize {
+ let before_ram = self.ram_bytes();
+ if before_ram == 0 {
+ return 0;
+ }
if self.try_compact_solid() {
- return self.format.byte_size();
+ return before_ram.saturating_sub(self.ram_bytes());
}
let TileStorage::Raw(raw) = &self.storage else {
return 0;
@@ -303,6 +316,116 @@ impl TileData {
}
}
+ /// Builds a demoted L2 `CompressedLz4` (or `SolidColor`) copy of this tile WITHOUT cloning
+ /// the raw pixel buffer first, returning `(new_tile, bytes_freed)` if RAM actually shrinks.
+ pub fn to_demoted_lz4(&self) -> Option<(TileData, usize)> {
+ let before_ram = self.ram_bytes();
+ if before_ram == 0 {
+ return None;
+ }
+ let TileStorage::Raw(raw) = &self.storage else {
+ return None;
+ };
+ if self.kind == TileKind::Mask {
+ if let Some(&first) = raw.first() {
+ if raw.iter().all(|&b| b == first) {
+ let rgba8 = [first, first, first, 255];
+ return Some((
+ TileData {
+ format: self.format,
+ kind: self.kind,
+ storage: TileStorage::SolidColor {
+ rgba8,
+ rgba16f: rgba8_pixel_to_f16(rgba8),
+ },
+ version: self.version,
+ remote_epoch: self.remote_epoch,
+ last_access_seq: self.last_access_seq,
+ },
+ before_ram,
+ ));
+ }
+ }
+ } else if let Some((rgba8, rgba16f)) = detect_solid_color(self.format, raw) {
+ return Some((
+ TileData {
+ format: self.format,
+ kind: self.kind,
+ storage: TileStorage::SolidColor { rgba8, rgba16f },
+ version: self.version,
+ remote_epoch: self.remote_epoch,
+ last_access_seq: self.last_access_seq,
+ },
+ before_ram,
+ ));
+ }
+
+ let old_len = raw.len();
+ let compressed = lz4_flex::block::compress(raw);
+ if compressed.len() < old_len {
+ let freed = old_len - compressed.len();
+ Some((
+ TileData {
+ format: self.format,
+ kind: self.kind,
+ storage: TileStorage::CompressedLz4 {
+ compressed,
+ uncompressed_len: old_len as u32,
+ },
+ version: self.version,
+ remote_epoch: self.remote_epoch,
+ last_access_seq: self.last_access_seq,
+ },
+ freed,
+ ))
+ } else {
+ None
+ }
+ }
+
+ /// Builds a demoted L3 `PagedToDisk` copy of this tile WITHOUT cloning via `Arc::make_mut`,
+ /// returning `Ok(Some((new_tile, bytes_freed)))` if paged out.
+ pub fn to_demoted_disk(
+ &self,
+ session_id: &str,
+ layer_key: &str,
+ coord: TileCoord,
+ scratch: &dyn ScratchBackend,
+ ) -> Result<Option<(TileData, usize)>, String> {
+ if self.is_solid() || self.is_paged_to_disk() {
+ return Ok(None);
+ }
+ let old_ram = self.ram_bytes();
+ let raw = self.materialize_raw(Some(scratch))?;
+ let uncompressed_len = raw.len() as u32;
+ scratch.write_tiles(
+ session_id,
+ vec![crate::memory::ScratchTileWrite {
+ layer_key: layer_key.to_string(),
+ tx: coord.tx,
+ ty: coord.ty,
+ data: raw,
+ }],
+ )?;
+ Ok(Some((
+ TileData {
+ format: self.format,
+ kind: self.kind,
+ storage: TileStorage::PagedToDisk {
+ session_id: session_id.to_string(),
+ layer_key: layer_key.to_string(),
+ tx: coord.tx,
+ ty: coord.ty,
+ uncompressed_len,
+ },
+ version: self.version,
+ remote_epoch: self.remote_epoch,
+ last_access_seq: self.last_access_seq,
+ },
+ old_ram,
+ )))
+ }
+
/// Demotes a `Raw` or `CompressedLz4` tile to L3 `PagedToDisk` via `scratch`.
/// Returns bytes freed in CPU RAM.
pub fn demote_to_disk(
@@ -366,6 +489,141 @@ impl TileData {
))
}
+ /// Writes this tile's 524,288-byte `Rgba16Float` pixel payload into `out_16f` reusing
+ /// caller-owned scratch buffers (zero 512 KB heap allocation per uploaded tile!).
+ pub fn write_rgba16f_into(
+ &self,
+ scratch: Option<&dyn ScratchBackend>,
+ out_16f: &mut Vec<u8>,
+ tmp_rgba8: &mut Vec<u8>,
+ ) -> Result<(), String> {
+ out_16f.resize(BYTES_16F, 0);
+ if let TileStorage::SolidColor { rgba16f, .. } = self.storage {
+ let mut px = [0u8; 8];
+ px[0..2].copy_from_slice(&rgba16f[0].to_le_bytes());
+ px[2..4].copy_from_slice(&rgba16f[1].to_le_bytes());
+ px[4..6].copy_from_slice(&rgba16f[2].to_le_bytes());
+ px[6..8].copy_from_slice(&rgba16f[3].to_le_bytes());
+ for chunk in out_16f.chunks_exact_mut(8) {
+ chunk.copy_from_slice(&px);
+ }
+ return Ok(());
+ }
+
+ let owned_raw: Vec<u8>;
+ let raw: &[u8] = match &self.storage {
+ TileStorage::Raw(v) => v.as_slice(),
+ _ => {
+ owned_raw = self.materialize_raw(scratch)?;
+ &owned_raw
+ }
+ };
+
+ if self.kind == TileKind::Mask {
+ tmp_rgba8.resize(BYTES_32BIT, 0);
+ unpack_mask8_to_rgba8(raw, tmp_rgba8);
+ super::format::rgba8_to_rgba16f(tmp_rgba8, out_16f);
+ return Ok(());
+ }
+
+ match self.format {
+ TileFormat::Rgba16Float => {
+ out_16f.copy_from_slice(raw);
+ }
+ TileFormat::Color32Bit => {
+ super::format::rgba8_to_rgba16f(raw, out_16f);
+ }
+ TileFormat::Monochrome1Bit => {
+ tmp_rgba8.resize(BYTES_32BIT, 0);
+ super::format::unpack_1bit_to_rgba8(
+ raw,
+ tmp_rgba8,
+ [0, 0, 0, 255],
+ [0, 0, 0, 0],
+ );
+ super::format::rgba8_to_rgba16f(tmp_rgba8, out_16f);
+ }
+ TileFormat::Grayscale8Bit => {
+ tmp_rgba8.resize(BYTES_32BIT, 0);
+ super::format::unpack_8bit_to_rgba8(raw, tmp_rgba8);
+ super::format::rgba8_to_rgba16f(tmp_rgba8, out_16f);
+ }
+ TileFormat::Height16Float => {
+ let converted = convert_tile_bytes(
+ raw,
+ self.format,
+ TileFormat::Rgba16Float,
+ 128,
+ false,
+ );
+ out_16f.copy_from_slice(&converted);
+ }
+ }
+ Ok(())
+ }
+
+ /// Writes this tile's 65,536-byte `R8Unorm` mask payload into `out_mask8` reusing `out_mask8`.
+ pub fn write_mask8_into(
+ &self,
+ scratch: Option<&dyn ScratchBackend>,
+ out_mask8: &mut Vec<u8>,
+ ) -> Result<(), String> {
+ let len = self.format.byte_size();
+ out_mask8.resize(len, 0);
+ match &self.storage {
+ TileStorage::SolidColor { rgba8, .. } => {
+ out_mask8.fill(rgba8[0]);
+ Ok(())
+ }
+ TileStorage::Raw(v) => {
+ out_mask8.copy_from_slice(v);
+ Ok(())
+ }
+ _ => {
+ let raw = self.materialize_raw(scratch)?;
+ out_mask8.copy_from_slice(&raw);
+ Ok(())
+ }
+ }
+ }
+
+ /// Writes this tile's 131,072-byte `R16Float` impasto height payload into `out_r16f`.
+ pub fn write_r16f_into(
+ &self,
+ scratch: Option<&dyn ScratchBackend>,
+ out_r16f: &mut Vec<u8>,
+ ) -> Result<(), String> {
+ out_r16f.resize(super::BYTES_R16F, 0);
+ if let TileStorage::SolidColor { rgba16f, .. } = self.storage {
+ let px = rgba16f[0].to_le_bytes();
+ for chunk in out_r16f.chunks_exact_mut(2) {
+ chunk.copy_from_slice(&px);
+ }
+ return Ok(());
+ }
+ let owned_raw: Vec<u8>;
+ let raw: &[u8] = match &self.storage {
+ TileStorage::Raw(v) => v.as_slice(),
+ _ => {
+ owned_raw = self.materialize_raw(scratch)?;
+ &owned_raw
+ }
+ };
+ if self.format == TileFormat::Height16Float {
+ out_r16f.copy_from_slice(raw);
+ return Ok(());
+ }
+ let converted = convert_tile_bytes(
+ raw,
+ self.format,
+ TileFormat::Height16Float,
+ 128,
+ false,
+ );
+ out_r16f.copy_from_slice(&converted);
+ Ok(())
+ }
+
/// Materializes this tile as 524,288-byte `Rgba16Float` for lossless GPU atlas upload.
pub fn to_rgba16f(&self, scratch: Option<&dyn ScratchBackend>) -> Result<Vec<u8>, String> {
if let TileStorage::SolidColor { rgba16f, .. } = self.storage {
diff --git a/crates/ink-engine/src/tools/fill.rs b/crates/ink-engine/src/tools/fill.rs
index 5fa99a1..e7ec5cc 100644
--- a/crates/ink-engine/src/tools/fill.rs
+++ b/crates/ink-engine/src/tools/fill.rs
@@ -536,7 +536,17 @@ fn commit_fill_coverage_mask(
) -> Result<FillOutcome, String> {
let w = work_rect.width as usize;
let h = work_rect.height as usize;
- let op = (opacity.clamp(0.0, 1.0) * (fill_rgba[3] as f32 / 255.0)).clamp(0.0, 1.0);
+ let is_erase = fill_rgba[3] == 0;
+ let op = if is_erase {
+ let clamped = opacity.clamp(0.0, 1.0);
+ if clamped <= 0.0005 {
+ 1.0
+ } else {
+ clamped
+ }
+ } else {
+ (opacity.clamp(0.0, 1.0) * (fill_rgba[3] as f32 / 255.0)).clamp(0.0, 1.0)
+ };
if op <= 0.0005 || w == 0 || h == 0 {
return Ok(FillOutcome {
modified: false,
@@ -602,6 +612,14 @@ fn commit_fill_coverage_mask(
l.meta.mono_threshold.unwrap_or(128),
)
};
+ if is_erase && alpha_locked {
+ return Ok(FillOutcome {
+ modified: false,
+ layer_id: layer_id.to_string(),
+ dirty_rect: RectI32::empty(),
+ filled_pixels: 0,
+ });
+ }
let tw = tight_rect.width as usize;
let mut dst_rgba = {
@@ -633,7 +651,20 @@ fn commit_fill_coverage_mask(
let sa = (cov as f32 / 255.0) * op;
let o = tx * 4;
let da = row[o + 3] as f32 / 255.0;
- if alpha_locked {
+ if is_erase {
+ if alpha_locked || da <= 1e-5 {
+ continue;
+ }
+ let out_a = (da * (1.0 - sa)).clamp(0.0, 1.0);
+ if out_a <= 1e-5 {
+ row[o] = 0;
+ row[o + 1] = 0;
+ row[o + 2] = 0;
+ row[o + 3] = 0;
+ } else {
+ row[o + 3] = (out_a * 255.0).round().clamp(0.0, 255.0) as u8;
+ }
+ } else if alpha_locked {
if da <= 0.001 {
continue;
}
@@ -1456,24 +1487,55 @@ fn sample_layer_pixel(
let ly = (y - coord.ty * TILE_SIZE_I32) as usize;
let mut px = match &tile.storage {
crate::tiles::TileStorage::SolidColor { rgba8, .. } => *rgba8,
- crate::tiles::TileStorage::Raw(buf) => {
- if tile.format == crate::tiles::TileFormat::Monochrome1Bit {
+ crate::tiles::TileStorage::Raw(buf) => match tile.format {
+ crate::tiles::TileFormat::Monochrome1Bit => {
let bit = ly * TILE_SIZE + lx;
- let on = (buf[bit >> 3] & (1 << (bit & 7))) != 0;
+ let byte_idx = bit >> 3;
+ let on = byte_idx < buf.len() && (buf[byte_idx] & (0x80 >> (bit & 7))) != 0;
if on {
[0, 0, 0, 255]
} else {
[0, 0, 0, 0]
}
- } else {
+ }
+ crate::tiles::TileFormat::Grayscale8Bit => {
+ let off = ly * TILE_SIZE + lx;
+ let v = buf.get(off).copied().unwrap_or(0);
+ if v == 0 {
+ [0, 0, 0, 0]
+ } else {
+ [v, v, v, 255]
+ }
+ }
+ crate::tiles::TileFormat::Color32Bit => {
let off = (ly * TILE_SIZE + lx) * 4;
- [buf[off], buf[off + 1], buf[off + 2], buf[off + 3]]
+ if off + 3 < buf.len() {
+ [buf[off], buf[off + 1], buf[off + 2], buf[off + 3]]
+ } else {
+ [0, 0, 0, 0]
+ }
}
- }
+ _ => {
+ if let Ok(rgba) = tile.to_rgba8(scratch, false) {
+ let off = (ly * TILE_SIZE + lx) * 4;
+ if off + 3 < rgba.len() {
+ [rgba[off], rgba[off + 1], rgba[off + 2], rgba[off + 3]]
+ } else {
+ [0, 0, 0, 0]
+ }
+ } else {
+ [0, 0, 0, 0]
+ }
+ }
+ },
_ => {
if let Ok(rgba) = tile.to_rgba8(scratch, false) {
let off = (ly * TILE_SIZE + lx) * 4;
- [rgba[off], rgba[off + 1], rgba[off + 2], rgba[off + 3]]
+ if off + 3 < rgba.len() {
+ [rgba[off], rgba[off + 1], rgba[off + 2], rgba[off + 3]]
+ } else {
+ [0, 0, 0, 0]
+ }
} else {
[0, 0, 0, 0]
}
@@ -1505,6 +1567,18 @@ pub fn pick_color_document(
y: i32,
sample_all_layers: bool,
scratch: Option<&dyn ScratchBackend>,
+) -> PickedColorDto {
+ pick_color_document_for_layer(doc, x, y, sample_all_layers, None, scratch)
+}
+
+/// Like [`pick_color_document`], honoring an explicit `layer_id` when `sample_all_layers` is `false`.
+pub fn pick_color_document_for_layer(
+ doc: &Document,
+ x: i32,
+ y: i32,
+ sample_all_layers: bool,
+ layer_id: Option<&str>,
+ scratch: Option<&dyn ScratchBackend>,
) -> PickedColorDto {
let px = if x < 0
|| y < 0
@@ -1513,7 +1587,10 @@ pub fn pick_color_document(
{
[0, 0, 0, 0]
} else if !sample_all_layers {
- doc.active_layer()
+ let target = layer_id
+ .and_then(|lid| doc.layer(lid))
+ .or_else(|| doc.active_layer());
+ target
.map(|l| sample_layer_pixel(l, x, y, scratch))
.unwrap_or([0, 0, 0, 0])
} else {
diff --git a/crates/ink-engine/src/tools/filters.rs b/crates/ink-engine/src/tools/filters.rs
index a8a7712..384fb48 100644
--- a/crates/ink-engine/src/tools/filters.rs
+++ b/crates/ink-engine/src/tools/filters.rs
@@ -18,7 +18,7 @@ use serde::{Deserialize, Serialize};
use std::sync::Arc;
#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(tag = "kind", rename_all = "kebab-case")]
+#[serde(tag = "kind", rename_all = "kebab-case", rename_all_fields = "camelCase")]
pub enum FilterSpec {
GaussianBlur {
radius: f32,
@@ -58,7 +58,7 @@ pub struct GradientMapStop {
}
#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(tag = "kind", rename_all = "kebab-case")]
+#[serde(tag = "kind", rename_all = "kebab-case", rename_all_fields = "camelCase")]
pub enum TonalSpec {
BrightnessContrast {
brightness: f32, // -100..100
@@ -638,9 +638,9 @@ pub fn apply_tonal_rgba8(src: &[u8], w: usize, h: usize, spec: &TonalSpec) -> Ve
let lut_b = build_curve_lut(b);
out.par_chunks_mut(4).for_each(|px| {
if px[3] > 0 {
- px[0] = lut_r[lut_rgb[px[0] as usize] as usize];
- px[1] = lut_g[lut_rgb[px[1] as usize] as usize];
- px[2] = lut_b[lut_rgb[px[2] as usize] as usize];
+ px[0] = lut_rgb[lut_r[px[0] as usize] as usize];
+ px[1] = lut_rgb[lut_g[px[1] as usize] as usize];
+ px[2] = lut_rgb[lut_b[px[2] as usize] as usize];
}
});
}
diff --git a/crates/ink-engine/src/tools/gradient.rs b/crates/ink-engine/src/tools/gradient.rs
index 8bd0bf3..0d7da27 100644
--- a/crates/ink-engine/src/tools/gradient.rs
+++ b/crates/ink-engine/src/tools/gradient.rs
@@ -283,6 +283,21 @@ pub fn render_gradient_rgba8(params: &GradientParams, rect: RectI32) -> Vec<u8>
})
.collect();
let stride = cols + 1;
+ let expected_nodes = stride * (rows + 1);
+ let mut has_deformed_uv = false;
+ if parsed_nodes.len() == expected_nodes {
+ 'uv_check: for r in 0..=rows {
+ let ev = r as f32 / rows as f32;
+ for c in 0..=cols {
+ let eu = c as f32 / cols as f32;
+ let n = &parsed_nodes[r * stride + c];
+ if (n.0 - eu).abs() > 1e-3 || (n.1 - ev).abs() > 1e-3 {
+ has_deformed_uv = true;
+ break 'uv_check;
+ }
+ }
+ }
+ }
let cx = mesh.x + mesh.width * 0.5;
let cy = mesh.y + mesh.height * 0.5;
let c_rot = (-mesh.rotation).cos();
@@ -290,6 +305,42 @@ pub fn render_gradient_rgba8(params: &GradientParams, rect: RectI32) -> Vec<u8>
let inv_w = 1.0 / mesh.width.max(1.0);
let inv_h = 1.0 / mesh.height.max(1.0);
+ let eval_tri = |px: f32,
+ py: f32,
+ a: (f32, f32, [f32; 4]),
+ b: (f32, f32, [f32; 4]),
+ c: (f32, f32, [f32; 4])|
+ -> Option<[f32; 4]> {
+ let v0x = b.0 - a.0;
+ let v0y = b.1 - a.1;
+ let v1x = c.0 - a.0;
+ let v1y = c.1 - a.1;
+ let det = v0x * v1y - v1x * v0y;
+ if det.abs() < 1e-7 {
+ return None;
+ }
+ let inv_det = 1.0 / det;
+ let vx = px - a.0;
+ let vy = py - a.1;
+ let w1 = (vx * v1y - v1x * vy) * inv_det;
+ let w2 = (v0x * vy - vx * v0y) * inv_det;
+ let w0 = 1.0 - w1 - w2;
+ if w0 >= -1e-4 && w1 >= -1e-4 && w2 >= -1e-4 {
+ let s0 = w0.clamp(0.0, 1.0);
+ let s1 = w1.clamp(0.0, 1.0);
+ let s2 = w2.clamp(0.0, 1.0);
+ let sum = (s0 + s1 + s2).max(1e-6);
+ let (f0, f1, f2) = (s0 / sum, s1 / sum, s2 / sum);
+ return Some([
+ a.2[0] * f0 + b.2[0] * f1 + c.2[0] * f2,
+ a.2[1] * f0 + b.2[1] * f1 + c.2[1] * f2,
+ a.2[2] * f0 + b.2[2] * f1 + c.2[2] * f2,
+ a.2[3] * f0 + b.2[3] * f1 + c.2[3] * f2,
+ ]);
+ }
+ None
+ };
+
out.par_chunks_mut(w * 4)
.enumerate()
.for_each(|(ry, row)| {
@@ -303,42 +354,79 @@ pub fn render_gradient_rgba8(params: &GradientParams, rect: RectI32) -> Vec<u8>
let u = (lx * inv_w + 0.5).clamp(0.0, 1.0);
let v = (ly * inv_h + 0.5).clamp(0.0, 1.0);
- let col_f = (u * cols as f32).min(cols as f32 - 1e-5);
- let row_f = (v * rows as f32).min(rows as f32 - 1e-5);
- let ci = col_f.floor() as usize;
- let ri = row_f.floor() as usize;
- let fu = smooth_hermite(col_f - ci as f32);
- let fv = smooth_hermite(row_f - ri as f32);
-
- let get_c = |c: usize, r: usize| -> [f32; 4] {
- parsed_nodes
- .get(r * stride + c)
- .map(|n| n.2)
- .unwrap_or([0.0, 0.0, 0.0, 1.0])
+ let mut col = if has_deformed_uv && parsed_nodes.len() == expected_nodes {
+ let mut hit: Option<[f32; 4]> = None;
+ 'quad_loop: for r in 0..rows {
+ for c in 0..cols {
+ let p00 = parsed_nodes[r * stride + c];
+ let p10 = parsed_nodes[r * stride + c + 1];
+ let p01 = parsed_nodes[(r + 1) * stride + c];
+ let p11 = parsed_nodes[(r + 1) * stride + c + 1];
+ if let Some(res) = eval_tri(u, v, p00, p10, p11)
+ .or_else(|| eval_tri(u, v, p00, p11, p01))
+ {
+ hit = Some(res);
+ break 'quad_loop;
+ }
+ }
+ }
+ let mut c = hit.unwrap_or_else(|| {
+ let mut acc = [0.0f32; 4];
+ let mut wsum = 0.0f32;
+ for &(nu, nv, nc) in &parsed_nodes {
+ let du = u - nu;
+ let dv = v - nv;
+ let d2 = du * du + dv * dv;
+ let wt = 1.0 / (d2 * d2 + 1e-6);
+ acc[0] += nc[0] * wt;
+ acc[1] += nc[1] * wt;
+ acc[2] += nc[2] * wt;
+ acc[3] += nc[3] * wt;
+ wsum += wt;
+ }
+ let inv = 1.0 / wsum.max(1e-6);
+ [acc[0] * inv, acc[1] * inv, acc[2] * inv, acc[3] * inv]
+ });
+ c[3] *= op;
+ c
+ } else {
+ let col_f = (u * cols as f32).min(cols as f32 - 1e-5);
+ let row_f = (v * rows as f32).min(rows as f32 - 1e-5);
+ let ci = col_f.floor() as usize;
+ let ri = row_f.floor() as usize;
+ let fu = smooth_hermite(col_f - ci as f32);
+ let fv = smooth_hermite(row_f - ri as f32);
+
+ let get_c = |c: usize, r: usize| -> [f32; 4] {
+ parsed_nodes
+ .get(r * stride + c)
+ .map(|n| n.2)
+ .unwrap_or([0.0, 0.0, 0.0, 1.0])
+ };
+ let c00 = get_c(ci, ri);
+ let c10 = get_c((ci + 1).min(cols), ri);
+ let c01 = get_c(ci, (ri + 1).min(rows));
+ let c11 = get_c((ci + 1).min(cols), (ri + 1).min(rows));
+
+ let top = [
+ c00[0] + (c10[0] - c00[0]) * fu,
+ c00[1] + (c10[1] - c00[1]) * fu,
+ c00[2] + (c10[2] - c00[2]) * fu,
+ c00[3] + (c10[3] - c00[3]) * fu,
+ ];
+ let bot = [
+ c01[0] + (c11[0] - c01[0]) * fu,
+ c01[1] + (c11[1] - c01[1]) * fu,
+ c01[2] + (c11[2] - c01[2]) * fu,
+ c01[3] + (c11[3] - c01[3]) * fu,
+ ];
+ [
+ top[0] + (bot[0] - top[0]) * fv,
+ top[1] + (bot[1] - top[1]) * fv,
+ top[2] + (bot[2] - top[2]) * fv,
+ (top[3] + (bot[3] - top[3]) * fv) * op,
+ ]
};
- let c00 = get_c(ci, ri);
- let c10 = get_c((ci + 1).min(cols), ri);
- let c01 = get_c(ci, (ri + 1).min(rows));
- let c11 = get_c((ci + 1).min(cols), (ri + 1).min(rows));
-
- let top = [
- c00[0] + (c10[0] - c00[0]) * fu,
- c00[1] + (c10[1] - c00[1]) * fu,
- c00[2] + (c10[2] - c00[2]) * fu,
- c00[3] + (c10[3] - c00[3]) * fu,
- ];
- let bot = [
- c01[0] + (c11[0] - c01[0]) * fu,
- c01[1] + (c11[1] - c01[1]) * fu,
- c01[2] + (c11[2] - c01[2]) * fu,
- c01[3] + (c11[3] - c01[3]) * fu,
- ];
- let mut col = [
- top[0] + (bot[0] - top[0]) * fv,
- top[1] + (bot[1] - top[1]) * fv,
- top[2] + (bot[2] - top[2]) * fv,
- (top[3] + (bot[3] - top[3]) * fv) * op,
- ];
if dither {
let b = BAYER_4X4[(ry & 3) * 4 + (rx & 3)] / 255.0;
col[0] += b;
diff --git a/crates/ink-engine/src/tools/liquify.rs b/crates/ink-engine/src/tools/liquify.rs
index f60d2c6..dbc462c 100644
--- a/crates/ink-engine/src/tools/liquify.rs
+++ b/crates/ink-engine/src/tools/liquify.rs
@@ -19,9 +19,11 @@ use bytemuck::{Pod, Zeroable};
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
+use std::num::NonZeroU64;
use std::sync::Arc;
const MAX_LIQUIFY_LOOKUP: usize = 512;
+const LIQUIFY_UNIFORM_STRIDE: u64 = 256;
/// All 8 InkStudio Liquify brush modes matching `src/types/editor.ts`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
@@ -476,31 +478,31 @@ impl LayerWarpState {
.min(device.limits().max_texture_array_layers.max(self.warped_cap));
if new_cap > self.warped_cap {
let (new_tex, new_view) = Self::alloc_rgba16f_array(device, new_cap);
- let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-liquify-warped-grow"),
- });
- for slot in 0..self.next_slot {
+ if self.next_slot > 0 {
+ let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-liquify-warped-grow"),
+ });
enc.copy_texture_to_texture(
wgpu::TexelCopyTextureInfo {
texture: &self.warped_tex,
mip_level: 0,
- origin: wgpu::Origin3d { x: 0, y: 0, z: slot },
+ origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
wgpu::TexelCopyTextureInfo {
texture: &new_tex,
mip_level: 0,
- origin: wgpu::Origin3d { x: 0, y: 0, z: slot },
+ origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
wgpu::Extent3d {
width: TILE_SIZE as u32,
height: TILE_SIZE as u32,
- depth_or_array_layers: 1,
+ depth_or_array_layers: self.next_slot,
},
);
+ queue.submit(Some(enc.finish()));
}
- queue.submit(Some(enc.finish()));
self.warped_tex = new_tex;
self.warped_view = new_view;
self.warped_cap = new_cap;
@@ -520,6 +522,7 @@ pub struct GpuLiquifyEngine {
disp_bgl: wgpu::BindGroupLayout,
disp_pipe: wgpu::RenderPipeline,
disp_uniform_buf: wgpu::Buffer,
+ disp_uniform_cap: usize,
disp_scratch_tex: wgpu::Texture,
disp_scratch_view: wgpu::TextureView,
_dummy_sel_tex: wgpu::Texture,
@@ -528,6 +531,7 @@ pub struct GpuLiquifyEngine {
warp_bgl: wgpu::BindGroupLayout,
warp_pipe: wgpu::ComputePipeline,
warp_uniform_buf: wgpu::Buffer,
+ warp_uniform_cap: usize,
lookup_buf: wgpu::Buffer,
warp_scratch_tex: wgpu::Texture,
warp_scratch_view: wgpu::TextureView,
@@ -562,8 +566,10 @@ impl GpuLiquifyEngine {
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
- has_dynamic_offset: false,
- min_binding_size: None,
+ has_dynamic_offset: true,
+ min_binding_size: NonZeroU64::new(
+ std::mem::size_of::<DisplaceUniforms>() as u64,
+ ),
},
count: None,
},
@@ -623,9 +629,10 @@ impl GpuLiquifyEngine {
multiview_mask: None,
cache: None,
});
+ let disp_uniform_cap = 64usize;
let disp_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("ink-liquify-disp-uniforms"),
- size: std::mem::size_of::<DisplaceUniforms>() as u64,
+ label: Some("ink-liquify-disp-uniforms-dyn"),
+ size: disp_uniform_cap as u64 * LIQUIFY_UNIFORM_STRIDE,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
@@ -675,8 +682,10 @@ impl GpuLiquifyEngine {
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
- has_dynamic_offset: false,
- min_binding_size: None,
+ has_dynamic_offset: true,
+ min_binding_size: NonZeroU64::new(
+ std::mem::size_of::<WarpUniforms>() as u64,
+ ),
},
count: None,
},
@@ -749,9 +758,10 @@ impl GpuLiquifyEngine {
compilation_options: Default::default(),
cache: None,
});
+ let warp_uniform_cap = 64usize;
let warp_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("ink-liquify-warp-uniforms"),
- size: std::mem::size_of::<WarpUniforms>() as u64,
+ label: Some("ink-liquify-warp-uniforms-dyn"),
+ size: warp_uniform_cap as u64 * LIQUIFY_UNIFORM_STRIDE,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
@@ -800,6 +810,7 @@ impl GpuLiquifyEngine {
disp_bgl,
disp_pipe,
disp_uniform_buf,
+ disp_uniform_cap,
disp_scratch_tex,
disp_scratch_view,
_dummy_sel_tex: dummy_sel_tex,
@@ -807,6 +818,7 @@ impl GpuLiquifyEngine {
warp_bgl,
warp_pipe,
warp_uniform_buf,
+ warp_uniform_cap,
lookup_buf,
warp_scratch_tex,
warp_scratch_view,
@@ -894,31 +906,31 @@ impl GpuLiquifyEngine {
.min(device.limits().max_texture_array_layers.max(self.disp_atlas_cap));
if new_cap > self.disp_atlas_cap {
let (new_tex, new_view) = Self::alloc_disp_atlas(device, new_cap);
- let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-liquify-disp-grow"),
- });
- for slot in 0..self.disp_next_slot {
+ if self.disp_next_slot > 0 {
+ let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-liquify-disp-grow"),
+ });
enc.copy_texture_to_texture(
wgpu::TexelCopyTextureInfo {
texture: &self.disp_atlas_tex,
mip_level: 0,
- origin: wgpu::Origin3d { x: 0, y: 0, z: slot },
+ origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
wgpu::TexelCopyTextureInfo {
texture: &new_tex,
mip_level: 0,
- origin: wgpu::Origin3d { x: 0, y: 0, z: slot },
+ origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
wgpu::Extent3d {
width: TILE_SIZE as u32,
height: TILE_SIZE as u32,
- depth_or_array_layers: 1,
+ depth_or_array_layers: self.disp_next_slot,
},
);
+ queue.submit(Some(enc.finish()));
}
- queue.submit(Some(enc.finish()));
self.disp_atlas_tex = new_tex;
self.disp_atlas_view = new_view;
self.disp_atlas_cap = new_cap;
@@ -1052,12 +1064,25 @@ impl GpuLiquifyEngine {
}
}
- // 1. Update sparse RG16Float displacement tiles on GPU
+ // 1. Pre-allocate all displacement slots & pack ALL DisplaceUniforms into dynamic buffer
+ let mut disp_jobs: Vec<(TileCoord, u32)> = Vec::with_capacity(touched_coords.len());
for &coord in &touched_coords {
let slot = self.get_or_alloc_disp_slot(device, queue, coord);
- let sel_view = active_sel
- .map(|s| s.atlas_view())
- .unwrap_or(&self.dummy_sel_view);
+ disp_jobs.push((coord, slot));
+ }
+
+ if disp_jobs.len() > self.disp_uniform_cap {
+ self.disp_uniform_cap = disp_jobs.len().next_power_of_two().max(64);
+ self.disp_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-liquify-disp-uniforms-dyn"),
+ size: self.disp_uniform_cap as u64 * LIQUIFY_UNIFORM_STRIDE,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ }
+ let stride = LIQUIFY_UNIFORM_STRIDE as usize;
+ let mut disp_bytes = vec![0u8; disp_jobs.len() * stride];
+ for (i, &(coord, slot)) in disp_jobs.iter().enumerate() {
let sel_slot_f = match active_sel {
Some(s) => s.tile_slot(&coord).map(|v| v as f32).unwrap_or(-1.0),
None => -2.0,
@@ -1083,96 +1108,124 @@ impl GpuLiquifyEngine {
self.doc_height as f32,
],
};
- queue.write_buffer(&self.disp_uniform_buf, 0, bytemuck::bytes_of(&u));
-
- let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-liquify-disp-bg"),
- layout: &self.disp_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: self.disp_uniform_buf.as_entire_binding(),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(&self.disp_atlas_view),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::TextureView(sel_view),
- },
- ],
- });
- let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-liquify-disp-enc"),
- });
- {
- let mut rp = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
- label: Some("ink-liquify-disp-pass"),
- color_attachments: &[Some(wgpu::RenderPassColorAttachment {
- view: &self.disp_scratch_view,
- depth_slice: None,
- resolve_target: None,
- ops: wgpu::Operations {
- load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
- store: wgpu::StoreOp::Store,
- },
- })],
- depth_stencil_attachment: None,
- timestamp_writes: None,
- occlusion_query_set: None,
- multiview_mask: None,
- });
- rp.set_pipeline(&self.disp_pipe);
- rp.set_bind_group(0, &bg, &[]);
- rp.draw(0..3, 0..1);
- }
- enc.copy_texture_to_texture(
- wgpu::TexelCopyTextureInfo {
- texture: &self.disp_scratch_tex,
- mip_level: 0,
- origin: wgpu::Origin3d::ZERO,
- aspect: wgpu::TextureAspect::All,
+ let src = bytemuck::bytes_of(&u);
+ disp_bytes[i * stride..i * stride + src.len()].copy_from_slice(src);
+ }
+ queue.write_buffer(&self.disp_uniform_buf, 0, &disp_bytes);
+
+ let sel_view = active_sel
+ .map(|s| s.atlas_view())
+ .unwrap_or(&self.dummy_sel_view);
+ let disp_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-liquify-disp-bg"),
+ layout: &self.disp_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.disp_uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(std::mem::size_of::<DisplaceUniforms>() as u64),
+ }),
},
- wgpu::TexelCopyTextureInfo {
- texture: &self.disp_atlas_tex,
- mip_level: 0,
- origin: wgpu::Origin3d {
- x: 0,
- y: 0,
- z: slot,
- },
- aspect: wgpu::TextureAspect::All,
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(&self.disp_atlas_view),
},
- wgpu::Extent3d {
- width: TILE_SIZE as u32,
- height: TILE_SIZE as u32,
- depth_or_array_layers: 1,
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(sel_view),
},
- );
- queue.submit(Some(enc.finish()));
+ ],
+ });
+
+ // 2. Encode ALL displacement updates + Layer 0 warp passes into ONE CommandEncoder + ONE queue.submit!
+ // (Additional layers in multi-layer sessions each batch ALL their tiles into 1 submit.)
+ if touched_coords.len() > self.warp_uniform_cap {
+ self.warp_uniform_cap = touched_coords.len().next_power_of_two().max(64);
+ self.warp_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-liquify-warp-uniforms-dyn"),
+ size: self.warp_uniform_cap as u64 * LIQUIFY_UNIFORM_STRIDE,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
}
- // 2. Re-warp touched tiles for every active target layer on GPU (zero CPU readback!)
let doc_id = self.doc_id.clone();
let doc_w = self.doc_width;
let doc_h = self.doc_height;
+ let mut disp_encoded = false;
+
+ let encode_disp_passes = |enc: &mut wgpu::CommandEncoder| {
+ for (i, &(_, slot)) in disp_jobs.iter().enumerate() {
+ let dyn_off = (i as u32) * (LIQUIFY_UNIFORM_STRIDE as u32);
+ {
+ let mut rp = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("ink-liquify-disp-pass"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &self.disp_scratch_view,
+ depth_slice: None,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ multiview_mask: None,
+ });
+ rp.set_pipeline(&self.disp_pipe);
+ rp.set_bind_group(0, &disp_bg, &[dyn_off]);
+ rp.draw(0..3, 0..1);
+ }
+ enc.copy_texture_to_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: &self.disp_scratch_tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::TexelCopyTextureInfo {
+ texture: &self.disp_atlas_tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d {
+ x: 0,
+ y: 0,
+ z: slot,
+ },
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::Extent3d {
+ width: TILE_SIZE as u32,
+ height: TILE_SIZE as u32,
+ depth_or_array_layers: 1,
+ },
+ );
+ }
+ };
+
for ls in &mut self.layers {
let Some(layer_node) = doc.layer(&ls.layer_id) else {
continue;
};
- // Ensure all tiles of this layer are resident in GpuTilePool and build compact lookup table
let mut lookup: Vec<TileLookupEntry> =
Vec::with_capacity(layer_node.grid.tiles.len().min(MAX_LIQUIFY_LOOKUP));
+ let mut pinned_base_slots: Vec<u32> = Vec::with_capacity(lookup.capacity());
+ let doc_key = tile_pool.intern_doc(&doc_id);
+ let layer_key = tile_pool.intern_layer(&ls.layer_id);
for (&c, tile_arc) in layer_node.grid.tiles.iter().take(MAX_LIQUIFY_LOOKUP) {
let key = GpuTileKey {
- doc_id: doc_id.clone(),
- layer_id: ls.layer_id.clone(),
+ doc_id: doc_key,
+ layer_id: layer_key,
lod: 0,
coord: c,
};
if let Ok(base_slot) = tile_pool.ensure_tile_uploaded(queue, key, tile_arc, scratch)
{
+ tile_pool.pin_slot(base_slot);
+ pinned_base_slots.push(base_slot);
lookup.push(TileLookupEntry {
tx: c.tx,
ty: c.ty,
@@ -1185,11 +1238,14 @@ impl GpuLiquifyEngine {
queue.write_buffer(&self.lookup_buf, 0, bytemuck::cast_slice(&lookup));
}
- for &coord in &touched_coords {
+ let mut warp_dst_slots: Vec<u32> = Vec::with_capacity(touched_coords.len());
+ let mut warp_bytes = vec![0u8; touched_coords.len() * stride];
+ for (i, &coord) in touched_coords.iter().enumerate() {
ls.before_tiles
.entry(coord)
.or_insert_with(|| layer_node.grid.tiles.get(&coord).cloned());
let dst_slot = ls.get_or_alloc(device, queue, coord);
+ warp_dst_slots.push(dst_slot);
let disp_slot = self
.disp_coord_to_slot
.get(&coord)
@@ -1204,48 +1260,62 @@ impl GpuLiquifyEngine {
],
doc_out: [doc_w as f32, doc_h as f32, 0.0, 0.0],
};
- queue.write_buffer(&self.warp_uniform_buf, 0, bytemuck::bytes_of(&wu));
-
- let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-liquify-warp-bg"),
- layout: &self.warp_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: self.warp_uniform_buf.as_entire_binding(),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(tile_pool.atlas_view()),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::TextureView(&self.disp_atlas_view),
- },
- wgpu::BindGroupEntry {
- binding: 3,
- resource: self.lookup_buf.as_entire_binding(),
- },
- wgpu::BindGroupEntry {
- binding: 4,
- resource: wgpu::BindingResource::TextureView(&self.warp_scratch_view),
- },
- wgpu::BindGroupEntry {
- binding: 5,
- resource: self.readback_storage_buf.as_entire_binding(),
- },
- ],
- });
- let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-liquify-warp-enc"),
- });
+ let src = bytemuck::bytes_of(&wu);
+ warp_bytes[i * stride..i * stride + src.len()].copy_from_slice(src);
+ }
+ queue.write_buffer(&self.warp_uniform_buf, 0, &warp_bytes);
+
+ let warp_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-liquify-warp-bg"),
+ layout: &self.warp_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.warp_uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(std::mem::size_of::<WarpUniforms>() as u64),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(tile_pool.atlas_view()),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(&self.disp_atlas_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: self.lookup_buf.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 4,
+ resource: wgpu::BindingResource::TextureView(&self.warp_scratch_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 5,
+ resource: self.readback_storage_buf.as_entire_binding(),
+ },
+ ],
+ });
+
+ let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-liquify-step-batch-enc"),
+ });
+ if !disp_encoded {
+ encode_disp_passes(&mut enc);
+ disp_encoded = true;
+ }
+ for (i, &dst_slot) in warp_dst_slots.iter().enumerate() {
+ let dyn_off = (i as u32) * (LIQUIFY_UNIFORM_STRIDE as u32);
{
let mut cp = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("ink-liquify-warp-pass"),
timestamp_writes: None,
});
cp.set_pipeline(&self.warp_pipe);
- cp.set_bind_group(0, &bg, &[]);
+ cp.set_bind_group(0, &warp_bg, &[dyn_off]);
cp.dispatch_workgroups(16, 16, 1);
}
enc.copy_texture_to_texture(
@@ -1271,8 +1341,19 @@ impl GpuLiquifyEngine {
depth_or_array_layers: 1,
},
);
- queue.submit(Some(enc.finish()));
}
+ queue.submit(Some(enc.finish()));
+ for s in pinned_base_slots {
+ tile_pool.unpin_slot(s);
+ }
+ }
+
+ if !disp_encoded {
+ let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-liquify-disp-batch-enc"),
+ });
+ encode_disp_passes(&mut enc);
+ queue.submit(Some(enc.finish()));
}
self.total_steps_dispatched += 1;
@@ -1306,6 +1387,7 @@ impl GpuLiquifyEngine {
let mut dirty_union = RectI32::empty();
let doc_rect = RectI32::new(0, 0, doc.dimensions.width, doc.dimensions.height);
+ self.active = false;
let layers_taken = std::mem::take(&mut self.layers);
for ls in layers_taken {
let mut coords: Vec<TileCoord> = ls.coord_to_slot.keys().copied().collect();
@@ -1338,15 +1420,20 @@ impl GpuLiquifyEngine {
let mono_thresh = layer_node.meta.mono_threshold.unwrap_or(128);
let mut lookup: Vec<TileLookupEntry> =
Vec::with_capacity(layer_node.grid.tiles.len().min(MAX_LIQUIFY_LOOKUP));
+ let mut pinned_base_slots: Vec<u32> = Vec::with_capacity(lookup.capacity());
+ let doc_key = tile_pool.intern_doc(&doc.id);
+ let layer_key = tile_pool.intern_layer(&ls.layer_id);
for (&c, tile_arc) in layer_node.grid.tiles.iter().take(MAX_LIQUIFY_LOOKUP) {
let key = GpuTileKey {
- doc_id: doc.id.clone(),
- layer_id: ls.layer_id.clone(),
+ doc_id: doc_key,
+ layer_id: layer_key,
lod: 0,
coord: c,
};
if let Ok(base_slot) = tile_pool.ensure_tile_uploaded(queue, key, tile_arc, scratch)
{
+ tile_pool.pin_slot(base_slot);
+ pinned_base_slots.push(base_slot);
lookup.push(TileLookupEntry {
tx: c.tx,
ty: c.ty,
@@ -1359,8 +1446,19 @@ impl GpuLiquifyEngine {
queue.write_buffer(&self.lookup_buf, 0, bytemuck::cast_slice(&lookup));
}
- // Re-run warp with `write_rgba8 = 1.0` to produce exact RGBA8 readback + GPU pool tiles
- let mut committed_tiles = Vec::with_capacity(coords.len());
+ if coords.len() > self.warp_uniform_cap {
+ self.warp_uniform_cap = coords.len().next_power_of_two().max(64);
+ self.warp_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-liquify-warp-uniforms-dyn"),
+ size: self.warp_uniform_cap as u64 * LIQUIFY_UNIFORM_STRIDE,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ }
+
+ // Re-run warp with `write_rgba8 = 1.0` across ALL tiles + readback copy in ONE submit!
+ let stride = LIQUIFY_UNIFORM_STRIDE as usize;
+ let mut warp_bytes = vec![0u8; coords.len() * stride];
for (idx, &coord) in coords.iter().enumerate() {
let disp_slot = self
.disp_coord_to_slot
@@ -1381,65 +1479,73 @@ impl GpuLiquifyEngine {
1.0,
],
};
- queue.write_buffer(&self.warp_uniform_buf, 0, bytemuck::bytes_of(&wu));
-
- let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-liquify-commit-bg"),
- layout: &self.warp_bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: self.warp_uniform_buf.as_entire_binding(),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(tile_pool.atlas_view()),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::TextureView(&self.disp_atlas_view),
- },
- wgpu::BindGroupEntry {
- binding: 3,
- resource: self.lookup_buf.as_entire_binding(),
- },
- wgpu::BindGroupEntry {
- binding: 4,
- resource: wgpu::BindingResource::TextureView(&self.warp_scratch_view),
- },
- wgpu::BindGroupEntry {
- binding: 5,
- resource: self.readback_storage_buf.as_entire_binding(),
- },
- ],
- });
- let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-liquify-commit-enc"),
- });
- {
- let mut cp = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
- label: Some("ink-liquify-commit-pass"),
- timestamp_writes: None,
- });
- cp.set_pipeline(&self.warp_pipe);
- cp.set_bind_group(0, &bg, &[]);
- cp.dispatch_workgroups(16, 16, 1);
- }
- queue.submit(Some(enc.finish()));
+ let src = bytemuck::bytes_of(&wu);
+ warp_bytes[idx * stride..idx * stride + src.len()].copy_from_slice(src);
}
+ queue.write_buffer(&self.warp_uniform_buf, 0, &warp_bytes);
+
+ let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-liquify-commit-bg"),
+ layout: &self.warp_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.warp_uniform_buf,
+ offset: 0,
+ size: NonZeroU64::new(std::mem::size_of::<WarpUniforms>() as u64),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(tile_pool.atlas_view()),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(&self.disp_atlas_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: self.lookup_buf.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 4,
+ resource: wgpu::BindingResource::TextureView(&self.warp_scratch_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 5,
+ resource: self.readback_storage_buf.as_entire_binding(),
+ },
+ ],
+ });
let total_bytes = (coords.len() * TILE_SIZE * TILE_SIZE * 4) as u64;
- let mut copy_enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-liquify-rb-copy"),
+ let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-liquify-commit-batch-enc"),
});
- copy_enc.copy_buffer_to_buffer(
+ for idx in 0..coords.len() {
+ let dyn_off = (idx as u32) * (LIQUIFY_UNIFORM_STRIDE as u32);
+ let mut cp = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("ink-liquify-commit-pass"),
+ timestamp_writes: None,
+ });
+ cp.set_pipeline(&self.warp_pipe);
+ cp.set_bind_group(0, &bg, &[dyn_off]);
+ cp.dispatch_workgroups(16, 16, 1);
+ }
+ enc.copy_buffer_to_buffer(
&self.readback_storage_buf,
0,
&self.readback_map_buf,
0,
total_bytes,
);
- queue.submit(Some(copy_enc.finish()));
+ queue.submit(Some(enc.finish()));
+ for s in pinned_base_slots {
+ tile_pool.unpin_slot(s);
+ }
+
+ let mut committed_tiles = Vec::with_capacity(coords.len());
let slice = self.readback_map_buf.slice(0..total_bytes);
let (tx, rx) = std::sync::mpsc::channel();
@@ -1480,10 +1586,12 @@ impl GpuLiquifyEngine {
all_deltas.extend(deltas);
modified_layers.push(ls.layer_id.clone());
}
+ let doc_key = tile_pool.intern_doc(&doc.id);
+ let layer_key = tile_pool.intern_layer(&ls.layer_id);
for cc in cleared_coords {
tile_pool.evict_key(&GpuTileKey {
- doc_id: doc.id.clone(),
- layer_id: ls.layer_id.clone(),
+ doc_id: doc_key,
+ layer_id: layer_key,
lod: 0,
coord: cc,
});
diff --git a/crates/ink-engine/src/tools/mod.rs b/crates/ink-engine/src/tools/mod.rs
index 5d4756e..11b4227 100644
--- a/crates/ink-engine/src/tools/mod.rs
+++ b/crates/ink-engine/src/tools/mod.rs
@@ -26,8 +26,9 @@ use std::borrow::Cow;
pub use fill::{
enclose_and_fill_document, flood_fill_document, lasso_fill_document, paint_unfilled_document,
- pick_color_document, EncloseFillParams, EncloseTarget, FillOutcome, FillReferMode,
- FloodFillParams, LassoFillParams, PaintUnfilledParams, PickedColorDto,
+ pick_color_document, pick_color_document_for_layer, EncloseFillParams, EncloseTarget,
+ FillOutcome, FillReferMode, FloodFillParams, LassoFillParams, PaintUnfilledParams,
+ PickedColorDto,
};
pub use filters::{
apply_filter_rgba8, apply_image_op_to_document, apply_tonal_rgba8, compute_layer_histogram,
@@ -143,7 +144,7 @@ pub struct GpuToolPreviewOverlay {
pipeline: wgpu::RenderPipeline,
uniform_buf: wgpu::Buffer,
sampler: wgpu::Sampler,
- active_tex: Option<(wgpu::Texture, wgpu::TextureView, RectI32, f32)>,
+ active_tex: Option<(wgpu::Texture, wgpu::TextureView, wgpu::BindGroup, RectI32, f32)>,
/// When set, hides this layer in the base compositor while a live Filter/Tonal replacement preview is shown.
pub replaced_layer_id: Option<String>,
}
@@ -289,7 +290,25 @@ impl GpuToolPreviewOverlay {
depth_or_array_layers: 1,
},
);
- self.active_tex = Some((tex, view, rect, opacity.clamp(0.0, 1.0)));
+ let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-tool-overlay-bg"),
+ layout: &self.bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: self.uniform_buf.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(&view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::Sampler(&self.sampler),
+ },
+ ],
+ });
+ self.active_tex = Some((tex, view, bg, rect, opacity.clamp(0.0, 1.0)));
self.replaced_layer_id = replaced_layer_id;
}
@@ -299,10 +318,10 @@ impl GpuToolPreviewOverlay {
}
#[allow(clippy::too_many_arguments)]
- pub fn render(
+ pub fn encode(
&self,
- device: &wgpu::Device,
queue: &wgpu::Queue,
+ encoder: &mut wgpu::CommandEncoder,
doc_w: u32,
doc_h: u32,
camera: &CameraState,
@@ -311,7 +330,7 @@ impl GpuToolPreviewOverlay {
dpr: f32,
target_view: &wgpu::TextureView,
) {
- let Some((_, ref view, rect, opacity)) = self.active_tex else {
+ let Some((_, _, ref bg, rect, opacity)) = self.active_tex else {
return;
};
if vp_w == 0 || vp_h == 0 || rect.is_empty() {
@@ -337,48 +356,47 @@ impl GpuToolPreviewOverlay {
],
};
queue.write_buffer(&self.uniform_buf, 0, bytemuck::bytes_of(&u));
- let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-tool-overlay-bg"),
- layout: &self.bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: self.uniform_buf.as_entire_binding(),
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("ink-tool-overlay-pass"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: target_view,
+ depth_slice: None,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Load,
+ store: wgpu::StoreOp::Store,
},
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(view),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::Sampler(&self.sampler),
- },
- ],
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ multiview_mask: None,
});
+ pass.set_pipeline(&self.pipeline);
+ pass.set_bind_group(0, bg, &[]);
+ pass.draw(0..6, 0..1);
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ pub fn render(
+ &self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ doc_w: u32,
+ doc_h: u32,
+ camera: &CameraState,
+ vp_w: u32,
+ vp_h: u32,
+ dpr: f32,
+ target_view: &wgpu::TextureView,
+ ) {
+ if self.active_tex.is_none() || vp_w == 0 || vp_h == 0 {
+ return;
+ }
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("ink-tool-overlay-enc"),
});
- {
- let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
- label: Some("ink-tool-overlay-pass"),
- color_attachments: &[Some(wgpu::RenderPassColorAttachment {
- view: target_view,
- depth_slice: None,
- resolve_target: None,
- ops: wgpu::Operations {
- load: wgpu::LoadOp::Load,
- store: wgpu::StoreOp::Store,
- },
- })],
- depth_stencil_attachment: None,
- timestamp_writes: None,
- occlusion_query_set: None,
- multiview_mask: None,
- });
- pass.set_pipeline(&self.pipeline);
- pass.set_bind_group(0, &bg, &[]);
- pass.draw(0..6, 0..1);
- }
+ self.encode(queue, &mut enc, doc_w, doc_h, camera, vp_w, vp_h, dpr, target_view);
queue.submit(Some(enc.finish()));
}
}
diff --git a/crates/ink-engine/src/tools/retouch.rs b/crates/ink-engine/src/tools/retouch.rs
index ef6c0b0..221f653 100644
--- a/crates/ink-engine/src/tools/retouch.rs
+++ b/crates/ink-engine/src/tools/retouch.rs
@@ -159,6 +159,7 @@ pub struct RetouchSession {
kind: RetouchKind,
last_pos: Option<[f32; 2]>,
clone_offset: Option<[f32; 2]>,
+ last_clone_source: Option<[f32; 2]>,
/// Persistent RGBA float pickup grid (`pickup_dim × pickup_dim`) carried along Smudge strokes.
smudge_buf: Vec<[f32; 4]>,
smudge_dim: usize,
@@ -201,8 +202,10 @@ impl RetouchSession {
if matches!(params.settings.kind, RetouchKind::CloneStamp | RetouchKind::Heal) {
if let Some(src) = params.clone_source {
- if !params.settings.clone_aligned || self.clone_offset.is_none() {
+ let source_changed = self.last_clone_source != Some(src);
+ if !params.settings.clone_aligned || self.clone_offset.is_none() || source_changed {
self.clone_offset = Some([src[0] - params.x, src[1] - params.y]);
+ self.last_clone_source = Some(src);
}
}
}
@@ -681,6 +684,7 @@ impl RetouchSession {
}
}
layer.grid.mark_all_lods_dirty();
+ layer.grid.bump_version();
d.dirty_for_render = true;
}
}
diff --git a/crates/ink-engine/src/tools/transform.rs b/crates/ink-engine/src/tools/transform.rs
index dc28fb0..0a5c4b4 100644
--- a/crates/ink-engine/src/tools/transform.rs
+++ b/crates/ink-engine/src/tools/transform.rs
@@ -910,12 +910,15 @@ struct TransformLayerSource {
/// GPU `Rgba8Unorm` texture for live 120+ FPS preview!
gpu_tex: wgpu::Texture,
gpu_view: wgpu::TextureView,
+ gpu_bg: Option<wgpu::BindGroup>,
}
pub struct GpuTransformEngine {
bgl: wgpu::BindGroupLayout,
pipeline: wgpu::RenderPipeline,
uniform_buf: wgpu::Buffer,
+ uniform_slot_align: u32,
+ uniform_cap_slots: usize,
vert_buf: wgpu::Buffer,
vert_cap: usize,
sampler: wgpu::Sampler,
@@ -949,8 +952,10 @@ impl GpuTransformEngine {
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
- has_dynamic_offset: false,
- min_binding_size: None,
+ has_dynamic_offset: true,
+ min_binding_size: std::num::NonZeroU64::new(
+ std::mem::size_of::<TransformMeshUniforms>() as u64,
+ ),
},
count: None,
},
@@ -1022,9 +1027,11 @@ impl GpuTransformEngine {
multiview_mask: None,
cache: None,
});
+ let uniform_slot_align = device.limits().min_uniform_buffer_offset_alignment.max(256);
+ let uniform_cap_slots = 16usize;
let uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("ink-transform-uniforms"),
- size: std::mem::size_of::<TransformMeshUniforms>() as u64,
+ size: (uniform_cap_slots as u64) * (uniform_slot_align as u64),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
@@ -1046,6 +1053,8 @@ impl GpuTransformEngine {
bgl,
pipeline,
uniform_buf,
+ uniform_slot_align,
+ uniform_cap_slots,
vert_buf,
vert_cap,
sampler,
@@ -1352,6 +1361,7 @@ impl GpuTransformEngine {
opacity: layer.meta.opacity.clamp(0.0, 1.0),
gpu_tex,
gpu_view,
+ gpu_bg: None,
});
}
@@ -1592,19 +1602,20 @@ impl GpuTransformEngine {
RectI32::new(x0, y0, (x1 - x0).max(1) as u32, (y1 - y0).max(1) as u32)
}
- /// Renders the live GPU Transform/Warp preview directly onto `target_view` at 120+ FPS!
+ /// Encodes the live GPU Transform/Warp preview directly into `encoder` (zero extra `queue.submit`!).
#[allow(clippy::too_many_arguments)]
- pub fn render_preview(
+ pub fn encode_preview(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
+ encoder: &mut wgpu::CommandEncoder,
camera: &CameraState,
vp_w: u32,
vp_h: u32,
dpr: f32,
target_view: &wgpu::TextureView,
) {
- if !self.active || self.cached_gpu_verts.is_empty() || vp_w == 0 || vp_h == 0 {
+ if !self.active || self.cached_gpu_verts.is_empty() || self.layers.is_empty() || vp_w == 0 || vp_h == 0 {
return;
}
if self.cached_gpu_verts.len() > self.vert_cap {
@@ -1618,8 +1629,25 @@ impl GpuTransformEngine {
}
queue.write_buffer(&self.vert_buf, 0, bytemuck::cast_slice(&self.cached_gpu_verts));
- // Render bottom-to-top so multi-layer groups preserve stacking order!
- for ls in self.layers.iter().rev() {
+ let layer_count = self.layers.len();
+ let stride = self.uniform_slot_align as usize;
+ if layer_count > self.uniform_cap_slots {
+ self.uniform_cap_slots = layer_count.next_power_of_two();
+ self.uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("ink-transform-uniforms"),
+ size: (self.uniform_cap_slots as u64) * (self.uniform_slot_align as u64),
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ for ls in &mut self.layers {
+ ls.gpu_bg = None;
+ }
+ }
+
+ // Pack all layers' uniforms (bottom-to-top) into one dynamic uniform upload
+ let mut uniform_staging = vec![0u8; layer_count * stride];
+ let u_size = std::mem::size_of::<TransformMeshUniforms>();
+ for (idx, ls) in self.layers.iter_mut().rev().enumerate() {
let u = TransformMeshUniforms {
viewport_size_phys: [vp_w as f32, vp_h as f32],
doc_size: [self.doc_width as f32, self.doc_height as f32],
@@ -1633,54 +1661,84 @@ impl GpuTransformEngine {
dpr: dpr.max(0.05),
opacity: ls.opacity,
};
- queue.write_buffer(&self.uniform_buf, 0, bytemuck::bytes_of(&u));
- let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("ink-transform-mesh-bg"),
- layout: &self.bgl,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: self.uniform_buf.as_entire_binding(),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::TextureView(&ls.gpu_view),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::Sampler(&self.sampler),
- },
- ],
- });
- let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
- label: Some("ink-transform-preview-enc"),
- });
- {
- let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
- label: Some("ink-transform-preview-pass"),
- color_attachments: &[Some(wgpu::RenderPassColorAttachment {
- view: target_view,
- depth_slice: None,
- resolve_target: None,
- ops: wgpu::Operations {
- load: wgpu::LoadOp::Load,
- store: wgpu::StoreOp::Store,
+ let dst = idx * stride;
+ uniform_staging[dst..dst + u_size].copy_from_slice(bytemuck::bytes_of(&u));
+ if ls.gpu_bg.is_none() {
+ ls.gpu_bg = Some(device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("ink-transform-mesh-bg"),
+ layout: &self.bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.uniform_buf,
+ offset: 0,
+ size: std::num::NonZeroU64::new(u_size as u64),
+ }),
},
- })],
- depth_stencil_attachment: None,
- timestamp_writes: None,
- occlusion_query_set: None,
- multiview_mask: None,
- });
- pass.set_pipeline(&self.pipeline);
- pass.set_bind_group(0, &bg, &[]);
- pass.set_vertex_buffer(0, self.vert_buf.slice(..));
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(&ls.gpu_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::Sampler(&self.sampler),
+ },
+ ],
+ }));
+ }
+ }
+ queue.write_buffer(&self.uniform_buf, 0, &uniform_staging);
+
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("ink-transform-preview-pass"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: target_view,
+ depth_slice: None,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Load,
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ multiview_mask: None,
+ });
+ pass.set_pipeline(&self.pipeline);
+ pass.set_vertex_buffer(0, self.vert_buf.slice(..));
+ for (idx, ls) in self.layers.iter().rev().enumerate() {
+ let dyn_off = (idx as u32) * self.uniform_slot_align;
+ if let Some(ref bg) = ls.gpu_bg {
+ pass.set_bind_group(0, bg, &[dyn_off]);
pass.draw(0..self.cached_gpu_verts.len() as u32, 0..1);
}
- queue.submit(Some(enc.finish()));
}
}
+ /// Renders the live GPU Transform/Warp preview directly onto `target_view` at 120+ FPS!
+ #[allow(clippy::too_many_arguments)]
+ pub fn render_preview(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ camera: &CameraState,
+ vp_w: u32,
+ vp_h: u32,
+ dpr: f32,
+ target_view: &wgpu::TextureView,
+ ) {
+ if !self.active || self.cached_gpu_verts.is_empty() || self.layers.is_empty() || vp_w == 0 || vp_h == 0 {
+ return;
+ }
+ let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("ink-transform-preview-enc"),
+ });
+ self.encode_preview(device, queue, &mut enc, camera, vp_w, vp_h, dpr, target_view);
+ queue.submit(Some(enc.finish()));
+ }
+
/// High-quality CPU Rayon Lanczos-3 / Lossless 90°-step bake for a single source layer buffer.
fn bake_layer_rgba(&self, src_rgba: &[u8], out_rect: RectI32) -> Vec<u8> {
let sw = self.source_bounds.width as usize;
@@ -1939,6 +1997,7 @@ impl GpuTransformEngine {
if let Some(layer) = d.layer_mut(&ls.layer_id) {
layer.grid.tiles = ls.before_tiles.clone();
layer.grid.mark_all_lods_dirty();
+ layer.grid.bump_version();
}
}
d.dirty_for_render = true;
diff --git a/crates/ink-engine/src/types.rs b/crates/ink-engine/src/types.rs
index 7fc891e..791d458 100644
--- a/crates/ink-engine/src/types.rs
+++ b/crates/ink-engine/src/types.rs
@@ -341,6 +341,7 @@ pub enum NativeNavEvent {
phys_x: f32,
phys_y: f32,
phase: u8, // 1=down, 2=move, 3=up
+ shift_held: bool,
timestamp_ms: f64,
},
}
@@ -493,6 +494,10 @@ pub enum EngineCommand {
RemoteNotifyTileDelta {
layer_id: String,
},
+ /// Toggles whether `EngineEvent::StrokeCommitted` includes the full `points` array
+ /// (enabled only when multiplayer collaboration is connected, avoiding per-stroke cloning &
+ /// JSON serialization overhead during solo sketching).
+ SetCollabPointsEnabled(bool),
/// Requests a graceful shutdown of the engine thread.
Shutdown,
}
@@ -529,6 +534,8 @@ pub struct EngineDiagnostics {
pub stack_cache_hits: u64,
#[serde(default)]
pub stack_cache_rebuilds: u64,
+ #[serde(default)]
+ pub is_idle: bool,
}
impl Default for EngineDiagnostics {
@@ -556,6 +563,7 @@ impl Default for EngineDiagnostics {
gpu_tiles_capacity: 0,
stack_cache_hits: 0,
stack_cache_rebuilds: 0,
+ is_idle: true,
}
}
}
@@ -612,9 +620,13 @@ pub enum EngineEvent {
doc_id: String,
selection: crate::selection::SelectionMetaSnapshot,
},
+ /// Emitted after OS DPI/display changes or window restore from minimize so the host UI
+ /// re-measures physical viewport cutout bounds and occlusion rects even if CSS size is unchanged.
+ ViewportInvalidated,
}
/// Raw GPU surface target accepted by `ink-engine` without depending on Tauri/wry/WinUI.
+#[derive(Clone)]
pub enum SurfaceTarget {
/// Windows DirectComposition `IDCompositionVisual` raw COM pointer (`*mut c_void`).
///
diff --git a/src-tauri/src/dcomp_host.rs b/src-tauri/src/dcomp_host.rs
index 811c641..55ade7b 100644
--- a/src-tauri/src/dcomp_host.rs
+++ b/src-tauri/src/dcomp_host.rs
@@ -36,6 +36,7 @@ mod imp {
use windows::Win32::Graphics::Direct2D::Common::D2D_RECT_F;
use windows::Win32::Graphics::DirectComposition::{
DCompositionCreateDevice2, IDCompositionDevice, IDCompositionTarget, IDCompositionVisual,
+ DCOMPOSITION_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR, DCOMPOSITION_BORDER_MODE_HARD,
};
use windows_core::{IUnknown, Interface};
@@ -46,6 +47,7 @@ mod imp {
canvas_visual: IDCompositionVisual,
webview_visual: Option<IDCompositionVisual>,
last_rect: (i32, i32, u32, u32, bool),
+ staged_rect: Option<(i32, i32, u32, u32, bool)>,
}
pub struct DCompHost {
@@ -93,6 +95,13 @@ mod imp {
.AddVisual(&canvas_visual, false, None)
.map_err(|e| format!("AddVisual(canvas) failed: {e}"))?;
+ // Enforce hard clip edges and 1:1 physical-pixel presentation with zero
+ // soft-border antialiasing seams or bilinear resampling blur.
+ let _ = canvas_visual.SetBorderMode(DCOMPOSITION_BORDER_MODE_HARD);
+ let _ = canvas_visual.SetBitmapInterpolationMode(
+ DCOMPOSITION_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR,
+ );
+
// Start hidden/clipped to 0x0 until React reports an active document viewport.
let empty_clip = D2D_RECT_F {
left: 0.0,
@@ -115,6 +124,7 @@ mod imp {
canvas_visual,
webview_visual: None,
last_rect: (0, 0, 0, 0, false),
+ staged_rect: None,
}),
})
}
@@ -177,6 +187,34 @@ mod imp {
Ok(guard.canvas_visual.as_raw())
}
+ /// Stages a canvas viewport offset/clip update to be applied and committed atomically
+ /// on the render thread when `commit()` runs after `wgpu::Surface::configure()` / frame
+ /// presentation, so the DirectComposition clip rect never updates ahead of DXGI swapchain
+ /// buffers. Hiding (`visible == false` or empty rect) is committed immediately.
+ pub fn stage_canvas_viewport(
+ &self,
+ x_px: i32,
+ y_px: i32,
+ width_px: u32,
+ height_px: u32,
+ visible: bool,
+ ) -> Result<(), String> {
+ if !visible || width_px == 0 || height_px == 0 {
+ return self.set_canvas_viewport(0, 0, 0, 0, false);
+ }
+ let mut guard = self
+ .inner
+ .lock()
+ .map_err(|_| "DirectComposition host mutex poisoned".to_string())?;
+ let next = (x_px, y_px, width_px, height_px, visible);
+ if guard.last_rect == next {
+ guard.staged_rect = None;
+ return Ok(());
+ }
+ guard.staged_rect = Some(next);
+ Ok(())
+ }
+
/// Positions and clips `canvas_visual` to the physical client-pixel viewport cutout
/// and commits the DirectComposition batch immediately.
pub fn set_canvas_viewport(
@@ -191,12 +229,28 @@ mod imp {
.inner
.lock()
.map_err(|_| "DirectComposition host mutex poisoned".to_string())?;
+ guard.staged_rect = None;
let next = (x_px, y_px, width_px, height_px, visible);
if guard.last_rect == next {
return Ok(());
}
+ Self::apply_rect_locked(&mut guard, next)?;
+ unsafe {
+ guard
+ .device
+ .Commit()
+ .map_err(|e| format!("IDCompositionDevice::Commit failed: {e}"))?;
+ }
+ Ok(())
+ }
+
+ fn apply_rect_locked(
+ guard: &mut DCompInner,
+ next: (i32, i32, u32, u32, bool),
+ ) -> Result<(), String> {
+ let (x_px, y_px, width_px, height_px, visible) = next;
let clip = if visible && width_px > 0 && height_px > 0 {
D2D_RECT_F {
left: 0.0,
@@ -226,21 +280,21 @@ mod imp {
.canvas_visual
.SetClip2(&clip)
.map_err(|e| format!("SetClip2 failed: {e}"))?;
- guard
- .device
- .Commit()
- .map_err(|e| format!("IDCompositionDevice::Commit failed: {e}"))?;
}
-
guard.last_rect = next;
Ok(())
}
- /// Commits pending DirectComposition updates (REQUIRED immediately after
- /// `wgpu::Surface::configure`, because `wgpu-hal` calls `IDCompositionVisual::SetContent`
- /// without committing the caller's `IDCompositionDevice`).
+ /// Applies any staged viewport offset/clip and commits pending DirectComposition updates
+ /// (REQUIRED immediately after `wgpu::Surface::configure`, because `wgpu-hal` calls
+ /// `IDCompositionVisual::SetContent` without committing the caller's `IDCompositionDevice`).
pub fn commit(&self) {
- if let Ok(guard) = self.inner.lock() {
+ if let Ok(mut guard) = self.inner.lock() {
+ if let Some(staged) = guard.staged_rect.take() {
+ if guard.last_rect != staged {
+ let _ = Self::apply_rect_locked(&mut guard, staged);
+ }
+ }
unsafe {
let _ = guard.device.Commit();
}
@@ -431,6 +485,47 @@ mod imp {
diag.total_frames_rendered
);
+ // Exercise DPI changes (1.0, 1.25, 1.5, 2.0), resize, 0x0 minimize guard,
+ // restore, and hide/show transitions without panic or device loss.
+ let transitions: &[(i32, i32, u32, u32, f32, bool)] = &[
+ (16, 16, 288, 208, 1.25, true),
+ (24, 18, 260, 190, 1.5, true),
+ (0, 0, 0, 0, 1.5, false), // Minimize / 0x0 guard
+ (20, 12, 300, 220, 2.0, true), // Restore at 2.0x DPR
+ (20, 12, 300, 220, 1.0, false), // WelcomeScreen / Home hide
+ (12, 12, 296, 216, 1.0, true), // Return to workspace
+ ];
+ let frames_before = handle.diagnostics().total_frames_rendered;
+ for &(x, y, w, h, dpr, vis) in transitions {
+ dcomp
+ .set_canvas_viewport(x, y, w, h, vis)
+ .expect("set_canvas_viewport transition");
+ handle.send_command(EngineCommand::SetViewport(ViewportRect {
+ x_px: x,
+ y_px: y,
+ width_px: w,
+ height_px: h,
+ dpr,
+ }));
+ handle.send_command(EngineCommand::SetVisible(vis));
+ std::thread::sleep(Duration::from_millis(25));
+ }
+ let settle_deadline = Instant::now() + Duration::from_secs(3);
+ while Instant::now() < settle_deadline {
+ let d = handle.diagnostics();
+ if d.total_frames_rendered > frames_before
+ && d.swapchain_width == 296
+ && d.swapchain_height == 216
+ {
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ let after = handle.diagnostics();
+ assert_eq!(after.device_lost_recoveries, 0);
+ assert_eq!(after.swapchain_width, 296);
+ assert_eq!(after.swapchain_height, 216);
+
// Verify strict ordered shutdown: engine stops & drops Surface BEFORE DCompHost drops.
handle.shutdown();
assert!(!handle.is_running());
diff --git a/src-tauri/src/file_open.rs b/src-tauri/src/file_open.rs
index 64d5618..13e3893 100644
--- a/src-tauri/src/file_open.rs
+++ b/src-tauri/src/file_open.rs
@@ -76,7 +76,10 @@ pub fn parse_arg_to_candidate_path(raw: &str, cwd: Option<&Path>) -> Option<Path
}
// Handle file:// URLs (e.g. macOS RunEvent::Opened or desktop launchers)
- if trimmed.len() >= 7 && trimmed[..7].eq_ignore_ascii_case("file://") {
+ if trimmed
+ .get(..7)
+ .is_some_and(|p| p.eq_ignore_ascii_case("file://"))
+ {
let rest = &trimmed[7..];
let without_host = if let Some(after_localhost) = rest
.strip_prefix("localhost/")
@@ -238,6 +241,31 @@ mod tests {
);
}
+ #[test]
+ fn parses_non_ascii_cyrillic_and_cjk_paths_without_utf8_panic() {
+ // Byte index 7 falls inside a multi-byte UTF-8 sequence for Cyrillic/CJK paths
+ assert_eq!(
+ parse_arg_to_candidate_path("C:\\Кисти\\рисунок.ink", None),
+ Some(PathBuf::from("C:\\Кисти\\рисунок.ink"))
+ );
+ assert_eq!(
+ parse_arg_to_candidate_path("C:\\Абв\\арт.ink", None),
+ Some(PathBuf::from("C:\\Абв\\арт.ink"))
+ );
+ assert_eq!(
+ parse_arg_to_candidate_path("C:\\日本語\\絵.ink", None),
+ Some(PathBuf::from("C:\\日本語\\絵.ink"))
+ );
+ assert_eq!(
+ parse_arg_to_candidate_path("file:///C:/Кисти/art.ink", None),
+ Some(PathBuf::from("C:/Кисти/art.ink"))
+ );
+ assert_eq!(
+ parse_arg_to_candidate_path("FILE:///C:/%D0%9A%D0%B8%D1%81%D1%82%D0%B8/art.ink", None),
+ Some(PathBuf::from("C:/Кисти/art.ink"))
+ );
+ }
+
#[test]
fn extracts_only_existing_openable_files_and_deduplicates() {
let dir = std::env::temp_dir().join(format!(
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 6e946eb..f58f357 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -817,6 +817,11 @@ fn native_engine_is_active() -> bool {
native_engine::is_active()
}
+#[tauri::command]
+fn native_engine_is_stroke_active() -> bool {
+ native_engine::is_stroke_active()
+}
+
#[tauri::command]
fn native_engine_set_viewport(
x_px: i32,
@@ -951,14 +956,17 @@ fn native_engine_set_mask_mode(enabled: bool) {
}
#[tauri::command]
-fn native_engine_render_brush_preview(
+async fn native_engine_render_brush_preview(
brush: ink_engine::NativeBrushConfig,
width: u32,
height: u32,
-) -> Result<String, String> {
- let (w, h, rgba) = native_engine::render_brush_preview(brush, width, height)?;
- let png = ink_engine::io::png_codec::encode_rgba8_to_png(w, h, &rgba)?;
- Ok(ink_engine::io::png_codec::png_bytes_to_data_url(&png))
+) -> Result<tauri::ipc::Response, String> {
+ let (w, h, rgba) = tauri::async_runtime::spawn_blocking(move || {
+ native_engine::render_brush_preview(brush, width, height)
+ })
+ .await
+ .map_err(|e| format!("Brush preview worker failed: {e}"))??;
+ Ok(pack_rgba_ipc_response(w, h, rgba))
}
#[tauri::command]
@@ -975,7 +983,7 @@ fn native_engine_set_rulers(
}
#[tauri::command]
-fn native_engine_upload_brush_texture(req: tauri::ipc::Request<'_>) -> Result<(), String> {
+async fn native_engine_upload_brush_texture(req: tauri::ipc::Request<'_>) -> Result<(), String> {
let headers = req.headers();
let hash = headers
.get("x-hash")
@@ -1010,8 +1018,18 @@ fn native_engine_upload_brush_texture(req: tauri::ipc::Request<'_>) -> Result<()
tauri::ipc::InvokeBody::Raw(bytes) => bytes.clone(),
_ => return Err("Expected raw binary body for brush texture upload".to_string()),
};
- native_engine::upload_brush_texture(hash, kind, is_png, width, height, data);
- Ok(())
+ tauri::async_runtime::spawn_blocking(move || -> Result<(), String> {
+ // Decode PNG on the blocking worker thread instead of stalling the DX12 render thread.
+ let (final_w, final_h, rgba8) = if is_png {
+ ink_engine::io::decode_png_rgba8(&data)?
+ } else {
+ (width, height, data)
+ };
+ native_engine::upload_brush_texture(hash, kind, false, final_w, final_h, rgba8);
+ Ok(())
+ })
+ .await
+ .map_err(|e| format!("Brush texture upload worker failed: {e}"))?
}
#[tauri::command]
@@ -1019,6 +1037,11 @@ fn native_engine_set_policy(policy: ink_engine::InteractionPolicy) {
native_engine::set_policy(policy);
}
+#[tauri::command]
+fn native_engine_set_collab_points_enabled(enabled: bool) {
+ native_engine::set_collab_points_enabled(enabled);
+}
+
#[tauri::command]
fn native_engine_clear_canvas() {
native_engine::clear_canvas();
@@ -1034,22 +1057,26 @@ fn native_engine_get_diagnostics() -> ink_engine::EngineDiagnostics {
// ---------------------------------------------------------------------------
#[tauri::command]
-fn native_engine_create_document(
+async fn native_engine_create_document(
doc_id: String,
name: String,
dimensions: ink_engine::CanvasDimensions,
color_mode: Option<ink_engine::CanvasColorMode>,
background_hex: Option<String>,
default_tone_frequency: Option<f32>,
-) -> ink_engine::DocumentMetaSnapshot {
- native_docs::create_document(
- doc_id,
- name,
- dimensions,
- color_mode.unwrap_or(ink_engine::CanvasColorMode::Color),
- background_hex.as_deref().unwrap_or("#ffffff"),
- default_tone_frequency.unwrap_or(60.0),
- )
+) -> Result<ink_engine::DocumentMetaSnapshot, String> {
+ tauri::async_runtime::spawn_blocking(move || {
+ native_docs::create_document(
+ doc_id,
+ name,
+ dimensions,
+ color_mode.unwrap_or(ink_engine::CanvasColorMode::Color),
+ background_hex.as_deref().unwrap_or("#ffffff"),
+ default_tone_frequency.unwrap_or(60.0),
+ )
+ })
+ .await
+ .map_err(|e| format!("Create document worker failed: {e}"))
}
#[tauri::command]
@@ -1165,147 +1192,306 @@ async fn native_engine_save_ink_with_dialog(
}
#[tauri::command]
-fn native_engine_switch_document(doc_id: String) -> Result<ink_engine::DocumentMetaSnapshot, String> {
- native_docs::switch_document(&doc_id)
+async fn native_engine_switch_document(
+ doc_id: String,
+) -> Result<ink_engine::DocumentMetaSnapshot, String> {
+ tauri::async_runtime::spawn_blocking(move || native_docs::switch_document(&doc_id))
+ .await
+ .map_err(|e| format!("Switch document worker failed: {e}"))?
}
#[tauri::command]
-fn native_engine_close_document(doc_id: String) -> bool {
- native_docs::close_document(&doc_id)
+async fn native_engine_close_document(doc_id: String) -> Result<bool, String> {
+ tauri::async_runtime::spawn_blocking(move || native_docs::close_document(&doc_id))
+ .await
+ .map_err(|e| format!("Close document worker failed: {e}"))
}
#[tauri::command]
-fn native_engine_get_document_state(
+async fn native_engine_get_document_state(
doc_id: Option<String>,
-) -> Option<ink_engine::DocumentMetaSnapshot> {
- native_docs::get_document_state(doc_id.as_deref())
+) -> Result<Option<ink_engine::DocumentMetaSnapshot>, String> {
+ tauri::async_runtime::spawn_blocking(move || {
+ native_docs::get_document_state(doc_id.as_deref())
+ })
+ .await
+ .map_err(|e| format!("Get document state worker failed: {e}"))
+}
+
+fn emit_doc_history(
+ app: &tauri::AppHandle,
+ doc_id: &str,
+ history: &ink_engine::HistoryStateSnapshot,
+) {
+ let _ = app.emit(
+ native_engine::EVENT_HISTORY,
+ native_engine::NativeHistoryEventPayload {
+ doc_id: doc_id.to_string(),
+ history: history.clone(),
+ },
+ );
+}
+
+#[tauri::command]
+async fn native_engine_set_active_layer(
+ doc_id: String,
+ layer_id: Option<String>,
+) -> Result<(), String> {
+ tauri::async_runtime::spawn_blocking(move || {
+ native_docs::set_active_layer(&doc_id, layer_id)
+ })
+ .await
+ .map_err(|e| format!("Set active layer worker failed: {e}"))?
}
#[tauri::command]
-fn native_engine_add_layer(
+async fn native_engine_sync_document_meta(
+ doc_id: String,
+ name: Option<String>,
+ perspective_ruler: Option<serde_json::Value>,
+ straight_ruler: Option<serde_json::Value>,
+ animation_timeline: Option<serde_json::Value>,
+ timelapse: Option<serde_json::Value>,
+ work_time_ms: Option<u64>,
+) -> Result<(), String> {
+ tauri::async_runtime::spawn_blocking(move || {
+ native_docs::sync_document_meta(
+ &doc_id,
+ name,
+ perspective_ruler,
+ straight_ruler,
+ animation_timeline,
+ timelapse,
+ work_time_ms,
+ )
+ })
+ .await
+ .map_err(|e| format!("Sync document meta worker failed: {e}"))?
+}
+
+#[tauri::command]
+async fn native_engine_add_layer(
+ app: tauri::AppHandle,
doc_id: String,
layer: ink_engine::LayerNodeMeta,
insert_index: Option<usize>,
record_history: Option<bool>,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
- native_docs::add_layer(&doc_id, layer, insert_index, record_history.unwrap_or(true))
+ let rec = record_history.unwrap_or(true);
+ let doc_id_emit = doc_id.clone();
+ let snap = tauri::async_runtime::spawn_blocking(move || {
+ native_docs::add_layer(&doc_id, layer, insert_index, rec)
+ })
+ .await
+ .map_err(|e| format!("Add layer worker failed: {e}"))??;
+ if rec {
+ emit_doc_history(&app, &doc_id_emit, &snap.history);
+ }
+ Ok(snap)
}
#[tauri::command]
-fn native_engine_delete_layer(
+async fn native_engine_delete_layer(
+ app: tauri::AppHandle,
doc_id: String,
layer_id: String,
record_history: Option<bool>,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
- native_docs::delete_layer(&doc_id, &layer_id, record_history.unwrap_or(true))
+ let rec = record_history.unwrap_or(true);
+ let doc_id_emit = doc_id.clone();
+ let snap = tauri::async_runtime::spawn_blocking(move || {
+ native_docs::delete_layer(&doc_id, &layer_id, rec)
+ })
+ .await
+ .map_err(|e| format!("Delete layer worker failed: {e}"))??;
+ if rec {
+ emit_doc_history(&app, &doc_id_emit, &snap.history);
+ }
+ Ok(snap)
}
#[tauri::command]
-fn native_engine_duplicate_layer(
+async fn native_engine_duplicate_layer(
+ app: tauri::AppHandle,
doc_id: String,
source_layer_id: String,
new_layer_id: String,
record_history: Option<bool>,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
- native_docs::duplicate_layer(
- &doc_id,
- &source_layer_id,
- new_layer_id,
- record_history.unwrap_or(true),
- )
+ let rec = record_history.unwrap_or(true);
+ let doc_id_emit = doc_id.clone();
+ let snap = tauri::async_runtime::spawn_blocking(move || {
+ native_docs::duplicate_layer(&doc_id, &source_layer_id, new_layer_id, rec)
+ })
+ .await
+ .map_err(|e| format!("Duplicate layer worker failed: {e}"))??;
+ if rec {
+ emit_doc_history(&app, &doc_id_emit, &snap.history);
+ }
+ Ok(snap)
}
#[tauri::command]
-fn native_engine_reorder_layers(
+async fn native_engine_reorder_layers(
+ app: tauri::AppHandle,
doc_id: String,
ordered_ids: Vec<String>,
parent_overrides: Option<std::collections::HashMap<String, Option<String>>>,
record_history: Option<bool>,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
- native_docs::reorder_layers(
- &doc_id,
- &ordered_ids,
- parent_overrides.as_ref(),
- record_history.unwrap_or(true),
- )
+ let rec = record_history.unwrap_or(true);
+ let doc_id_emit = doc_id.clone();
+ let snap = tauri::async_runtime::spawn_blocking(move || {
+ native_docs::reorder_layers(&doc_id, &ordered_ids, parent_overrides.as_ref(), rec)
+ })
+ .await
+ .map_err(|e| format!("Reorder layers worker failed: {e}"))??;
+ if rec {
+ emit_doc_history(&app, &doc_id_emit, &snap.history);
+ }
+ Ok(snap)
}
#[tauri::command]
-fn native_engine_update_layer(
+async fn native_engine_update_layer(
+ app: tauri::AppHandle,
doc_id: String,
layer_id: String,
patch: ink_engine::LayerPropsPatch,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
- native_docs::update_layer(&doc_id, &layer_id, patch)
+ let rec = patch.record_history.unwrap_or(true);
+ let doc_id_emit = doc_id.clone();
+ let snap = tauri::async_runtime::spawn_blocking(move || {
+ native_docs::update_layer(&doc_id, &layer_id, patch)
+ })
+ .await
+ .map_err(|e| format!("Update layer worker failed: {e}"))??;
+ if rec {
+ emit_doc_history(&app, &doc_id_emit, &snap.history);
+ }
+ Ok(snap)
}
#[tauri::command]
-fn native_engine_sync_layers(
+async fn native_engine_sync_layers(
+ app: tauri::AppHandle,
doc_id: String,
layers: Vec<ink_engine::LayerNodeMeta>,
active_layer_id: Option<String>,
+ record_history: Option<bool>,
+ history_label: Option<String>,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
- native_docs::sync_layers(&doc_id, layers, active_layer_id)
+ let rec = record_history.unwrap_or(false);
+ let doc_id_emit = doc_id.clone();
+ let snap = tauri::async_runtime::spawn_blocking(move || {
+ native_docs::sync_layers(&doc_id, layers, active_layer_id, rec, history_label)
+ })
+ .await
+ .map_err(|e| format!("Sync layers worker failed: {e}"))??;
+ if rec {
+ emit_doc_history(&app, &doc_id_emit, &snap.history);
+ }
+ Ok(snap)
}
#[tauri::command]
-fn native_engine_clear_layer(
+async fn native_engine_clear_layer(
+ app: tauri::AppHandle,
doc_id: String,
layer_id: String,
record_history: Option<bool>,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
- native_docs::clear_layer(&doc_id, &layer_id, record_history.unwrap_or(true))
+ let rec = record_history.unwrap_or(true);
+ let doc_id_emit = doc_id.clone();
+ let snap = tauri::async_runtime::spawn_blocking(move || {
+ native_docs::clear_layer(&doc_id, &layer_id, rec)
+ })
+ .await
+ .map_err(|e| format!("Clear layer worker failed: {e}"))??;
+ if rec {
+ emit_doc_history(&app, &doc_id_emit, &snap.history);
+ }
+ Ok(snap)
}
#[tauri::command]
-fn native_engine_merge_down(
+async fn native_engine_merge_down(
+ app: tauri::AppHandle,
doc_id: String,
src_layer_id: String,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
- native_docs::merge_down(&doc_id, &src_layer_id)
+ let doc_id_emit = doc_id.clone();
+ let snap = tauri::async_runtime::spawn_blocking(move || {
+ native_docs::merge_down(&doc_id, &src_layer_id)
+ })
+ .await
+ .map_err(|e| format!("Merge down worker failed: {e}"))??;
+ emit_doc_history(&app, &doc_id_emit, &snap.history);
+ Ok(snap)
}
#[tauri::command]
-fn native_engine_merge_folder(
+async fn native_engine_merge_folder(
+ app: tauri::AppHandle,
doc_id: String,
folder_id: String,
new_layer_id: String,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
- native_docs::merge_folder(&doc_id, &folder_id, new_layer_id)
+ let doc_id_emit = doc_id.clone();
+ let snap = tauri::async_runtime::spawn_blocking(move || {
+ native_docs::merge_folder(&doc_id, &folder_id, new_layer_id)
+ })
+ .await
+ .map_err(|e| format!("Merge folder worker failed: {e}"))??;
+ emit_doc_history(&app, &doc_id_emit, &snap.history);
+ Ok(snap)
}
#[tauri::command]
-fn native_engine_add_mask(
+async fn native_engine_add_mask(
+ app: tauri::AppHandle,
doc_id: String,
layer_id: String,
default_value: Option<u8>,
record_history: Option<bool>,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
- native_docs::add_mask(
- &doc_id,
- &layer_id,
- default_value.unwrap_or(255),
- record_history.unwrap_or(true),
- )
+ let rec = record_history.unwrap_or(true);
+ let doc_id_emit = doc_id.clone();
+ let snap = tauri::async_runtime::spawn_blocking(move || {
+ native_docs::add_mask(&doc_id, &layer_id, default_value.unwrap_or(255), rec)
+ })
+ .await
+ .map_err(|e| format!("Add mask worker failed: {e}"))??;
+ if rec {
+ emit_doc_history(&app, &doc_id_emit, &snap.history);
+ }
+ Ok(snap)
}
#[tauri::command]
-fn native_engine_remove_mask(
+async fn native_engine_remove_mask(
+ app: tauri::AppHandle,
doc_id: String,
layer_id: String,
apply_to_raster: Option<bool>,
record_history: Option<bool>,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
- native_docs::remove_mask(
- &doc_id,
- &layer_id,
- apply_to_raster.unwrap_or(false),
- record_history.unwrap_or(true),
- )
+ let rec = record_history.unwrap_or(true);
+ let doc_id_emit = doc_id.clone();
+ let snap = tauri::async_runtime::spawn_blocking(move || {
+ native_docs::remove_mask(&doc_id, &layer_id, apply_to_raster.unwrap_or(false), rec)
+ })
+ .await
+ .map_err(|e| format!("Remove mask worker failed: {e}"))??;
+ if rec {
+ emit_doc_history(&app, &doc_id_emit, &snap.history);
+ }
+ Ok(snap)
}
#[tauri::command]
-fn native_engine_resize_canvas(
+async fn native_engine_resize_canvas(
+ app: tauri::AppHandle,
doc_id: String,
dimensions: ink_engine::CanvasDimensions,
offset_x: Option<i32>,
@@ -1314,19 +1500,30 @@ fn native_engine_resize_canvas(
bg_hex: Option<String>,
record_history: Option<bool>,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
- native_docs::resize_canvas(
- &doc_id,
- dimensions,
- offset_x.unwrap_or(0),
- offset_y.unwrap_or(0),
- scale_content.unwrap_or(false),
- bg_hex.as_deref().unwrap_or("#ffffff"),
- record_history.unwrap_or(true),
- )
+ let rec = record_history.unwrap_or(true);
+ let doc_id_emit = doc_id.clone();
+ let snap = tauri::async_runtime::spawn_blocking(move || {
+ native_docs::resize_canvas(
+ &doc_id,
+ dimensions,
+ offset_x.unwrap_or(0),
+ offset_y.unwrap_or(0),
+ scale_content.unwrap_or(false),
+ bg_hex.as_deref().unwrap_or("#ffffff"),
+ rec,
+ )
+ })
+ .await
+ .map_err(|e| format!("Resize canvas worker failed: {e}"))??;
+ if rec {
+ emit_doc_history(&app, &doc_id_emit, &snap.history);
+ }
+ Ok(snap)
}
#[tauri::command]
async fn native_engine_ingest_dirty_rect(
+ app: tauri::AppHandle,
request: tauri::ipc::Request<'_>,
) -> Result<ink_engine::DocumentMetaSnapshot, String> {
let doc_id = header_str(&request, "x-doc-id")?;
@@ -1344,7 +1541,8 @@ async fn native_engine_ingest_dirty_rect(
let stroke_id = header_opt_str(&request, "x-stroke-id");
let body = raw_body(&request)?.to_vec();
- tokio::task::spawn_blocking(move || {
+ let doc_id_for_emit = doc_id.clone();
+ let snap = tokio::task::spawn_blocking(move || {
native_docs::ingest_dirty_rect(
&doc_id,
&layer_id,
@@ -1359,46 +1557,69 @@ async fn native_engine_ingest_dirty_rect(
)
})
.await
- .map_err(|e| format!("Native dirty-rect ingest worker failed: {e}"))?
+ .map_err(|e| format!("Native dirty-rect ingest worker failed: {e}"))??;
+ if record_history {
+ emit_doc_history(&app, &doc_id_for_emit, &snap.history);
+ }
+ Ok(snap)
}
#[tauri::command]
-fn native_engine_undo(doc_id: String) -> Result<native_docs::NativeHistoryMutationResult, String> {
- native_docs::undo(&doc_id)
+async fn native_engine_undo(
+ doc_id: String,
+) -> Result<native_docs::NativeHistoryMutationResult, String> {
+ tauri::async_runtime::spawn_blocking(move || native_docs::undo(&doc_id))
+ .await
+ .map_err(|e| format!("Undo worker failed: {e}"))?
}
#[tauri::command]
-fn native_engine_redo(doc_id: String) -> Result<native_docs::NativeHistoryMutationResult, String> {
- native_docs::redo(&doc_id)
+async fn native_engine_redo(
+ doc_id: String,
+) -> Result<native_docs::NativeHistoryMutationResult, String> {
+ tauri::async_runtime::spawn_blocking(move || native_docs::redo(&doc_id))
+ .await
+ .map_err(|e| format!("Redo worker failed: {e}"))?
}
#[tauri::command]
-fn native_engine_jump_history(
+async fn native_engine_jump_history(
doc_id: String,
target_index: usize,
) -> Result<native_docs::NativeHistoryMutationResult, String> {
- native_docs::jump_history(&doc_id, target_index)
+ tauri::async_runtime::spawn_blocking(move || native_docs::jump_history(&doc_id, target_index))
+ .await
+ .map_err(|e| format!("Jump history worker failed: {e}"))?
}
#[tauri::command]
-fn native_engine_selective_undo(
+async fn native_engine_selective_undo(
doc_id: String,
peer_id: Option<String>,
stroke_id: Option<String>,
) -> Result<native_docs::NativeHistoryMutationResult, String> {
- native_docs::selective_undo(&doc_id, peer_id.as_deref(), stroke_id.as_deref())
+ tauri::async_runtime::spawn_blocking(move || {
+ native_docs::selective_undo(&doc_id, peer_id.as_deref(), stroke_id.as_deref())
+ })
+ .await
+ .map_err(|e| format!("Selective undo worker failed: {e}"))?
}
#[tauri::command]
-fn native_engine_selective_redo(
+async fn native_engine_selective_redo(
doc_id: String,
peer_id: Option<String>,
) -> Result<native_docs::NativeHistoryMutationResult, String> {
- native_docs::selective_redo(&doc_id, peer_id.as_deref())
+ tauri::async_runtime::spawn_blocking(move || {
+ native_docs::selective_redo(&doc_id, peer_id.as_deref())
+ })
+ .await
+ .map_err(|e| format!("Selective redo worker failed: {e}"))?
}
#[tauri::command]
-fn native_engine_push_history_meta(
+async fn native_engine_push_history_meta(
+ app: tauri::AppHandle,
doc_id: String,
action_type: String,
label: String,
@@ -1406,44 +1627,69 @@ fn native_engine_push_history_meta(
document_state_delta: Option<serde_json::Value>,
coalesce_key: Option<String>,
) -> Result<ink_engine::HistoryStateSnapshot, String> {
- native_docs::push_history_meta(
- &doc_id,
- action_type,
- label,
- layer_id,
- document_state_delta,
- coalesce_key,
- )
+ let doc_id_emit = doc_id.clone();
+ let history = tauri::async_runtime::spawn_blocking(move || {
+ native_docs::push_history_meta(
+ &doc_id,
+ action_type,
+ label,
+ layer_id,
+ document_state_delta,
+ coalesce_key,
+ )
+ })
+ .await
+ .map_err(|e| format!("Push history meta worker failed: {e}"))??;
+ emit_doc_history(&app, &doc_id_emit, &history);
+ Ok(history)
}
#[tauri::command]
-fn native_engine_get_history(doc_id: String) -> Result<ink_engine::HistoryStateSnapshot, String> {
- native_docs::get_history(&doc_id)
+async fn native_engine_get_history(
+ doc_id: String,
+) -> Result<ink_engine::HistoryStateSnapshot, String> {
+ tauri::async_runtime::spawn_blocking(move || native_docs::get_history(&doc_id))
+ .await
+ .map_err(|e| format!("Get history worker failed: {e}"))?
}
#[tauri::command]
-fn native_engine_reset_history(
+async fn native_engine_reset_history(
+ app: tauri::AppHandle,
doc_id: String,
label: Option<String>,
) -> Result<ink_engine::HistoryStateSnapshot, String> {
- native_docs::reset_history(&doc_id, label)
+ let doc_id_emit = doc_id.clone();
+ let history = tauri::async_runtime::spawn_blocking(move || {
+ native_docs::reset_history(&doc_id, label)
+ })
+ .await
+ .map_err(|e| format!("Reset history worker failed: {e}"))??;
+ emit_doc_history(&app, &doc_id_emit, &history);
+ Ok(history)
}
#[tauri::command]
-fn native_engine_get_memory_stats() -> ink_engine::MemoryStats {
- native_docs::get_memory_stats()
+async fn native_engine_get_memory_stats() -> Result<ink_engine::MemoryStats, String> {
+ tauri::async_runtime::spawn_blocking(native_docs::get_memory_stats)
+ .await
+ .map_err(|e| format!("Get memory stats worker failed: {e}"))
}
#[tauri::command]
-fn native_engine_set_memory_budget(
+async fn native_engine_set_memory_budget(
input: native_docs::NativeMemoryBudgetInput,
) -> Result<ink_engine::MemoryStats, String> {
- native_docs::set_memory_budget(input)
+ tauri::async_runtime::spawn_blocking(move || native_docs::set_memory_budget(input))
+ .await
+ .map_err(|e| format!("Set memory budget worker failed: {e}"))?
}
#[tauri::command]
-fn native_engine_purge_memory() -> Result<ink_engine::MemoryStats, String> {
- native_docs::purge_memory()
+async fn native_engine_purge_memory() -> Result<ink_engine::MemoryStats, String> {
+ tauri::async_runtime::spawn_blocking(native_docs::purge_memory)
+ .await
+ .map_err(|e| format!("Purge memory worker failed: {e}"))?
}
#[tauri::command]
@@ -1495,13 +1741,17 @@ async fn native_engine_recovery_restore(
}
#[tauri::command]
-fn os_hotkeys_sync(
+async fn os_hotkeys_sync(
window: tauri::WebviewWindow,
bindings: Vec<os_hotkeys::NativeOsHotkeyBinding>,
recording: bool,
on_event: tauri::ipc::Channel<os_hotkeys::NativeOsHotkeyEvent>,
) -> Result<os_hotkeys::OsHotkeyStatus, String> {
- os_hotkeys::sync_os_hotkeys(&window, bindings, recording, on_event)
+ tauri::async_runtime::spawn_blocking(move || {
+ os_hotkeys::sync_os_hotkeys(&window, bindings, recording, on_event)
+ })
+ .await
+ .map_err(|e| format!("OS hotkeys sync worker failed: {e}"))?
}
#[tauri::command]
@@ -1765,6 +2015,7 @@ pub fn run() {
tablet_stop_input,
tablet_get_status,
native_engine_is_active,
+ native_engine_is_stroke_active,
native_engine_set_viewport,
native_engine_set_occluded_rects,
native_engine_set_document,
@@ -1785,6 +2036,7 @@ pub fn run() {
native_engine_set_rulers,
native_engine_upload_brush_texture,
native_engine_set_policy,
+ native_engine_set_collab_points_enabled,
native_engine_clear_canvas,
native_engine_get_diagnostics,
native_engine_create_document,
@@ -1795,6 +2047,8 @@ pub fn run() {
native_engine_switch_document,
native_engine_close_document,
native_engine_get_document_state,
+ native_engine_set_active_layer,
+ native_engine_sync_document_meta,
native_engine_add_layer,
native_engine_delete_layer,
native_engine_duplicate_layer,
diff --git a/src-tauri/src/native_docs.rs b/src-tauri/src/native_docs.rs
index d1da706..58dc395 100644
--- a/src-tauri/src/native_docs.rs
+++ b/src-tauri/src/native_docs.rs
@@ -501,14 +501,26 @@ pub fn open_document_from_bytes(
}
/// Serializes an open Rust document directly into `.ink` v2 ZIP bytes (parallelized with Rayon).
+/// Takes a microsecond zero-copy `Arc<TileData>` + metadata snapshot under `docs.read()` and
+/// immediately releases the read guard before running DEFLATE/ZIP/PNG compression!
pub fn serialize_document_ink(doc_id: &str) -> Result<SerializedInkResult, String> {
let docs = documents_handle();
- let mgr = docs.read();
- let scratch = mgr.scratch_backend();
- let doc = mgr
- .get_document(doc_id)
- .ok_or_else(|| format!("Document not found: {doc_id}"))?;
- serialize_ink_document(doc, 1, Some(scratch.as_ref()))
+ serialize_document_ink_from_docs(&docs, doc_id)
+}
+
+pub(crate) fn serialize_document_ink_from_docs(
+ docs: &RwLock<DocumentManager>,
+ doc_id: &str,
+) -> Result<SerializedInkResult, String> {
+ let (snapshot, scratch) = {
+ let mgr = docs.read();
+ let scratch = Arc::clone(mgr.scratch_backend());
+ let doc = mgr
+ .get_document(doc_id)
+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;
+ (doc.clone_cow_snapshot(), scratch)
+ };
+ serialize_ink_document(&snapshot, 1, Some(scratch.as_ref()))
}
pub fn switch_document(doc_id: &str) -> Result<DocumentMetaSnapshot, String> {
@@ -639,6 +651,8 @@ pub fn sync_layers(
doc_id: &str,
layers: Vec<LayerNodeMeta>,
active_layer_id: Option<String>,
+ record_history: bool,
+ history_label: Option<String>,
) -> Result<DocumentMetaSnapshot, String> {
let docs = documents_handle();
let snap = {
@@ -646,13 +660,100 @@ pub fn sync_layers(
let doc = mgr
.get_document_mut(doc_id)
.ok_or_else(|| format!("Document not found: {doc_id}"))?;
+ let before_layers = if record_history {
+ Some(doc.layers.iter().map(|l| l.meta.clone()).collect::<Vec<_>>())
+ } else {
+ None
+ };
+ let before_active = if record_history {
+ doc.active_layer_id.clone()
+ } else {
+ None
+ };
+ let before_grids = if record_history {
+ let incoming_ids: std::collections::HashSet<&str> =
+ layers.iter().map(|l| l.id.as_str()).collect();
+ doc.layers
+ .iter()
+ .filter(|l| !incoming_ids.contains(l.meta.id.as_str()))
+ .map(|l| (l.meta.id.clone(), l.grid.clone_cow()))
+ .collect::<Vec<_>>()
+ } else {
+ Vec::new()
+ };
doc.sync_layers_metadata(layers, active_layer_id);
+ if let Some(bl) = before_layers {
+ let target_id = doc.active_layer_id.clone();
+ doc.record_tree_history(
+ "layer",
+ history_label.unwrap_or_else(|| "Update Layers".to_string()),
+ target_id,
+ bl,
+ before_active,
+ before_grids,
+ Vec::new(),
+ Vec::new(),
+ None,
+ );
+ }
doc.snapshot_meta()
};
native_engine::sync_active_document();
Ok(snap)
}
+pub fn set_active_layer(doc_id: &str, layer_id: Option<String>) -> Result<(), String> {
+ let docs = documents_handle();
+ let changed = {
+ let mut mgr = docs.write();
+ let doc = mgr
+ .get_document_mut(doc_id)
+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;
+ doc.set_active_layer(layer_id)
+ };
+ if changed {
+ native_engine::sync_active_document();
+ }
+ Ok(())
+}
+
+pub fn sync_document_meta(
+ doc_id: &str,
+ name: Option<String>,
+ perspective_ruler: Option<serde_json::Value>,
+ straight_ruler: Option<serde_json::Value>,
+ animation_timeline: Option<serde_json::Value>,
+ timelapse: Option<serde_json::Value>,
+ work_time_ms: Option<u64>,
+) -> Result<(), String> {
+ let docs = documents_handle();
+ let mut mgr = docs.write();
+ let doc = mgr
+ .get_document_mut(doc_id)
+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;
+ if let Some(n) = name {
+ if !n.trim().is_empty() {
+ doc.name = n;
+ }
+ }
+ if let Some(pr) = perspective_ruler {
+ doc.perspective_ruler = if pr.is_null() { None } else { Some(pr) };
+ }
+ if let Some(sr) = straight_ruler {
+ doc.straight_ruler = if sr.is_null() { None } else { Some(sr) };
+ }
+ if let Some(at) = animation_timeline {
+ doc.animation_timeline = if at.is_null() { None } else { Some(at) };
+ }
+ if let Some(tl) = timelapse {
+ doc.timelapse = if tl.is_null() { None } else { Some(tl) };
+ }
+ if let Some(wt) = work_time_ms {
+ doc.work_time_ms = wt;
+ }
+ Ok(())
+}
+
pub fn clear_layer(
doc_id: &str,
layer_id: &str,
@@ -952,11 +1053,11 @@ pub fn push_history_meta(
.unwrap_or(0);
let entry = ink_engine::history::HistoryEntry {
meta: HistoryItemMeta {
- id: format!("hist-{now}"),
+ id: ink_engine::history::next_history_id("hist-meta", now),
action_type,
label,
timestamp: now,
- time_formatted: String::new(),
+ time_formatted: ink_engine::history::format_time_hms(now),
thumbnail_url: String::new(),
layer_id,
undone: false,
@@ -1048,14 +1149,27 @@ pub fn purge_memory() -> Result<MemoryStats, String> {
Ok(attach_gpu_pool_stats(outcome.stats))
}
-/// Generates 64x64 layer & mask thumbnails asynchronously in a Rayon worker and emits
-/// `native-engine://thumbnails` back to React (never blocking the main UI or GPU thread).
+/// Generates 64x64 layer & mask thumbnails asynchronously on Tauri's blocking pool and emits
+/// `native-engine://thumbnails` back to React (never blocking the main UI or GPU thread, and
+/// safe to call from synchronous `#[tauri::command]` handlers outside a Tokio runtime context).
pub fn spawn_thumbnail_generation(
app: tauri::AppHandle,
doc_id: String,
layer_ids: Vec<String>,
) {
- tokio::task::spawn_blocking(move || {
+ spawn_thumbnail_generation_with_sink(doc_id, layer_ids, move |doc_id, updates| {
+ let _ = app.emit(
+ native_engine::EVENT_THUMBNAILS,
+ native_engine::NativeThumbnailsEventPayload { doc_id, updates },
+ );
+ });
+}
+
+fn spawn_thumbnail_generation_with_sink<F>(doc_id: String, layer_ids: Vec<String>, on_updates: F)
+where
+ F: FnOnce(String, Vec<ThumbnailUpdate>) + Send + 'static,
+{
+ tauri::async_runtime::spawn_blocking(move || {
let docs = documents_handle();
let gpu_active = native_engine::is_active();
let (target_ids, gpu_thumb_ids): (Vec<String>, HashSet<String>) = {
@@ -1103,69 +1217,138 @@ pub fn spawn_thumbnail_generation(
}
}
- let updates: Vec<ThumbnailUpdate> = {
+ struct ThumbLayerSnapshot {
+ layer_id: String,
+ layer_version: u64,
+ has_tiles: bool,
+ tiles: HashMap<TileCoord, Arc<TileData>>,
+ tint: Option<([u8; 4], [u8; 4])>,
+ has_mask: bool,
+ mask_tiles: HashMap<TileCoord, Arc<TileData>>,
+ mask_default_value: u8,
+ }
+
+ // Microsecond zero-copy Arc<TileData> snapshot under docs.read(); release guard
+ // BEFORE Rayon CPU thumbnail rendering and PNG encoding!
+ let (dims, scratch, layer_snaps): (
+ CanvasDimensions,
+ Arc<dyn ScratchBackend>,
+ Vec<ThumbLayerSnapshot>,
+ ) = {
let mgr = docs.read();
- let scratch = mgr.scratch_backend();
+ let scratch = Arc::clone(mgr.scratch_backend());
let Some(doc) = mgr.get_document(&doc_id) else {
return;
};
let dims = doc.dimensions;
- target_ids
- .into_par_iter()
+ let snaps = target_ids
+ .into_iter()
.filter_map(|lid| {
let node = doc.layer(&lid)?;
- let thumb = if node.meta.layer_type.has_tiles() {
- gpu_rendered.get(&lid).cloned().or_else(|| {
- render_layer_thumb_url(
- node,
- dims.width,
- dims.height,
- Some(scratch.as_ref()),
- )
- })
- } else {
- None
- };
- let mask_thumb = if node.grid.has_mask {
- render_mask_thumb_url(node, dims.width, dims.height, Some(scratch.as_ref()))
- } else {
- None
- };
- if thumb.is_none() && mask_thumb.is_none() {
- return None;
- }
- Some(ThumbnailUpdate {
+ let has_tiles = node.meta.layer_type.has_tiles();
+ let need_cpu_tiles = has_tiles && !gpu_rendered.contains_key(&lid);
+ Some(ThumbLayerSnapshot {
layer_id: lid,
- thumbnail_url: thumb,
- mask_thumbnail_url: mask_thumb,
+ layer_version: node.grid.layer_version,
+ has_tiles,
+ tiles: if need_cpu_tiles {
+ node.grid.tiles.clone()
+ } else {
+ HashMap::new()
+ },
+ tint: if need_cpu_tiles {
+ compositor_cpu::extract_layer_tint(node)
+ } else {
+ None
+ },
+ has_mask: node.grid.has_mask,
+ mask_tiles: if node.grid.has_mask {
+ node.grid.mask_tiles.clone()
+ } else {
+ HashMap::new()
+ },
+ mask_default_value: node.grid.mask_default_value,
})
})
- .collect()
+ .collect();
+ (dims, scratch, snaps)
};
- if updates.is_empty() {
+ let updates_with_ver: Vec<(u64, ThumbnailUpdate)> = layer_snaps
+ .into_par_iter()
+ .filter_map(|snap| {
+ let thumb = if snap.has_tiles {
+ gpu_rendered.get(&snap.layer_id).cloned().or_else(|| {
+ compositor_cpu::render_layer_thumbnail_rgba_from_tiles(
+ &snap.tiles,
+ snap.tint,
+ dims.width,
+ dims.height,
+ 64,
+ 64,
+ Some(scratch.as_ref()),
+ )
+ .ok()
+ .and_then(|(tw, th, rgba)| encode_rgba8_to_png(tw, th, &rgba).ok())
+ .map(|png| png_bytes_to_data_url(&png))
+ })
+ } else {
+ None
+ };
+ let mask_thumb = if snap.has_mask {
+ compositor_cpu::render_mask_thumbnail_rgba_from_tiles(
+ &snap.mask_tiles,
+ snap.mask_default_value,
+ dims.width,
+ dims.height,
+ 64,
+ 64,
+ Some(scratch.as_ref()),
+ )
+ .ok()
+ .and_then(|(tw, th, rgba)| encode_rgba8_to_png(tw, th, &rgba).ok())
+ .map(|png| png_bytes_to_data_url(&png))
+ } else {
+ None
+ };
+ if thumb.is_none() && mask_thumb.is_none() {
+ return None;
+ }
+ Some((
+ snap.layer_version,
+ ThumbnailUpdate {
+ layer_id: snap.layer_id,
+ thumbnail_url: thumb,
+ mask_thumbnail_url: mask_thumb,
+ },
+ ))
+ })
+ .collect();
+
+ if updates_with_ver.is_empty() {
return;
}
- // Cache thumbnails on Document metadata as well
+ // Cache thumbnails on Document metadata as well (skip stale writes if layer changed)
{
let mut mgr = docs.write();
if let Some(doc) = mgr.get_document_mut(&doc_id) {
- for u in &updates {
+ for (ver, u) in &updates_with_ver {
if let Some(node) = doc.layer_mut(&u.layer_id) {
- if let Some(ref url) = u.thumbnail_url {
- node.meta.thumbnail_url = Some(url.clone());
- }
- if let Some(ref murl) = u.mask_thumbnail_url {
- node.meta.mask_thumbnail_url = Some(murl.clone());
+ if node.grid.layer_version == *ver {
+ if let Some(ref url) = u.thumbnail_url {
+ node.meta.thumbnail_url = Some(url.clone());
+ }
+ if let Some(ref murl) = u.mask_thumbnail_url {
+ node.meta.mask_thumbnail_url = Some(murl.clone());
+ }
}
}
}
}
}
- let _ = app.emit(
- native_engine::EVENT_THUMBNAILS,
- native_engine::NativeThumbnailsEventPayload { doc_id, updates },
- );
+ let updates: Vec<ThumbnailUpdate> =
+ updates_with_ver.into_iter().map(|(_, u)| u).collect();
+ on_updates(doc_id, updates);
});
}
@@ -1183,24 +1366,28 @@ pub fn flatten_document_rgba(
}
}
- let docs = documents_handle();
- let mgr = docs.read();
- let scratch = mgr.scratch_backend();
- let doc = match doc_id.as_deref() {
- Some(id) => mgr.get_document(id),
- None => mgr.active_document(),
- }
- .ok_or_else(|| "Document not found for flatten".to_string())?;
+ let (snapshot, scratch) = {
+ let docs = documents_handle();
+ let mgr = docs.read();
+ let scratch = Arc::clone(mgr.scratch_backend());
+ let doc = match doc_id.as_deref() {
+ Some(id) => mgr.get_document(id),
+ None => mgr.active_document(),
+ }
+ .ok_or_else(|| "Document not found for flatten".to_string())?;
+ (doc.clone_cow_snapshot(), scratch)
+ };
if let Some(max_dim) = options.max_dim {
compositor_cpu::composite_document_downscaled_rgba(
- doc,
+ &snapshot,
max_dim.max(1),
options.fill_white_background,
Some(scratch.as_ref()),
)
} else {
- let mut rgba = compositor_cpu::composite_document_full_rgba(doc, Some(scratch.as_ref()))?;
+ let mut rgba =
+ compositor_cpu::composite_document_full_rgba(&snapshot, Some(scratch.as_ref()))?;
if options.fill_white_background {
for px in rgba.as_chunks_mut::<4>().0 {
let a = px[3] as u32;
@@ -1211,7 +1398,7 @@ pub fn flatten_document_rgba(
px[3] = 255;
}
}
- Ok((doc.dimensions.width, doc.dimensions.height, rgba))
+ Ok((snapshot.dimensions.width, snapshot.dimensions.height, rgba))
}
}
@@ -1253,8 +1440,12 @@ pub fn import_image_as_layer(
let doc_h = doc_u32_h as i32;
let ox = offset_x.unwrap_or((doc_w - img_w as i32) / 2);
let oy = offset_y.unwrap_or((doc_h - img_h as i32) / 2);
- let meta = LayerNodeMeta::new_raster(layer_id.clone(), name);
- doc.add_layer(meta, Some(0), true, record_history);
+ let before_layers: Vec<LayerNodeMeta> =
+ doc.layers.iter().map(|l| l.meta.clone()).collect();
+ let before_active = doc.active_layer_id.clone();
+ let meta = LayerNodeMeta::new_raster(layer_id.clone(), name.clone());
+ doc.add_layer(meta, Some(0), true, false);
+ let mut after_grids = Vec::new();
if let Some(node) = doc.layer_mut(&layer_id) {
let rect = RectI32::new(ox, oy, img_w, img_h);
let _ = node.grid.write_rgba8_rect(&rgba, rect, 128, Some(scratch.as_ref()));
@@ -1264,6 +1455,20 @@ pub fn import_image_as_layer(
doc_u32_h,
Some(scratch.as_ref()),
);
+ after_grids.push((layer_id.clone(), node.grid.clone_cow()));
+ }
+ if record_history {
+ doc.record_tree_history(
+ "layer",
+ format!("Import {name}"),
+ Some(layer_id),
+ before_layers,
+ before_active,
+ Vec::new(),
+ after_grids,
+ Vec::new(),
+ None,
+ );
}
doc.snapshot_meta()
};
@@ -1396,6 +1601,23 @@ pub async fn capture_timelapse_frame(
})
}
+/// Snapshots the document under a microsecond `docs.read()` guard, releases the lock immediately,
+/// and encodes the crash-recovery checkpoint completely lock-free.
+pub(crate) fn encode_recovery_checkpoint_from_docs(
+ docs: &RwLock<DocumentManager>,
+ doc_id: &str,
+) -> Result<(String, Vec<u8>, Vec<u8>), String> {
+ let (snapshot, scratch) = {
+ let mgr = docs.read();
+ let scratch = Arc::clone(mgr.scratch_backend());
+ let doc = mgr
+ .get_document(doc_id)
+ .ok_or_else(|| format!("Document not found: {doc_id}"))?;
+ (doc.clone_cow_snapshot(), scratch)
+ };
+ encode_document_checkpoint(&snapshot, Some(scratch.as_ref()))
+}
+
/// Writes an atomic crash-recovery checkpoint (`INKG v1` base snapshot + manifest + PNG thumbnail)
/// directly from the Rust `Document` into `src-tauri/src/recovery.rs` (zero JS pixel IPC!).
pub async fn recovery_checkpoint_document(
@@ -1407,12 +1629,7 @@ pub async fn recovery_checkpoint_document(
let (generated_manifest, snapshot_bytes, thumb_png) =
tokio::task::spawn_blocking(move || -> Result<(String, Vec<u8>, Vec<u8>), String> {
let docs = documents_handle();
- let mgr = docs.read();
- let scratch = mgr.scratch_backend();
- let doc = mgr
- .get_document(&doc_id)
- .ok_or_else(|| format!("Document not found: {doc_id}"))?;
- encode_document_checkpoint(doc, Some(scratch.as_ref()))
+ encode_recovery_checkpoint_from_docs(&docs, &doc_id)
})
.await
.map_err(|e| format!("Recovery checkpoint worker failed: {e}"))??;
@@ -1625,4 +1842,237 @@ mod tests {
.expect("reloaded read failed");
assert_eq!(reloaded_px, [240, 20, 10, 200]);
}
+
+ #[test]
+ fn test_spawn_thumbnail_generation_safe_outside_tokio_runtime() {
+ // Confirm this test thread has NO active Tokio runtime context (matching synchronous
+ // #[tauri::command] handlers called inline inside WebView2's COM callback).
+ assert!(tokio::runtime::Handle::try_current().is_err());
+
+ let doc_id = "doc-thumb-sync-test".to_string();
+ let layer_id = {
+ let docs = documents_handle();
+ let mut mgr = docs.write();
+ let snap = mgr.create_document(
+ doc_id.clone(),
+ "ThumbTest".to_string(),
+ CanvasDimensions {
+ width: 64,
+ height: 64,
+ dpi: 300,
+ },
+ CanvasColorMode::Color,
+ "#ffffff",
+ 60.0,
+ );
+ // Pick the solid-filled Background layer so a non-empty PNG thumbnail is produced
+ snap.layers
+ .last()
+ .expect("blank doc should have background layer")
+ .id
+ .clone()
+ };
+
+ let (tx, rx) = std::sync::mpsc::channel();
+ spawn_thumbnail_generation_with_sink(
+ doc_id.clone(),
+ vec![layer_id.clone()],
+ move |id, updates| {
+ let _ = tx.send((id, updates));
+ },
+ );
+
+ let (emitted_doc_id, updates) = rx
+ .recv_timeout(std::time::Duration::from_secs(5))
+ .expect("thumbnail worker did not complete");
+ assert_eq!(emitted_doc_id, doc_id);
+ assert_eq!(updates.len(), 1);
+ assert_eq!(updates[0].layer_id, layer_id);
+ assert!(updates[0]
+ .thumbnail_url
+ .as_deref()
+ .is_some_and(|u| u.starts_with("data:image/png;base64,")));
+
+ // Clean up temporary document from fallback store
+ let docs = documents_handle();
+ let _ = docs.write().close_document(&doc_id);
+ }
+
+ struct BlockingTestScratch {
+ store: Mutex<HashMap<(String, String, i32, i32), Vec<u8>>>,
+ entered_tx: Mutex<Option<std::sync::mpsc::Sender<()>>>,
+ release_rx: Mutex<Option<std::sync::mpsc::Receiver<()>>>,
+ }
+
+ impl BlockingTestScratch {
+ fn new(
+ entered_tx: std::sync::mpsc::Sender<()>,
+ release_rx: std::sync::mpsc::Receiver<()>,
+ ) -> Self {
+ Self {
+ store: Mutex::new(HashMap::new()),
+ entered_tx: Mutex::new(Some(entered_tx)),
+ release_rx: Mutex::new(Some(release_rx)),
+ }
+ }
+ }
+
+ impl ScratchBackend for BlockingTestScratch {
+ fn init_session(&self, _session_id: &str) -> Result<(), String> {
+ Ok(())
+ }
+ fn write_tiles(
+ &self,
+ session_id: &str,
+ tiles: Vec<ScratchTileWrite>,
+ ) -> Result<usize, String> {
+ let mut g = self.store.lock().unwrap();
+ let n = tiles.len();
+ for t in tiles {
+ g.insert((session_id.to_string(), t.layer_key, t.tx, t.ty), t.data);
+ }
+ Ok(n)
+ }
+ fn read_tile(
+ &self,
+ session_id: &str,
+ layer_key: &str,
+ tx: i32,
+ ty: i32,
+ ) -> Result<Vec<u8>, String> {
+ // Pause on the first tile read so the test thread can deterministically verify
+ // that `docs.write()` is NOT blocked during checkpoint / `.ink` ZIP encoding!
+ let entered = self.entered_tx.lock().unwrap().take();
+ let release = self.release_rx.lock().unwrap().take();
+ if let Some(etx) = entered {
+ let _ = etx.send(());
+ }
+ if let Some(rrx) = release {
+ let _ = rrx.recv_timeout(std::time::Duration::from_secs(5));
+ }
+ let g = self.store.lock().unwrap();
+ g.get(&(session_id.to_string(), layer_key.to_string(), tx, ty))
+ .cloned()
+ .ok_or_else(|| "missing scratch tile".to_string())
+ }
+ fn clear_session(&self, _session_id: &str) -> Result<(), String> {
+ Ok(())
+ }
+ }
+
+ fn make_doc_with_paged_tile(
+ scratch: Arc<dyn ScratchBackend>,
+ doc_id: &str,
+ ) -> Arc<RwLock<DocumentManager>> {
+ let mgr_arc = Arc::new(RwLock::new(DocumentManager::new(
+ MemoryBudgetConfig::default(),
+ Arc::clone(&scratch),
+ )));
+ {
+ let mut mgr = mgr_arc.write();
+ mgr.create_document(
+ doc_id.to_string(),
+ "LockFreeTest".to_string(),
+ CanvasDimensions {
+ width: 256,
+ height: 256,
+ dpi: 300,
+ },
+ CanvasColorMode::Color,
+ "#ffffff",
+ 60.0,
+ );
+ let doc = mgr.get_document_mut(doc_id).unwrap();
+ let layer = &mut doc.layers[0];
+ // Create a non-solid raw tile and demote it to PagedToDisk so serialization triggers `read_tile`
+ let mut raw = vec![0u8; 256 * 256 * 4];
+ raw[0..4].copy_from_slice(&[200, 40, 20, 255]);
+ raw[4..8].copy_from_slice(&[10, 180, 90, 255]);
+ let mut td = TileData::from_raw_auto_compact(
+ TileFormat::Color32Bit,
+ TileKind::Raster,
+ raw,
+ );
+ td.demote_to_disk(
+ doc_id,
+ &layer.meta.id,
+ TileCoord::new(0, 0),
+ scratch.as_ref(),
+ )
+ .expect("demote_to_disk failed");
+ layer.grid.set_tile(TileCoord::new(0, 0), Arc::new(td));
+ }
+ mgr_arc
+ }
+
+ #[test]
+ fn test_recovery_checkpoint_releases_doc_read_lock_before_deflate() {
+ let (entered_tx, entered_rx) = std::sync::mpsc::channel();
+ let (release_tx, release_rx) = std::sync::mpsc::channel();
+ let scratch: Arc<dyn ScratchBackend> =
+ Arc::new(BlockingTestScratch::new(entered_tx, release_rx));
+ let docs = make_doc_with_paged_tile(scratch, "doc-wal-lockfree");
+
+ let docs_worker = Arc::clone(&docs);
+ let handle = std::thread::spawn(move || {
+ encode_recovery_checkpoint_from_docs(&docs_worker, "doc-wal-lockfree")
+ });
+
+ // Wait until worker is actively inside `encode_document_checkpoint` (reading & deflating tiles)
+ entered_rx
+ .recv_timeout(std::time::Duration::from_secs(5))
+ .expect("worker never reached tile materialization");
+
+ // Concurrent `docs.write()` MUST succeed immediately without blocking!
+ let write_guard = docs.try_write();
+ assert!(
+ write_guard.is_some(),
+ "docs.write() was blocked while recovery checkpoint compression was running!"
+ );
+ drop(write_guard);
+
+ let _ = release_tx.send(());
+ let (manifest_json, snapshot_bytes, thumb_png) = handle
+ .join()
+ .expect("worker panicked")
+ .expect("checkpoint failed");
+ assert!(!manifest_json.is_empty());
+ assert!(!snapshot_bytes.is_empty());
+ assert!(!thumb_png.is_empty());
+ }
+
+ #[test]
+ fn test_serialize_document_ink_releases_doc_read_lock_before_zip() {
+ let (entered_tx, entered_rx) = std::sync::mpsc::channel();
+ let (release_tx, release_rx) = std::sync::mpsc::channel();
+ let scratch: Arc<dyn ScratchBackend> =
+ Arc::new(BlockingTestScratch::new(entered_tx, release_rx));
+ let docs = make_doc_with_paged_tile(scratch, "doc-ink-lockfree");
+
+ let docs_worker = Arc::clone(&docs);
+ let handle = std::thread::spawn(move || {
+ serialize_document_ink_from_docs(&docs_worker, "doc-ink-lockfree")
+ });
+
+ // Wait until worker is actively inside `serialize_ink_document`
+ entered_rx
+ .recv_timeout(std::time::Duration::from_secs(5))
+ .expect("worker never reached tile materialization");
+
+ // Concurrent `docs.write()` MUST succeed immediately without blocking!
+ let write_guard = docs.try_write();
+ assert!(
+ write_guard.is_some(),
+ "docs.write() was blocked while .ink ZIP serialization was running!"
+ );
+ drop(write_guard);
+
+ let _ = release_tx.send(());
+ let saved = handle
+ .join()
+ .expect("worker panicked")
+ .expect("serialize_document_ink failed");
+ assert!(!saved.bytes.is_empty());
+ assert!(saved.tile_count >= 1);
+ }
}
diff --git a/src-tauri/src/native_engine.rs b/src-tauri/src/native_engine.rs
index de4b939..690bdff 100644
--- a/src-tauri/src/native_engine.rs
+++ b/src-tauri/src/native_engine.rs
@@ -90,6 +90,7 @@ pub const EVENT_HISTORY: &str = "native-engine://history";
pub const EVENT_THUMBNAILS: &str = "native-engine://thumbnails";
pub const EVENT_STROKE_COMMITTED: &str = "native-engine://stroke-committed";
pub const EVENT_SELECTION_CHANGED: &str = "native-engine://selection-changed";
+pub const EVENT_VIEWPORT_INVALIDATED: &str = "native-engine://viewport-invalidated";
static FALLBACK_RETOUCH_SESSION: LazyLock<Arc<Mutex<RetouchSession>>> =
LazyLock::new(|| Arc::new(Mutex::new(RetouchSession::default())));
@@ -108,35 +109,37 @@ mod win_host {
use std::sync::{mpsc, Arc, LazyLock, Mutex};
use std::thread::JoinHandle;
use tauri::Emitter;
- use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, POINT, WPARAM};
+ use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, POINT, RECT, WPARAM};
use windows_sys::Win32::Graphics::Gdi::ScreenToClient;
use windows_sys::Win32::System::Threading::{
GetCurrentThread, GetCurrentThreadId, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL,
};
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
- GetAsyncKeyState, VK_CONTROL, VK_SHIFT, VK_SPACE,
+ GetAsyncKeyState, VK_CONTROL, VK_LBUTTON, VK_MBUTTON, VK_MENU, VK_RBUTTON, VK_SHIFT,
+ VK_SPACE,
};
use windows_sys::Win32::UI::Shell::{
DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass,
};
use windows_sys::Win32::UI::WindowsAndMessaging::{
- CallNextHookEx, DispatchMessageW, GetAncestor, GetForegroundWindow, GetMessageW,
- PostThreadMessageW, SetWindowsHookExW, TranslateMessage, UnhookWindowsHookEx,
- WindowFromPoint, GA_ROOT, HHOOK, MSG, MSLLHOOKSTRUCT, SIZE_MINIMIZED, WH_MOUSE_LL,
- WM_DESTROY, WM_DISPLAYCHANGE, WM_DPICHANGED, WM_LBUTTONDOWN, WM_LBUTTONUP,
- WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MOUSEHWHEEL, WM_MOUSEMOVE, WM_MOUSEWHEEL, WM_QUIT,
- WM_SIZE,
+ CallNextHookEx, DispatchMessageW, GetAncestor, GetClientRect, GetForegroundWindow,
+ GetMessageW, GetSystemMetrics, IsWindow, PostThreadMessageW, SetWindowsHookExW,
+ TranslateMessage, UnhookWindowsHookEx, WindowFromPoint, GA_ROOT, HHOOK, MSG,
+ MSLLHOOKSTRUCT, SIZE_MINIMIZED, SM_SWAPBUTTON, WA_INACTIVE, WH_MOUSE_LL, WM_ACTIVATE,
+ WM_ACTIVATEAPP, WM_APP, WM_CANCELMODE, WM_CAPTURECHANGED, WM_DISPLAYCHANGE,
+ WM_DPICHANGED, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP,
+ WM_MOUSEHWHEEL, WM_MOUSEMOVE, WM_MOUSEWHEEL, WM_NCDESTROY, WM_QUIT, WM_SIZE,
};
const LIFECYCLE_SUBCLASS_ID: usize = 0x494E_4B45; // "INKE"
+ const WM_APP_RESET_MOUSE_STATE: u32 = WM_APP + 1;
const MI_WP_SIGNATURE: usize = 0xFF51_5700;
const MI_WP_MASK: usize = 0xFFFF_FF00;
const WHEEL_DELTA_NORM: f32 = 100.0 / 120.0;
struct NativeEngineRuntime {
dcomp: Arc<DCompHost>,
- engine: EngineHandle,
- hit_test: SharedHitTest,
+ engine: Arc<EngineHandle>,
main_hwnd: isize,
composition_mode: String,
event_thread: Option<JoinHandle<()>>,
@@ -152,10 +155,13 @@ mod win_host {
static WINDOW_MINIMIZED: AtomicBool = AtomicBool::new(false);
static MOUSE_HOOK_THREAD_ID: AtomicU32 = AtomicU32::new(0);
static MOUSE_HOOK_RUNNING: AtomicBool = AtomicBool::new(false);
+ static MOUSE_STATE_RESET_REQUESTED: AtomicBool = AtomicBool::new(false);
- // Non-blocking handles mirrored for the dedicated WH_MOUSE_LL hook thread
+ // Non-blocking handles mirrored for the dedicated WH_MOUSE_LL hook thread & background tasks
static HOOK_HIT_TEST: LazyLock<Mutex<Option<SharedHitTest>>> =
LazyLock::new(|| Mutex::new(None));
+ static STROKE_ACTIVE_FLAG: LazyLock<parking_lot::RwLock<Option<Arc<AtomicBool>>>> =
+ LazyLock::new(|| parking_lot::RwLock::new(None));
#[derive(Clone, Copy, PartialEq, Eq)]
enum ActiveNavButton {
@@ -168,7 +174,10 @@ mod win_host {
nav_tx: Option<NavRingProducer>,
hit_test: Option<SharedHitTest>,
nav_button: ActiveNavButton,
+ nav_down_ms: f64,
mouse_drawing: bool,
+ mouse_down_ms: f64,
+ last_mouse_phys: (f32, f32),
was_hovering_canvas: bool,
}
@@ -178,7 +187,10 @@ mod win_host {
nav_tx: None,
hit_test: None,
nav_button: ActiveNavButton::None,
+ nav_down_ms: 0.0,
mouse_drawing: false,
+ mouse_down_ms: 0.0,
+ last_mouse_phys: (0.0, 0.0),
was_hovering_canvas: false,
})
};
@@ -189,6 +201,62 @@ mod win_host {
unsafe { (GetAsyncKeyState(vk as i32) as u16 & 0x8000) != 0 }
}
+ #[inline]
+ fn is_primary_mouse_button_down() -> bool {
+ unsafe {
+ let vk = if GetSystemMetrics(SM_SWAPBUTTON) != 0 {
+ VK_RBUTTON
+ } else {
+ VK_LBUTTON
+ };
+ (GetAsyncKeyState(vk as i32) as u16 & 0x8000) != 0
+ }
+ }
+
+ fn request_mouse_hook_state_reset() {
+ MOUSE_STATE_RESET_REQUESTED.store(true, Ordering::Release);
+ let tid = MOUSE_HOOK_THREAD_ID.load(Ordering::Acquire);
+ if tid != 0 {
+ unsafe {
+ let _ = PostThreadMessageW(tid, WM_APP_RESET_MOUSE_STATE, 0, 0);
+ }
+ }
+ }
+
+ fn flush_reset_mouse_hook_local() {
+ MOUSE_HOOK_LOCAL.with(|cell| {
+ let mut st = cell.borrow_mut();
+ let now_ms = ink_engine::clock::now_ms();
+ let (px, py) = st.last_mouse_phys;
+ if st.mouse_drawing {
+ st.mouse_drawing = false;
+ if let Some(nav_tx) = st.nav_tx.as_mut() {
+ nav_tx.push(NativeNavEvent::MouseDraw {
+ phys_x: px,
+ phys_y: py,
+ phase: 3,
+ shift_held: false,
+ timestamp_ms: now_ms,
+ });
+ }
+ }
+ if st.nav_button != ActiveNavButton::None {
+ st.nav_button = ActiveNavButton::None;
+ if let Some(nav_tx) = st.nav_tx.as_mut() {
+ nav_tx.push(NativeNavEvent::GestureEnd {
+ timestamp_ms: now_ms,
+ });
+ }
+ }
+ if st.was_hovering_canvas {
+ st.was_hovering_canvas = false;
+ if let Some(nav_tx) = st.nav_tx.as_mut() {
+ nav_tx.push(NativeNavEvent::HoverLeave);
+ }
+ }
+ });
+ }
+
#[inline]
fn is_main_window_foreground(main_hwnd: HWND) -> bool {
unsafe {
@@ -225,8 +293,56 @@ mod win_host {
if (extra_info & MI_WP_MASK) == MI_WP_SIGNATURE {
return true;
}
- let last_stylus = tablet_input::last_stylus_activity_ms();
- last_stylus > 0.0 && (now_ms - last_stylus) < 120.0
+ if tablet_input::is_stylus_in_contact() {
+ return true;
+ }
+ // WinTab CXO_SYSTEM synthesizes Win32 mouse events without MI_WP_SIGNATURE while
+ // the stylus is in proximity; gate with the same 100ms window as `ink-engine`.
+ let last_wt = tablet_input::last_wintab_activity_ms();
+ last_wt > 0.0 && (now_ms - last_wt) < 100.0
+ }
+
+ /// Clamps a physical viewport rect strictly inside `main_hwnd`'s current client rect.
+ /// Returns `(clamped_viewport, has_nonempty_client_area)`.
+ fn clamp_viewport_to_client_rect(main_hwnd: HWND, vp: ViewportRect) -> (ViewportRect, bool) {
+ if main_hwnd.is_null() {
+ return (vp, vp.width_px > 0 && vp.height_px > 0);
+ }
+ let mut rc: RECT = unsafe { std::mem::zeroed() };
+ let ok = unsafe { GetClientRect(main_hwnd, &mut rc) } != 0;
+ if !ok {
+ return (vp, vp.width_px > 0 && vp.height_px > 0);
+ }
+ let client_w = (rc.right - rc.left).max(0);
+ let client_h = (rc.bottom - rc.top).max(0);
+ if client_w == 0 || client_h == 0 || vp.width_px == 0 || vp.height_px == 0 {
+ return (
+ ViewportRect {
+ x_px: 0,
+ y_px: 0,
+ width_px: 0,
+ height_px: 0,
+ dpr: vp.dpr,
+ },
+ false,
+ );
+ }
+ let x0 = vp.x_px.clamp(0, client_w);
+ let y0 = vp.y_px.clamp(0, client_h);
+ let x1 = vp.x_px.saturating_add(vp.width_px as i32).clamp(x0, client_w);
+ let y1 = vp.y_px.saturating_add(vp.height_px as i32).clamp(y0, client_h);
+ let w = (x1 - x0).max(0) as u32;
+ let h = (y1 - y0).max(0) as u32;
+ (
+ ViewportRect {
+ x_px: x0,
+ y_px: y0,
+ width_px: w,
+ height_px: h,
+ dpr: vp.dpr,
+ },
+ w > 0 && h > 0,
+ )
}
/// Low-level mouse hook callback running on dedicated high-priority `inkstudio-native-mouse`
@@ -241,47 +357,99 @@ mod win_host {
return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);
}
- let main_raw = MAIN_HWND_RAW.load(Ordering::Relaxed);
- if main_raw == 0 || WINDOW_MINIMIZED.load(Ordering::Relaxed) {
- return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);
- }
- let main_hwnd = main_raw as HWND;
- let ms = &*(l_param as *const MSLLHOOKSTRUCT);
- let msg = w_param as u32;
-
let consume = std::panic::catch_unwind(|| -> bool {
+ if MOUSE_STATE_RESET_REQUESTED.swap(false, Ordering::AcqRel) {
+ flush_reset_mouse_hook_local();
+ }
+
+ let main_raw = MAIN_HWND_RAW.load(Ordering::Relaxed);
+ if main_raw == 0 || l_param == 0 || WINDOW_MINIMIZED.load(Ordering::Relaxed) {
+ return false;
+ }
+ let main_hwnd = main_raw as HWND;
+ let ms = &*(l_param as *const MSLLHOOKSTRUCT);
+ let msg = w_param as u32;
+
MOUSE_HOOK_LOCAL.with(|cell| {
let mut st_ref = cell.borrow_mut();
let MouseHookLocal {
nav_tx,
hit_test,
nav_button,
+ nav_down_ms,
mouse_drawing,
+ mouse_down_ms,
+ last_mouse_phys,
was_hovering_canvas,
} = &mut *st_ref;
let (Some(nav_tx), Some(hit_test)) = (nav_tx.as_mut(), hit_test.as_ref()) else {
return false;
};
+ let has_active_capture = *nav_button != ActiveNavButton::None || *mouse_drawing;
+ if !has_active_capture && !is_main_window_foreground(main_hwnd) {
+ if *was_hovering_canvas {
+ *was_hovering_canvas = false;
+ nav_tx.push(NativeNavEvent::HoverLeave);
+ }
+ return false;
+ }
+
let now_ms = ink_engine::clock::now_ms();
let (px, py) = screen_to_client_phys(main_hwnd, ms.pt);
+ *last_mouse_phys = (px, py);
match msg {
WM_MOUSEMOVE => {
if *nav_button != ActiveNavButton::None {
+ let focus_lost = !is_main_window_foreground(main_hwnd);
+ let missed_release = (now_ms - *nav_down_ms) > 50.0
+ && match *nav_button {
+ ActiveNavButton::Middle => !is_vk_pressed(VK_MBUTTON),
+ ActiveNavButton::LeftSpaceNav => {
+ !is_primary_mouse_button_down()
+ && !tablet_input::is_stylus_in_contact()
+ }
+ ActiveNavButton::None => false,
+ };
+ if focus_lost || missed_release {
+ *nav_button = ActiveNavButton::None;
+ nav_tx.push(NativeNavEvent::GestureEnd {
+ timestamp_ms: now_ms,
+ });
+ return false;
+ }
nav_tx.push(NativeNavEvent::GestureMove {
phys_x: px,
phys_y: py,
- snap_15_deg: is_vk_pressed(VK_SHIFT),
+ // Alt or Ctrl snaps rotation to 15° (matching useCanvasNavigation.ts);
+ // Shift is the Rotate trigger itself (Space+Shift+Drag / Middle+Shift+Drag).
+ snap_15_deg: is_vk_pressed(VK_MENU) || is_vk_pressed(VK_CONTROL),
timestamp_ms: now_ms,
});
return false;
}
if *mouse_drawing {
+ let focus_lost = !is_main_window_foreground(main_hwnd);
+ let stylus_took_over = tablet_input::is_stylus_in_contact();
+ let missed_release =
+ (now_ms - *mouse_down_ms) > 50.0 && !is_primary_mouse_button_down();
+ if focus_lost || missed_release || stylus_took_over {
+ *mouse_drawing = false;
+ nav_tx.push(NativeNavEvent::MouseDraw {
+ phys_x: px,
+ phys_y: py,
+ phase: 3,
+ shift_held: false,
+ timestamp_ms: now_ms,
+ });
+ return false;
+ }
nav_tx.push(NativeNavEvent::MouseDraw {
phys_x: px,
phys_y: py,
phase: 2,
+ shift_held: is_vk_pressed(VK_SHIFT),
timestamp_ms: now_ms,
});
return false;
@@ -292,8 +460,8 @@ mod win_host {
if is_pen_or_touch_synthesized(ms.dwExtraInfo, now_ms) {
return false;
}
- let over_unoccluded = is_main_window_foreground(main_hwnd)
- && is_point_over_main_window(main_hwnd, ms.pt)
+ // Foreground already verified above when !has_active_capture.
+ let over_unoccluded = is_point_over_main_window(main_hwnd, ms.pt)
&& hit_test.try_is_unoccluded_canvas_point(px, py);
if over_unoccluded {
*was_hovering_canvas = true;
@@ -309,7 +477,7 @@ mod win_host {
false
}
WM_MOUSEWHEEL | WM_MOUSEHWHEEL => {
- if !is_main_window_foreground(main_hwnd)
+ if (has_active_capture && !is_main_window_foreground(main_hwnd))
|| !is_point_over_main_window(main_hwnd, ms.pt)
{
return false;
@@ -325,6 +493,18 @@ mod win_host {
if raw_delta == 0.0 {
return false;
}
+ // Cleanly commit any active mouse stroke before wheel zoom/scroll so it
+ // never resumes spuriously after navigation.
+ if *mouse_drawing {
+ *mouse_drawing = false;
+ nav_tx.push(NativeNavEvent::MouseDraw {
+ phys_x: px,
+ phys_y: py,
+ phase: 3,
+ shift_held: false,
+ timestamp_ms: now_ms,
+ });
+ }
let (delta_x, delta_y) = if msg == WM_MOUSEWHEEL {
(0.0, -raw_delta * WHEEL_DELTA_NORM)
} else {
@@ -342,14 +522,27 @@ mod win_host {
true
}
WM_MBUTTONDOWN => {
- if !is_main_window_foreground(main_hwnd)
+ if (has_active_capture && !is_main_window_foreground(main_hwnd))
|| !is_point_over_main_window(main_hwnd, ms.pt)
{
return false;
}
+ if *nav_button != ActiveNavButton::None {
+ return true;
+ }
if !hit_test.try_should_capture_native_nav(px, py) {
return false;
}
+ if *mouse_drawing {
+ *mouse_drawing = false;
+ nav_tx.push(NativeNavEvent::MouseDraw {
+ phys_x: px,
+ phys_y: py,
+ phase: 3,
+ shift_held: false,
+ timestamp_ms: now_ms,
+ });
+ }
let gesture = if is_vk_pressed(VK_SHIFT) {
NativeNavGesture::Rotate
} else if is_vk_pressed(VK_CONTROL) {
@@ -358,6 +551,7 @@ mod win_host {
NativeNavGesture::Pan
};
*nav_button = ActiveNavButton::Middle;
+ *nav_down_ms = now_ms;
nav_tx.push(NativeNavEvent::GestureStart {
gesture,
phys_x: px,
@@ -377,16 +571,29 @@ mod win_host {
false
}
WM_LBUTTONDOWN => {
- if !is_main_window_foreground(main_hwnd)
+ if (has_active_capture && !is_main_window_foreground(main_hwnd))
|| !is_point_over_main_window(main_hwnd, ms.pt)
{
return false;
}
+ if *nav_button != ActiveNavButton::None {
+ return true;
+ }
// Space + Left Drag -> native Pan / Shift+Rotate / Ctrl+ZoomDrag
if is_vk_pressed(VK_SPACE)
&& !hit_test.try_text_input_focused()
&& hit_test.try_should_capture_native_nav(px, py)
{
+ if *mouse_drawing {
+ *mouse_drawing = false;
+ nav_tx.push(NativeNavEvent::MouseDraw {
+ phys_x: px,
+ phys_y: py,
+ phase: 3,
+ shift_held: false,
+ timestamp_ms: now_ms,
+ });
+ }
let gesture = if is_vk_pressed(VK_CONTROL) {
NativeNavGesture::ZoomDrag
} else if is_vk_pressed(VK_SHIFT) {
@@ -395,6 +602,7 @@ mod win_host {
NativeNavGesture::Pan
};
*nav_button = ActiveNavButton::LeftSpaceNav;
+ *nav_down_ms = now_ms;
nav_tx.push(NativeNavEvent::GestureStart {
gesture,
phys_x: px,
@@ -404,16 +612,30 @@ mod win_host {
return true;
}
- // Mouse PoC stroke on unoccluded canvas (skip pen-synthesized clicks so
- // WinTab/Windows Ink remains sole owner of stylus strokes).
+ // Mouse stroke on unoccluded canvas (skip pen-synthesized clicks so
+ // WinTab/Windows Ink remains sole owner of stylus strokes, and skip Alt
+ // modifier drags like Alt+Click eyedropper / Ctrl+Alt brush resize).
if !is_pen_or_touch_synthesized(ms.dwExtraInfo, now_ms)
+ && !is_vk_pressed(VK_MENU)
&& hit_test.try_should_capture_native_stroke(px, py)
{
+ if *mouse_drawing {
+ *mouse_drawing = false;
+ nav_tx.push(NativeNavEvent::MouseDraw {
+ phys_x: px,
+ phys_y: py,
+ phase: 3,
+ shift_held: false,
+ timestamp_ms: now_ms,
+ });
+ }
*mouse_drawing = true;
+ *mouse_down_ms = now_ms;
nav_tx.push(NativeNavEvent::MouseDraw {
phys_x: px,
phys_y: py,
phase: 1,
+ shift_held: is_vk_pressed(VK_SHIFT),
timestamp_ms: now_ms,
});
// Do NOT swallow WM_LBUTTONDOWN here so DOM focus/blur & non-modal
@@ -435,6 +657,7 @@ mod win_host {
phys_x: px,
phys_y: py,
phase: 3,
+ shift_held: false,
timestamp_ms: now_ms,
});
}
@@ -473,7 +696,10 @@ mod win_host {
st.nav_tx = Some(nav_tx);
st.hit_test = Some(hit_test);
st.nav_button = ActiveNavButton::None;
+ st.nav_down_ms = 0.0;
st.mouse_drawing = false;
+ st.mouse_down_ms = 0.0;
+ st.last_mouse_phys = (0.0, 0.0);
st.was_hovering_canvas = false;
});
@@ -490,6 +716,11 @@ mod win_host {
let mut msg: MSG = std::mem::zeroed();
while GetMessageW(&mut msg, std::ptr::null_mut(), 0, 0) > 0 {
+ if msg.message == WM_APP_RESET_MOUSE_STATE {
+ MOUSE_STATE_RESET_REQUESTED.store(false, Ordering::Release);
+ flush_reset_mouse_hook_local();
+ continue;
+ }
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
@@ -497,12 +728,16 @@ mod win_host {
UnhookWindowsHookEx(hook);
MOUSE_HOOK_RUNNING.store(false, Ordering::SeqCst);
MOUSE_HOOK_THREAD_ID.store(0, Ordering::SeqCst);
+ MOUSE_STATE_RESET_REQUESTED.store(false, Ordering::SeqCst);
MOUSE_HOOK_LOCAL.with(|cell| {
let mut st = cell.borrow_mut();
st.nav_tx = None;
st.hit_test = None;
st.nav_button = ActiveNavButton::None;
+ st.nav_down_ms = 0.0;
st.mouse_drawing = false;
+ st.mouse_down_ms = 0.0;
+ st.last_mouse_phys = (0.0, 0.0);
st.was_hovering_canvas = false;
});
})
@@ -538,7 +773,7 @@ mod win_host {
/// Top-level `main_hwnd` Win32 lifecycle subclass: handles minimize/restore (`WM_SIZE`),
/// monitor DPI change (`WM_DPICHANGED`), display mode change (`WM_DISPLAYCHANGE`),
- /// and window teardown (`WM_DESTROY`).
+ /// and window teardown (`WM_NCDESTROY`).
unsafe extern "system" fn lifecycle_subclass_proc(
hwnd: HWND,
msg: u32,
@@ -549,43 +784,86 @@ mod win_host {
) -> LRESULT {
let _ = std::panic::catch_unwind(|| match msg {
WM_SIZE => {
- let minimized = wparam == SIZE_MINIMIZED as usize;
+ let client_w = (lparam & 0xFFFF) as u32;
+ let client_h = ((lparam >> 16) & 0xFFFF) as u32;
+ let minimized =
+ wparam == SIZE_MINIMIZED as usize || client_w == 0 || client_h == 0;
let prev = WINDOW_MINIMIZED.swap(minimized, Ordering::SeqCst);
- if let Ok(guard) = RUNTIME.try_lock() {
- if let Some(rt) = guard.as_ref() {
- if minimized && !prev {
- rt.engine.send_command(EngineCommand::SetVisible(false));
- let _ = rt.dcomp.set_canvas_viewport(0, 0, 0, 0, false);
- } else if !minimized && prev {
- let vp = rt.last_viewport;
- let vis = rt.ui_visible && vp.width_px > 0 && vp.height_px > 0;
- let _ = rt.dcomp.set_canvas_viewport(
- vp.x_px,
- vp.y_px,
- vp.width_px,
- vp.height_px,
- vis,
- );
- rt.engine.send_command(EngineCommand::SetVisible(vis));
- rt.engine
- .send_command(EngineCommand::NotifySurfaceInvalidated);
- } else if !minimized {
- rt.engine
- .send_command(EngineCommand::NotifySurfaceInvalidated);
- }
+ if minimized && !prev {
+ request_mouse_hook_state_reset();
+ let handles = RUNTIME.try_lock().ok().and_then(|guard| {
+ guard.as_ref().map(|rt| {
+ (
+ Arc::clone(&rt.dcomp),
+ Arc::clone(&rt.engine),
+ )
+ })
+ });
+ if let Some((dcomp, engine)) = handles {
+ engine.send_command(EngineCommand::SetVisible(false));
+ let _ = dcomp.set_canvas_viewport(0, 0, 0, 0, false);
}
+ } else if !minimized && prev {
+ let state = RUNTIME.try_lock().ok().and_then(|guard| {
+ guard.as_ref().map(|rt| {
+ (
+ Arc::clone(&rt.dcomp),
+ Arc::clone(&rt.engine),
+ rt.last_viewport,
+ rt.ui_visible,
+ )
+ })
+ });
+ if let Some((dcomp, engine, last_viewport, ui_visible)) = state {
+ let (clamped_vp, non_empty) =
+ clamp_viewport_to_client_rect(hwnd, last_viewport);
+ let vis = ui_visible && non_empty;
+ let _ = dcomp.stage_canvas_viewport(
+ clamped_vp.x_px,
+ clamped_vp.y_px,
+ clamped_vp.width_px,
+ clamped_vp.height_px,
+ vis,
+ );
+ engine.send_command(EngineCommand::SetViewport(clamped_vp));
+ engine.send_command(EngineCommand::SetVisible(vis));
+ engine.send_command(EngineCommand::NotifySurfaceInvalidated);
+ }
+ }
+ // Note: during normal non-minimized drag resizes, do NOT force-reconfigure
+ // the swapchain with stale old dimensions on every WM_SIZE pixel; React's
+ // ResizeObserver drives `set_viewport` with exact new physical bounds once/frame.
+ }
+ WM_CAPTURECHANGED | WM_CANCELMODE => {
+ request_mouse_hook_state_reset();
+ }
+ WM_ACTIVATE => {
+ if (wparam & 0xFFFF) == WA_INACTIVE as usize {
+ request_mouse_hook_state_reset();
+ }
+ }
+ WM_ACTIVATEAPP => {
+ if wparam == 0 {
+ request_mouse_hook_state_reset();
}
}
WM_DPICHANGED | WM_DISPLAYCHANGE => {
- if let Ok(guard) = RUNTIME.try_lock() {
- if let Some(rt) = guard.as_ref() {
- rt.engine
- .send_command(EngineCommand::NotifySurfaceInvalidated);
- }
+ let engine = RUNTIME
+ .try_lock()
+ .ok()
+ .and_then(|guard| guard.as_ref().map(|rt| Arc::clone(&rt.engine)));
+ if let Some(engine) = engine {
+ engine.send_command(EngineCommand::NotifySurfaceInvalidated);
}
}
- WM_DESTROY => {
+ WM_NCDESTROY => {
RemoveWindowSubclass(hwnd, Some(lifecycle_subclass_proc), uid_subclass);
+ let _ = MAIN_HWND_RAW.compare_exchange(
+ hwnd as isize,
+ 0,
+ Ordering::SeqCst,
+ Ordering::SeqCst,
+ );
}
_ => {}
});
@@ -653,6 +931,7 @@ mod win_host {
..EngineConfig::default()
};
let (engine, producers) = EngineHandle::spawn(target, engine_cfg)?;
+ *STROKE_ACTIVE_FLAG.write() = Some(engine.stroke_active_flag());
crate::native_docs::attach_engine_documents(engine.documents());
let hit_test = engine.hit_test();
@@ -758,6 +1037,9 @@ mod win_host {
NativeSelectionChangedPayload { doc_id, selection },
);
}
+ EngineEvent::ViewportInvalidated => {
+ let _ = app_handle.emit(EVENT_VIEWPORT_INVALIDATED, ());
+ }
}
}
})
@@ -766,8 +1048,7 @@ mod win_host {
if let Ok(mut guard) = RUNTIME.lock() {
*guard = Some(NativeEngineRuntime {
dcomp,
- engine,
- hit_test,
+ engine: Arc::new(engine),
main_hwnd: main_hwnd_raw,
composition_mode,
event_thread,
@@ -782,6 +1063,7 @@ mod win_host {
pub fn shutdown() {
ENGINE_ACTIVE.store(false, Ordering::SeqCst);
+ *STROKE_ACTIVE_FLAG.write() = None;
crate::native_docs::detach_engine_documents();
tablet_input::detach_engine_rings();
@@ -795,12 +1077,15 @@ mod win_host {
// 2. Remove main_hwnd lifecycle subclass
if rt.main_hwnd != 0 {
+ let hwnd = rt.main_hwnd as HWND;
unsafe {
- let _ = RemoveWindowSubclass(
- rt.main_hwnd as HWND,
- Some(lifecycle_subclass_proc),
- LIFECYCLE_SUBCLASS_ID,
- );
+ if IsWindow(hwnd) != 0 {
+ let _ = RemoveWindowSubclass(
+ hwnd,
+ Some(lifecycle_subclass_proc),
+ LIFECYCLE_SUBCLASS_ID,
+ );
+ }
}
}
@@ -822,36 +1107,55 @@ mod win_host {
ENGINE_ACTIVE.load(Ordering::Acquire)
}
+ pub fn is_stroke_active() -> bool {
+ STROKE_ACTIVE_FLAG
+ .read()
+ .as_ref()
+ .is_some_and(|flag| flag.load(Ordering::Acquire))
+ }
+
pub fn set_viewport(viewport: ViewportRect, visible: bool) -> Result<(), String> {
- let mut guard = RUNTIME
- .lock()
- .map_err(|_| "Native engine runtime lock poisoned".to_string())?;
- let Some(rt) = guard.as_mut() else {
- return Ok(());
+ let (main_hwnd, dcomp, engine) = {
+ let mut guard = RUNTIME
+ .lock()
+ .map_err(|_| "Native engine runtime lock poisoned".to_string())?;
+ let Some(rt) = guard.as_mut() else {
+ return Ok(());
+ };
+ rt.last_viewport = viewport;
+ rt.ui_visible = visible;
+ (
+ rt.main_hwnd,
+ Arc::clone(&rt.dcomp),
+ Arc::clone(&rt.engine),
+ )
};
- rt.last_viewport = viewport;
- rt.ui_visible = visible;
+
+ // Release RUNTIME before invoking Win32 (`GetClientRect`) / DirectComposition (`Commit`)
+ // to eliminate any main-thread re-entrant deadlock with `lifecycle_subclass_proc`.
+ let (clamped_vp, has_client_area) =
+ clamp_viewport_to_client_rect(main_hwnd as HWND, viewport);
let effective_visible =
- visible && !WINDOW_MINIMIZED.load(Ordering::Acquire) && viewport.width_px > 0 && viewport.height_px > 0;
- rt.dcomp.set_canvas_viewport(
- viewport.x_px,
- viewport.y_px,
- viewport.width_px,
- viewport.height_px,
+ visible && !WINDOW_MINIMIZED.load(Ordering::Acquire) && has_client_area;
+ // Stage DComp offset/clip update so it commits atomically on the render thread right
+ // after `surface.configure` / present (hiding commits immediately to avoid stale visual).
+ dcomp.stage_canvas_viewport(
+ clamped_vp.x_px,
+ clamped_vp.y_px,
+ clamped_vp.width_px,
+ clamped_vp.height_px,
effective_visible,
)?;
- rt.hit_test.set_viewport(viewport);
- rt.hit_test.set_visible(effective_visible);
- rt.engine.send_command(EngineCommand::SetViewport(viewport));
- rt.engine
- .send_command(EngineCommand::SetVisible(effective_visible));
+ // `EngineHandle::send_command` updates `SharedHitTest` once synchronously.
+ engine.send_command(EngineCommand::SetViewport(clamped_vp));
+ engine.send_command(EngineCommand::SetVisible(effective_visible));
Ok(())
}
pub fn set_occluded_rects(rects: Vec<UiRect>) {
if let Ok(guard) = RUNTIME.lock() {
if let Some(rt) = guard.as_ref() {
- rt.hit_test.set_occluded_rects(rects.clone());
+ // `EngineHandle::send_command` updates `SharedHitTest` once with zero Vec clone.
rt.engine
.send_command(EngineCommand::SetOccludedRects(rects));
}
@@ -1075,13 +1379,22 @@ mod win_host {
pub fn set_policy(policy: InteractionPolicy) {
if let Ok(guard) = RUNTIME.lock() {
if let Some(rt) = guard.as_ref() {
- rt.hit_test.set_policy(policy);
+ // `EngineHandle::send_command` updates `SharedHitTest` once synchronously.
rt.engine
.send_command(EngineCommand::SetInteractionPolicy(policy));
}
}
}
+ pub fn set_collab_points_enabled(enabled: bool) {
+ if let Ok(guard) = RUNTIME.lock() {
+ if let Some(rt) = guard.as_ref() {
+ rt.engine
+ .send_command(EngineCommand::SetCollabPointsEnabled(enabled));
+ }
+ }
+ }
+
pub fn clear_canvas() {
if let Ok(guard) = RUNTIME.lock() {
if let Some(rt) = guard.as_ref() {
@@ -1403,6 +1716,9 @@ mod win_host {
pub fn is_active() -> bool {
false
}
+ pub fn is_stroke_active() -> bool {
+ false
+ }
pub fn set_viewport(_viewport: ViewportRect, _visible: bool) -> Result<(), String> {
Ok(())
}
@@ -1453,6 +1769,7 @@ mod win_host {
) {
}
pub fn set_policy(_policy: InteractionPolicy) {}
+ pub fn set_collab_points_enabled(_enabled: bool) {}
pub fn clear_canvas() {}
pub fn sync_active_document() {}
pub fn set_vram_budget(_budget_bytes: u64) {}
@@ -1520,14 +1837,16 @@ mod win_host {
pub fn remote_notify_tile_delta(_layer_id: String) {}
}
+#[allow(unused_imports)]
pub use win_host::{
clean_dirty_brush, clear_canvas, clear_tool_preview, flush_gpu_pool, get_diagnostics,
- gpu_pool_stats, init_for_main_window, invalidate_compositor_cache, is_active, liquify_begin,
- liquify_cancel, liquify_commit, liquify_step, remote_notify_tile_delta, remote_peer_dispose,
- remote_stroke_chunk, remote_stroke_dispose, remote_stroke_finish, remote_stroke_start,
- render_brush_preview, render_document_flattened, render_layer_thumbnail_gpu, retouch_session,
- set_appearance, set_brush, set_camera, set_cursor, set_display_config, set_document,
- set_full_brush, set_mask_mode, set_occluded_rects, set_policy, set_pressure_curve, set_rulers,
+ gpu_pool_stats, init_for_main_window, invalidate_compositor_cache, is_active, is_stroke_active,
+ liquify_begin, liquify_cancel, liquify_commit, liquify_step, remote_notify_tile_delta,
+ remote_peer_dispose, remote_stroke_chunk, remote_stroke_dispose, remote_stroke_finish,
+ remote_stroke_start, render_brush_preview, render_document_flattened,
+ render_layer_thumbnail_gpu, retouch_session, set_appearance, set_brush, set_camera,
+ set_collab_points_enabled, set_cursor, set_display_config, set_document, set_full_brush,
+ set_mask_mode, set_occluded_rects, set_policy, set_pressure_curve, set_rulers,
set_tool_preview_rgba8, set_viewport, set_vram_budget, shutdown, sync_active_document,
transform_begin, transform_cancel, transform_commit, transform_switch_mode, transform_update,
upload_brush_texture,
diff --git a/src-tauri/src/native_tools.rs b/src-tauri/src/native_tools.rs
index 3794a37..aeb7867 100644
--- a/src-tauri/src/native_tools.rs
+++ b/src-tauri/src/native_tools.rs
@@ -26,7 +26,8 @@ use ink_engine::tiles::{parse_hex_rgba8, RectI32, TileCoord};
use ink_engine::tools::{
apply_image_op_to_document, commit_gradient_to_document, commit_shape_to_document,
compute_layer_histogram, enclose_and_fill_document, flood_fill_document, lasso_fill_document,
- paint_unfilled_document, pick_color_document, rasterize_bezier_path, rasterize_vector_layer,
+ paint_unfilled_document, pick_color_document_for_layer, rasterize_bezier_path,
+ rasterize_vector_layer,
recognize_quick_shape, render_gradient_rgba8, render_image_op_preview_rgba, render_shape_rgba8,
shape_bounds, BezierPathParams, EncloseFillParams, FillOutcome, FilterApplyResult,
FloodFillParams, GradientCommitResult, GradientParams, ImageOpSpec, LassoFillParams,
@@ -102,7 +103,7 @@ fn notify_after_doc_mutation(app: &tauri::AppHandle, doc_id: &str, dirty_layer_i
// ============================================================================
#[tauri::command]
-pub fn native_select_rect(
+pub async fn native_select_rect(
app: tauri::AppHandle,
doc_id: Option<String>,
x: i32,
@@ -111,51 +112,65 @@ pub fn native_select_rect(
height: u32,
mode: Option<SelectionCombineMode>,
) -> Result<SelectionMetaSnapshot, String> {
- let did = resolve_doc_id(doc_id.as_deref())?;
- let snap = {
- let docs = documents_handle();
- let mut mgr = docs.write();
- let doc = mgr
- .get_document_mut(&did)
- .ok_or_else(|| format!("Document not found: {did}"))?;
- let s = select_rect(
- doc,
- RectI32::new(x, y, width, height),
- mode.unwrap_or(SelectionCombineMode::Replace),
- );
- doc.dirty_for_render = true;
- s
- };
+ let (did, snap) = tauri::async_runtime::spawn_blocking(
+ move || -> Result<(String, SelectionMetaSnapshot), String> {
+ let did = resolve_doc_id(doc_id.as_deref())?;
+ let snap = {
+ let docs = documents_handle();
+ let mut mgr = docs.write();
+ let doc = mgr
+ .get_document_mut(&did)
+ .ok_or_else(|| format!("Document not found: {did}"))?;
+ let s = select_rect(
+ doc,
+ RectI32::new(x, y, width, height),
+ mode.unwrap_or(SelectionCombineMode::Replace),
+ );
+ doc.dirty_for_render = true;
+ s
+ };
+ Ok((did, snap))
+ },
+ )
+ .await
+ .map_err(|e| format!("Select rect worker failed: {e}"))??;
native_engine::sync_active_document();
emit_selection_event(&app, did, &snap);
Ok(snap)
}
#[tauri::command]
-pub fn native_select_lasso(
+pub async fn native_select_lasso(
app: tauri::AppHandle,
doc_id: Option<String>,
points: Vec<[f32; 2]>,
anti_alias: Option<bool>,
mode: Option<SelectionCombineMode>,
) -> Result<SelectionMetaSnapshot, String> {
- let did = resolve_doc_id(doc_id.as_deref())?;
- let poly: Vec<(f32, f32)> = points.into_iter().map(|p| (p[0], p[1])).collect();
- let snap = {
- let docs = documents_handle();
- let mut mgr = docs.write();
- let doc = mgr
- .get_document_mut(&did)
- .ok_or_else(|| format!("Document not found: {did}"))?;
- let s = select_lasso(
- doc,
- &poly,
- anti_alias.unwrap_or(true),
- mode.unwrap_or(SelectionCombineMode::Replace),
- );
- doc.dirty_for_render = true;
- s
- };
+ let (did, snap) = tauri::async_runtime::spawn_blocking(
+ move || -> Result<(String, SelectionMetaSnapshot), String> {
+ let did = resolve_doc_id(doc_id.as_deref())?;
+ let poly: Vec<(f32, f32)> = points.into_iter().map(|p| (p[0], p[1])).collect();
+ let snap = {
+ let docs = documents_handle();
+ let mut mgr = docs.write();
+ let doc = mgr
+ .get_document_mut(&did)
+ .ok_or_else(|| format!("Document not found: {did}"))?;
+ let s = select_lasso(
+ doc,
+ &poly,
+ anti_alias.unwrap_or(true),
+ mode.unwrap_or(SelectionCombineMode::Replace),
+ );
+ doc.dirty_for_render = true;
+ s
+ };
+ Ok((did, snap))
+ },
+ )
+ .await
+ .map_err(|e| format!("Select lasso worker failed: {e}"))??;
native_engine::sync_active_document();
emit_selection_event(&app, did, &snap);
Ok(snap)
@@ -174,29 +189,30 @@ pub async fn native_select_magic_wand(
refer_mode: Option<WandReferMode>,
mode: Option<SelectionCombineMode>,
) -> Result<SelectionMetaSnapshot, String> {
- let did = resolve_doc_id(doc_id.as_deref())?;
- let did_clone = did.clone();
- let snap = tokio::task::spawn_blocking(move || -> Result<SelectionMetaSnapshot, String> {
- let docs = documents_handle();
- let mut mgr = docs.write();
- let scratch = std::sync::Arc::clone(mgr.scratch_backend());
- let doc = mgr
- .get_document_mut(&did_clone)
- .ok_or_else(|| format!("Document not found: {did_clone}"))?;
- let s = select_magic_wand(
- doc,
- x,
- y,
- tolerance.unwrap_or(32.0),
- contiguous.unwrap_or(true),
- anti_alias.unwrap_or(true),
- refer_mode.unwrap_or(WandReferMode::Active),
- mode.unwrap_or(SelectionCombineMode::Replace),
- Some(scratch.as_ref()),
- )?;
- doc.dirty_for_render = true;
- Ok(s)
- })
+ let (did, snap) = tauri::async_runtime::spawn_blocking(
+ move || -> Result<(String, SelectionMetaSnapshot), String> {
+ let did = resolve_doc_id(doc_id.as_deref())?;
+ let docs = documents_handle();
+ let mut mgr = docs.write();
+ let scratch = std::sync::Arc::clone(mgr.scratch_backend());
+ let doc = mgr
+ .get_document_mut(&did)
+ .ok_or_else(|| format!("Document not found: {did}"))?;
+ let s = select_magic_wand(
+ doc,
+ x,
+ y,
+ tolerance.unwrap_or(32.0),
+ contiguous.unwrap_or(true),
+ anti_alias.unwrap_or(true),
+ refer_mode.unwrap_or(WandReferMode::Active),
+ mode.unwrap_or(SelectionCombineMode::Replace),
+ Some(scratch.as_ref()),
+ )?;
+ doc.dirty_for_render = true;
+ Ok((did, s))
+ },
+ )
.await
.map_err(|e| format!("Magic wand worker failed: {e}"))??;
native_engine::sync_active_document();
@@ -205,86 +221,106 @@ pub async fn native_select_magic_wand(
}
#[tauri::command]
-pub fn native_select_all(
+pub async fn native_select_all(
app: tauri::AppHandle,
doc_id: Option<String>,
) -> Result<SelectionMetaSnapshot, String> {
- let did = resolve_doc_id(doc_id.as_deref())?;
- let snap = {
- let docs = documents_handle();
- let mut mgr = docs.write();
- let doc = mgr
- .get_document_mut(&did)
- .ok_or_else(|| format!("Document not found: {did}"))?;
- let sel = SparseSelectionMask::new_all(doc.dimensions.width, doc.dimensions.height);
- let s = sel.snapshot_meta();
- doc.selection = Some(sel);
- doc.dirty_for_render = true;
- s
- };
+ let (did, snap) = tauri::async_runtime::spawn_blocking(
+ move || -> Result<(String, SelectionMetaSnapshot), String> {
+ let did = resolve_doc_id(doc_id.as_deref())?;
+ let snap = {
+ let docs = documents_handle();
+ let mut mgr = docs.write();
+ let doc = mgr
+ .get_document_mut(&did)
+ .ok_or_else(|| format!("Document not found: {did}"))?;
+ let sel = SparseSelectionMask::new_all(doc.dimensions.width, doc.dimensions.height);
+ let s = sel.snapshot_meta();
+ doc.selection = Some(sel);
+ doc.dirty_for_render = true;
+ s
+ };
+ Ok((did, snap))
+ },
+ )
+ .await
+ .map_err(|e| format!("Select all worker failed: {e}"))??;
native_engine::sync_active_document();
emit_selection_event(&app, did, &snap);
Ok(snap)
}
#[tauri::command]
-pub fn native_deselect(
+pub async fn native_deselect(
app: tauri::AppHandle,
doc_id: Option<String>,
) -> Result<SelectionMetaSnapshot, String> {
- let did = resolve_doc_id(doc_id.as_deref())?;
- let mut dirty_layers = Vec::new();
- {
- let docs = documents_handle();
- let mut mgr = docs.write();
- let scratch = std::sync::Arc::clone(mgr.scratch_backend());
- let doc = mgr
- .get_document_mut(&did)
- .ok_or_else(|| format!("Document not found: {did}"))?;
- if let Some(ref sel) = doc.selection {
- if let Some(ref fl) = sel.floating {
- dirty_layers.push(fl.layer_id.clone());
+ let app_for_worker = app.clone();
+ let did = tauri::async_runtime::spawn_blocking(move || -> Result<String, String> {
+ let did = resolve_doc_id(doc_id.as_deref())?;
+ let mut dirty_layers = Vec::new();
+ {
+ let docs = documents_handle();
+ let mut mgr = docs.write();
+ let scratch = std::sync::Arc::clone(mgr.scratch_backend());
+ let doc = mgr
+ .get_document_mut(&did)
+ .ok_or_else(|| format!("Document not found: {did}"))?;
+ if let Some(ref sel) = doc.selection {
+ if let Some(ref fl) = sel.floating {
+ dirty_layers.push(fl.layer_id.clone());
+ }
}
+ if !dirty_layers.is_empty() {
+ let _ = commit_floating_selection(doc, Some(scratch.as_ref()));
+ }
+ doc.selection = None;
+ doc.dirty_for_render = true;
}
- if !dirty_layers.is_empty() {
- let _ = commit_floating_selection(doc, Some(scratch.as_ref()));
- }
- doc.selection = None;
- doc.dirty_for_render = true;
- }
+ notify_after_doc_mutation(&app_for_worker, &did, dirty_layers);
+ Ok(did)
+ })
+ .await
+ .map_err(|e| format!("Deselect worker failed: {e}"))??;
let empty = SelectionMetaSnapshot::empty();
- notify_after_doc_mutation(&app, &did, dirty_layers);
emit_selection_event(&app, did, &empty);
Ok(empty)
}
#[tauri::command]
-pub fn native_selection_invert(
+pub async fn native_selection_invert(
app: tauri::AppHandle,
doc_id: Option<String>,
) -> Result<SelectionMetaSnapshot, String> {
- let did = resolve_doc_id(doc_id.as_deref())?;
- let snap = {
- let docs = documents_handle();
- let mut mgr = docs.write();
- let doc = mgr
- .get_document_mut(&did)
- .ok_or_else(|| format!("Document not found: {did}"))?;
- let w = doc.dimensions.width;
- let h = doc.dimensions.height;
- let sel = doc
- .selection
- .get_or_insert_with(|| SparseSelectionMask::new_empty(w, h));
- sel.invert();
- let s = if sel.is_empty() {
- doc.selection = None;
- SelectionMetaSnapshot::empty()
- } else {
- sel.snapshot_meta()
- };
- doc.dirty_for_render = true;
- s
- };
+ let (did, snap) = tauri::async_runtime::spawn_blocking(
+ move || -> Result<(String, SelectionMetaSnapshot), String> {
+ let did = resolve_doc_id(doc_id.as_deref())?;
+ let snap = {
+ let docs = documents_handle();
+ let mut mgr = docs.write();
+ let doc = mgr
+ .get_document_mut(&did)
+ .ok_or_else(|| format!("Document not found: {did}"))?;
+ let w = doc.dimensions.width;
+ let h = doc.dimensions.height;
+ let sel = doc
+ .selection
+ .get_or_insert_with(|| SparseSelectionMask::new_empty(w, h));
+ sel.invert();
+ let s = if sel.is_empty() {
+ doc.selection = None;
+ SelectionMetaSnapshot::empty()
+ } else {
+ sel.snapshot_meta()
+ };
+ doc.dirty_for_render = true;
+ s
+ };
+ Ok((did, snap))
+ },
+ )
+ .await
+ .map_err(|e| format!("Selection invert worker failed: {e}"))??;
native_engine::sync_active_document();
emit_selection_event(&app, did, &snap);
Ok(snap)
@@ -296,28 +332,29 @@ pub async fn native_selection_expand(
doc_id: Option<String>,
pixels: i32,
) -> Result<SelectionMetaSnapshot, String> {
- let did = resolve_doc_id(doc_id.as_deref())?;
- let did_clone = did.clone();
- let snap = tokio::task::spawn_blocking(move || -> Result<SelectionMetaSnapshot, String> {
- let docs = documents_handle();
- let mut mgr = docs.write();
- let doc = mgr
- .get_document_mut(&did_clone)
- .ok_or_else(|| format!("Document not found: {did_clone}"))?;
- let s = if let Some(ref mut sel) = doc.selection {
- sel.expand_or_contract(pixels);
- if sel.is_empty() {
- doc.selection = None;
- SelectionMetaSnapshot::empty()
+ let (did, snap) = tauri::async_runtime::spawn_blocking(
+ move || -> Result<(String, SelectionMetaSnapshot), String> {
+ let did = resolve_doc_id(doc_id.as_deref())?;
+ let docs = documents_handle();
+ let mut mgr = docs.write();
+ let doc = mgr
+ .get_document_mut(&did)
+ .ok_or_else(|| format!("Document not found: {did}"))?;
+ let s = if let Some(ref mut sel) = doc.selection {
+ sel.expand_or_contract(pixels);
+ if sel.is_empty() {
+ doc.selection = None;
+ SelectionMetaSnapshot::empty()
+ } else {
+ sel.snapshot_meta()
+ }
} else {
- sel.snapshot_meta()
- }
- } else {
- SelectionMetaSnapshot::empty()
- };
- doc.dirty_for_render = true;
- Ok(s)
- })
+ SelectionMetaSnapshot::empty()
+ };
+ doc.dirty_for_render = true;
+ Ok((did, s))
+ },
+ )
.await
.map_err(|e| format!("Selection expand worker failed: {e}"))??;
native_engine::sync_active_document();
@@ -331,28 +368,29 @@ pub async fn native_selection_feather(
doc_id: Option<String>,
radius: f32,
) -> Result<SelectionMetaSnapshot, String> {
- let did = resolve_doc_id(doc_id.as_deref())?;
- let did_clone = did.clone();
- let snap = tokio::task::spawn_blocking(move || -> Result<SelectionMetaSnapshot, String> {
- let docs = documents_handle();
- let mut mgr = docs.write();
- let doc = mgr
- .get_document_mut(&did_clone)
- .ok_or_else(|| format!("Document not found: {did_clone}"))?;
- let s = if let Some(ref mut sel) = doc.selection {
- sel.feather(radius);
- if sel.is_empty() {
- doc.selection = None;
- SelectionMetaSnapshot::empty()
+ let (did, snap) = tauri::async_runtime::spawn_blocking(
+ move || -> Result<(String, SelectionMetaSnapshot), String> {
+ let did = resolve_doc_id(doc_id.as_deref())?;
+ let docs = documents_handle();
+ let mut mgr = docs.write();
+ let doc = mgr
+ .get_document_mut(&did)
+ .ok_or_else(|| format!("Document not found: {did}"))?;
+ let s = if let Some(ref mut sel) = doc.selection {
+ sel.feather(radius);
+ if sel.is_empty() {
+ doc.selection = None;
+ SelectionMetaSnapshot::empty()
+ } else {
+ sel.snapshot_meta()
+ }
} else {
- sel.snapshot_meta()
- }
- } else {
- SelectionMetaSnapshot::empty()
- };
- doc.dirty_for_render = true;
- Ok(s)
- })
+ SelectionMetaSnapshot::empty()
+ };
+ doc.dirty_for_render = true;
+ Ok((did, s))
+ },
+ )
.await
.map_err(|e| format!("Selection feather worker failed: {e}"))??;
native_engine::sync_active_document();
@@ -361,284 +399,351 @@ pub async fn native_selection_feather(
}
#[tauri::command]
-pub fn native_selection_clear_pixels(
+pub async fn native_selection_clear_pixels(
app: tauri::AppHandle,
doc_id: Option<String>,
layer_id: Option<String>,
) -> Result<SelectionFillResult, String> {
- let did = resolve_doc_id(doc_id.as_deref())?;
- let (res, lid) = {
- let docs = documents_handle();
- let mut mgr = docs.write();
- let scratch = std::sync::Arc::clone(mgr.scratch_backend());
- let doc = mgr
- .get_document_mut(&did)
- .ok_or_else(|| format!("Document not found: {did}"))?;
- let lid = layer_id
- .or_else(|| doc.active_layer_id.clone())
- .ok_or_else(|| "No active layer".to_string())?;
- let r = clear_selection_pixels(doc, &lid, Some(scratch.as_ref()))?;
- (r, lid)
- };
- if res.modified {
- notify_after_doc_mutation(&app, &did, vec![lid]);
- }
- Ok(res)
+ tauri::async_runtime::spawn_blocking(move || -> Result<SelectionFillResult, String> {
+ let did = resolve_doc_id(doc_id.as_deref())?;
+ let (res, lid) = {
+ let docs = documents_handle();
+ let mut mgr = docs.write();
+ let scratch = std::sync::Arc::clone(mgr.scratch_backend());
+ let doc = mgr
+ .get_document_mut(&did)
+ .ok_or_else(|| format!("Document not found: {did}"))?;
+ let lid = layer_id
+ .or_else(|| doc.active_layer_id.clone())
+ .ok_or_else(|| "No active layer".to_string())?;
+ let r = clear_selection_pixels(doc, &lid, Some(scratch.as_ref()))?;
+ (r, lid)
+ };
+ if res.modified {
+ notify_after_doc_mutation(&app, &did, vec![lid]);
+ }
+ Ok(res)
+ })
+ .await
+ .map_err(|e| format!("Selection clear pixels worker failed: {e}"))?
}
#[tauri::command]
-pub fn native_selection_clear_outside(
+pub async fn native_selection_clear_outside(
app: tauri::AppHandle,
doc_id: Option<String>,
layer_id: Option<String>,
) -> Result<SelectionFillResult, String> {
- let did = resolve_doc_id(doc_id.as_deref())?;
- let (res, lid) = {
- let docs = documents_handle();
- let mut mgr = docs.write();
- let scratch = std::sync::Arc::clone(mgr.scratch_backend());
- let doc = mgr
- .get_document_mut(&did)
- .ok_or_else(|| format!("Document not found: {did}"))?;
- let lid = layer_id
- .or_else(|| doc.active_layer_id.clone())
- .ok_or_else(|| "No active layer".to_string())?;
- let r = clear_outside_selection(doc, &lid, Some(scratch.as_ref()))?;
- (r, lid)
- };
- if res.modified {
- notify_after_doc_mutation(&app, &did, vec![lid]);
- }
- Ok(res)
+ tauri::async_runtime::spawn_blocking(move || -> Result<SelectionFillResult, String> {
+ let did = resolve_doc_id(doc_id.as_deref())?;
+ let (res, lid) = {
+ let docs = documents_handle();
+ let mut mgr = docs.write();
+ let scratch = std::sync::Arc::clone(mgr.scratch_backend());
+ let doc = mgr
+ .get_document_mut(&did)
+ .ok_or_else(|| format!("Document not found: {did}"))?;
+ let lid = layer_id
+ .or_else(|| doc.active_layer_id.clone())
+ .ok_or_else(|| "No active layer".to_string())?;
+ let r = clear_outside_selection(doc, &lid, Some(scratch.as_ref()))?;
+ (r, lid)
+ };
+ if res.modified {
+ notify_after_doc_mutation(&app, &did, vec![lid]);
+ }
+ Ok(res)
+ })
+ .await
+ .map_err(|e| format!("Selection clear outside worker failed: {e}"))?
}
#[tauri::command]
-pub fn native_selection_fill_color(
+pub async fn native_selection_fill_color(
app: tauri::AppHandle,
doc_id: Option<String>,
layer_id: Option<String>,
color: String,
opacity: Option<f32>,
) -> Result<SelectionFillResult, String> {
- let did = resolve_doc_id(doc_id.as_deref())?;
- let rgba8 = parse_hex_rgba8(&color).unwrap_or([0, 0, 0, 255]);
- let (res, lid) = {
- let docs = documents_handle();
- let mut mgr = docs.write();
- let scratch = std::sync::Arc::clone(mgr.scratch_backend());
- let doc = mgr
- .get_document_mut(&did)
- .ok_or_else(|| format!("Document not found: {did}"))?;
- let lid = layer_id
- .or_else(|| doc.active_layer_id.clone())
- .ok_or_else(|| "No active layer".to_string())?;
- let r = fill_selection_color(doc, &lid, rgba8, opacity.unwrap_or(1.0), Some(scratch.as_ref()))?;
- (r, lid)
- };
- if res.modified {
- notify_after_doc_mutation(&app, &did, vec![lid]);
- }
- Ok(res)
-}
-
-#[tauri::command]
-pub fn native_selection_copy(
- doc_id: Option<String>,
- layer_id: Option<String>,
-) -> Result<bool, String> {
- let did = resolve_doc_id(doc_id.as_deref())?;
- let docs = documents_handle();
- let mut mgr = docs.write();
- let scratch = mgr.scratch_backend();
- let clip = {
- let doc = mgr
- .get_document(&did)
- .ok_or_else(|| format!("Document not found: {did}"))?;
- let lid = layer_id
- .or_else(|| doc.active_layer_id.clone())
- .ok_or_else(|| "No active layer".to_string())?;
- copy_selection(doc, &lid, Some(scratch.as_ref()))?
- };
- let ok = clip.is_some();
- if let Some(c) = clip {
- mgr.clipboard = Some(c);
- }
- Ok(ok)
+ tauri::async_runtime::spawn_blocking(move || -> Result<SelectionFillResult, String> {
+ let did = resolve_doc_id(doc_id.as_deref())?;
+ let rgba8 = parse_hex_rgba8(&color).unwrap_or([0, 0, 0, 255]);
+ let (res, lid) = {
+ let docs = documents_handle();
+ let mut mgr = docs.write();
+ let scratch = std::sync::Arc::clone(mgr.scratch_backend());
+ let doc = mgr
+ .get_document_mut(&did)
+ .ok_or_else(|| format!("Document not found: {did}"))?;
+ let lid = layer_id
+ .or_else(|| doc.active_layer_id.clone())
+ .ok_or_else(|| "No active layer".to_string())?;
+ let r = fill_selection_color(
+ doc,
+ &lid,
+ rgba8,
+ opacity.unwrap_or(1.0),
+ Some(scratch.as_ref()),
+ )?;
+ (r, lid)
+ };
+ if res.modified {
+ notify_after_doc_mutation(&app, &did, vec![lid]);
+ }
+ Ok(res)
+ })
+ .await
+ .map_err(|e| format!("Selection fill color worker failed: {e}"))?
}
#[tauri::command]
-pub fn native_selection_cut(
- app: tauri::AppHandle,
+pub async fn native_selection_copy(
doc_id: Option<String>,
layer_id: Option<String>,
) -> Result<bool, String> {
- let did = resolve_doc_id(doc_id.as_deref())?;
- let (ok, lid) = {
+ tauri::async_runtime::spawn_blocking(move || -> Result<bool, String> {
+ let did = resolve_doc_id(doc_id.as_deref())?;
let docs = documents_handle();
let mut mgr = docs.write();
- let scratch = std::sync::Arc::clone(mgr.scratch_backend());
- let (clip, lid) = {
+ let scratch = mgr.scratch_backend();
+ let clip = {
let doc = mgr
- .get_document_mut(&did)
+ .get_document(&did)
.ok_or_else(|| format!("Document not found: {did}"))?;
let lid = layer_id
.or_else(|| doc.active_layer_id.clone())
.ok_or_else(|| "No active layer".to_string())?;
- let c = cut_selection(doc, &lid, Some(scratch.as_ref()))?;
- (c, lid)
+ copy_selection(doc, &lid, Some(scratch.as_ref()))?
};
let ok = clip.is_some();
if let Some(c) = clip {
mgr.clipboard = Some(c);
}
- (ok, lid)
- };
- if ok {
- notify_after_doc_mutation(&app, &did, vec![lid]);
- }
- Ok(ok)
+ Ok(ok)
+ })
+ .await
+ .map_err(|e| format!("Selection copy worker failed: {e}"))?
+}
+
+#[tauri::command]
+pub async fn native_selection_cut(
+ app: tauri::AppHandle,
+ doc_id: Option<String>,
+ layer_id: Option<String>,
+) -> Result<bool, String> {
+ tauri::async_runtime::spawn_blocking(move || -> Result<bool, String> {
+ let did = resolve_doc_id(doc_id.as_deref())?;
+ let (ok, lid) = {
+ let docs = documents_handle();
+ let mut mgr = docs.write();
+ let scratch = std::sync::Arc::clone(mgr.scratch_backend());
+ let (clip, lid) = {
+ let doc = mgr
+ .get_document_mut(&did)
+ .ok_or_else(|| format!("Document not found: {did}"))?;
+ let lid = layer_id
+ .or_else(|| doc.active_layer_id.clone())
+ .ok_or_else(|| "No active layer".to_string())?;
+ let c = cut_selection(doc, &lid, Some(scratch.as_ref()))?;
+ (c, lid)
+ };
+ let ok = clip.is_some();
+ if let Some(c) = clip {
+ mgr.clipboard = Some(c);
+ }
+ (ok, lid)
+ };
+ if ok {
+ notify_after_doc_mutation(&app, &did, vec![lid]);
+ }
+ Ok(ok)
+ })
+ .await
+ .map_err(|e| format!("Selection cut worker failed: {e}"))?
}
#[tauri::command]
-pub fn native_selection_paste(
+pub async fn native_selection_paste(
app: tauri::AppHandle,
doc_id: Option<String>,
new_layer_id: String,
) -> Result<Option<DocumentMetaSnapshot>, String> {
- let did = resolve_doc_id(doc_id.as_deref())?;
- let (snap, pasted_id) = {
- let docs = documents_handle();
- let mut mgr = docs.write();
- let Some(clip) = mgr.clipboard.clone() else {
- return Ok(None);
- };
- let scratch = std::sync::Arc::clone(mgr.scratch_backend());
- let doc = mgr
- .get_document_mut(&did)
- .ok_or_else(|| format!("Document not found: {did}"))?;
- let lid = paste_selection(doc, &clip, new_layer_id, Some(scratch.as_ref()))?;
- (Some(doc.snapshot_meta()), Some(lid))
- };
- if let Some(lid) = pasted_id {
- notify_after_doc_mutation(&app, &did, vec![lid]);
- }
- Ok(snap)
+ tauri::async_runtime::spawn_blocking(
+ move || -> Result<Option<DocumentMetaSnapshot>, String> {
+ let did = resolve_doc_id(doc_id.as_deref())?;
+ let (snap, pasted_id) = {
+ let docs = documents_handle();
+ let mut mgr = docs.write();
+ let Some(clip) = mgr.clipboard.clone() else {
+ return Ok(None);
+ };
+ let scratch = std::sync::Arc::clone(mgr.scratch_backend());
+ let doc = mgr
+ .get_document_mut(&did)
+ .ok_or_else(|| format!("Document not found: {did}"))?;
+ let lid = paste_selection(doc, &clip, new_layer_id, Some(scratch.as_ref()))?;
+ (Some(doc.snapshot_meta()), Some(lid))
+ };
+ if let Some(lid) = pasted_id {
+ notify_after_doc_mutation(&app, &did, vec![lid]);
+ }
+ Ok(snap)
+ },
+ )
+ .await
+ .map_err(|e| format!("Selection paste worker failed: {e}"))?
}
#[tauri::command]
-pub fn native_selection_move_to_new_layer(
+pub async fn native_selection_move_to_new_layer(
app: tauri::AppHandle,
doc_id: Option<String>,
src_layer_id: Option<String>,
new_layer_id: String,
) -> Result<Option<DocumentMetaSnapshot>, String> {
- let did = resolve_doc_id(doc_id.as_deref())?;
- let (snap, dirty) = {
- let docs = documents_handle();
- let mut mgr = docs.write();
- let scratch = std::sync::Arc::clone(mgr.scratch_backend());
- let doc = mgr
- .get_document_mut(&did)
- .ok_or_else(|| format!("Document not found: {did}"))?;
- let src_id = src_layer_id
- .or_else(|| doc.active_layer_id.clone())
- .ok_or_else(|| "No active layer".to_string())?;
- let moved = move_selection_to_new_layer(doc, &src_id, new_layer_id, Some(scratch.as_ref()))?;
- if let Some(new_id) = moved {
- (Some(doc.snapshot_meta()), vec![src_id, new_id])
- } else {
- (None, Vec::new())
- }
- };
- if !dirty.is_empty() {
- notify_after_doc_mutation(&app, &did, dirty);
- }
- Ok(snap)
+ tauri::async_runtime::spawn_blocking(
+ move || -> Result<Option<DocumentMetaSnapshot>, String> {
+ let did = resolve_doc_id(doc_id.as_deref())?;
+ let (snap, dirty) = {
+ let docs = documents_handle();
+ let mut mgr = docs.write();
+ let scratch = std::sync::Arc::clone(mgr.scratch_backend());
+ let doc = mgr
+ .get_document_mut(&did)
+ .ok_or_else(|| format!("Document not found: {did}"))?;
+ let src_id = src_layer_id
+ .or_else(|| doc.active_layer_id.clone())
+ .ok_or_else(|| "No active layer".to_string())?;
+ let moved =
+ move_selection_to_new_layer(doc, &src_id, new_layer_id, Some(scratch.as_ref()))?;
+ if let Some(new_id) = moved {
+ (Some(doc.snapshot_meta()), vec![src_id, new_id])
+ } else {
+ (None, Vec::new())
+ }
+ };
+ if !dirty.is_empty() {
+ notify_after_doc_mutation(&app, &did, dirty);
+ }
+ Ok(snap)
+ },
+ )
+ .await
+ .map_err(|e| format!("Selection move to new layer worker failed: {e}"))?
}
#[tauri::command]
-pub fn native_selection_lift_floating(
+pub async fn native_selection_lift_floating(
app: tauri::AppHandle,
doc_id: Option<String>,
layer_id: Option<String>,
) -> Result<SelectionMetaSnapshot, String> {
- let did = resolve_doc_id(doc_id.as_deref())?;
- let snap = {
- let docs = documents_handle();
- let mut mgr = docs.write();
- let scratch = std::sync::Arc::clone(mgr.scratch_backend());
- let doc = mgr
- .get_document_mut(&did)
- .ok_or_else(|| format!("Document not found: {did}"))?;
- let lid = layer_id
- .or_else(|| doc.active_layer_id.clone())
- .ok_or_else(|| "No active layer".to_string())?;
- lift_floating_selection(doc, &lid, Some(scratch.as_ref()))?
- };
+ let (did, snap) = tauri::async_runtime::spawn_blocking(
+ move || -> Result<(String, SelectionMetaSnapshot), String> {
+ let did = resolve_doc_id(doc_id.as_deref())?;
+ let snap = {
+ let docs = documents_handle();
+ let mut mgr = docs.write();
+ let scratch = std::sync::Arc::clone(mgr.scratch_backend());
+ let doc = mgr
+ .get_document_mut(&did)
+ .ok_or_else(|| format!("Document not found: {did}"))?;
+ let lid = layer_id
+ .or_else(|| doc.active_layer_id.clone())
+ .ok_or_else(|| "No active layer".to_string())?;
+ lift_floating_selection(doc, &lid, Some(scratch.as_ref()))?
+ };
+ Ok((did, snap))
+ },
+ )
+ .await
+ .map_err(|e| format!("Selection lift floating worker failed: {e}"))??;
native_engine::sync_active_document();
emit_selection_event(&app, did, &snap);
Ok(snap)
}
#[tauri::command]
-pub fn native_selection_move_floating(
+pub async fn native_selection_move_floating(
app: tauri::AppHandle,
doc_id: Option<String>,
x: i32,
y: i32,
) -> Result<SelectionMetaSnapshot, String> {
- let did = resolve_doc_id(doc_id.as_deref())?;
- let snap = {
- let docs = documents_handle();
- let mut mgr = docs.write();
- let doc = mgr
- .get_document_mut(&did)
- .ok_or_else(|| format!("Document not found: {did}"))?;
- move_floating_selection(doc, x, y)
- };
+ let (did, snap) = tauri::async_runtime::spawn_blocking(
+ move || -> Result<(String, SelectionMetaSnapshot), String> {
+ let did = resolve_doc_id(doc_id.as_deref())?;
+ let snap = {
+ let docs = documents_handle();
+ let mut mgr = docs.write();
+ let doc = mgr
+ .get_document_mut(&did)
+ .ok_or_else(|| format!("Document not found: {did}"))?;
+ move_floating_selection(doc, x, y)
+ };
+ Ok((did, snap))
+ },
+ )
+ .await
+ .map_err(|e| format!("Selection move floating worker failed: {e}"))??;
native_engine::sync_active_document();
emit_selection_event(&app, did, &snap);
Ok(snap)
}
#[tauri::command]
-pub fn native_selection_commit_floating(
+pub async fn native_selection_commit_floating(
app: tauri::AppHandle,
doc_id: Option<String>,
) -> Result<SelectionMetaSnapshot, String> {
- let did = resolve_doc_id(doc_id.as_deref())?;
- let (snap, dirty) = {
- let docs = documents_handle();
- let mut mgr = docs.write();
- let scratch = std::sync::Arc::clone(mgr.scratch_backend());
- let doc = mgr
- .get_document_mut(&did)
- .ok_or_else(|| format!("Document not found: {did}"))?;
- let fl_layer = doc
- .selection
- .as_ref()
- .and_then(|s| s.floating.as_ref().map(|f| f.layer_id.clone()));
- let s = commit_floating_selection(doc, Some(scratch.as_ref()))?;
- (s, fl_layer.into_iter().collect::<Vec<_>>())
- };
- notify_after_doc_mutation(&app, &did, dirty);
+ let app_for_worker = app.clone();
+ let (did, snap) = tauri::async_runtime::spawn_blocking(
+ move || -> Result<(String, SelectionMetaSnapshot), String> {
+ let did = resolve_doc_id(doc_id.as_deref())?;
+ let (snap, dirty) = {
+ let docs = documents_handle();
+ let mut mgr = docs.write();
+ let scratch = std::sync::Arc::clone(mgr.scratch_backend());
+ let doc = mgr
+ .get_document_mut(&did)
+ .ok_or_else(|| format!("Document not found: {did}"))?;
+ let fl_layer = doc
+ .selection
+ .as_ref()
+ .and_then(|s| s.floating.as_ref().map(|f| f.layer_id.clone()));
+ let s = commit_floating_selection(doc, Some(scratch.as_ref()))?;
+ (s, fl_layer.into_iter().collect::<Vec<_>>())
+ };
+ notify_after_doc_mutation(&app_for_worker, &did, dirty);
+ Ok((did, snap))
+ },
+ )
+ .await
+ .map_err(|e| format!("Selection commit floating worker failed: {e}"))??;
emit_selection_event(&app, did, &snap);
Ok(snap)
}
#[tauri::command]
-pub fn native_selection_get_state(doc_id: Option<String>) -> Result<SelectionMetaSnapshot, String> {
- let did = resolve_doc_id(doc_id.as_deref())?;
- let docs = documents_handle();
- let mgr = docs.read();
- let doc = mgr
- .get_document(&did)
- .ok_or_else(|| format!("Document not found: {did}"))?;
- Ok(doc
- .selection
- .as_ref()
- .map(|s| s.snapshot_meta())
- .unwrap_or_else(SelectionMetaSnapshot::empty))
+pub async fn native_selection_get_state(
+ doc_id: Option<String>,
+) -> Result<SelectionMetaSnapshot, String> {
+ tauri::async_runtime::spawn_blocking(move || -> Result<SelectionMetaSnapshot, String> {
+ let did = resolve_doc_id(doc_id.as_deref())?;
+ let docs = documents_handle();
+ let mgr = docs.read();
+ let doc = mgr
+ .get_document(&did)
+ .ok_or_else(|| format!("Document not found: {did}"))?;
+ Ok(doc
+ .selection
+ .as_ref()
+ .map(|s| s.snapshot_meta())
+ .unwrap_or_else(SelectionMetaSnapshot::empty))
+ })
+ .await
+ .map_err(|e| format!("Selection get state worker failed: {e}"))?
}
// ============================================================================
@@ -792,27 +897,32 @@ pub async fn native_paint_unfilled_doc(
}
#[tauri::command]
-pub fn native_pick_color(
+pub async fn native_pick_color(
doc_id: Option<String>,
x: i32,
y: i32,
sample_all_layers: Option<bool>,
- _layer_id: Option<String>,
+ layer_id: Option<String>,
) -> Result<PickedColorDto, String> {
- let did = resolve_doc_id(doc_id.as_deref())?;
- let docs = documents_handle();
- let mgr = docs.read();
- let scratch = mgr.scratch_backend();
- let doc = mgr
- .get_document(&did)
- .ok_or_else(|| format!("Document not found: {did}"))?;
- Ok(pick_color_document(
- doc,
- x,
- y,
- sample_all_layers.unwrap_or(true),
- Some(scratch.as_ref()),
- ))
+ tauri::async_runtime::spawn_blocking(move || -> Result<PickedColorDto, String> {
+ let did = resolve_doc_id(doc_id.as_deref())?;
+ let docs = documents_handle();
+ let mgr = docs.read();
+ let scratch = mgr.scratch_backend();
+ let doc = mgr
+ .get_document(&did)
+ .ok_or_else(|| format!("Document not found: {did}"))?;
+ Ok(pick_color_document_for_layer(
+ doc,
+ x,
+ y,
+ sample_all_layers.unwrap_or(true),
+ layer_id.as_deref(),
+ Some(scratch.as_ref()),
+ ))
+ })
+ .await
+ .map_err(|e| format!("Pick color worker failed: {e}"))?
}
// ============================================================================
@@ -899,43 +1009,51 @@ pub async fn native_retouch_step(
}
#[tauri::command]
-pub fn native_retouch_commit(
+pub async fn native_retouch_commit(
app: tauri::AppHandle,
doc_id: Option<String>,
) -> Result<RetouchCommitResult, String> {
- let did = resolve_doc_id(doc_id.as_deref())?;
- let res = {
+ tauri::async_runtime::spawn_blocking(move || -> Result<RetouchCommitResult, String> {
+ let did = resolve_doc_id(doc_id.as_deref())?;
+ let res = {
+ let sess_arc = native_engine::retouch_session();
+ let mut sess = sess_arc
+ .lock()
+ .map_err(|_| "Retouch session lock poisoned".to_string())?;
+ let docs = documents_handle();
+ let mut mgr = docs.write();
+ let doc = mgr
+ .get_document_mut(&did)
+ .ok_or_else(|| format!("Document not found: {did}"))?;
+ sess.commit(doc)
+ };
+ if res.modified {
+ notify_after_doc_mutation(&app, &did, vec![res.layer_id.clone()]);
+ }
+ Ok(res)
+ })
+ .await
+ .map_err(|e| format!("Retouch commit worker failed: {e}"))?
+}
+
+#[tauri::command]
+pub async fn native_retouch_cancel(doc_id: Option<String>) -> Result<(), String> {
+ tauri::async_runtime::spawn_blocking(move || -> Result<(), String> {
+ let did = resolve_doc_id(doc_id.as_deref()).ok();
let sess_arc = native_engine::retouch_session();
let mut sess = sess_arc
.lock()
.map_err(|_| "Retouch session lock poisoned".to_string())?;
let docs = documents_handle();
let mut mgr = docs.write();
- let doc = mgr
- .get_document_mut(&did)
- .ok_or_else(|| format!("Document not found: {did}"))?;
- sess.commit(doc)
- };
- if res.modified {
- notify_after_doc_mutation(&app, &did, vec![res.layer_id.clone()]);
- }
- Ok(res)
-}
-
-#[tauri::command]
-pub fn native_retouch_cancel(doc_id: Option<String>) -> Result<(), String> {
- let did = resolve_doc_id(doc_id.as_deref()).ok();
- let sess_arc = native_engine::retouch_session();
- let mut sess = sess_arc
- .lock()
- .map_err(|_| "Retouch session lock poisoned".to_string())?;
- let docs = documents_handle();
- let mut mgr = docs.write();
- let doc_opt = did.as_deref().and_then(|id| mgr.get_document_mut(id));
- sess.cancel(doc_opt);
- drop(mgr);
- native_engine::sync_active_document();
- Ok(())
+ let doc_opt = did.as_deref().and_then(|id| mgr.get_document_mut(id));
+ sess.cancel(doc_opt);
+ drop(mgr);
+ native_engine::sync_active_document();
+ Ok(())
+ })
+ .await
+ .map_err(|e| format!("Retouch cancel worker failed: {e}"))?
}
// ============================================================================
@@ -1288,7 +1406,7 @@ pub async fn native_collab_encode_tiles(
/// Applies a single binary `CODE_TILE_DELTA` packet directly into Rust's `SparseLayerGrid`,
/// notifies the DX12 GPU remote draft manager for zero-flicker handoff, and triggers redraw!
#[tauri::command]
-pub fn native_collab_apply_tile_delta(
+pub async fn native_collab_apply_tile_delta(
app: tauri::AppHandle,
request: tauri::ipc::Request<'_>,
) -> Result<AppliedTileDeltaInfo, String> {
@@ -1312,24 +1430,28 @@ pub fn native_collab_apply_tile_delta(
.map(|s| s == "1" || s.eq_ignore_ascii_case("true"))
.unwrap_or(true);
let body = match request.body() {
- tauri::ipc::InvokeBody::Raw(bytes) => bytes.as_slice(),
+ tauri::ipc::InvokeBody::Raw(bytes) => bytes.to_vec(),
_ => return Err("Expected raw binary tile delta body".to_string()),
};
- let did = resolve_doc_id(doc_id_hdr.as_deref())?;
- let info = {
- let docs = documents_handle();
- let mut mgr = docs.write();
- let scratch = std::sync::Arc::clone(mgr.scratch_backend());
- let doc = mgr
- .get_document_mut(&did)
- .ok_or_else(|| format!("Document not found: {did}"))?;
- apply_tile_delta_packet(doc, &layer_id, body, bump_epoch, Some(scratch.as_ref()))?
- };
- native_engine::remote_notify_tile_delta(layer_id.clone());
- native_engine::sync_active_document();
- native_docs::spawn_thumbnail_generation(app, did, vec![layer_id]);
- Ok(info)
+ tauri::async_runtime::spawn_blocking(move || -> Result<AppliedTileDeltaInfo, String> {
+ let did = resolve_doc_id(doc_id_hdr.as_deref())?;
+ let info = {
+ let docs = documents_handle();
+ let mut mgr = docs.write();
+ let scratch = std::sync::Arc::clone(mgr.scratch_backend());
+ let doc = mgr
+ .get_document_mut(&did)
+ .ok_or_else(|| format!("Document not found: {did}"))?;
+ apply_tile_delta_packet(doc, &layer_id, &body, bump_epoch, Some(scratch.as_ref()))?
+ };
+ native_engine::remote_notify_tile_delta(layer_id.clone());
+ native_engine::sync_active_document();
+ native_docs::spawn_thumbnail_generation(app, did, vec![layer_id]);
+ Ok(info)
+ })
+ .await
+ .map_err(|e| format!("Collab apply tile delta worker failed: {e}"))?
}
#[tauri::command]
@@ -1337,8 +1459,8 @@ pub async fn native_collab_encode_mask(
doc_id: Option<String>,
layer_id: String,
) -> Result<tauri::ipc::Response, String> {
- let did = resolve_doc_id(doc_id.as_deref())?;
- let bytes = tokio::task::spawn_blocking(move || -> Result<Vec<u8>, String> {
+ let bytes = tauri::async_runtime::spawn_blocking(move || -> Result<Vec<u8>, String> {
+ let did = resolve_doc_id(doc_id.as_deref())?;
let docs = documents_handle();
let mgr = docs.read();
let scratch = std::sync::Arc::clone(mgr.scratch_backend());
@@ -1353,7 +1475,7 @@ pub async fn native_collab_encode_mask(
}
#[tauri::command]
-pub fn native_collab_apply_mask(
+pub async fn native_collab_apply_mask(
app: tauri::AppHandle,
request: tauri::ipc::Request<'_>,
) -> Result<(), String> {
@@ -1371,23 +1493,27 @@ pub fn native_collab_apply_mask(
.filter(|s| !s.is_empty())
.ok_or_else(|| "Missing x-layer-id header".to_string())?;
let body = match request.body() {
- tauri::ipc::InvokeBody::Raw(bytes) => bytes.as_slice(),
+ tauri::ipc::InvokeBody::Raw(bytes) => bytes.to_vec(),
_ => return Err("Expected raw binary layer mask body".to_string()),
};
- let did = resolve_doc_id(doc_id_hdr.as_deref())?;
- {
- let docs = documents_handle();
- let mut mgr = docs.write();
- let scratch = std::sync::Arc::clone(mgr.scratch_backend());
- let doc = mgr
- .get_document_mut(&did)
- .ok_or_else(|| format!("Document not found: {did}"))?;
- apply_layer_mask_packet(doc, &layer_id, body, Some(scratch.as_ref()))?;
- }
- native_engine::sync_active_document();
- native_docs::spawn_thumbnail_generation(app, did, vec![layer_id]);
- Ok(())
+ tauri::async_runtime::spawn_blocking(move || -> Result<(), String> {
+ let did = resolve_doc_id(doc_id_hdr.as_deref())?;
+ {
+ let docs = documents_handle();
+ let mut mgr = docs.write();
+ let scratch = std::sync::Arc::clone(mgr.scratch_backend());
+ let doc = mgr
+ .get_document_mut(&did)
+ .ok_or_else(|| format!("Document not found: {did}"))?;
+ apply_layer_mask_packet(doc, &layer_id, &body, Some(scratch.as_ref()))?;
+ }
+ native_engine::sync_active_document();
+ native_docs::spawn_thumbnail_generation(app, did, vec![layer_id]);
+ Ok(())
+ })
+ .await
+ .map_err(|e| format!("Collab apply mask worker failed: {e}"))?
}
#[tauri::command]
@@ -1429,6 +1555,7 @@ pub async fn native_engine_export_image(
#[tauri::command]
pub async fn native_engine_import_image_layer(
+ app: tauri::AppHandle,
request: tauri::ipc::Request<'_>,
) -> Result<DocumentMetaSnapshot, String> {
let doc_id_hdr = request
@@ -1472,7 +1599,8 @@ pub async fn native_engine_import_image_layer(
_ => return Err("Expected raw binary image bytes".to_string()),
};
let did = resolve_doc_id(doc_id_hdr.as_deref())?;
- tokio::task::spawn_blocking(move || {
+ let did_for_emit = did.clone();
+ let snap = tokio::task::spawn_blocking(move || {
native_docs::import_image_as_layer(
&did,
layer_id,
@@ -1484,7 +1612,17 @@ pub async fn native_engine_import_image_layer(
)
})
.await
- .map_err(|e| format!("Image import worker failed: {e}"))?
+ .map_err(|e| format!("Image import worker failed: {e}"))??;
+ if record_history {
+ let _ = app.emit(
+ native_engine::EVENT_HISTORY,
+ native_engine::NativeHistoryEventPayload {
+ doc_id: did_for_emit,
+ history: snap.history.clone(),
+ },
+ );
+ }
+ Ok(snap)
}
/// Returns tight non-empty layer pixels as `[has: u8, x: i32 LE, y: i32 LE, w: u32 LE, h: u32 LE, rgba8...]`
diff --git a/src-tauri/src/os_hotkeys.rs b/src-tauri/src/os_hotkeys.rs
index 2db58c8..7b94703 100644
--- a/src-tauri/src/os_hotkeys.rs
+++ b/src-tauri/src/os_hotkeys.rs
@@ -334,123 +334,132 @@ mod win_impl {
w_param: WPARAM,
l_param: LPARAM,
) -> LRESULT {
- if n_code < 0 {
+ if n_code < 0 || l_param == 0 {
return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);
}
- let kb = &*(l_param as *const KBDLLHOOKSTRUCT);
- // Never intercept injected keys (including our own 0xE8 Start Menu suppressor)
- if (kb.flags & LLKHF_INJECTED) != 0 {
- return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);
- }
+ let consume = std::panic::catch_unwind(|| -> bool {
+ let kb = &*(l_param as *const KBDLLHOOKSTRUCT);
+ // Never intercept injected keys (including our own 0xE8 Start Menu suppressor)
+ if (kb.flags & LLKHF_INJECTED) != 0 {
+ return false;
+ }
- let msg = w_param as u32;
- let is_down = msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN;
- let is_up = msg == WM_KEYUP || msg == WM_SYSKEYUP;
- if !is_down && !is_up {
- return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);
- }
+ let msg = w_param as u32;
+ let is_down = msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN;
+ let is_up = msg == WM_KEYUP || msg == WM_SYSKEYUP;
+ if !is_down && !is_up {
+ return false;
+ }
- let vk = kb.vkCode;
- let is_extended = (kb.flags & LLKHF_EXTENDED) != 0;
+ let vk = kb.vkCode;
+ let is_extended = (kb.flags & LLKHF_EXTENDED) != 0;
- // Track Win key physical press/release cleanly without ever swallowing Win keyup
- if vk == VK_LWIN as u32 || vk == VK_RWIN as u32 {
- if is_down {
- if !WIN_DOWN.swap(true, Ordering::SeqCst) {
+ // Track Win key physical press/release cleanly without ever swallowing Win keyup
+ if vk == VK_LWIN as u32 || vk == VK_RWIN as u32 {
+ if is_down {
+ if !WIN_DOWN.swap(true, Ordering::SeqCst) {
+ WIN_COMBO_CONSUMED.store(false, Ordering::SeqCst);
+ }
+ } else {
+ WIN_DOWN.store(false, Ordering::SeqCst);
WIN_COMBO_CONSUMED.store(false, Ordering::SeqCst);
}
- } else {
- WIN_DOWN.store(false, Ordering::SeqCst);
- WIN_COMBO_CONSUMED.store(false, Ordering::SeqCst);
+ return false;
}
- return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);
- }
- // Release previously consumed key cleanly even if focus changed mid-hold
- if is_up {
- let was_consumed = CONSUMED_VKS
- .try_lock()
- .map(|mut set| set.remove(&vk))
- .unwrap_or(false);
- if was_consumed {
- if let Some((code, key)) = vk_to_dom_code_and_key(vk, is_extended) {
- emit_async(NativeOsHotkeyEvent {
- phase: "keyup".to_string(),
- code: code.to_string(),
- key: key.to_string(),
- ctrl_key: is_vk_pressed(VK_CONTROL),
- meta_key: WIN_DOWN.load(Ordering::Relaxed)
- || is_vk_pressed(VK_LWIN)
- || is_vk_pressed(VK_RWIN),
- shift_key: is_vk_pressed(VK_SHIFT),
- alt_key: is_vk_pressed(VK_MENU),
- repeat: false,
- is_recording: RECORDING_MODE.load(Ordering::Relaxed),
- });
+ // Release previously consumed key cleanly even if focus changed mid-hold
+ if is_up {
+ let was_consumed = CONSUMED_VKS
+ .try_lock()
+ .map(|mut set| set.remove(&vk))
+ .unwrap_or(false);
+ if was_consumed {
+ if let Some((code, key)) = vk_to_dom_code_and_key(vk, is_extended) {
+ emit_async(NativeOsHotkeyEvent {
+ phase: "keyup".to_string(),
+ code: code.to_string(),
+ key: key.to_string(),
+ ctrl_key: is_vk_pressed(VK_CONTROL),
+ meta_key: WIN_DOWN.load(Ordering::Relaxed)
+ || is_vk_pressed(VK_LWIN)
+ || is_vk_pressed(VK_RWIN),
+ shift_key: is_vk_pressed(VK_SHIFT),
+ alt_key: is_vk_pressed(VK_MENU),
+ repeat: false,
+ is_recording: RECORDING_MODE.load(Ordering::Relaxed),
+ });
+ }
+ return true;
}
- return 1;
+ return false;
}
- return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);
- }
- // Only evaluate keydowns when Win key is actively held AND Ink Studio is foreground
- let win_held =
- WIN_DOWN.load(Ordering::Relaxed) || is_vk_pressed(VK_LWIN) || is_vk_pressed(VK_RWIN);
- if !win_held || is_pure_modifier_vk(vk) || !is_our_window_foreground() {
- return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);
- }
+ // Only evaluate keydowns when Win key is actively held AND Ink Studio is foreground
+ let win_held =
+ WIN_DOWN.load(Ordering::Relaxed) || is_vk_pressed(VK_LWIN) || is_vk_pressed(VK_RWIN);
+ if !win_held || is_pure_modifier_vk(vk) || !is_our_window_foreground() {
+ return false;
+ }
- let ctrl = is_vk_pressed(VK_CONTROL);
- let shift = is_vk_pressed(VK_SHIFT);
- let alt = is_vk_pressed(VK_MENU);
+ let ctrl = is_vk_pressed(VK_CONTROL);
+ let shift = is_vk_pressed(VK_SHIFT);
+ let alt = is_vk_pressed(VK_MENU);
- // Never fight Windows Lock Screen (Win+L without extra modifiers)
- if vk == 0x4C && !ctrl && !shift && !alt {
- return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);
- }
+ // Never fight Windows Lock Screen (Win+L without extra modifiers)
+ if vk == 0x4C && !ctrl && !shift && !alt {
+ return false;
+ }
- let Some((code, key)) = vk_to_dom_code_and_key(vk, is_extended) else {
- return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);
- };
+ let Some((code, key)) = vk_to_dom_code_and_key(vk, is_extended) else {
+ return false;
+ };
- let is_recording = RECORDING_MODE.load(Ordering::Relaxed);
- let matched = if is_recording {
- // Do not capture bare Escape when recording; let user cancel
- vk != 0x1B
- } else {
- BINDINGS
- .try_read()
- .map(|set| set.contains(&VkBinding { vk, ctrl, shift, alt }))
- .unwrap_or(false)
- };
+ let is_recording = RECORDING_MODE.load(Ordering::Relaxed);
+ let matched = if is_recording {
+ // Do not capture bare Escape when recording; let user cancel
+ vk != 0x1B
+ } else {
+ BINDINGS
+ .try_read()
+ .map(|set| set.contains(&VkBinding { vk, ctrl, shift, alt }))
+ .unwrap_or(false)
+ };
- if !matched {
- return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);
- }
+ if !matched {
+ return false;
+ }
- let is_repeat = CONSUMED_VKS
- .try_lock()
- .map(|mut set| !set.insert(vk))
- .unwrap_or(false);
+ let is_repeat = CONSUMED_VKS
+ .try_lock()
+ .map(|mut set| !set.insert(vk))
+ .unwrap_or(false);
- if !WIN_COMBO_CONSUMED.swap(true, Ordering::SeqCst) {
- suppress_start_menu_tap();
- }
+ if !WIN_COMBO_CONSUMED.swap(true, Ordering::SeqCst) {
+ suppress_start_menu_tap();
+ }
- emit_async(NativeOsHotkeyEvent {
- phase: "keydown".to_string(),
- code: code.to_string(),
- key: key.to_string(),
- ctrl_key: ctrl,
- meta_key: true,
- shift_key: shift,
- alt_key: alt,
- repeat: is_repeat,
- is_recording,
- });
-
- 1
+ emit_async(NativeOsHotkeyEvent {
+ phase: "keydown".to_string(),
+ code: code.to_string(),
+ key: key.to_string(),
+ ctrl_key: ctrl,
+ meta_key: true,
+ shift_key: shift,
+ alt_key: alt,
+ repeat: is_repeat,
+ is_recording,
+ });
+
+ true
+ })
+ .unwrap_or(false);
+
+ if consume {
+ 1
+ } else {
+ CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param)
+ }
}
fn ensure_hook_running() -> Result<(), String> {
diff --git a/src-tauri/src/recovery.rs b/src-tauri/src/recovery.rs
index d897538..4639925 100644
--- a/src-tauri/src/recovery.rs
+++ b/src-tauri/src/recovery.rs
@@ -184,9 +184,7 @@ pub async fn init_session(
let _wal_guard = WAL_IO_LOCK.lock().await;
let safe_id = sanitize_session_id(session_id);
let session_dir = get_recovery_root(app).join(&safe_id);
- tokio::fs::create_dir_all(&session_dir)
- .await
- .map_err(|e| format!("Failed to create recovery dir: {}", e))?;
+ ensure_session_lock(&session_dir).await?;
let lock = SessionLock {
pid: std::process::id(),
@@ -213,6 +211,27 @@ pub async fn init_session(
Ok(())
}
+async fn ensure_session_lock(session_dir: &std::path::Path) -> Result<(), String> {
+ tokio::fs::create_dir_all(session_dir)
+ .await
+ .map_err(|e| format!("Failed to create recovery dir: {}", e))?;
+ let lock_path = session_dir.join("session.lock");
+ if !tokio::fs::try_exists(&lock_path).await.unwrap_or(false) {
+ let lock = SessionLock {
+ pid: std::process::id(),
+ timestamp: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_millis() as u64)
+ .unwrap_or(0),
+ };
+ let lock_json = serde_json::to_string_pretty(&lock).map_err(|e| e.to_string())?;
+ tokio::fs::write(&lock_path, lock_json.as_bytes())
+ .await
+ .map_err(|e| format!("Failed to write session.lock: {}", e))?;
+ }
+ Ok(())
+}
+
pub async fn append_wal_entry(
app: &tauri::AppHandle,
session_id: &str,
@@ -252,6 +271,7 @@ pub async fn append_wal_entry(
let _wal_guard = WAL_IO_LOCK.lock().await;
let safe_id = sanitize_session_id(session_id);
let session_dir = get_recovery_root(app).join(&safe_id);
+ ensure_session_lock(&session_dir).await?;
let wal_path = session_dir.join("journal.wal");
let mut file = tokio::fs::OpenOptions::new()
@@ -281,9 +301,7 @@ pub async fn checkpoint(
let _wal_guard = WAL_IO_LOCK.lock().await;
let safe_id = sanitize_session_id(session_id);
let session_dir = get_recovery_root(app).join(&safe_id);
- tokio::fs::create_dir_all(&session_dir)
- .await
- .map_err(|e| format!("Failed to create recovery dir: {}", e))?;
+ ensure_session_lock(&session_dir).await?;
let seq = WAL_TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
diff --git a/src-tauri/src/tablet_input.rs b/src-tauri/src/tablet_input.rs
index 45c4186..cdaaae4 100644
--- a/src-tauri/src/tablet_input.rs
+++ b/src-tauri/src/tablet_input.rs
@@ -370,12 +370,12 @@ impl WintabCoordMapper {
let cur_y = cy as f64;
let (best_mode, best_sy, best_err) = pick_best_mode(cur_y);
let mid_y = sys_org_y as f64 + (sys_ext_y as f64) * 0.5;
- let off_center = (cur_y - mid_y).abs() > (sys_ext_y.abs() as f64) * 0.06;
+ let off_center = (cur_y - mid_y).abs() > (sys_ext_y.unsigned_abs() as f64) * 0.06;
if best_err <= 24.0 && (off_center || best_mode == WintabYMode::SignedNeg) {
self.locked_y_mode = Some(best_mode);
}
best_sy
- } else if out_ext_y < 0 && pk_y < out_org_y - 16 {
+ } else if out_ext_y < 0 && pk_y < out_org_y.saturating_sub(16) {
eval_y(WintabYMode::SignedNeg)
} else {
eval_y(WintabYMode::StandardPos)
@@ -409,6 +409,153 @@ impl WintabCoordMapper {
}
}
+/// Assigns the correct per-sample phase when emitting coalesced Windows Ink history
+/// oldest -> newest (`is_newest` is `true` only for `idx == 0`).
+///
+/// Crucially, when `phase_code == 1` (`WM_POINTERDOWN`) arrives with coalesced history `n > 1`,
+/// the **first** (oldest) in-contact sample receives `phase = 1` (Down) and subsequent in-contact
+/// samples receive `phase = 2` (Move) — never `2` before `1`, which would clip stroke starts!
+#[inline]
+pub fn assign_coalesced_ink_sample_phase(
+ phase_code: u8,
+ in_contact: bool,
+ is_newest: bool,
+ emitted_down: &mut bool,
+) -> u8 {
+ match phase_code {
+ 1 => {
+ if in_contact {
+ if !*emitted_down {
+ *emitted_down = true;
+ 1
+ } else {
+ 2
+ }
+ } else if is_newest && !*emitted_down {
+ *emitted_down = true;
+ 1
+ } else {
+ 0
+ }
+ }
+ 2 => {
+ if is_newest || in_contact {
+ 2
+ } else {
+ 0
+ }
+ }
+ 3 => {
+ if is_newest {
+ 3
+ } else if in_contact {
+ 2
+ } else {
+ 0
+ }
+ }
+ 4 => {
+ if is_newest {
+ 4
+ } else if in_contact {
+ 2
+ } else {
+ 0
+ }
+ }
+ _ => 0,
+ }
+}
+
+/// Routes a stylus sample between the DX12 `rtrb` ring and JS fallback using non-blocking
+/// `SharedHitTest::try_*` (`try_read()`) queries.
+///
+/// Returns `(ring_sample_opt, owned_by_engine)`:
+/// - `ring_sample_opt`: `Some(sample)` to push into the DX12 `rtrb` ring, or `None` to avoid
+/// spurious DX12 render-thread wakeups (e.g. hovering outside the unoccluded canvas viewport,
+/// where only a single `phase = 4` leave transition is emitted upon exiting the canvas).
+/// - `owned_by_engine`: `true` when JS Channel forwarding should be suppressed.
+#[inline]
+pub fn route_and_filter_native_sample(
+ sample: ink_engine::NativeInputSample,
+ hit_test: Option<&ink_engine::SharedHitTest>,
+ native_stroke_owned: &mut bool,
+ was_hovering_canvas: &mut bool,
+) -> (Option<ink_engine::NativeInputSample>, bool) {
+ let Some(ht) = hit_test else {
+ *native_stroke_owned = false;
+ *was_hovering_canvas = false;
+ return (Some(sample), false);
+ };
+ match sample.phase {
+ 1 => {
+ let owned = ht.try_should_capture_native_stroke(sample.phys_x, sample.phys_y);
+ *native_stroke_owned = owned;
+ if owned {
+ *was_hovering_canvas = false;
+ (Some(sample), true)
+ } else if *was_hovering_canvas {
+ *was_hovering_canvas = false;
+ let leave = ink_engine::NativeInputSample {
+ pressure: 0.0,
+ phase: 4,
+ ..sample
+ };
+ (Some(leave), false)
+ } else {
+ (None, false)
+ }
+ }
+ 2 => {
+ if *native_stroke_owned {
+ *was_hovering_canvas = false;
+ (Some(sample), true)
+ } else {
+ (None, false)
+ }
+ }
+ 3 => {
+ let was_owned = *native_stroke_owned;
+ *native_stroke_owned = false;
+ *was_hovering_canvas = false;
+ if was_owned {
+ (Some(sample), true)
+ } else {
+ (None, false)
+ }
+ }
+ 4 => {
+ let was_owned = *native_stroke_owned;
+ *native_stroke_owned = false;
+ if was_owned || *was_hovering_canvas {
+ *was_hovering_canvas = false;
+ (Some(sample), was_owned)
+ } else {
+ (None, false)
+ }
+ }
+ 0 => {
+ let (over_canvas, capture_stroke) =
+ ht.try_classify_canvas_point(sample.phys_x, sample.phys_y);
+ if over_canvas {
+ *was_hovering_canvas = true;
+ (Some(sample), capture_stroke)
+ } else if *was_hovering_canvas {
+ *was_hovering_canvas = false;
+ let leave = ink_engine::NativeInputSample {
+ pressure: 0.0,
+ phase: 4,
+ ..sample
+ };
+ (Some(leave), false)
+ } else {
+ (None, false)
+ }
+ }
+ _ => (None, false),
+ }
+}
+
/// Packs a slice of TabletSamples into a raw little-endian binary frame:
/// `[count: u32 LE][sample_0: 36 bytes]...[sample_N-1: 36 bytes]`
pub fn pack_tablet_samples(samples: &[TabletSample]) -> Vec<u8> {
@@ -443,9 +590,12 @@ mod win_impl {
QueryPerformanceCounter, QueryPerformanceFrequency,
};
use windows_sys::Win32::System::Threading::{
- GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL,
+ GetCurrentThread, GetCurrentThreadId, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL,
};
use windows_sys::Win32::UI::HiDpi::GetDpiForWindow;
+ use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
+ GetAsyncKeyState, VK_CONTROL, VK_MENU, VK_SHIFT, VK_SPACE,
+ };
use windows_sys::Win32::UI::Input::Pointer::{
GetPointerPenInfoHistory, GetPointerType, POINTER_FLAG_FIRSTBUTTON,
POINTER_FLAG_INCONTACT, POINTER_FLAG_SECONDBUTTON, POINTER_PEN_INFO,
@@ -463,11 +613,13 @@ mod win_impl {
};
use windows_sys::Win32::UI::WindowsAndMessaging::{
CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, EnumChildWindows,
- GetCursorPos, GetForegroundWindow, GetMessageW, GetSystemMetrics, PostMessageW,
- PostThreadMessageW, RegisterClassW, TranslateMessage, HWND_MESSAGE, MSG, PT_PEN,
- SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN,
- WM_ACTIVATE, WM_ACTIVATEAPP, WM_APP, WM_NCACTIVATE, WM_POINTERDOWN, WM_POINTERENTER,
- WM_POINTERLEAVE, WM_POINTERUP, WM_POINTERUPDATE, WM_QUIT, WM_SETFOCUS, WNDCLASSW,
+ GetCursorPos, GetForegroundWindow, GetMessageW, GetSystemMetrics,
+ GetWindowThreadProcessId, IsWindow, PostMessageW, PostThreadMessageW, RegisterClassW,
+ TranslateMessage, HWND_MESSAGE, MSG, PT_PEN, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN,
+ SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, WM_ACTIVATE, WM_ACTIVATEAPP, WM_APP, WM_CREATE,
+ WM_DISPLAYCHANGE, WM_DPICHANGED, WM_NCACTIVATE, WM_NCDESTROY, WM_PARENTNOTIFY,
+ WM_POINTERDOWN, WM_POINTERENTER, WM_POINTERLEAVE, WM_POINTERUP, WM_POINTERUPDATE, WM_QUIT,
+ WM_SETFOCUS, WNDCLASSW,
};
const WM_APP_WINTAB_FOCUS: u32 = WM_APP + 1;
@@ -582,6 +734,7 @@ mod win_impl {
type FnWTInfoW = unsafe extern "system" fn(u32, u32, *mut c_void) -> u32;
type FnWTOpenW = unsafe extern "system" fn(HWND, *mut LogContextW, BOOL) -> HCTX;
+ type FnWTGetW = unsafe extern "system" fn(HCTX, *mut LogContextW) -> BOOL;
type FnWTClose = unsafe extern "system" fn(HCTX) -> BOOL;
type FnWTPacketsGet = unsafe extern "system" fn(HCTX, i32, *mut c_void) -> i32;
type FnWTOverlap = unsafe extern "system" fn(HCTX, BOOL) -> BOOL;
@@ -592,6 +745,7 @@ mod win_impl {
module: *mut c_void,
wt_info: FnWTInfoW,
wt_open: FnWTOpenW,
+ wt_get: Option<FnWTGetW>,
wt_close: FnWTClose,
wt_packets_get: FnWTPacketsGet,
wt_overlap: Option<FnWTOverlap>,
@@ -611,6 +765,7 @@ mod win_impl {
}
let wt_info = GetProcAddress(module, b"WTInfoW\0".as_ptr())?;
let wt_open = GetProcAddress(module, b"WTOpenW\0".as_ptr())?;
+ let wt_get = GetProcAddress(module, b"WTGetW\0".as_ptr());
let wt_close = GetProcAddress(module, b"WTClose\0".as_ptr())?;
let wt_packets_get = GetProcAddress(module, b"WTPacketsGet\0".as_ptr())?;
let wt_overlap = GetProcAddress(module, b"WTOverlap\0".as_ptr());
@@ -621,6 +776,7 @@ mod win_impl {
module,
wt_info: std::mem::transmute(wt_info),
wt_open: std::mem::transmute(wt_open),
+ wt_get: wt_get.map(|f| std::mem::transmute(f)),
wt_close: std::mem::transmute(wt_close),
wt_packets_get: std::mem::transmute(wt_packets_get),
wt_overlap: wt_overlap.map(|f| std::mem::transmute(f)),
@@ -640,6 +796,47 @@ mod win_impl {
}
}
+ const MAX_WINTAB_NAME_BYTES: usize = 4096;
+
+ /// Safely queries a fixed-size WinTab struct via `WTInfoW` after verifying the driver's
+ /// reported byte length fits within `target` (preventing stack buffer overflows).
+ unsafe fn query_wintab_struct<T>(lib: &WintabLib, cat: u32, idx: u32, target: &mut T) -> bool {
+ let req_bytes = (lib.wt_info)(cat, idx, std::ptr::null_mut()) as usize;
+ if req_bytes == 0 || req_bytes > std::mem::size_of_val(target) {
+ return false;
+ }
+ (lib.wt_info)(cat, idx, target as *mut T as *mut c_void) > 0
+ }
+
+ /// Safely queries the WinTab device name into a heap buffer sized to `WTInfoW`'s reported
+ /// byte length (clamped to `MAX_WINTAB_NAME_BYTES`).
+ unsafe fn query_wintab_device_name(lib: &WintabLib) -> Option<String> {
+ let req_bytes = (lib.wt_info)(WTI_DEVICES, DVC_NAME, std::ptr::null_mut()) as usize;
+ if req_bytes == 0 || req_bytes > MAX_WINTAB_NAME_BYTES {
+ return Some("WinTab Digitizer".to_string());
+ }
+ let u16_len = req_bytes.div_ceil(2);
+ let mut name_buf = vec![0u16; u16_len];
+ let written = (lib.wt_info)(
+ WTI_DEVICES,
+ DVC_NAME,
+ name_buf.as_mut_ptr() as *mut c_void,
+ ) as usize;
+ if written > 0 {
+ let chars = (written / 2).min(name_buf.len());
+ let s = String::from_utf16_lossy(&name_buf[..chars])
+ .trim_end_matches('\0')
+ .to_string();
+ if s.is_empty() {
+ None
+ } else {
+ Some(s)
+ }
+ } else {
+ Some("WinTab Digitizer".to_string())
+ }
+ }
+
fn qpc_freq_per_ms() -> f64 {
static FREQ: LazyLock<f64> = LazyLock::new(|| unsafe {
let mut f = 0i64;
@@ -661,39 +858,100 @@ mod win_impl {
}
}
- fn screen_to_physical_and_css_client_f64(
- main_hwnd: HWND,
- sx: f64,
- sy: f64,
- ) -> ((f32, f32), (f32, f32)) {
- unsafe {
- let ix = sx.floor() as i32;
- let iy = sy.floor() as i32;
- let fx = sx - (ix as f64);
- let fy = sy - (iy as f64);
- let mut pt = POINT { x: ix, y: iy };
- ScreenToClient(main_hwnd, &mut pt);
- let phys_x = (pt.x as f64 + fx) as f32;
- let phys_y = (pt.y as f64 + fy) as f32;
+ /// Pre-computed per-burst window coordinate transform (1 `ScreenToClient` + 1 `GetDpiForWindow`
+ /// per burst instead of per sample).
+ #[derive(Clone, Copy)]
+ struct WindowCoordTransform {
+ offset_x: f64,
+ offset_y: f64,
+ inv_scale: f64,
+ }
+
+ impl WindowCoordTransform {
+ #[inline]
+ unsafe fn for_hwnd(main_hwnd: HWND) -> Self {
+ let mut origin = POINT { x: 0, y: 0 };
+ ScreenToClient(main_hwnd, &mut origin);
let dpi = GetDpiForWindow(main_hwnd);
- let scale = if dpi > 0 { (dpi as f64) / 96.0 } else { 1.0 };
+ let inv_scale = if dpi > 0 { 96.0 / (dpi as f64) } else { 1.0 };
+ Self {
+ offset_x: origin.x as f64,
+ offset_y: origin.y as f64,
+ inv_scale,
+ }
+ }
+
+ #[inline]
+ fn map(&self, sx: f64, sy: f64) -> ((f32, f32), (f32, f32)) {
+ let phys_x = (self.offset_x + sx) as f32;
+ let phys_y = (self.offset_y + sy) as f32;
(
(phys_x, phys_y),
- ((phys_x as f64 / scale) as f32, (phys_y as f64 / scale) as f32),
+ (
+ (phys_x as f64 * self.inv_scale) as f32,
+ (phys_y as f64 * self.inv_scale) as f32,
+ ),
)
}
}
+ /// Queries modifier key bits ONCE per `WM_POINTER*` / `WT_PACKET` burst (4 syscalls total
+ /// instead of `4 * N` syscalls per burst).
+ #[inline]
+ unsafe fn query_modifier_bits() -> u16 {
+ let mut mod_bits = 0u16;
+ if (GetAsyncKeyState(VK_SHIFT as i32) as u16 & 0x8000) != 0 {
+ mod_bits |= 0x0100;
+ }
+ if (GetAsyncKeyState(VK_MENU as i32) as u16 & 0x8000) != 0 {
+ mod_bits |= 0x0200;
+ }
+ if (GetAsyncKeyState(VK_SPACE as i32) as u16 & 0x8000) != 0 {
+ mod_bits |= 0x0400;
+ }
+ if (GetAsyncKeyState(VK_CONTROL as i32) as u16 & 0x8000) != 0 {
+ mod_bits |= 0x0800;
+ }
+ mod_bits
+ }
+
type FnGetPointerDeviceRects =
unsafe extern "system" fn(HANDLE, *mut RECT, *mut RECT) -> BOOL;
- fn try_himetric_to_screen_f64(
- source_device: HANDLE,
- himetric_x: i32,
- himetric_y: i32,
- pixel_x: i32,
- pixel_y: i32,
- ) -> (f64, f64) {
+ #[derive(Clone, Copy)]
+ struct PointerDeviceRects {
+ dev_left: f64,
+ dev_top: f64,
+ inv_dev_w: f64,
+ inv_dev_h: f64,
+ disp_left: f64,
+ disp_top: f64,
+ disp_w: f64,
+ disp_h: f64,
+ }
+
+ impl PointerDeviceRects {
+ #[inline]
+ fn map_himetric(
+ &self,
+ himetric_x: i32,
+ himetric_y: i32,
+ pixel_x: i32,
+ pixel_y: i32,
+ ) -> (f64, f64) {
+ let sx = self.disp_left + ((himetric_x as f64 - self.dev_left) * self.inv_dev_w) * self.disp_w;
+ let sy = self.disp_top + ((himetric_y as f64 - self.dev_top) * self.inv_dev_h) * self.disp_h;
+ // Guard against exotic multi-monitor DPI discrepancies:
+ // accept sub-pixel HIMETRIC only when tightly aligned with ptPixelLocationRaw.
+ if (sx - pixel_x as f64).abs() <= 2.0 && (sy - pixel_y as f64).abs() <= 2.0 {
+ (sx, sy)
+ } else {
+ (pixel_x as f64, pixel_y as f64)
+ }
+ }
+ }
+
+ fn query_pointer_device_rects(source_device: HANDLE) -> Option<PointerDeviceRects> {
static FN_PTR: LazyLock<Option<FnGetPointerDeviceRects>> = LazyLock::new(|| unsafe {
let user32: Vec<u16> = "user32.dll\0".encode_utf16().collect();
let hmod = GetModuleHandleW(user32.as_ptr());
@@ -704,34 +962,71 @@ mod win_impl {
Some(std::mem::transmute(proc))
});
- if !source_device.is_null() {
- if let Some(get_rects) = *FN_PTR {
- unsafe {
- let mut dev_rect: RECT = std::mem::zeroed();
- let mut disp_rect: RECT = std::mem::zeroed();
- if get_rects(source_device, &mut dev_rect, &mut disp_rect) != 0 {
- let dev_w = (dev_rect.right - dev_rect.left) as f64;
- let dev_h = (dev_rect.bottom - dev_rect.top) as f64;
- let disp_w = (disp_rect.right - disp_rect.left) as f64;
- let disp_h = (disp_rect.bottom - disp_rect.top) as f64;
- if dev_w > 0.0 && dev_h > 0.0 && disp_w > 0.0 && disp_h > 0.0 {
- let sx = disp_rect.left as f64
- + ((himetric_x - dev_rect.left) as f64 / dev_w) * disp_w;
- let sy = disp_rect.top as f64
- + ((himetric_y - dev_rect.top) as f64 / dev_h) * disp_h;
- // Guard against exotic multi-monitor DPI discrepancies:
- // accept sub-pixel HIMETRIC only when tightly aligned with ptPixelLocationRaw.
- if (sx - pixel_x as f64).abs() <= 2.0
- && (sy - pixel_y as f64).abs() <= 2.0
- {
- return (sx, sy);
- }
- }
- }
+ if source_device.is_null() {
+ return None;
+ }
+ let get_rects = (*FN_PTR)?;
+ unsafe {
+ let mut dev_rect: RECT = std::mem::zeroed();
+ let mut disp_rect: RECT = std::mem::zeroed();
+ if get_rects(source_device, &mut dev_rect, &mut disp_rect) != 0 {
+ let dev_w = dev_rect.right as f64 - dev_rect.left as f64;
+ let dev_h = dev_rect.bottom as f64 - dev_rect.top as f64;
+ let disp_w = disp_rect.right as f64 - disp_rect.left as f64;
+ let disp_h = disp_rect.bottom as f64 - disp_rect.top as f64;
+ if dev_w > 0.0 && dev_h > 0.0 && disp_w > 0.0 && disp_h > 0.0 {
+ return Some(PointerDeviceRects {
+ dev_left: dev_rect.left as f64,
+ dev_top: dev_rect.top as f64,
+ inv_dev_w: 1.0 / dev_w,
+ inv_dev_h: 1.0 / dev_h,
+ disp_left: disp_rect.left as f64,
+ disp_top: disp_rect.top as f64,
+ disp_w,
+ disp_h,
+ });
}
}
}
- (pixel_x as f64, pixel_y as f64)
+ None
+ }
+
+ /// Thread-local scratch buffers & per-`sourceDevice` `GetPointerDeviceRects` cache
+ /// reused across every `WM_POINTER*` message (zero per-message heap allocations!).
+ struct WinInkTlsScratch {
+ device_rects_cache: Vec<(isize, Option<PointerDeviceRects>)>,
+ ring_samples: Vec<ink_engine::NativeInputSample>,
+ forward_js: Vec<TabletSample>,
+ }
+
+ impl WinInkTlsScratch {
+ fn resolve_device_rects(&mut self, source_device: HANDLE) -> Option<PointerDeviceRects> {
+ let key = source_device as isize;
+ if key == 0 {
+ return None;
+ }
+ for &(cached_key, rects) in &self.device_rects_cache {
+ if cached_key == key {
+ return rects;
+ }
+ }
+ let rects = query_pointer_device_rects(source_device);
+ if self.device_rects_cache.len() >= 16 {
+ self.device_rects_cache.clear();
+ }
+ self.device_rects_cache.push((key, rects));
+ rects
+ }
+ }
+
+ thread_local! {
+ static WININK_SCRATCH: std::cell::RefCell<WinInkTlsScratch> = const {
+ std::cell::RefCell::new(WinInkTlsScratch {
+ device_rects_cache: Vec::new(),
+ ring_samples: Vec::new(),
+ forward_js: Vec::new(),
+ })
+ };
}
fn wintab_orientation_to_tilt(
@@ -744,7 +1039,7 @@ mod win_impl {
let mut tilt_y = 0.0f32;
if az_max > 0 && alt_max > 0 {
let az = (ori.or_azimuth as f64 / az_max as f64) * std::f64::consts::TAU;
- let alt = (ori.or_altitude.abs() as f64 / alt_max as f64)
+ let alt = (ori.or_altitude.unsigned_abs() as f64 / alt_max as f64)
* std::f64::consts::FRAC_PI_2;
let sin_alt = alt.sin().max(1e-5);
let cos_alt = alt.cos();
@@ -765,6 +1060,7 @@ mod win_impl {
}
static ACTIVE_SINK: LazyLock<Mutex<Option<ActiveSink>>> = LazyLock::new(|| Mutex::new(None));
+ static HAS_JS_SINK: AtomicBool = AtomicBool::new(false);
static SUBCLASSED_HWNDS: LazyLock<Mutex<Vec<isize>>> = LazyLock::new(|| Mutex::new(Vec::new()));
static WINTAB_RUNNING: AtomicBool = AtomicBool::new(false);
static WINTAB_THREAD_ID: AtomicIsize = AtomicIsize::new(0);
@@ -772,30 +1068,37 @@ mod win_impl {
static WINTAB_FOCUS_SUBCLASS_HWND: AtomicIsize = AtomicIsize::new(0);
static LAST_WINTAB_PACKET_MS_BITS: AtomicU64 = AtomicU64::new(0);
static LAST_STYLUS_ACTIVITY_MS_BITS: AtomicU64 = AtomicU64::new(0);
+ static STYLUS_IN_CONTACT: AtomicBool = AtomicBool::new(false);
+ static WINTAB_IN_PROXIMITY: AtomicBool = AtomicBool::new(false);
static WINTAB_THREAD: LazyLock<Mutex<Option<JoinHandle<()>>>> =
LazyLock::new(|| Mutex::new(None));
- // Lock-free SPSC ring handoff slots into `ink-engine` (claimed once per producer thread).
+ // Lock-free SPSC ring handoff slots into `ink-engine`.
static ENGINE_ATTACHED: AtomicBool = AtomicBool::new(false);
static WINTAB_RING_PENDING: AtomicBool = AtomicBool::new(false);
- static WININK_RING_PENDING: AtomicBool = AtomicBool::new(false);
static WINTAB_RING_SLOT: LazyLock<Mutex<Option<ink_engine::TabletRingProducer>>> =
LazyLock::new(|| Mutex::new(None));
- static WININK_RING_SLOT: LazyLock<Mutex<Option<ink_engine::TabletRingProducer>>> =
- LazyLock::new(|| Mutex::new(None));
static ENGINE_HIT_TEST: LazyLock<Mutex<Option<ink_engine::SharedHitTest>>> =
LazyLock::new(|| Mutex::new(None));
- struct WinInkEngineLocal {
+ /// Shared Windows Ink ring producer + ownership state (prevents TLS single-take loss
+ /// across multiple windows/threads or detach/re-attach cycles).
+ struct WinInkEngineShared {
tx: Option<ink_engine::TabletRingProducer>,
hit_test: Option<ink_engine::SharedHitTest>,
native_stroke_owned: bool,
+ was_hovering_canvas: bool,
}
- thread_local! {
- static WININK_ENGINE: std::cell::RefCell<WinInkEngineLocal> =
- const { std::cell::RefCell::new(WinInkEngineLocal { tx: None, hit_test: None, native_stroke_owned: false }) };
- }
+ static WININK_ENGINE_SHARED: LazyLock<parking_lot::Mutex<WinInkEngineShared>> =
+ LazyLock::new(|| {
+ parking_lot::Mutex::new(WinInkEngineShared {
+ tx: None,
+ hit_test: None,
+ native_stroke_owned: false,
+ was_hovering_canvas: false,
+ })
+ });
pub fn attach_engine_rings(
wintab_tx: ink_engine::TabletRingProducer,
@@ -803,39 +1106,38 @@ mod win_impl {
hit_test: ink_engine::SharedHitTest,
) {
if let Ok(mut guard) = ENGINE_HIT_TEST.lock() {
- *guard = Some(hit_test);
+ *guard = Some(hit_test.clone());
}
if let Ok(mut guard) = WINTAB_RING_SLOT.lock() {
*guard = Some(wintab_tx);
}
- if let Ok(mut guard) = WININK_RING_SLOT.lock() {
- *guard = Some(winink_tx);
+ {
+ let mut ink_eng = WININK_ENGINE_SHARED.lock();
+ ink_eng.tx = Some(winink_tx);
+ ink_eng.hit_test = Some(hit_test);
+ ink_eng.native_stroke_owned = false;
+ ink_eng.was_hovering_canvas = false;
}
WINTAB_RING_PENDING.store(true, Ordering::Release);
- WININK_RING_PENDING.store(true, Ordering::Release);
ENGINE_ATTACHED.store(true, Ordering::Release);
}
pub fn detach_engine_rings() {
ENGINE_ATTACHED.store(false, Ordering::SeqCst);
WINTAB_RING_PENDING.store(false, Ordering::SeqCst);
- WININK_RING_PENDING.store(false, Ordering::SeqCst);
if let Ok(mut guard) = WINTAB_RING_SLOT.lock() {
*guard = None;
}
- if let Ok(mut guard) = WININK_RING_SLOT.lock() {
- *guard = None;
- }
if let Ok(mut guard) = ENGINE_HIT_TEST.lock() {
*guard = None;
}
- // Clear UI-thread TLS if called on the main thread
- WININK_ENGINE.with(|cell| {
- let mut st = cell.borrow_mut();
- st.tx = None;
- st.hit_test = None;
- st.native_stroke_owned = false;
- });
+ {
+ let mut ink_eng = WININK_ENGINE_SHARED.lock();
+ ink_eng.tx = None;
+ ink_eng.hit_test = None;
+ ink_eng.native_stroke_owned = false;
+ ink_eng.was_hovering_canvas = false;
+ }
}
#[inline]
@@ -848,6 +1150,24 @@ mod win_impl {
}
}
+ #[inline]
+ pub fn last_wintab_activity_ms() -> f64 {
+ if !WINTAB_IN_PROXIMITY.load(Ordering::Acquire) {
+ return 0.0;
+ }
+ let bits = LAST_WINTAB_PACKET_MS_BITS.load(Ordering::Relaxed);
+ if bits == 0 {
+ 0.0
+ } else {
+ f64::from_bits(bits)
+ }
+ }
+
+ #[inline]
+ pub fn is_stylus_in_contact() -> bool {
+ STYLUS_IN_CONTACT.load(Ordering::Acquire)
+ }
+
fn take_wintab_engine_binding() -> (
Option<ink_engine::TabletRingProducer>,
Option<ink_engine::SharedHitTest>,
@@ -863,56 +1183,6 @@ mod win_impl {
(tx, ht)
}
- fn sync_winink_engine_local(local: &mut WinInkEngineLocal) {
- if !ENGINE_ATTACHED.load(Ordering::Acquire) {
- local.tx = None;
- local.hit_test = None;
- local.native_stroke_owned = false;
- return;
- }
- if local.tx.is_none() && WININK_RING_PENDING.load(Ordering::Acquire) {
- local.tx = WININK_RING_SLOT.lock().ok().and_then(|mut g| g.take());
- local.hit_test = ENGINE_HIT_TEST.lock().ok().and_then(|g| g.clone());
- if local.tx.is_some() {
- WININK_RING_PENDING.store(false, Ordering::Release);
- }
- }
- }
-
- #[inline]
- fn route_sample_ownership(
- native_owned: &mut bool,
- hit_test: Option<&ink_engine::SharedHitTest>,
- phys_x: f32,
- phys_y: f32,
- phase: u8,
- ) -> bool {
- let Some(ht) = hit_test else {
- *native_owned = false;
- return false;
- };
- match phase {
- 1 => {
- // Pen down: capture natively iff landing inside unoccluded canvas viewport
- // for a native-handled tool (Brush/Eraser).
- let owned = ht.should_capture_native_stroke(phys_x, phys_y);
- *native_owned = owned;
- owned
- }
- 2 => *native_owned,
- 3 | 4 => {
- let was_owned = *native_owned;
- *native_owned = false;
- was_owned
- }
- 0 => {
- // Hover: suppress JS Channel flood while hovering unoccluded native canvas
- // so the native GPU brush cursor handles 240Hz hover with zero IPC.
- ht.should_capture_native_stroke(phys_x, phys_y)
- }
- _ => false,
- }
- }
static CURRENT_STATUS: LazyLock<Mutex<TabletStatus>> = LazyLock::new(|| {
Mutex::new(TabletStatus {
active: false,
@@ -927,12 +1197,12 @@ mod win_impl {
const SUBCLASS_ID: usize = 0x494E_4B54; // "INKT"
fn send_samples(samples: &[TabletSample]) {
- if samples.is_empty() {
+ if samples.is_empty() || !HAS_JS_SINK.load(Ordering::Acquire) {
return;
}
- let packed = pack_tablet_samples(samples);
if let Ok(guard) = ACTIVE_SINK.lock() {
if let Some(sink) = guard.as_ref() {
+ let packed = pack_tablet_samples(samples);
let _ = sink.channel.send(InvokeResponseBody::Raw(packed));
}
}
@@ -947,42 +1217,72 @@ mod win_impl {
msg: u32,
wparam: WPARAM,
lparam: LPARAM,
- _uid_subclass: usize,
+ uid_subclass: usize,
dw_ref_data: usize,
) -> LRESULT {
let _ = std::panic::catch_unwind(|| {
+ if msg == WM_NCDESTROY {
+ RemoveWindowSubclass(hwnd, Some(ink_subclass_proc), uid_subclass);
+ let raw = hwnd as isize;
+ if let Ok(mut list) = SUBCLASSED_HWNDS.try_lock() {
+ list.retain(|&h| h != raw);
+ } else if let Ok(mut list) = SUBCLASSED_HWNDS.lock() {
+ list.retain(|&h| h != raw);
+ }
+ return;
+ }
let main_hwnd = dw_ref_data as HWND;
+ if msg == WM_DISPLAYCHANGE || msg == WM_DPICHANGED {
+ WININK_SCRATCH.with(|cell| {
+ cell.borrow_mut().device_rects_cache.clear();
+ });
+ return;
+ }
+ // Catch late-created WebView2 child HWNDs (`Chrome_WidgetWin_1` / `Chrome_RenderWidgetHostHWND`)
+ if msg == WM_PARENTNOTIFY && (wparam & 0xFFFF) == WM_CREATE as usize {
+ ensure_child_windows_subclassed(main_hwnd);
+ return;
+ }
+ if hwnd == main_hwnd && msg == WM_ACTIVATE && (wparam & 0xFFFF) != 0 {
+ ensure_child_windows_subclassed(main_hwnd);
+ return;
+ }
if hwnd == main_hwnd
&& ((msg == WM_ACTIVATE && (wparam & 0xFFFF) == 0)
|| (msg == WM_ACTIVATEAPP && wparam == 0))
{
+ STYLUS_IN_CONTACT.store(false, Ordering::Release);
let had_active = INK_DEDUP
.lock()
.map(|mut dedup| dedup.force_end_all_active())
.unwrap_or(false);
if had_active {
let ts = qpc_now_ms();
- let was_native = WININK_ENGINE.with(|cell| {
- let mut local = cell.borrow_mut();
- sync_winink_engine_local(&mut local);
- if let Some(tx) = local.tx.as_mut() {
- tx.push(ink_engine::NativeInputSample {
- phys_x: 0.0,
- phys_y: 0.0,
- pressure: 0.0,
- tilt_x: 0.0,
- tilt_y: 0.0,
- twist: 0.0,
- timestamp_ms: ts,
- buttons: 0,
- phase: 3,
- backend: 2,
- });
+ let was_native = {
+ let mut eng_guard = WININK_ENGINE_SHARED.lock();
+ let eng = &mut *eng_guard;
+ let need_end = eng.native_stroke_owned || eng.was_hovering_canvas;
+ if need_end {
+ if let Some(tx) = eng.tx.as_mut() {
+ tx.push(ink_engine::NativeInputSample {
+ phys_x: 0.0,
+ phys_y: 0.0,
+ pressure: 0.0,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: ts,
+ buttons: 0,
+ phase: 3,
+ backend: 2,
+ });
+ }
}
- let owned = local.native_stroke_owned;
- local.native_stroke_owned = false;
+ let owned = eng.native_stroke_owned;
+ eng.native_stroke_owned = false;
+ eng.was_hovering_canvas = false;
owned
- });
+ };
if !was_native {
send_samples(&[TabletSample {
client_x: 0.0,
@@ -1024,7 +1324,6 @@ mod win_impl {
let pointer_id = (wparam & 0xFFFF) as u32;
let mut ptype = 0i32;
if GetPointerType(pointer_id, &mut ptype) != 0 && ptype == PT_PEN {
- let main_hwnd = dw_ref_data as HWND;
let mut count: u32 = 64;
let mut history: [POINTER_PEN_INFO; 64] = std::mem::zeroed();
if GetPointerPenInfoHistory(pointer_id, &mut count, history.as_mut_ptr()) != 0
@@ -1037,215 +1336,241 @@ mod win_impl {
let ts_now = qpc_now_ms();
let qpc_ms = qpc_freq_per_ms();
- // Per-pointer contact tracking & cross-HWND frame deduplication so
- // child/parent WebView2 HWND transitions NEVER emit spurious leave/up mid-stroke.
- let decision = {
- let Ok(mut dedup) = INK_DEDUP.lock() else {
- return;
- };
- dedup.process_message(
- hwnd as isize,
- main_hwnd as isize,
- pointer_id,
- raw_phase_code,
- newest_frame_id,
- newest_in_contact,
- )
- };
- let Some(decision) = decision else {
- return;
- };
- let phase_code = decision.emit_phase;
- let prev_perf_cutoff = decision.prev_perf_cutoff;
- let prev_ts_ms = decision.prev_ts_ms;
-
- let mut js_samples = Vec::with_capacity(n);
- let mut native_samples = Vec::with_capacity(n);
- let mut max_perf_emitted = prev_perf_cutoff;
- let mut running_ts = prev_ts_ms;
- LAST_STYLUS_ACTIVITY_MS_BITS.store(ts_now.to_bits(), Ordering::Relaxed);
-
- // Fallback span when hardware PerformanceCount is unavailable
- let fallback_span = if prev_ts_ms > 0.0 && ts_now > prev_ts_ms + 0.5 {
- (ts_now - prev_ts_ms).min(40.0)
- } else {
- (n as f64) * 4.0
- };
- let fallback_start = ts_now - fallback_span;
-
- // History is reverse chronological (0 = newest), emit oldest -> newest
- for (emit_pos, idx) in (0..n).rev().enumerate() {
- let info = &history[idx];
- let pinfo = &info.pointerInfo;
-
- // Skip already-emitted overlapping history samples during drag
- if phase_code == 2
- && prev_perf_cutoff > 0
- && pinfo.PerformanceCount > 0
- && pinfo.PerformanceCount <= prev_perf_cutoff
- {
- continue;
- }
- if pinfo.PerformanceCount > max_perf_emitted {
- max_perf_emitted = pinfo.PerformanceCount;
- }
-
- let (sx, sy) = try_himetric_to_screen_f64(
- pinfo.sourceDevice,
- pinfo.ptHimetricLocationRaw.x,
- pinfo.ptHimetricLocationRaw.y,
- pinfo.ptPixelLocationRaw.x,
- pinfo.ptPixelLocationRaw.y,
- );
- let ((phys_x, phys_y), (cx, cy)) =
- screen_to_physical_and_css_client_f64(main_hwnd, sx, sy);
-
- let in_contact = (pinfo.pointerFlags & POINTER_FLAG_INCONTACT) != 0;
- let pressure = if (info.penMask & PEN_MASK_PRESSURE) != 0 {
- let p = (info.pressure as f32 / 1024.0).clamp(0.0, 1.0);
- if in_contact { p.max(0.006) } else { p }
- } else if in_contact {
- // Never fabricate a fake 0.5 pressure spike on initial WM_POINTERDOWN
- // before the pen digitizer populates PEN_MASK_PRESSURE.
- if phase_code == 1 { 0.006 } else { 0.5 }
- } else {
- 0.0
- };
-
- let tilt_x = if (info.penMask & PEN_MASK_TILT_X) != 0 {
- (info.tiltX as f32).clamp(-90.0, 90.0)
- } else {
- 0.0
- };
- let tilt_y = if (info.penMask & PEN_MASK_TILT_Y) != 0 {
- (info.tiltY as f32).clamp(-90.0, 90.0)
- } else {
- 0.0
- };
- let twist = if (info.penMask & PEN_MASK_ROTATION) != 0 {
- (info.rotation as f32).rem_euclid(360.0)
- } else {
- 0.0
- };
-
- let mut buttons: u16 = 0;
- if in_contact || (pinfo.pointerFlags & POINTER_FLAG_FIRSTBUTTON) != 0 {
- buttons |= 1;
- }
- if (info.penFlags & PEN_FLAG_BARREL) != 0
- || (pinfo.pointerFlags & POINTER_FLAG_SECONDBUTTON) != 0
- {
- buttons |= 2;
- }
- if (info.penFlags & (PEN_FLAG_ERASER | PEN_FLAG_INVERTED)) != 0 {
- buttons |= 8;
- }
+ // Hoist window client origin, DPI, and modifier key queries ONCE per burst!
+ let coord_xform = WindowCoordTransform::for_hwnd(main_hwnd);
+ let mod_bits = query_modifier_bits();
+ let has_js_sink = HAS_JS_SINK.load(Ordering::Relaxed);
- let sample_phase = if idx == 0 {
- phase_code
- } else if in_contact {
- 2
- } else {
- 0
- };
+ WININK_SCRATCH.with(|scratch_cell| {
+ let mut scratch = scratch_cell.borrow_mut();
+ scratch.ring_samples.clear();
+ scratch.forward_js.clear();
- let raw_sample_ts = if pinfo.PerformanceCount > 0 {
- (pinfo.PerformanceCount as f64) / qpc_ms
- } else {
- fallback_start
- + fallback_span * ((emit_pos + 1) as f64 / (n as f64))
- };
- let sample_ts = if running_ts > 0.0 && raw_sample_ts < running_ts + 0.25
- {
- running_ts + 0.5
- } else {
- raw_sample_ts
- };
- running_ts = sample_ts;
+ // Lock INK_DEDUP ONCE per WM_POINTER* message (process + record_emitted).
+ let (phase_code, emitted_any) = {
+ let Ok(mut dedup) = INK_DEDUP.lock() else {
+ return;
+ };
+ let Some(decision) = dedup.process_message(
+ hwnd as isize,
+ main_hwnd as isize,
+ pointer_id,
+ raw_phase_code,
+ newest_frame_id,
+ newest_in_contact,
+ ) else {
+ return;
+ };
+ let phase_code = decision.emit_phase;
+ let prev_perf_cutoff = decision.prev_perf_cutoff;
+ let prev_ts_ms = decision.prev_ts_ms;
+ let mut max_perf_emitted = prev_perf_cutoff;
+ let mut running_ts = prev_ts_ms;
+ let mut emitted_down = false;
+
+ LAST_STYLUS_ACTIVITY_MS_BITS
+ .store(ts_now.to_bits(), Ordering::Relaxed);
+ STYLUS_IN_CONTACT.store(
+ phase_code == 1 || phase_code == 2,
+ Ordering::Release,
+ );
- let mut mod_bits = 0u16;
- unsafe {
- use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
- GetAsyncKeyState, VK_MENU, VK_SHIFT,
+ // Fallback span when hardware PerformanceCount is unavailable
+ let fallback_span = if prev_ts_ms > 0.0 && ts_now > prev_ts_ms + 0.5
+ {
+ (ts_now - prev_ts_ms).min(40.0)
+ } else {
+ (n as f64) * 4.0
};
- if (GetAsyncKeyState(VK_SHIFT as i32) as u16 & 0x8000) != 0 {
- mod_bits |= 0x0100;
- }
- if (GetAsyncKeyState(VK_MENU as i32) as u16 & 0x8000) != 0 {
- mod_bits |= 0x0200;
- }
- }
- native_samples.push(ink_engine::NativeInputSample {
- phys_x,
- phys_y,
- pressure,
- tilt_x,
- tilt_y,
- twist,
- timestamp_ms: sample_ts,
- buttons: buttons | mod_bits,
- phase: sample_phase,
- backend: 2,
- });
+ let fallback_start = ts_now - fallback_span;
+
+ // Resolve cached GetPointerDeviceRects ONCE for this burst's device
+ let mut last_dev = history[0].pointerInfo.sourceDevice;
+ let mut cached_rects = scratch.resolve_device_rects(last_dev);
+
+ // History is reverse chronological (0 = newest), emit oldest -> newest
+ for (emit_pos, idx) in (0..n).rev().enumerate() {
+ let info = &history[idx];
+ let pinfo = &info.pointerInfo;
+
+ // Skip already-emitted overlapping history samples during drag
+ if phase_code == 2
+ && prev_perf_cutoff > 0
+ && pinfo.PerformanceCount > 0
+ && pinfo.PerformanceCount <= prev_perf_cutoff
+ {
+ continue;
+ }
+ if pinfo.PerformanceCount > max_perf_emitted {
+ max_perf_emitted = pinfo.PerformanceCount;
+ }
- js_samples.push(TabletSample {
- client_x: cx,
- client_y: cy,
- pressure,
- tilt_x,
- tilt_y,
- twist,
- timestamp_ms: sample_ts,
- buttons,
- phase: sample_phase,
- backend: 2,
- });
- }
+ if pinfo.sourceDevice != last_dev {
+ last_dev = pinfo.sourceDevice;
+ cached_rects = scratch.resolve_device_rects(last_dev);
+ }
+ let (sx, sy) = match cached_rects {
+ Some(r) => r.map_himetric(
+ pinfo.ptHimetricLocationRaw.x,
+ pinfo.ptHimetricLocationRaw.y,
+ pinfo.ptPixelLocationRaw.x,
+ pinfo.ptPixelLocationRaw.y,
+ ),
+ None => (
+ pinfo.ptPixelLocationRaw.x as f64,
+ pinfo.ptPixelLocationRaw.y as f64,
+ ),
+ };
+ let ((phys_x, phys_y), _) = coord_xform.map(sx, sy);
+
+ let in_contact =
+ (pinfo.pointerFlags & POINTER_FLAG_INCONTACT) != 0;
+ let sample_phase = assign_coalesced_ink_sample_phase(
+ phase_code,
+ in_contact,
+ idx == 0,
+ &mut emitted_down,
+ );
+
+ let pressure = if (info.penMask & PEN_MASK_PRESSURE) != 0 {
+ let p = (info.pressure as f32 / 1024.0).clamp(0.0, 1.0);
+ if in_contact { p.max(0.006) } else { p }
+ } else if in_contact {
+ // Never fabricate a fake 0.5 pressure spike on initial WM_POINTERDOWN
+ // before the pen digitizer populates PEN_MASK_PRESSURE.
+ if sample_phase == 1 { 0.006 } else { 0.5 }
+ } else {
+ 0.0
+ };
+
+ let tilt_x = if (info.penMask & PEN_MASK_TILT_X) != 0 {
+ (info.tiltX as f32).clamp(-90.0, 90.0)
+ } else {
+ 0.0
+ };
+ let tilt_y = if (info.penMask & PEN_MASK_TILT_Y) != 0 {
+ (info.tiltY as f32).clamp(-90.0, 90.0)
+ } else {
+ 0.0
+ };
+ let twist = if (info.penMask & PEN_MASK_ROTATION) != 0 {
+ (info.rotation as f32).rem_euclid(360.0)
+ } else {
+ 0.0
+ };
+
+ let mut buttons: u16 = 0;
+ if in_contact
+ || (pinfo.pointerFlags & POINTER_FLAG_FIRSTBUTTON) != 0
+ {
+ buttons |= 1;
+ }
+ if (info.penFlags & PEN_FLAG_BARREL) != 0
+ || (pinfo.pointerFlags & POINTER_FLAG_SECONDBUTTON) != 0
+ {
+ buttons |= 2;
+ }
+ if (info.penFlags & (PEN_FLAG_ERASER | PEN_FLAG_INVERTED)) != 0
+ {
+ buttons |= 8;
+ }
- if !native_samples.is_empty() {
- if let Ok(mut dedup) = INK_DEDUP.lock() {
- dedup.record_emitted(
- pointer_id,
- phase_code,
- max_perf_emitted,
- running_ts,
- );
- }
+ let raw_sample_ts = if pinfo.PerformanceCount > 0 {
+ (pinfo.PerformanceCount as f64) / qpc_ms
+ } else {
+ fallback_start
+ + fallback_span * ((emit_pos + 1) as f64 / (n as f64))
+ };
+ let sample_ts = if running_ts > 0.0
+ && raw_sample_ts < running_ts + 0.25
+ {
+ running_ts + 0.5
+ } else {
+ raw_sample_ts
+ };
+ running_ts = sample_ts;
+
+ scratch.ring_samples.push(ink_engine::NativeInputSample {
+ phys_x,
+ phys_y,
+ pressure,
+ tilt_x,
+ tilt_y,
+ twist,
+ timestamp_ms: sample_ts,
+ buttons: buttons | mod_bits,
+ phase: sample_phase,
+ backend: 2,
+ });
+ }
- // Push directly into lock-free SPSC ring for `ink-engine` (zero IPC),
- // and suppress Tauri Channel forwarding when natively owned.
- let mut forward_js: Vec<TabletSample> = Vec::new();
- WININK_ENGINE.with(|cell| {
- let mut local = cell.borrow_mut();
- sync_winink_engine_local(&mut local);
- let WinInkEngineLocal {
- tx,
- hit_test,
- native_stroke_owned,
- } = &mut *local;
- if let Some(tx) = tx.as_mut() {
- tx.push_batch(&native_samples);
- for (ns, js) in native_samples.iter().zip(js_samples) {
- let owned_by_engine = route_sample_ownership(
- native_stroke_owned,
- hit_test.as_ref(),
- ns.phys_x,
- ns.phys_y,
- ns.phase,
- );
- if !owned_by_engine {
- forward_js.push(js);
+ let emitted_any = !scratch.ring_samples.is_empty();
+ if emitted_any {
+ dedup.record_emitted(
+ pointer_id,
+ phase_code,
+ max_perf_emitted,
+ running_ts,
+ );
+ }
+ (phase_code, emitted_any)
+ };
+ let _ = phase_code;
+
+ if emitted_any {
+ // Route & filter into the shared DX12 SPSC ring (zero wakeups for
+ // out-of-canvas hover!) and optionally collect JS fallback samples.
+ {
+ let mut eng_guard = WININK_ENGINE_SHARED.lock();
+ let eng = &mut *eng_guard;
+ let has_engine = eng.tx.is_some();
+ let mut write_idx = 0usize;
+ for i in 0..scratch.ring_samples.len() {
+ let ns = scratch.ring_samples[i];
+ let (ring_opt, owned_by_engine) = if has_engine {
+ route_and_filter_native_sample(
+ ns,
+ eng.hit_test.as_ref(),
+ &mut eng.native_stroke_owned,
+ &mut eng.was_hovering_canvas,
+ )
+ } else {
+ (None, false)
+ };
+ if let Some(filtered) = ring_opt {
+ scratch.ring_samples[write_idx] = filtered;
+ write_idx += 1;
+ }
+ if has_js_sink && !owned_by_engine {
+ scratch.forward_js.push(TabletSample {
+ client_x: (ns.phys_x as f64 * coord_xform.inv_scale)
+ as f32,
+ client_y: (ns.phys_y as f64 * coord_xform.inv_scale)
+ as f32,
+ pressure: ns.pressure,
+ tilt_x: ns.tilt_x,
+ tilt_y: ns.tilt_y,
+ twist: ns.twist,
+ timestamp_ms: ns.timestamp_ms,
+ buttons: ns.buttons & 0x00FF,
+ phase: ns.phase,
+ backend: 2,
+ });
+ }
+ }
+ scratch.ring_samples.truncate(write_idx);
+ if !scratch.ring_samples.is_empty() {
+ if let Some(tx) = eng.tx.as_mut() {
+ tx.push_batch(&scratch.ring_samples);
}
}
- } else {
- forward_js = js_samples;
}
- });
- if !forward_js.is_empty() {
- send_samples(&forward_js);
+ if has_js_sink && !scratch.forward_js.is_empty() {
+ send_samples(&scratch.forward_js);
+ }
}
- }
+ });
}
}
}
@@ -1255,18 +1580,42 @@ mod win_impl {
}
unsafe extern "system" fn enum_child_install_subclass(hwnd: HWND, lparam: LPARAM) -> BOOL {
- let main_hwnd = lparam as usize;
- if SetWindowSubclass(hwnd, Some(ink_subclass_proc), SUBCLASS_ID, main_hwnd) != 0 {
- if let Ok(mut list) = SUBCLASSED_HWNDS.lock() {
- let raw = hwnd as isize;
- if !list.contains(&raw) {
- list.push(raw);
+ let _ = std::panic::catch_unwind(|| {
+ // comctl32 window subclassing across threads is UB; only hook child HWNDs
+ // owned by the current UI thread.
+ if GetWindowThreadProcessId(hwnd, std::ptr::null_mut()) != GetCurrentThreadId() {
+ return;
+ }
+ let raw = hwnd as isize;
+ let already = SUBCLASSED_HWNDS
+ .try_lock()
+ .map(|list| list.contains(&raw))
+ .unwrap_or(false);
+ if already {
+ return;
+ }
+ let main_hwnd = lparam as usize;
+ if SetWindowSubclass(hwnd, Some(ink_subclass_proc), SUBCLASS_ID, main_hwnd) != 0 {
+ if let Ok(mut list) = SUBCLASSED_HWNDS.lock() {
+ if !list.contains(&raw) {
+ list.push(raw);
+ }
}
}
- }
+ });
1 // continue enumeration
}
+ unsafe fn ensure_child_windows_subclassed(main_hwnd: HWND) {
+ if !main_hwnd.is_null() && IsWindow(main_hwnd) != 0 {
+ EnumChildWindows(
+ main_hwnd,
+ Some(enum_child_install_subclass),
+ main_hwnd as LPARAM,
+ );
+ }
+ }
+
fn install_windows_ink_hooks(main_hwnd: HWND) -> Result<(), String> {
uninstall_windows_ink_hooks();
unsafe {
@@ -1277,7 +1626,7 @@ mod win_impl {
}
}
// Also hook WebView2 child HWNDs (Chrome_WidgetWin_1 / Chrome_RenderWidgetHostHWND)
- EnumChildWindows(main_hwnd, Some(enum_child_install_subclass), main_ref as LPARAM);
+ ensure_child_windows_subclassed(main_hwnd);
}
Ok(())
}
@@ -1291,9 +1640,15 @@ mod win_impl {
};
for raw in hwnds {
unsafe {
- RemoveWindowSubclass(raw as HWND, Some(ink_subclass_proc), SUBCLASS_ID);
+ let hwnd = raw as HWND;
+ if !hwnd.is_null() && IsWindow(hwnd) != 0 {
+ RemoveWindowSubclass(hwnd, Some(ink_subclass_proc), SUBCLASS_ID);
+ }
}
}
+ WININK_SCRATCH.with(|cell| {
+ cell.borrow_mut().device_rects_cache.clear();
+ });
if let Ok(mut dedup) = INK_DEDUP.lock() {
dedup.reset();
}
@@ -1325,6 +1680,10 @@ mod win_impl {
engine_tx: Option<ink_engine::TabletRingProducer>,
hit_test: Option<ink_engine::SharedHitTest>,
native_stroke_owned: bool,
+ was_hovering_canvas: bool,
+ scratch_pkts: Vec<WtPacket>,
+ scratch_ring_samples: Vec<ink_engine::NativeInputSample>,
+ scratch_forward_js: Vec<TabletSample>,
}
thread_local! {
@@ -1336,32 +1695,44 @@ mod win_impl {
msg: u32,
wparam: WPARAM,
lparam: LPARAM,
- _uid_subclass: usize,
+ uid_subclass: usize,
_dw_ref_data: usize,
) -> LRESULT {
- let should_raise = match msg {
- WM_ACTIVATE => (wparam & 0xFFFF) != 0,
- WM_ACTIVATEAPP => wparam != 0,
- WM_NCACTIVATE => wparam != 0,
- WM_SETFOCUS => true,
- _ => false,
- };
- let should_blur = match msg {
- WM_ACTIVATE => (wparam & 0xFFFF) == 0,
- WM_ACTIVATEAPP => wparam == 0,
- _ => false,
- };
- if should_raise || should_blur {
- let wt_hwnd = WINTAB_MSG_HWND.load(Ordering::Acquire);
- if wt_hwnd != 0 {
- let app_msg = if should_raise {
- WM_APP_WINTAB_FOCUS
- } else {
- WM_APP_WINTAB_BLUR
- };
- PostMessageW(wt_hwnd as HWND, app_msg, 0, 0);
+ let _ = std::panic::catch_unwind(|| {
+ if msg == WM_NCDESTROY {
+ RemoveWindowSubclass(hwnd, Some(wintab_focus_subclass_proc), uid_subclass);
+ let _ = WINTAB_FOCUS_SUBCLASS_HWND.compare_exchange(
+ hwnd as isize,
+ 0,
+ Ordering::SeqCst,
+ Ordering::SeqCst,
+ );
+ return;
}
- }
+ let should_raise = match msg {
+ WM_ACTIVATE => (wparam & 0xFFFF) != 0,
+ WM_ACTIVATEAPP => wparam != 0,
+ WM_NCACTIVATE => wparam != 0,
+ WM_SETFOCUS => true,
+ _ => false,
+ };
+ let should_blur = match msg {
+ WM_ACTIVATE => (wparam & 0xFFFF) == 0,
+ WM_ACTIVATEAPP => wparam == 0,
+ _ => false,
+ };
+ if should_raise || should_blur {
+ let wt_hwnd = WINTAB_MSG_HWND.load(Ordering::Acquire);
+ if wt_hwnd != 0 {
+ let app_msg = if should_raise {
+ WM_APP_WINTAB_FOCUS
+ } else {
+ WM_APP_WINTAB_BLUR
+ };
+ PostMessageW(wt_hwnd as HWND, app_msg, 0, 0);
+ }
+ }
+ });
DefSubclassProc(hwnd, msg, wparam, lparam)
}
@@ -1384,11 +1755,14 @@ mod win_impl {
let prev = WINTAB_FOCUS_SUBCLASS_HWND.swap(0, Ordering::SeqCst);
if prev != 0 {
unsafe {
- RemoveWindowSubclass(
- prev as HWND,
- Some(wintab_focus_subclass_proc),
- WINTAB_FOCUS_SUBCLASS_ID,
- );
+ let hwnd = prev as HWND;
+ if !hwnd.is_null() && IsWindow(hwnd) != 0 {
+ RemoveWindowSubclass(
+ hwnd,
+ Some(wintab_focus_subclass_proc),
+ WINTAB_FOCUS_SUBCLASS_ID,
+ );
+ }
}
}
}
@@ -1413,6 +1787,8 @@ mod win_impl {
rt.was_foreground = true;
});
} else if msg == WM_APP_WINTAB_BLUR {
+ STYLUS_IN_CONTACT.store(false, Ordering::Release);
+ WINTAB_IN_PROXIMITY.store(false, Ordering::Release);
WT_RT.with(|cell| {
let mut borrow = cell.borrow_mut();
let Some(rt) = borrow.as_mut() else { return };
@@ -1420,10 +1796,28 @@ mod win_impl {
if rt.contact.was_down {
rt.contact.reset();
let ts = qpc_now_ms();
- if let Some(tx) = rt.engine_tx.as_mut() {
- tx.push(ink_engine::NativeInputSample {
- phys_x: 0.0,
- phys_y: 0.0,
+ let was_native = rt.native_stroke_owned;
+ rt.native_stroke_owned = false;
+ rt.was_hovering_canvas = false;
+ if was_native {
+ if let Some(tx) = rt.engine_tx.as_mut() {
+ tx.push(ink_engine::NativeInputSample {
+ phys_x: 0.0,
+ phys_y: 0.0,
+ pressure: 0.0,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: ts,
+ buttons: 0,
+ phase: 3,
+ backend: 1,
+ });
+ }
+ } else {
+ send_samples(&[TabletSample {
+ client_x: 0.0,
+ client_y: 0.0,
pressure: 0.0,
tilt_x: 0.0,
tilt_y: 0.0,
@@ -1432,23 +1826,23 @@ mod win_impl {
buttons: 0,
phase: 3,
backend: 1,
- });
+ }]);
}
- let was_native = rt.native_stroke_owned;
- rt.native_stroke_owned = false;
- if !was_native {
- send_samples(&[TabletSample {
- client_x: 0.0,
- client_y: 0.0,
+ } else if rt.was_hovering_canvas {
+ rt.was_hovering_canvas = false;
+ if let Some(tx) = rt.engine_tx.as_mut() {
+ tx.push(ink_engine::NativeInputSample {
+ phys_x: 0.0,
+ phys_y: 0.0,
pressure: 0.0,
tilt_x: 0.0,
tilt_y: 0.0,
twist: 0.0,
- timestamp_ms: ts,
+ timestamp_ms: qpc_now_ms(),
buttons: 0,
- phase: 3,
+ phase: 4,
backend: 1,
- }]);
+ });
}
}
});
@@ -1462,6 +1856,7 @@ mod win_impl {
rt.engine_tx = None;
rt.hit_test = None;
rt.native_stroke_owned = false;
+ rt.was_hovering_canvas = false;
} else if rt.engine_tx.is_none()
&& WINTAB_RING_PENDING.load(Ordering::Acquire)
{
@@ -1480,18 +1875,83 @@ mod win_impl {
}
rt.was_foreground = is_fg;
+ // Drain full WinTab queue (up to 4 x 64 = 256 packets) so a 128-packet queue
+ // is never half-drained under load.
+ rt.scratch_pkts.clear();
let mut buf: [WtPacket; 64] = std::mem::zeroed();
- let n = (rt.lib.wt_packets_get)(rt.hctx, 64, buf.as_mut_ptr() as *mut c_void);
- if n <= 0 {
+ for _ in 0..4 {
+ let n = (rt.lib.wt_packets_get)(rt.hctx, 64, buf.as_mut_ptr() as *mut c_void);
+ if n <= 0 {
+ break;
+ }
+ let got = (n as usize).min(buf.len());
+ rt.scratch_pkts.extend_from_slice(&buf[..got]);
+ if got < buf.len() {
+ break;
+ }
+ }
+ let count = rt.scratch_pkts.len();
+ if count == 0 {
+ return;
+ }
+
+ // Drain driver queue above so it never stalls, but NEVER paint onto InkStudio
+ // when another application window has focus.
+ if !is_fg {
+ STYLUS_IN_CONTACT.store(false, Ordering::Release);
+ WINTAB_IN_PROXIMITY.store(false, Ordering::Release);
+ if rt.contact.was_down {
+ rt.contact.reset();
+ let ts = qpc_now_ms();
+ if rt.native_stroke_owned {
+ if let Some(tx) = rt.engine_tx.as_mut() {
+ tx.push(ink_engine::NativeInputSample {
+ phys_x: 0.0,
+ phys_y: 0.0,
+ pressure: 0.0,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: ts,
+ buttons: 0,
+ phase: 3,
+ backend: 1,
+ });
+ }
+ }
+ rt.native_stroke_owned = false;
+ rt.was_hovering_canvas = false;
+ } else if rt.was_hovering_canvas {
+ rt.was_hovering_canvas = false;
+ if let Some(tx) = rt.engine_tx.as_mut() {
+ tx.push(ink_engine::NativeInputSample {
+ phys_x: 0.0,
+ phys_y: 0.0,
+ pressure: 0.0,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: qpc_now_ms(),
+ buttons: 0,
+ phase: 4,
+ backend: 1,
+ });
+ }
+ }
return;
}
- let count = n as usize;
let ts_now = qpc_now_ms();
LAST_WINTAB_PACKET_MS_BITS.store(ts_now.to_bits(), Ordering::Relaxed);
LAST_STYLUS_ACTIVITY_MS_BITS.store(ts_now.to_bits(), Ordering::Relaxed);
- let mut native_samples = Vec::with_capacity(count);
- let mut forward_js = Vec::new();
+
+ // Hoist window client origin, DPI, and modifier key queries ONCE per burst!
+ let coord_xform = WindowCoordTransform::for_hwnd(rt.main_hwnd);
+ let mod_bits = query_modifier_bits();
+ let has_js_sink = HAS_JS_SINK.load(Ordering::Relaxed);
+
+ rt.scratch_ring_samples.clear();
+ rt.scratch_forward_js.clear();
let denom_p = (rt.max_pressure.max(1)) as f32;
let mut cur_pt = POINT { x: 0, y: 0 };
@@ -1504,7 +1964,7 @@ mod win_impl {
// Pre-calibrate Y-axis orientation on newest packet (which aligns with GetCursorPos)
// before mapping older packets in this burst.
if rt.coord_mapper.locked_mode().is_none() {
- let newest = &buf[count - 1];
+ let newest = rt.scratch_pkts[count - 1];
let _ = rt.coord_mapper.map_to_screen(
newest.pk_x,
newest.pk_y,
@@ -1521,8 +1981,8 @@ mod win_impl {
}
// Resolve true hardware packet timestamps from pk_time (with clean even interpolation fallback)
- let newest_pk_time = buf[count - 1].pk_time;
- let oldest_pk_time = buf[0].pk_time;
+ let newest_pk_time = rt.scratch_pkts[count - 1].pk_time;
+ let oldest_pk_time = rt.scratch_pkts[0].pk_time;
let pk_span = newest_pk_time.wrapping_sub(oldest_pk_time);
let has_valid_pk_span = count > 1 && pk_span > 0 && pk_span <= 200;
let fallback_span = if rt.last_ts_ms > 0.0 && ts_now > rt.last_ts_ms + 0.5 {
@@ -1531,8 +1991,10 @@ mod win_impl {
(count as f64) * 4.0
};
let fallback_start = ts_now - fallback_span;
+ let has_engine = rt.engine_tx.is_some();
- for (idx, pkt) in buf[..count].iter().enumerate() {
+ for idx in 0..count {
+ let pkt = rt.scratch_pkts[idx];
// Map WinTab high-res output space -> sub-pixel virtual screen -> physical + CSS client pixels.
// Pass cursor_pos only for the newest packet in the burst so older history points
// preserve exact sub-pixel positions while still guarding against driver quirks.
@@ -1550,8 +2012,7 @@ mod win_impl {
rt.sys_ext_y,
pkt_cursor,
);
- let ((phys_x, phys_y), (cx, cy)) =
- screen_to_physical_and_css_client_f64(rt.main_hwnd, sx, sy);
+ let ((phys_x, phys_y), (cx, cy)) = coord_xform.map(sx, sy);
let raw_pressure = (pkt.pk_normal_pressure as f32 / denom_p).clamp(0.0, 1.0);
let (tilt_x, tilt_y, twist) = wintab_orientation_to_tilt(
@@ -1585,6 +2046,8 @@ mod win_impl {
tip_button_down,
sample_ts,
);
+ WINTAB_IN_PROXIMITY.store(!out_of_proximity, Ordering::Release);
+ STYLUS_IN_CONTACT.store(eff_tip_down, Ordering::Release);
let mut buttons: u16 = 0;
if eff_tip_down {
@@ -1600,20 +2063,7 @@ mod win_impl {
buttons |= 8;
}
- let mut mod_bits = 0u16;
- unsafe {
- use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
- GetAsyncKeyState, VK_MENU, VK_SHIFT,
- };
- if (GetAsyncKeyState(VK_SHIFT as i32) as u16 & 0x8000) != 0 {
- mod_bits |= 0x0100;
- }
- if (GetAsyncKeyState(VK_MENU as i32) as u16 & 0x8000) != 0 {
- mod_bits |= 0x0200;
- }
- }
-
- native_samples.push(ink_engine::NativeInputSample {
+ let ns = ink_engine::NativeInputSample {
phys_x,
phys_y,
pressure,
@@ -1624,22 +2074,25 @@ mod win_impl {
buttons: buttons | mod_bits,
phase,
backend: 1,
- });
+ };
- let owned_by_engine = if rt.engine_tx.is_some() {
- route_sample_ownership(
- &mut rt.native_stroke_owned,
+ let (ring_opt, owned_by_engine) = if has_engine {
+ route_and_filter_native_sample(
+ ns,
rt.hit_test.as_ref(),
- phys_x,
- phys_y,
- phase,
+ &mut rt.native_stroke_owned,
+ &mut rt.was_hovering_canvas,
)
} else {
- false
+ (None, false)
};
- if !owned_by_engine {
- forward_js.push(TabletSample {
+ if let Some(filtered) = ring_opt {
+ rt.scratch_ring_samples.push(filtered);
+ }
+
+ if has_js_sink && !owned_by_engine {
+ rt.scratch_forward_js.push(TabletSample {
client_x: cx,
client_y: cy,
pressure,
@@ -1654,37 +2107,46 @@ mod win_impl {
}
}
- // Lock-free SPSC push directly into `ink-engine` (zero IPC, immediate wake)
- if let Some(tx) = rt.engine_tx.as_mut() {
- tx.push_batch(&native_samples);
+ // Lock-free SPSC push directly into `ink-engine` ONLY when there are samples
+ // relevant to the canvas (zero wakeups when hovering sidebars/toolbars!)
+ if !rt.scratch_ring_samples.is_empty() {
+ if let Some(tx) = rt.engine_tx.as_mut() {
+ tx.push_batch(&rt.scratch_ring_samples);
+ }
}
- if !forward_js.is_empty() {
- send_samples(&forward_js);
+ if has_js_sink && !rt.scratch_forward_js.is_empty() {
+ send_samples(&rt.scratch_forward_js);
}
});
} else if msg == WT_PROXIMITY {
let entering = (lparam & 0xFFFF) != 0;
+ WINTAB_IN_PROXIMITY.store(entering, Ordering::Release);
if !entering {
+ STYLUS_IN_CONTACT.store(false, Ordering::Release);
let ts = qpc_now_ms();
let was_native = WT_RT.with(|cell| {
if let Some(rt) = cell.borrow_mut().as_mut() {
rt.contact.reset();
- if let Some(tx) = rt.engine_tx.as_mut() {
- tx.push(ink_engine::NativeInputSample {
- phys_x: 0.0,
- phys_y: 0.0,
- pressure: 0.0,
- tilt_x: 0.0,
- tilt_y: 0.0,
- twist: 0.0,
- timestamp_ms: ts,
- buttons: 0,
- phase: 4,
- backend: 1,
- });
- }
let owned = rt.native_stroke_owned;
+ let was_hovering = rt.was_hovering_canvas;
rt.native_stroke_owned = false;
+ rt.was_hovering_canvas = false;
+ if owned || was_hovering {
+ if let Some(tx) = rt.engine_tx.as_mut() {
+ tx.push(ink_engine::NativeInputSample {
+ phys_x: 0.0,
+ phys_y: 0.0,
+ pressure: 0.0,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: ts,
+ buttons: 0,
+ phase: 4,
+ backend: 1,
+ });
+ }
+ }
owned
} else {
false
@@ -1719,28 +2181,10 @@ mod win_impl {
if id_len == 0 {
return (false, None, 1024);
}
- let mut name_buf = [0u16; 128];
- let name_bytes = (lib.wt_info)(
- WTI_DEVICES,
- DVC_NAME,
- name_buf.as_mut_ptr() as *mut c_void,
- );
- let device_name = if name_bytes > 0 {
- let chars = (name_bytes as usize / 2).min(name_buf.len());
- let s = String::from_utf16_lossy(&name_buf[..chars])
- .trim_end_matches('\0')
- .to_string();
- if s.is_empty() { None } else { Some(s) }
- } else {
- Some("WinTab Digitizer".to_string())
- };
+ let device_name = query_wintab_device_name(&lib);
let mut p_axis: Axis = std::mem::zeroed();
- let max_p = if (lib.wt_info)(
- WTI_DEVICES,
- DVC_NPRESSURE,
- &mut p_axis as *mut Axis as *mut c_void,
- ) > 0
+ let max_p = if query_wintab_struct(&lib, WTI_DEVICES, DVC_NPRESSURE, &mut p_axis)
&& p_axis.ax_max > 0
{
p_axis.ax_max as u32
@@ -1760,7 +2204,7 @@ mod win_impl {
.name("inkstudio-wintab".to_string())
.spawn(move || unsafe {
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
- let tid = windows_sys::Win32::System::Threading::GetCurrentThreadId();
+ let tid = GetCurrentThreadId();
WINTAB_THREAD_ID.store(tid as isize, Ordering::SeqCst);
let Some(lib) = WintabLib::load() else {
@@ -1770,39 +2214,16 @@ mod win_impl {
};
let mut lc: LogContextW = std::mem::zeroed();
- if (lib.wt_info)(
- WTI_DEFSYSCTX,
- 0,
- &mut lc as *mut LogContextW as *mut c_void,
- ) == 0
- {
- let _ = tx.send(Err("WinTab driver reported no default system context".to_string()));
+ if !query_wintab_struct(&lib, WTI_DEFSYSCTX, 0, &mut lc) {
+ let _ = tx.send(Err("WinTab driver reported no compatible default system context".to_string()));
WINTAB_RUNNING.store(false, Ordering::SeqCst);
return;
}
- let mut name_buf = [0u16; 128];
- let nbytes = (lib.wt_info)(
- WTI_DEVICES,
- DVC_NAME,
- name_buf.as_mut_ptr() as *mut c_void,
- );
- let device_name = if nbytes > 0 {
- let chars = (nbytes as usize / 2).min(name_buf.len());
- let s = String::from_utf16_lossy(&name_buf[..chars])
- .trim_end_matches('\0')
- .to_string();
- if s.is_empty() { None } else { Some(s) }
- } else {
- Some("WinTab Digitizer".to_string())
- };
+ let device_name = query_wintab_device_name(&lib);
let mut p_axis: Axis = std::mem::zeroed();
- let max_pressure = if (lib.wt_info)(
- WTI_DEVICES,
- DVC_NPRESSURE,
- &mut p_axis as *mut Axis as *mut c_void,
- ) > 0
+ let max_pressure = if query_wintab_struct(&lib, WTI_DEVICES, DVC_NPRESSURE, &mut p_axis)
&& p_axis.ax_max > 0
{
p_axis.ax_max as u32
@@ -1811,11 +2232,8 @@ mod win_impl {
};
let mut ori_axes: [Axis; 3] = std::mem::zeroed();
- let has_ori = (lib.wt_info)(
- WTI_DEVICES,
- DVC_ORIENTATION,
- ori_axes.as_mut_ptr() as *mut c_void,
- ) > 0;
+ let has_ori =
+ query_wintab_struct(&lib, WTI_DEVICES, DVC_ORIENTATION, &mut ori_axes);
let (az_max, alt_max, twist_max) = if has_ori {
(ori_axes[0].ax_max, ori_axes[1].ax_max, ori_axes[2].ax_max)
} else {
@@ -1887,6 +2305,25 @@ mod win_impl {
return;
}
+ // Re-verify active packet format matches our #[repr(C)] WtPacket layout
+ // so WTPacketsGet can never write mismatched struct fields onto the stack.
+ if let Some(wt_get) = lib.wt_get {
+ let mut active_lc: LogContextW = std::mem::zeroed();
+ if wt_get(hctx, &mut active_lc) != 0 {
+ lc = active_lc;
+ }
+ }
+ if lc.lc_pkt_data != PACKET_DATA_MASK {
+ (lib.wt_close)(hctx);
+ DestroyWindow(msg_hwnd);
+ let _ = tx.send(Err(format!(
+ "WinTab driver returned incompatible packet mask: 0x{:08X} (expected 0x{:08X})",
+ lc.lc_pkt_data, PACKET_DATA_MASK
+ )));
+ WINTAB_RUNNING.store(false, Ordering::SeqCst);
+ return;
+ }
+
if let Some(qset) = lib.wt_queue_size_set {
qset(hctx, 128);
}
@@ -1924,6 +2361,10 @@ mod win_impl {
engine_tx,
hit_test,
native_stroke_owned: false,
+ was_hovering_canvas: false,
+ scratch_pkts: Vec::with_capacity(128),
+ scratch_ring_samples: Vec::with_capacity(128),
+ scratch_forward_js: Vec::with_capacity(64),
});
});
@@ -2012,6 +2453,7 @@ mod win_impl {
.lock()
.map_err(|_| "Failed to lock tablet sink".to_string())?;
*sink = Some(ActiveSink { channel });
+ HAS_JS_SINK.store(true, Ordering::Release);
}
let (wt_avail, _, _) = probe_wintab();
@@ -2080,6 +2522,9 @@ mod win_impl {
pub fn stop() {
stop_wintab_thread();
uninstall_windows_ink_hooks();
+ STYLUS_IN_CONTACT.store(false, Ordering::SeqCst);
+ WINTAB_IN_PROXIMITY.store(false, Ordering::SeqCst);
+ HAS_JS_SINK.store(false, Ordering::SeqCst);
if let Ok(mut sink) = ACTIVE_SINK.lock() {
*sink = None;
}
@@ -2233,10 +2678,21 @@ pub fn start_native_only_if_idle(main_hwnd_raw: isize) {
}
#[cfg(target_os = "windows")]
+#[allow(dead_code)]
pub fn last_stylus_activity_ms() -> f64 {
win_impl::last_stylus_activity_ms()
}
+#[cfg(target_os = "windows")]
+pub fn last_wintab_activity_ms() -> f64 {
+ win_impl::last_wintab_activity_ms()
+}
+
+#[cfg(target_os = "windows")]
+pub fn is_stylus_in_contact() -> bool {
+ win_impl::is_stylus_in_contact()
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -2527,4 +2983,189 @@ mod tests {
assert!((sx_fast - 1370.5).abs() < 1e-4, "fast flick snapped back to cursor: {}", sx_fast);
assert!((sy_fast - 460.25).abs() < 1e-4, "fast flick snapped back to cursor: {}", sy_fast);
}
+
+ #[test]
+ fn test_coalesced_pointerdown_assigns_phase_1_to_first_in_contact_sample() {
+ // 1. All 3 coalesced WM_POINTERDOWN samples are in contact -> oldest gets phase=1, later get phase=2
+ let mut emitted_down = false;
+ let in_contact_flags = [true, true, true];
+ let phases: Vec<u8> = in_contact_flags
+ .iter()
+ .enumerate()
+ .map(|(i, &ic)| {
+ assign_coalesced_ink_sample_phase(
+ 1,
+ ic,
+ i + 1 == in_contact_flags.len(),
+ &mut emitted_down,
+ )
+ })
+ .collect();
+ assert_eq!(
+ phases,
+ vec![1, 2, 2],
+ "first in-contact sample must receive phase=1, never phase=2 before phase=1"
+ );
+
+ // 2. Leading hover sample before pen touches down -> [0, 1, 2]
+ let mut emitted_down = false;
+ let flags_with_hover = [false, true, true];
+ let phases_hover: Vec<u8> = flags_with_hover
+ .iter()
+ .enumerate()
+ .map(|(i, &ic)| {
+ assign_coalesced_ink_sample_phase(
+ 1,
+ ic,
+ i + 1 == flags_with_hover.len(),
+ &mut emitted_down,
+ )
+ })
+ .collect();
+ assert_eq!(phases_hover, vec![0, 1, 2]);
+
+ // 3. Edge case: WM_POINTERDOWN without INCONTACT bit set -> newest still gets phase=1
+ let mut emitted_down = false;
+ let no_contact = [false, false];
+ let phases_fallback: Vec<u8> = no_contact
+ .iter()
+ .enumerate()
+ .map(|(i, &ic)| {
+ assign_coalesced_ink_sample_phase(
+ 1,
+ ic,
+ i + 1 == no_contact.len(),
+ &mut emitted_down,
+ )
+ })
+ .collect();
+ assert_eq!(phases_fallback, vec![0, 1]);
+
+ // 4. Coalesced WM_POINTERUP with trailing drag points before lift -> [2, 2, 3]
+ let mut emitted_down = false;
+ let up_flags = [true, true, false];
+ let phases_up: Vec<u8> = up_flags
+ .iter()
+ .enumerate()
+ .map(|(i, &ic)| {
+ assign_coalesced_ink_sample_phase(
+ 3,
+ ic,
+ i + 1 == up_flags.len(),
+ &mut emitted_down,
+ )
+ })
+ .collect();
+ assert_eq!(phases_up, vec![2, 2, 3]);
+ }
+
+ #[test]
+ fn test_non_canvas_hover_does_not_wake_render_ring() {
+ let ht = ink_engine::SharedHitTest::new();
+ ht.set_visible(true);
+ ht.set_viewport(ink_engine::ViewportRect {
+ x_px: 200,
+ y_px: 80,
+ width_px: 1000,
+ height_px: 700,
+ dpr: 1.0,
+ });
+ // Occluded floating brush pill inside viewport
+ ht.set_occluded_rects(vec![ink_engine::UiRect {
+ x: 212.0,
+ y: 280.0,
+ width: 48.0,
+ height: 260.0,
+ }]);
+ ht.set_policy(ink_engine::InteractionPolicy::default());
+
+ let mk_hover = |x: f32, y: f32, ts: f64| ink_engine::NativeInputSample {
+ phys_x: x,
+ phys_y: y,
+ pressure: 0.0,
+ tilt_x: 0.0,
+ tilt_y: 0.0,
+ twist: 0.0,
+ timestamp_ms: ts,
+ buttons: 0,
+ phase: 0,
+ backend: 1,
+ };
+
+ let mut native_owned = false;
+ let mut was_hovering = false;
+
+ // 1. Hovering outside canvas (left sidebar) NEVER pushes to render ring
+ for i in 0..20 {
+ let (ring_opt, owned) = route_and_filter_native_sample(
+ mk_hover(50.0, 200.0 + i as f32, i as f64 * 4.0),
+ Some(&ht),
+ &mut native_owned,
+ &mut was_hovering,
+ );
+ assert!(ring_opt.is_none(), "sidebar hover must not wake render ring");
+ assert!(!owned);
+ assert!(!was_hovering);
+ }
+
+ // 2. Entering unoccluded canvas pushes hover sample & suppresses JS flood
+ let (ring_in, owned_in) = route_and_filter_native_sample(
+ mk_hover(600.0, 400.0, 100.0),
+ Some(&ht),
+ &mut native_owned,
+ &mut was_hovering,
+ );
+ assert_eq!(ring_in.map(|s| s.phase), Some(0));
+ assert!(owned_in);
+ assert!(was_hovering);
+
+ // 3. Moving over occluded FloatingBrushPill emits ONE phase=4 leave transition,
+ // then ZERO subsequent wakeups while hovering the pill
+ let (ring_leave_pill, owned_pill) = route_and_filter_native_sample(
+ mk_hover(230.0, 350.0, 104.0),
+ Some(&ht),
+ &mut native_owned,
+ &mut was_hovering,
+ );
+ assert_eq!(ring_leave_pill.map(|s| s.phase), Some(4));
+ assert!(!owned_pill);
+ assert!(!was_hovering);
+
+ for i in 0..10 {
+ let (ring_opt, _) = route_and_filter_native_sample(
+ mk_hover(232.0, 355.0 + i as f32, 108.0 + i as f64 * 4.0),
+ Some(&ht),
+ &mut native_owned,
+ &mut was_hovering,
+ );
+ assert!(ring_opt.is_none(), "occluded UI hover must not wake render ring");
+ }
+
+ // 4. Re-enter canvas, then exit to sidebar -> exactly ONE phase=4 leave transition
+ let (ring_reenter, _) = route_and_filter_native_sample(
+ mk_hover(500.0, 300.0, 200.0),
+ Some(&ht),
+ &mut native_owned,
+ &mut was_hovering,
+ );
+ assert_eq!(ring_reenter.map(|s| s.phase), Some(0));
+ assert!(was_hovering);
+
+ let (ring_exit, _) = route_and_filter_native_sample(
+ mk_hover(40.0, 300.0, 204.0),
+ Some(&ht),
+ &mut native_owned,
+ &mut was_hovering,
+ );
+ assert_eq!(ring_exit.map(|s| s.phase), Some(4));
+ assert!(!was_hovering);
+
+ let (ring_outside_again, _) = route_and_filter_native_sample(
+ mk_hover(30.0, 300.0, 208.0),
+ Some(&ht),
+ &mut native_owned,
+ &mut was_hovering,
+ );
+ assert!(ring_outside_again.is_none());
+ }
}
diff --git a/src/App.tsx b/src/App.tsx
index a55347b..fab502a 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -22,6 +22,7 @@ import {
addNativeLayer,
clearNativeLayer,
nativeSelectionFillColor,
+ updateNativeLayer,
} from './utils/nativeEngineBridge';
import { multiplayerService } from './services/multiplayerService';
import { recoveryService } from './services/recoveryService';
@@ -331,6 +332,17 @@ export function App() {
[]
);
+ const handleSyncNativeLayersFromSelection = useCallback(
+ (nextLayers: LayerItem[], nextActiveLayerId?: string) => {
+ layerMgr.layersRef.current = nextLayers;
+ layerMgr.setLayers(nextLayers);
+ if (nextActiveLayerId) {
+ layerMgr.setActiveLayerId(nextActiveLayerId);
+ }
+ },
+ [layerMgr.layersRef, layerMgr.setLayers, layerMgr.setActiveLayerId]
+ );
+
// Modular Selection & Transform Tools (mounted before useCanvasDrawing so selection is always synchronous)
const selectionTools = useSelectionTools({
dimensions,
@@ -342,6 +354,7 @@ export function App() {
flushPendingHistoryTasks: stableFlushPendingHistoryTasks,
updateLayerThumbnail: layerMgr.updateLayerThumbnail,
pushHistoryStep: stablePushHistoryStep,
+ onSyncNativeLayers: handleSyncNativeLayersFromSelection,
showToast,
});
@@ -795,11 +808,33 @@ export function App() {
const handleToggleReferenceLayer = useCallback(
(layerId: string) => {
- const beforeLayers = layerMgr.layers;
+ if (collab.isConnected || collab.isReconnecting) {
+ if (collab.myRole === 'viewer') {
+ showToast(t('Viewers have read-only access'));
+ return;
+ }
+ const perm = collab.canEditLayerById(layerId);
+ if (!perm.allowed) {
+ showToast(perm.reason || t('Layer is locked by its owner'));
+ return;
+ }
+ }
+ const beforeLayers = layerMgr.layersRef.current;
+ const target = beforeLayers.find((l) => l.id === layerId);
+ if (!target) return;
+ const nextIsReference = !target.isReference;
const nextLayers = beforeLayers.map((l) =>
- l.id === layerId ? { ...l, isReference: !l.isReference } : l
+ l.id === layerId ? { ...l, isReference: nextIsReference } : l
);
+ layerMgr.layersRef.current = nextLayers;
layerMgr.setLayers(nextLayers);
+ if (activeDocumentId) {
+ void updateNativeLayer(activeDocumentId, layerId, {
+ isReference: nextIsReference,
+ recordHistory: true,
+ historyLabel: t('Toggle Reference Layer'),
+ }).catch(() => {});
+ }
pushHistoryStepRef.current?.(
'layer',
t('Toggle Reference Layer'),
@@ -816,7 +851,15 @@ export function App() {
);
documentStoreActions.markDocumentDirty(activeDocumentId, true);
},
- [activeDocumentId, layerMgr]
+ [
+ activeDocumentId,
+ collab.isConnected,
+ collab.isReconnecting,
+ collab.myRole,
+ collab.canEditLayerById,
+ layerMgr,
+ showToast,
+ ]
);
const handleToggleTone = useCallback(
@@ -858,7 +901,10 @@ export function App() {
return;
}
const activeIdx = layerMgr.layers.findIndex((l) => l.id === layerMgr.activeLayerId);
- const belowLayer = activeIdx >= 0 ? layerMgr.layers[activeIdx + 1] : undefined;
+ const belowLayer =
+ activeIdx >= 0
+ ? layerMgr.layers.slice(activeIdx + 1).find((l) => l.type === 'raster')
+ : undefined;
if (belowLayer) {
const belowPerm = collab.canEditLayerById(belowLayer.id);
if (!belowPerm.allowed) {
@@ -890,6 +936,20 @@ export function App() {
const handleMergeFolder = useCallback(
(folderId?: string) => {
+ const targetId = folderId || layerMgr.activeLayerId;
+ if (collab.isConnected || collab.isReconnecting) {
+ if (collab.myRole === 'viewer') {
+ showToast(t('Viewers have read-only access'));
+ return;
+ }
+ if (targetId) {
+ const perm = collab.canDeleteLayerById(targetId);
+ if (!perm.allowed) {
+ showToast(perm.reason || t('Cannot merge a protected folder'));
+ return;
+ }
+ }
+ }
if (selectionTools.selection?.floating) {
selectionTools.handleCommitFloatingSelection();
}
@@ -905,7 +965,17 @@ export function App() {
showToast(t('Cannot merge folder: select an unlocked folder'));
}
},
- [layerMgr.mergeFolder, activeDocumentId, selectionTools, showToast]
+ [
+ collab.isConnected,
+ collab.isReconnecting,
+ collab.myRole,
+ collab.canDeleteLayerById,
+ layerMgr.activeLayerId,
+ layerMgr.mergeFolder,
+ activeDocumentId,
+ selectionTools,
+ showToast,
+ ]
);
const handleAddDefaultFrameFolder = useCallback(() => {
@@ -1176,7 +1246,7 @@ export function App() {
layerMgr.runWithoutLayerHistory(() => layerMgr.setOpacity(id, opacity)),
setVisibility: (id) => layerMgr.runWithoutLayerHistory(() => layerMgr.toggleVisibility(id)),
setClipping: (id, clipped) => {
- const existing = layerMgr.layers.find((l) => l.id === id);
+ const existing = layerMgr.layersRef.current.find((l) => l.id === id);
if (clipped === undefined || Boolean(existing?.clipped) !== clipped) {
layerMgr.runWithoutLayerHistory(() => layerMgr.toggleClipping(id));
}
@@ -1187,7 +1257,7 @@ export function App() {
setLayerColor: (id, enabled, color) => {
layerMgr.runWithoutLayerHistory(() => {
if (color) layerMgr.setLayerColor(id, color);
- const existing = layerMgr.layers.find((l) => l.id === id);
+ const existing = layerMgr.layersRef.current.find((l) => l.id === id);
if (Boolean(existing?.layerColorEnabled) !== enabled) {
layerMgr.toggleLayerColor(id);
}
@@ -1195,7 +1265,7 @@ export function App() {
},
setTone: (id, enabled, opts) => {
layerMgr.runWithoutLayerHistory(() => {
- const existing = layerMgr.layers.find((l) => l.id === id);
+ const existing = layerMgr.layersRef.current.find((l) => l.id === id);
if (Boolean(existing?.toneEnabled) !== enabled) {
layerMgr.toggleTone(id);
}
@@ -1245,7 +1315,7 @@ export function App() {
groupLayerTreeDelta ??
createLayerTreeSnapshotDelta(
beforeAutoLayers,
- layerMgr.layers,
+ layerMgr.layersRef.current,
beforeAutoActiveId,
currentLayerId
);
@@ -1369,7 +1439,11 @@ export function App() {
itemId: null,
});
useEffect(() => {
- const currentItem = drawing.historyList[drawing.historyIndex];
+ const safeHistoryList = Array.isArray(drawing.historyList) ? drawing.historyList : [];
+ const currentItem =
+ drawing.historyIndex >= 0 && drawing.historyIndex < safeHistoryList.length
+ ? safeHistoryList[drawing.historyIndex]
+ : undefined;
const currentItemId = currentItem?.id ?? null;
const prev = lastHistoryMetaRef.current;
if (
@@ -1403,7 +1477,11 @@ export function App() {
getTimelapseCaptureContext,
]);
- // Unified Pointer Dispatcher reading tool imperatively from useToolStore
+ // Unified Pointer Dispatcher reading tool imperatively from useToolStore.
+ // Tracks which tool initiated the current pointer drag so a mid-drag tool switch
+ // never leaves gradient/retouch/pen/vector-edit/selection/shape drag state stuck.
+ const activePointerToolRef = useRef<ReturnType<typeof useToolStore.getState>['tool'] | null>(null);
+
const handlePointerDown = useCallback(
(e: React.PointerEvent<HTMLElement>, coalescedEvents?: PointerEvent[]) => {
if (!hasOpenDocument || e.button !== 0) return;
@@ -1428,13 +1506,17 @@ export function App() {
}
}
+ activePointerToolRef.current = tool;
+
if (tool === 'brush' || tool === 'decoration' || tool === 'eraser') {
const curLayer = layerMgr.activeLayer;
if (curLayer?.type === 'text' || curLayer?.type === 'balloon') {
+ activePointerToolRef.current = null;
showToast(t('Use Text/Object tool to edit, or Rasterize Layer to paint directly'));
return;
}
if (curLayer?.type === 'frame-folder') {
+ activePointerToolRef.current = null;
showToast(t('Select a child layer inside the Frame Border Folder to draw'));
return;
}
@@ -1501,7 +1583,7 @@ export function App() {
drawing.handlePointerMove(e, coalescedEvents, predictedEvents);
return;
}
- const tool = useToolStore.getState().tool;
+ const tool = activePointerToolRef.current ?? useToolStore.getState().tool;
if (tool === 'brush' || tool === 'decoration' || tool === 'eraser') {
drawing.handlePointerMove(e, coalescedEvents, predictedEvents);
return;
@@ -1530,13 +1612,15 @@ export function App() {
const handlePointerUp = useCallback(
(e: React.PointerEvent<HTMLElement>) => {
+ const startedTool = activePointerToolRef.current;
+ activePointerToolRef.current = null;
// Always finalize an active brush stroke even if tool changed mid-stroke (e.g. modifier/shortcut)
// so drawing.isDrawingRef can never be left stranded true.
if (drawing.isDrawingRef.current) {
drawing.handlePointerUp(e);
return;
}
- const tool = useToolStore.getState().tool;
+ const tool = startedTool ?? useToolStore.getState().tool;
if (tool === 'brush' || tool === 'decoration' || tool === 'eraser') {
drawing.handlePointerUp(e);
return;
diff --git a/src/components/AdjustmentModal.tsx b/src/components/AdjustmentModal.tsx
index d0dd446..8ef353d 100644
--- a/src/components/AdjustmentModal.tsx
+++ b/src/components/AdjustmentModal.tsx
@@ -233,10 +233,16 @@ export const AdjustmentModal: React.FC<AdjustmentModalProps> = ({
// Native Rust layer histogram for Tone Curve / Levels background
const histogramData = useMemo(() => {
if (!nativeHist) return null;
- if (curveChannel === 'r') return new Uint32Array(nativeHist.r);
- if (curveChannel === 'g') return new Uint32Array(nativeHist.g);
- if (curveChannel === 'b') return new Uint32Array(nativeHist.b);
- return new Uint32Array(nativeHist.luminance);
+ const raw =
+ curveChannel === 'r'
+ ? nativeHist.r
+ : curveChannel === 'g'
+ ? nativeHist.g
+ : curveChannel === 'b'
+ ? nativeHist.b
+ : (nativeHist.rgb ?? nativeHist.luminance);
+ if (!Array.isArray(raw) || raw.length < 256) return null;
+ return new Uint32Array(raw);
}, [nativeHist, curveChannel]);
const maxHistogramCount = useMemo(() => {
@@ -382,7 +388,11 @@ export const AdjustmentModal: React.FC<AdjustmentModalProps> = ({
e.stopPropagation();
setSelectedStopIdx(idx);
setIsDraggingStop(true);
- (e.target as Element).setPointerCapture(e.pointerId);
+ try {
+ (e.target as Element).setPointerCapture(e.pointerId);
+ } catch {
+ // Ignore synthetic/non-capturable pointers
+ }
};
const handleStopPointerMove = (e: React.PointerEvent) => {
@@ -390,9 +400,11 @@ export const AdjustmentModal: React.FC<AdjustmentModalProps> = ({
const ramp = gradientRampRef.current;
if (!ramp) return;
const rect = ramp.getBoundingClientRect();
+ if (rect.width <= 0) return;
const pos = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
setGradientStops((prev) => {
+ if (selectedStopIdx < 0 || selectedStopIdx >= prev.length) return prev;
const stops = [...prev];
stops[selectedStopIdx] = {
...stops[selectedStopIdx],
@@ -408,8 +420,16 @@ export const AdjustmentModal: React.FC<AdjustmentModalProps> = ({
try {
(e.target as Element).releasePointerCapture(e.pointerId);
} catch (_) {}
- // Re-sort stops
- setGradientStops((prev) => [...prev].sort((a, b) => a.position - b.position));
+ // Re-sort stops while preserving selection on the dragged stop
+ const draggedStop = gradientStops[selectedStopIdx];
+ const sorted = [...gradientStops].sort((a, b) => a.position - b.position);
+ setGradientStops(sorted);
+ if (draggedStop) {
+ const nextIdx = sorted.indexOf(draggedStop);
+ if (nextIdx >= 0) {
+ setSelectedStopIdx(nextIdx);
+ }
+ }
}
};
diff --git a/src/components/AnimationTimeline.tsx b/src/components/AnimationTimeline.tsx
index 7b36249..bddbf86 100644
--- a/src/components/AnimationTimeline.tsx
+++ b/src/components/AnimationTimeline.tsx
@@ -103,35 +103,51 @@ export const AnimationTimeline: React.FC<AnimationTimelineProps> = ({
}
}, [timeline.currentFrame, timeline.cels, onSelectCelLayer]);
+ const scrubCleanupRef = useRef<(() => void) | null>(null);
+
+ useEffect(() => {
+ return () => {
+ scrubCleanupRef.current?.();
+ scrubCleanupRef.current = null;
+ };
+ }, []);
+
// Handle Scrub Click/Drag
- const handleScrub = useCallback(
- (clientX: number) => {
- if (!scrubberRef.current) return;
- const rect = scrubberRef.current.getBoundingClientRect();
- const clickX = Math.max(0, Math.min(rect.width, clientX - rect.left));
- const frameRatio = clickX / rect.width;
- const newFrame = Math.max(0, Math.min(timeline.totalFrames - 1, Math.floor(frameRatio * timeline.totalFrames)));
-
- onChangeTimeline({
- ...timeline,
- currentFrame: newFrame,
- });
- },
- [timeline, onChangeTimeline]
- );
+ const handleScrub = useCallback((clientX: number) => {
+ if (!scrubberRef.current) return;
+ const rect = scrubberRef.current.getBoundingClientRect();
+ if (rect.width <= 0) return;
+ const curr = timelineRef.current;
+ const totalFrames = Math.max(1, curr.totalFrames);
+ const clickX = Math.max(0, Math.min(rect.width, clientX - rect.left));
+ const frameRatio = clickX / rect.width;
+ const newFrame = Math.max(0, Math.min(totalFrames - 1, Math.floor(frameRatio * totalFrames)));
+
+ onChangeTimelineRef.current({
+ ...curr,
+ currentFrame: newFrame,
+ });
+ }, []);
const handlePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
e.preventDefault();
+ scrubCleanupRef.current?.();
handleScrub(e.clientX);
const onPointerMove = (ev: PointerEvent) => handleScrub(ev.clientX);
- const onPointerUp = () => {
+ const cleanup = () => {
window.removeEventListener('pointermove', onPointerMove);
- window.removeEventListener('pointerup', onPointerUp);
+ window.removeEventListener('pointerup', cleanup);
+ window.removeEventListener('pointercancel', cleanup);
+ if (scrubCleanupRef.current === cleanup) {
+ scrubCleanupRef.current = null;
+ }
};
+ scrubCleanupRef.current = cleanup;
window.addEventListener('pointermove', onPointerMove);
- window.addEventListener('pointerup', onPointerUp);
+ window.addEventListener('pointerup', cleanup);
+ window.addEventListener('pointercancel', cleanup);
};
// Keyboard navigation shortcuts (Alt+Space anywhere, or Space when timeline has focus, avoiding canvas Space-pan collision)
diff --git a/src/components/AppShell.tsx b/src/components/AppShell.tsx
index 3fd6407..d92cb41 100644
--- a/src/components/AppShell.tsx
+++ b/src/components/AppShell.tsx
@@ -38,6 +38,7 @@ import {
} from '../utils/fileDropImport';
import { HalftoneDotShape } from '../utils/screentoneEngine';
import { applyInterfaceScale, DEFAULT_INTERFACE_SCALE } from '../utils/interfaceScale';
+import { isNativeCanvasActive, setNativeViewport } from '../utils/nativeEngineBridge';
import {
documentStoreActions,
selectHasOpenDocument,
@@ -699,6 +700,29 @@ export const AppShell: React.FC<AppShellProps> = React.memo(
void applyInterfaceScale(interfaceScale);
}, [interfaceScale]);
+ // Failsafe: whenever WelcomeScreen is visible (`appView !== 'workspace'` or `!hasOpenDocument`),
+ // strictly hide the Windows DirectComposition canvas visual and restore opaque WebView2 background.
+ useEffect(() => {
+ if (hasOpenDocument && appView === 'workspace') return;
+ if (typeof document !== 'undefined' && document.documentElement) {
+ if (typeof document.documentElement.removeAttribute === 'function') {
+ document.documentElement.removeAttribute('data-native-canvas');
+ } else if (document.documentElement.dataset) {
+ delete document.documentElement.dataset.nativeCanvas;
+ }
+ }
+ if (isNativeCanvasActive()) {
+ void setNativeViewport({
+ xPx: 0,
+ yPx: 0,
+ widthPx: 0,
+ heightPx: 0,
+ dpr: typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1,
+ visible: false,
+ });
+ }
+ }, [hasOpenDocument, appView]);
+
const handleToggleFocusMode = useCallback(() => {
workspaceStoreActions.togglePalettesHidden();
}, []);
diff --git a/src/components/BrushPreview.tsx b/src/components/BrushPreview.tsx
index a80c470..4f79fad 100644
--- a/src/components/BrushPreview.tsx
+++ b/src/components/BrushPreview.tsx
@@ -1,6 +1,10 @@
import React, { useRef, useEffect, useState } from 'react';
import { BrushSettings, BrushPresetId, CspSubTip } from '../types/editor';
-import { renderBrushStrokePreview, BrushPreviewOptions } from '../utils/brushPreview';
+import {
+ cancelBrushPreviewForCanvas,
+ renderBrushStrokePreview,
+ BrushPreviewOptions,
+} from '../utils/brushPreview';
import { getBuiltinBrushConfig } from '../utils/presetBrushes';
import { getPreloadedTipImage, preloadTipImage } from '../utils/brushStorage';
import { DEFAULT_BRUSH_PRESET_ID } from '../utils/brushPresetManager';
@@ -452,6 +456,7 @@ export const BrushPreview: React.FC<BrushPreviewProps> = React.memo(({
cancelAnimationFrame(rafIdRef.current);
rafIdRef.current = null;
}
+ cancelBrushPreviewForCanvas(canvas);
};
}, [
isVisible,
diff --git a/src/components/CanvasArea.tsx b/src/components/CanvasArea.tsx
index e66e4a0..e9c189b 100644
--- a/src/components/CanvasArea.tsx
+++ b/src/components/CanvasArea.tsx
@@ -66,8 +66,11 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {
const isResizeCanvasOpen = useUiStore((s) => s.isResizeCanvasModalOpen);
const activeEditTarget = useDocumentStore((s) => s.activeEditTarget);
+ const palettesHidden = useWorkspaceStore((s) => s.palettesHidden);
- const activeLayer = layers.find((l) => l.id === activeLayerId);
+ const activeLayer = Array.isArray(layers)
+ ? layers.find((l) => l.id === activeLayerId)
+ : undefined;
const isMaskMode = activeEditTarget === 'mask' && Boolean(activeLayer?.hasMask || activeLayer?.maskCanvas);
// Dynamic cursor dimensions according to brush tip shape, aspect ratio, and thickness
@@ -95,7 +98,6 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {
const {
nativeActive,
nativeStrokeOwned,
- diagnostics: nativeDiagnostics,
onClearNativeCanvas,
} = useNativeEngineViewport({
viewportRef,
@@ -135,6 +137,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {
cursorWidth,
cursorHeight,
totalAngleDeg,
+ liveResizePreview,
cursorConfigRef,
lastPointerPosRef,
cursorRingRef,
@@ -275,8 +278,6 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {
);
}
- const palettesHidden = useWorkspaceStore((s) => s.palettesHidden);
-
const showFloatingPill =
!palettesHidden &&
!isResizeCanvasOpen &&
@@ -404,12 +405,12 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {
thicknessRatio={thicknessRatio}
tipOutline={tipOutline}
isResizingBrush={isResizingBrush}
+ liveResizePreview={liveResizePreview}
resizePreviewX={resizePreviewX}
resizePreviewY={resizePreviewY}
quickPalettePos={quickPalettePos}
setQuickPalettePos={setQuickPalettePos}
nativeCanvasActive={nativeActive}
- nativeDiagnostics={nativeDiagnostics}
onClearNativeCanvas={onClearNativeCanvas}
/>
</main>
diff --git a/src/components/CanvasResizeOverlay.tsx b/src/components/CanvasResizeOverlay.tsx
index 079c180..a1d1f42 100644
--- a/src/components/CanvasResizeOverlay.tsx
+++ b/src/components/CanvasResizeOverlay.tsx
@@ -905,6 +905,7 @@ export const CanvasResizeOverlay: React.FC<CanvasResizeOverlayProps> = ({
createPortal(
<div
data-testid="canvas-crop-action-bar"
+ data-native-occluder="true"
className="fixed bottom-9 left-1/2 -translate-x-1/2 z-[48] max-w-[95vw] bg-ui-floating border border-ui-default rounded-ui-md shadow-ui-floating px-2 py-1 flex flex-wrap items-center justify-center gap-1 select-none text-[11px] text-ui-primary"
onPointerDown={(e) => e.stopPropagation()}
>
diff --git a/src/components/ColorPanel.tsx b/src/components/ColorPanel.tsx
index 49358bd..3214af9 100644
--- a/src/components/ColorPanel.tsx
+++ b/src/components/ColorPanel.tsx
@@ -76,8 +76,13 @@ export const ColorPanel: React.FC<ColorPanelProps> = ({
activeTab === 'slider' ? 'slider' : 'wheel'
);
+ const safePrimaryColor =
+ typeof primaryColor === 'string' && primaryColor.trim().length > 0 ? primaryColor : '#000000';
+ const safeSecondaryColor =
+ typeof secondaryColor === 'string' && secondaryColor.trim().length > 0 ? secondaryColor : '#ffffff';
+
const [activeTarget, setActiveTarget] = useState<'primary' | 'secondary'>('primary');
- const activeColor = activeTarget === 'primary' ? primaryColor : secondaryColor;
+ const activeColor = activeTarget === 'primary' ? safePrimaryColor : safeSecondaryColor;
const isMonoCanvas = colorMode === 'grayscale' || colorMode === 'monochrome';
// Local hex draft so partial edits type cleanly
diff --git a/src/components/CommandBar.tsx b/src/components/CommandBar.tsx
index 4a9e562..b06c632 100644
--- a/src/components/CommandBar.tsx
+++ b/src/components/CommandBar.tsx
@@ -428,7 +428,10 @@ export const CommandBar: React.FC<CommandBarProps> = React.memo(({
</button>
{isCustomizeOpen && (
- <div className="fixed top-9 left-1/2 -translate-x-1/2 w-64 rounded-ui-md shadow-ui-popover p-2 z-50 text-[11px] bg-ui-elevated border border-ui-default text-ui-primary">
+ <div
+ data-native-occluder="true"
+ className="fixed top-9 left-1/2 -translate-x-1/2 w-64 rounded-ui-md shadow-ui-popover p-2 z-50 text-[11px] bg-ui-elevated border border-ui-default text-ui-primary"
+ >
<div className="flex items-center justify-between pb-1.5 mb-1.5 border-b border-ui-subtle">
<span className="font-medium text-xs">{t('Command Bar')}</span>
<button
@@ -580,6 +583,7 @@ export const CommandBar: React.FC<CommandBarProps> = React.memo(({
{isPresetMenuOpen && (
<div
data-testid="workspace-preset-menu"
+ data-native-occluder="true"
className="absolute top-7 right-0 w-60 rounded-ui-md shadow-ui-popover p-1.5 z-50 text-[11px] bg-ui-elevated border border-ui-default text-ui-primary"
>
<div className="px-2 py-0.5 text-[9.5px] uppercase tracking-wider text-ui-muted">
diff --git a/src/components/DockWorkspace.tsx b/src/components/DockWorkspace.tsx
index 6644aae..bb4f4bf 100644
--- a/src/components/DockWorkspace.tsx
+++ b/src/components/DockWorkspace.tsx
@@ -408,14 +408,18 @@ const DockCellPanel: React.FC<DockCellPanelProps> = React.memo(({
};
}, [menuOpen, computeMenuPosition]);
- const activePanelId = cell.panelIds.includes(cell.activePanelId)
+ const safePanelIds = Array.isArray(cell?.panelIds)
+ ? cell.panelIds.filter((pid) => Boolean(DOCK_PANEL_META[pid]))
+ : [];
+ const activePanelId = safePanelIds.includes(cell.activePanelId)
? cell.activePanelId
- : cell.panelIds[0];
+ : safePanelIds[0];
const handleDetachActivePanel = useCallback(() => {
- if (lockMove) return;
+ if (lockMove || !activePanelId) return;
const rect = cellRootRef.current?.getBoundingClientRect();
const meta = DOCK_PANEL_META[activePanelId];
+ if (!meta) return;
if (rect && typeof window !== 'undefined') {
const offsetX =
side === 'left'
@@ -459,7 +463,11 @@ const DockCellPanel: React.FC<DockCellPanelProps> = React.memo(({
onEndDragPanel();
};
- const canSplitActiveTab = cell.panelIds.length > 1;
+ if (!activePanelId || !DOCK_PANEL_META[activePanelId]) {
+ return null;
+ }
+
+ const canSplitActiveTab = safePanelIds.length > 1;
return (
<div
@@ -505,8 +513,9 @@ const DockCellPanel: React.FC<DockCellPanelProps> = React.memo(({
}`}
>
<div className="flex items-center gap-0.5 min-w-0 overflow-x-auto no-scrollbar h-full">
- {cell.panelIds.map((pid) => {
+ {safePanelIds.map((pid) => {
const meta = DOCK_PANEL_META[pid];
+ if (!meta) return null;
const isActive = pid === activePanelId;
return (
<button
@@ -516,7 +525,7 @@ const DockCellPanel: React.FC<DockCellPanelProps> = React.memo(({
onPointerDown={(e) => {
if (e.button !== 0 || lockMove) return;
e.stopPropagation();
- onStartPointerTabDrag?.(e, pid, colId, rowId, cell.panelIds.length, cell.id);
+ onStartPointerTabDrag?.(e, pid, colId, rowId, safePanelIds.length, cell.id);
}}
onDragStart={(e) => {
if (lockMove) {
@@ -550,12 +559,12 @@ const DockCellPanel: React.FC<DockCellPanelProps> = React.memo(({
{renderPanelIcon(pid, 'w-3 h-3 shrink-0')}
{!isCompactToolOnly && (
<span className="truncate max-w-[84px]">
- {cell.panelIds.length > 1 || isSplitRow
+ {safePanelIds.length > 1 || isSplitRow
? td(meta.shortTitle, 'panelShort')
: td(meta.title)}
</span>
)}
- {isActive && cell.panelIds.length > 1 && (
+ {isActive && safePanelIds.length > 1 && (
<span className="absolute bottom-0 left-1 right-1 h-[2px] bg-ui-accent rounded-full" />
)}
</button>
@@ -893,19 +902,21 @@ export const DockGroupView: React.FC<DockGroupViewProps> = React.memo(({
const cells = getGroupCells(group);
const isSplitRow = cells.length > 1;
const isCollapsed = Boolean(group.collapsed);
+ const groupPanelIds = Array.isArray(group.panelIds) ? group.panelIds : [];
const isCompactToolOnly =
!isSplitRow &&
col.width <= 64 &&
- group.panelIds.length === 1 &&
- group.panelIds[0] === 'tools';
+ groupPanelIds.length === 1 &&
+ groupPanelIds[0] === 'tools';
const adjacentRowForSideSplit = React.useMemo(() => {
- if (col.groups.length <= 1) return null;
- if (groupIndex > 0) {
- return { id: col.groups[groupIndex - 1].id, direction: 'above' as const };
+ const groups = Array.isArray(col.groups) ? col.groups : [];
+ if (groups.length <= 1) return null;
+ if (groupIndex > 0 && groups[groupIndex - 1]) {
+ return { id: groups[groupIndex - 1].id, direction: 'above' as const };
}
- if (groupIndex + 1 < col.groups.length) {
- return { id: col.groups[groupIndex + 1].id, direction: 'below' as const };
+ if (groupIndex + 1 < groups.length && groups[groupIndex + 1]) {
+ return { id: groups[groupIndex + 1].id, direction: 'below' as const };
}
return null;
}, [col.groups, groupIndex]);
@@ -1276,20 +1287,22 @@ const DockColumnView: React.FC<DockColumnViewProps> = React.memo(({
cellId: string;
cellPanelCount: number;
}> = [];
- for (const grp of col.groups) {
+ for (const grp of Array.isArray(col.groups) ? col.groups : []) {
for (const cell of getGroupCells(grp)) {
- for (const pid of cell.panelIds) {
+ const pids = Array.isArray(cell.panelIds) ? cell.panelIds : [];
+ for (const pid of pids) {
+ if (!DOCK_PANEL_META[pid]) continue;
panelOwners.push({
panelId: pid,
groupId: grp.id,
cellId: cell.id,
- cellPanelCount: cell.panelIds.length,
+ cellPanelCount: pids.length,
});
}
}
}
const popoverWidth = Math.max(204, col.width);
- const firstGroupId = col.groups[0]?.id ?? '';
+ const firstGroupId = col.groups?.[0]?.id ?? '';
return (
<div
@@ -1360,7 +1373,7 @@ const DockColumnView: React.FC<DockColumnViewProps> = React.memo(({
</div>
{/* CSP Pop-out Floating Palette Popover */}
- {activePopoverPanelId && (
+ {activePopoverPanelId && DOCK_PANEL_META[activePopoverPanelId] && (
<div
data-testid={`dock-popover-${activePopoverPanelId}`}
style={{ width: popoverWidth }}
@@ -2070,7 +2083,8 @@ export function detectDockDropTarget(
}
if (bestFloatingMatch) {
const targetFp = (layout.floatingPanels ?? []).find((p) => p.id === bestFloatingMatch!.id);
- const title = targetFp ? translateData(DOCK_PANEL_META[targetFp.activePanelId].title) : translate('Panel');
+ const targetMeta = targetFp ? DOCK_PANEL_META[targetFp.activePanelId] : undefined;
+ const title = targetMeta ? translateData(targetMeta.title) : translate('Panel');
return {
kind: 'floating-tab',
targetFloatingId: bestFloatingMatch.id,
@@ -3130,7 +3144,7 @@ export const DockWorkspace: React.FC<DockWorkspaceProps> = React.memo(({
data-testid="left-dock-zone"
className="flex h-full shrink-0 gap-px relative z-20"
>
- {layout.leftDocks.map((col, colIdx) => (
+ {(layout?.leftDocks ?? []).map((col, colIdx) => (
<DockColumnView
key={col.id}
side="left"
@@ -3257,7 +3271,7 @@ export const DockWorkspace: React.FC<DockWorkspaceProps> = React.memo(({
/>
)}
- {layout.rightDocks.map((col, colIdx) => (
+ {(layout?.rightDocks ?? []).map((col, colIdx) => (
<DockColumnView
key={col.id}
side="right"
diff --git a/src/components/DocumentLifecycleManager.tsx b/src/components/DocumentLifecycleManager.tsx
index 5f52550..b6de021 100644
--- a/src/components/DocumentLifecycleManager.tsx
+++ b/src/components/DocumentLifecycleManager.tsx
@@ -69,7 +69,9 @@ import {
closeNativeDocument,
flushNativeGpuPool,
fromNativeLayerNodeMeta,
+ getNativeMemoryStats,
isNativeCanvasActive,
+ NativeMemoryStats,
nativeRecoveryRestore,
openNativeDocumentBytes,
openNativeDocumentFromPath,
@@ -78,6 +80,7 @@ import {
saveNativeInkDocument,
saveNativeInkDocumentWithDialog,
setNativeMemoryBudget,
+ subscribeNativeCanvasActive,
subscribeNativeStrokeCommitted,
vramBudgetMbFromPreset,
} from '../utils/nativeEngineBridge';
@@ -335,37 +338,64 @@ export function useDocumentLifecycle({
if (useUiStore.getState().isResizeCanvasModalOpen) {
uiStoreActions.setResizeCanvasModalOpen(false);
}
+ const safeWidth =
+ typeof options?.width === 'number' && Number.isFinite(options.width) && options.width >= 1
+ ? Math.round(options.width)
+ : 1920;
+ const safeHeight =
+ typeof options?.height === 'number' && Number.isFinite(options.height) && options.height >= 1
+ ? Math.round(options.height)
+ : 1080;
+ const safeDpi =
+ typeof options?.dpi === 'number' && Number.isFinite(options.dpi) && options.dpi >= 1
+ ? Math.round(options.dpi)
+ : 300;
+ const safeColorMode: CanvasColorMode =
+ options?.colorMode === 'monochrome' || options?.colorMode === 'grayscale'
+ ? options.colorMode
+ : 'color';
+ const safeBackgroundColor =
+ typeof options?.backgroundColor === 'string' && options.backgroundColor.trim().length > 0
+ ? options.backgroundColor
+ : '#ffffff';
const newDims: CanvasDimensions = {
- width: options.width,
- height: options.height,
- dpi: options.dpi,
+ width: safeWidth,
+ height: safeHeight,
+ dpi: safeDpi,
};
documentStoreActions.setDimensions(newDims);
- documentStoreActions.setColorMode(options.colorMode);
- let name = (options.name || 'Untitled').trim();
+ documentStoreActions.setColorMode(safeColorMode);
+ let name = (typeof options?.name === 'string' && options.name.trim() ? options.name : 'Untitled').trim();
if (!/\.[a-zA-Z0-9]+$/.test(name) && !name.endsWith('*')) {
name = `${name}*`;
}
documentStoreActions.setDocumentName(name);
documentStoreActions.setSavedFileInfo(null);
- const primaryColor = useToolStore.getState().primaryColor;
- if (options.colorMode === 'monochrome') {
+ const rawPrimaryColor = useToolStore.getState().primaryColor;
+ const primaryColor =
+ typeof rawPrimaryColor === 'string' && rawPrimaryColor.trim().length > 0
+ ? rawPrimaryColor
+ : '#000000';
+ if (safeColorMode === 'monochrome') {
const snapPrimary = enforceColorMode(primaryColor, 'monochrome');
toolStoreActions.setPrimaryColor(snapPrimary, false, 'monochrome');
toolStoreActions.updateBrushSettings({ color: snapPrimary, hardness: 1.0 });
- } else if (options.colorMode === 'grayscale') {
+ } else if (safeColorMode === 'grayscale') {
const snapPrimary = enforceColorMode(primaryColor, 'grayscale');
toolStoreActions.setPrimaryColor(snapPrimary, false, 'grayscale');
toolStoreActions.updateBrushSettings({ color: snapPrimary });
}
- const defaultFreq = options.defaultFrequency ?? 60;
+ const defaultFreq =
+ typeof options?.defaultFrequency === 'number' && Number.isFinite(options.defaultFrequency)
+ ? options.defaultFrequency
+ : 60;
const newDocId = `doc-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
const { layers: initialLayers, activeLayerId: topId } = resetToNewCanvas(
newDims,
- options.backgroundColor,
- options.colorMode,
+ safeBackgroundColor,
+ safeColorMode,
defaultFreq,
newDocId
);
@@ -378,8 +408,8 @@ export function useDocumentLifecycle({
id: newDocId,
name,
dimensions: newDims,
- colorMode: options.colorMode,
- layers: initialLayers,
+ colorMode: safeColorMode,
+ layers: Array.isArray(initialLayers) ? initialLayers : [],
activeLayerId: topId,
perspectiveRuler: null,
defaultFrequency: defaultFreq,
@@ -389,7 +419,7 @@ export function useDocumentLifecycle({
artworkTimeTracker.initDocument(newDocId, 0);
documentStoreActions.setPerspectiveRuler(null, { recordHistory: false });
documentStoreActions.setStraightRuler(null, { recordHistory: false });
- documentStoreActions.setDocuments((prev) => [...prev, newDoc]);
+ documentStoreActions.setDocuments((prev) => (Array.isArray(prev) ? [...prev, newDoc] : [newDoc]));
documentStoreActions.setActiveDocumentId(newDocId);
uiStoreActions.setAppView('workspace');
showToast(t('Created {name}', { name }));
@@ -591,39 +621,41 @@ export function useDocumentLifecycle({
needsAdaptiveFitRef.current = true;
resetZoomAndCenter(newDims);
- pushHistoryStep(
- 'canvas-resize',
- scaleContent
- ? t('Resize Canvas ({width} × {height})', {
- width: newDims.width,
- height: newDims.height,
- })
- : t('Crop / Resize Canvas ({width} × {height})', {
- width: newDims.width,
- height: newDims.height,
- }),
- null,
- null,
- activeLayerId || layersRef.current[0]?.id || '',
- { x: 0, y: 0, width: newDims.width, height: newDims.height },
- resizeRes?.tileDeltas,
- undefined,
- undefined,
- undefined,
- false,
- resizeRes?.layerTreeDelta,
- {
- beforeDimensions: beforeDims,
- afterDimensions: { ...newDims },
- ...(beforePersp
- ? { beforePerspectiveRuler: beforePersp, afterPerspectiveRuler: afterPersp }
- : {}),
- ...(beforeStraight
- ? { beforeStraightRuler: beforeStraight, afterStraightRuler: afterStraight }
- : {}),
- ...(beforeSelection ? { beforeSelection, afterSelection: null } : {}),
- }
- );
+ if (!useNativeResize) {
+ pushHistoryStep(
+ 'canvas-resize',
+ scaleContent
+ ? t('Resize Canvas ({width} × {height})', {
+ width: newDims.width,
+ height: newDims.height,
+ })
+ : t('Crop / Resize Canvas ({width} × {height})', {
+ width: newDims.width,
+ height: newDims.height,
+ }),
+ null,
+ null,
+ activeLayerId || layersRef.current[0]?.id || '',
+ { x: 0, y: 0, width: newDims.width, height: newDims.height },
+ resizeRes?.tileDeltas,
+ undefined,
+ undefined,
+ undefined,
+ false,
+ resizeRes?.layerTreeDelta,
+ {
+ beforeDimensions: beforeDims,
+ afterDimensions: { ...newDims },
+ ...(beforePersp
+ ? { beforePerspectiveRuler: beforePersp, afterPerspectiveRuler: afterPersp }
+ : {}),
+ ...(beforeStraight
+ ? { beforeStraightRuler: beforeStraight, afterStraightRuler: afterStraight }
+ : {}),
+ ...(beforeSelection ? { beforeSelection, afterSelection: null } : {}),
+ }
+ );
+ }
if (multiplayerService.isConnected()) {
multiplayerService.sendCanvasResize(newDims, options);
@@ -904,10 +936,10 @@ export function useDocumentLifecycle({
if (
autoId &&
prev.length === 1 &&
- prev[0].id === autoId &&
- !prev[0].isDirty &&
- !prev[0].savedFileInfo &&
- !prev[0].sourcePath
+ prev[0]?.id === autoId &&
+ !prev[0]?.isDirty &&
+ !prev[0]?.savedFileInfo &&
+ !prev[0]?.sourcePath
) {
replacedAutoDocId = autoId;
autoCreatedInitialDocIdRef.current = null;
@@ -1018,61 +1050,61 @@ export function useDocumentLifecycle({
const handleCloseDocument = useCallback(
(id: string) => {
- if (id === activeDocumentId && useUiStore.getState().isResizeCanvasModalOpen) {
+ const storeState = useDocumentStore.getState();
+ const curActiveId = storeState.activeDocumentId;
+ if (id === curActiveId && useUiStore.getState().isResizeCanvasModalOpen) {
uiStoreActions.setResizeCanvasModalOpen(false);
}
- documentStoreActions.setDocuments((prev) => {
- const next = prev.filter((d) => d.id !== id);
- if (id === activeDocumentId) {
- if (next.length > 0) {
- const nextActive = next[next.length - 1];
- documentStoreActions.setDimensions(nextActive.dimensions);
- documentStoreActions.setColorMode(nextActive.colorMode);
- documentStoreActions.setDocumentName(nextActive.name);
- documentStoreActions.setPerspectiveRuler(nextActive.perspectiveRuler ?? null, {
- recordHistory: false,
- });
- documentStoreActions.setStraightRuler(nextActive.straightRuler ?? null, {
- recordHistory: false,
+ const next = storeState.documents.filter((d) => d.id !== id);
+ documentStoreActions.setDocuments(next);
+ if (id === curActiveId) {
+ if (next.length > 0) {
+ const nextActive = next[next.length - 1];
+ documentStoreActions.setDimensions(nextActive.dimensions);
+ documentStoreActions.setColorMode(nextActive.colorMode);
+ documentStoreActions.setDocumentName(nextActive.name);
+ documentStoreActions.setPerspectiveRuler(nextActive.perspectiveRuler ?? null, {
+ recordHistory: false,
+ });
+ documentStoreActions.setStraightRuler(nextActive.straightRuler ?? null, {
+ recordHistory: false,
+ });
+ if (nextActive.savedFileInfo && nextActive.savedFileInfo.extension) {
+ documentStoreActions.setSavedFileInfo({
+ name: nextActive.savedFileInfo.name,
+ handle: nextActive.savedFileInfo.handle,
+ ...(nextActive.savedFileInfo.path ? { path: nextActive.savedFileInfo.path } : {}),
+ extension: nextActive.savedFileInfo.extension,
});
- if (nextActive.savedFileInfo && nextActive.savedFileInfo.extension) {
- documentStoreActions.setSavedFileInfo({
- name: nextActive.savedFileInfo.name,
- handle: nextActive.savedFileInfo.handle,
- ...(nextActive.savedFileInfo.path ? { path: nextActive.savedFileInfo.path } : {}),
- extension: nextActive.savedFileInfo.extension,
- });
- } else {
- documentStoreActions.setSavedFileInfo(null);
- }
- if (nextActive.layers && nextActive.layers.length > 0) {
- switchDocumentSession(
- nextActive.id,
- nextActive.layers,
- nextActive.activeLayerId || '',
- nextActive.dimensions
- );
- documentStoreActions.setActiveDocumentId(nextActive.id);
- needsAdaptiveFitRef.current = true;
- pendingFitDimsRef.current = nextActive.dimensions;
- resetZoomAndCenter(nextActive.dimensions);
- } else {
- documentStoreActions.setActiveDocumentId(nextActive.id);
- clearDocument();
- }
} else {
- documentStore.setActiveDocument(null);
- documentStoreActions.setActiveDocumentId(null);
- documentStoreActions.setDocumentName('');
documentStoreActions.setSavedFileInfo(null);
+ }
+ if (nextActive.layers && nextActive.layers.length > 0) {
+ switchDocumentSession(
+ nextActive.id,
+ nextActive.layers,
+ nextActive.activeLayerId || '',
+ nextActive.dimensions
+ );
+ documentStoreActions.setActiveDocumentId(nextActive.id);
+ needsAdaptiveFitRef.current = true;
+ pendingFitDimsRef.current = nextActive.dimensions;
+ resetZoomAndCenter(nextActive.dimensions);
+ } else {
+ documentStoreActions.setActiveDocumentId(nextActive.id);
clearDocument();
- documentStoreActions.setPerspectiveRuler(null, { recordHistory: false });
- documentStoreActions.setStraightRuler(null, { recordHistory: false });
- uiStoreActions.setAppView('home');
}
+ } else {
+ documentStore.setActiveDocument(null);
+ documentStoreActions.setActiveDocumentId(null);
+ documentStoreActions.setDocumentName('');
+ documentStoreActions.setSavedFileInfo(null);
+ clearDocument();
+ documentStoreActions.setPerspectiveRuler(null, { recordHistory: false });
+ documentStoreActions.setStraightRuler(null, { recordHistory: false });
+ uiStoreActions.setAppView('home');
}
- return next;
- });
+ }
if (id) {
artworkTimeTracker.removeDocument(id);
globalTimelapseManager.detachSession(id).catch(console.warn);
@@ -1083,7 +1115,7 @@ export function useDocumentLifecycle({
}
}
},
- [activeDocumentId, clearDocument, resetZoomAndCenter, switchDocumentSession]
+ [clearDocument, resetZoomAndCenter, switchDocumentSession]
);
const handleRestoreCrashedSession = useCallback(
@@ -1096,6 +1128,9 @@ export function useDocumentLifecycle({
);
const restoredLayers = restoredMeta.layers.map(fromNativeLayerNodeMeta);
const restoredDims: CanvasDimensions = restoredMeta.dimensions;
+ const restoredPersp = (restoredMeta.perspectiveRuler as any) ?? null;
+ const restoredStraight = (restoredMeta.straightRuler as any) ?? null;
+ const restoredAnim = (restoredMeta.animationTimeline as any) ?? null;
loadDocument(
{
name: restoredMeta.name,
@@ -1112,6 +1147,13 @@ export function useDocumentLifecycle({
documentStoreActions.setDimensions(restoredDims);
documentStoreActions.setColorMode(restoredMeta.colorMode);
documentStoreActions.setDocumentName(restoredMeta.name);
+ documentStoreActions.setSavedFileInfo(null);
+ documentStoreActions.setPerspectiveRuler(restoredPersp, { recordHistory: false });
+ documentStoreActions.setStraightRuler(restoredStraight, { recordHistory: false });
+ documentStoreActions.setAnimationTimeline(restoredAnim);
+ if (typeof restoredMeta.defaultToneFrequency === 'number' && restoredMeta.defaultToneFrequency > 0) {
+ setDefaultToneFrequency(restoredMeta.defaultToneFrequency);
+ }
const restoredWorkTimeMs = sanitizeWorkTimeMs(restoredMeta.workTimeMs);
artworkTimeTracker.initDocument(session.session_id, restoredWorkTimeMs);
const restoredDoc: DocumentTab = {
@@ -1120,8 +1162,12 @@ export function useDocumentLifecycle({
isDirty: true,
dimensions: restoredDims,
colorMode: restoredMeta.colorMode,
+ defaultFrequency: restoredMeta.defaultToneFrequency || undefined,
layers: restoredLayers,
activeLayerId: restoredMeta.activeLayerId || restoredLayers[0]?.id || '',
+ perspectiveRuler: restoredPersp,
+ straightRuler: restoredStraight,
+ animation: restoredAnim ?? undefined,
workTimeMs: restoredWorkTimeMs,
};
documentStoreActions.setDocuments((prev) => {
@@ -1148,7 +1194,7 @@ export function useDocumentLifecycle({
});
}
},
- [loadDocument, resetZoomAndCenter, showToast, setActiveLayerId]
+ [loadDocument, resetZoomAndCenter, setDefaultToneFrequency, showToast, setActiveLayerId]
);
const handleDiscardCrashedSession = useCallback(
@@ -1293,6 +1339,7 @@ export function useDocumentLifecycle({
isLayerEffectivelyVisible: (layer) => computeLayerVisibleForLayers(liveLayers, layer),
tabId: curDocId || undefined,
perspectiveRuler: docStoreState.perspectiveRuler,
+ straightRuler: docStoreState.straightRuler,
animationTimeline: docStoreState.animationTimeline,
timelapse: tlMeta,
timelapseFrameProvider: globalTimelapseManager.createPersistenceProvider(curDocId),
@@ -1344,6 +1391,9 @@ export function useDocumentLifecycle({
perspectiveRuler: isActive
? storeState.perspectiveRuler
: targetDoc.perspectiveRuler ?? null,
+ straightRuler: isActive
+ ? storeState.straightRuler
+ : targetDoc.straightRuler ?? null,
animationTimeline:
targetDoc.animation !== undefined
? targetDoc.animation
@@ -1553,11 +1603,14 @@ export function useDocumentLifecycle({
const initialDir = getParentDirectory(savedFileInfo?.path ?? activeDoc?.sourcePath);
const info = await promptSaveAs(docData, defaultExt, true, { initialDir });
- documentStoreActions.setSavedFileInfo(info);
- documentStoreActions.setDocumentName(info.name);
+ const targetDocId = currentId || activeDocumentId;
+ if (useDocumentStore.getState().activeDocumentId === targetDocId) {
+ documentStoreActions.setSavedFileInfo(info);
+ documentStoreActions.setDocumentName(info.name);
+ }
documentStoreActions.setDocuments((prev) =>
prev.map((d) =>
- d.id === activeDocumentId
+ d.id === targetDocId
? {
...d,
name: info.name,
@@ -1571,16 +1624,19 @@ export function useDocumentLifecycle({
: d
)
);
- globalTimelapseManager.linkDocumentSave(activeDocumentId, {
+ if (targetDocId) {
+ void recoveryService.markCleanSaved(targetDocId).catch(console.warn);
+ }
+ globalTimelapseManager.linkDocumentSave(targetDocId, {
documentName: info.name,
sourcePath: info.path || `InkStudio\\${info.name}`,
});
saveRecentDocument({
- id: activeDocumentId || `doc-${Date.now()}`,
+ id: targetDocId || `doc-${Date.now()}`,
title: info.name,
path: info.path || `InkStudio\\${info.name}`,
size: info.size || 1572864,
- coverUrl: info.previewDataUrl || layersRef.current[0]?.thumbnailUrl,
+ coverUrl: info.previewDataUrl || docData.layers[0]?.thumbnailUrl,
isStarred: false,
fileType: info.extension,
width: docData.dimensions.width,
@@ -1853,14 +1909,19 @@ export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> =
documentStore.setTileBudgetMb(appSettings.tileMemoryBudgetMb || 1024);
documentStore.setSharedUndoRamStepsBudget(appSettings.undoRamSteps || 15);
documentStore.setOffloadInactiveUndoOnSwitch(appSettings.offloadInactiveTabs);
- if (isNativeCanvasActive()) {
+ const syncNativeBudget = () => {
+ if (!isNativeCanvasActive()) return;
void setNativeMemoryBudget({
ramBudgetMb: appSettings.tileMemoryBudgetMb || 1024,
vramBudgetMb: vramBudgetMbFromPreset(appSettings.gpuTexturePoolPreset),
maxHistorySteps: appSettings.maxHistorySteps || 50,
offloadInactiveTabs: appSettings.offloadInactiveTabs !== false,
});
- }
+ };
+ syncNativeBudget();
+ return subscribeNativeCanvasActive((active) => {
+ if (active) syncNativeBudget();
+ });
}, [
appSettings.tileMemoryBudgetMb,
appSettings.gpuTexturePoolPreset,
@@ -1870,14 +1931,30 @@ export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> =
]);
useEffect(() => {
+ let cachedNativeStats: NativeMemoryStats | null = null;
+ const refreshNativeMemoryStats = async () => {
+ if (!isNativeCanvasActive()) return null;
+ const stats = await getNativeMemoryStats();
+ if (stats) {
+ cachedNativeStats = stats;
+ }
+ return stats;
+ };
+ void refreshNativeMemoryStats();
+
performanceManager.registerMemoryHooks({
- getActiveTileBytes: () => 0,
- getTileBudgetBytes: () => (useUiStore.getState().appSettings.tileMemoryBudgetMb || 1024) * 1024 * 1024,
+ getActiveTileBytes: () => cachedNativeStats?.ramTotalBytes ?? 0,
+ getTileBudgetBytes: () =>
+ (cachedNativeStats && cachedNativeStats.ramBudgetBytes > 0
+ ? cachedNativeStats.ramBudgetBytes
+ : null) ??
+ (useUiStore.getState().appSettings.tileMemoryBudgetMb || 1024) * 1024 * 1024,
getUndoStats: () => documentStore.getUndoMemoryStats(),
getActiveSessionIds: () => documentStore.getActiveSessionIds(),
purgeTiles: async () => {
if (isNativeCanvasActive()) {
- await purgeNativeMemory();
+ const stats = await purgeNativeMemory();
+ if (stats) cachedNativeStats = stats;
}
return documentStore.purgeTileMemory();
},
@@ -1887,6 +1964,7 @@ export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> =
void flushNativeGpuPool();
}
},
+ refreshNativeMemoryStats,
});
let cancelled = false;
diff --git a/src/components/FloatingPanelWindow.tsx b/src/components/FloatingPanelWindow.tsx
index 9eac047..15cdf35 100644
--- a/src/components/FloatingPanelWindow.tsx
+++ b/src/components/FloatingPanelWindow.tsx
@@ -63,11 +63,14 @@ export const FloatingPanelWindow: React.FC<FloatingPanelWindowProps> = React.mem
const menuBtnRef = useRef<HTMLButtonElement>(null);
const portalMenuRef = useRef<HTMLDivElement>(null);
- const activePanelId = panel.panelIds.includes(panel.activePanelId)
+ const safePanelIds = Array.isArray(panel?.panelIds)
+ ? panel.panelIds.filter((pid) => Boolean(DOCK_PANEL_META[pid]))
+ : [];
+ const activePanelId = safePanelIds.includes(panel.activePanelId)
? panel.activePanelId
- : panel.panelIds[0];
- const activeMeta = DOCK_PANEL_META[activePanelId];
- const isMultiTab = panel.panelIds.length > 1;
+ : safePanelIds[0];
+ const activeMeta = activePanelId ? DOCK_PANEL_META[activePanelId] : undefined;
+ const isMultiTab = safePanelIds.length > 1;
const isNarrow = panel.width < 150;
const computeMenuPosition = useCallback(() => {
@@ -217,6 +220,10 @@ export const FloatingPanelWindow: React.FC<FloatingPanelWindowProps> = React.mem
const zIndex = isDragging ? 49 : Math.min(48, 35 + panel.zIndex);
const bodyHeight = Math.max(80, panel.height - FLOATING_HEADER_HEIGHT);
+ if (!activePanelId || !activeMeta) {
+ return null;
+ }
+
const floatingContent = (
<div
data-testid={`floating-panel-${activePanelId}`}
@@ -304,8 +311,9 @@ export const FloatingPanelWindow: React.FC<FloatingPanelWindowProps> = React.mem
{/* Center: Title or Draggable Tab Strip */}
{isMultiTab ? (
<div className="flex-1 min-w-0 flex items-center gap-0.5 overflow-x-auto no-scrollbar h-full py-0.5">
- {panel.panelIds.map((pid) => {
+ {safePanelIds.map((pid) => {
const meta = DOCK_PANEL_META[pid];
+ if (!meta) return null;
const isActive = pid === activePanelId;
return (
<button
diff --git a/src/components/GlobalShortcutListener.tsx b/src/components/GlobalShortcutListener.tsx
index e1b7ab8..99a40be 100644
--- a/src/components/GlobalShortcutListener.tsx
+++ b/src/components/GlobalShortcutListener.tsx
@@ -383,46 +383,8 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = Rea
'edit.delete': () => {
const p = propsRef.current;
if (!p.hasOpenDocument) return;
- if (p.transformSession?.active) {
- if (
- p.transformSession.mode === 'puppet' &&
- p.transformSession.puppet?.selectedPinId &&
- p.setTransformSession
- ) {
- const delId = p.transformSession.puppet.selectedPinId;
- p.setTransformSession((prev) => {
- if (!prev?.puppet) return prev;
- const nextPins = prev.puppet.pins.filter((pin) => pin.id !== delId);
- return {
- ...prev,
- puppet: {
- ...prev.puppet,
- pins: nextPins,
- selectedPinId: nextPins.length > 0 ? nextPins[nextPins.length - 1].id : null,
- },
- };
- });
- } else if (
- p.transformSession.mode === 'cage' &&
- p.transformSession.cage?.selectedPointId &&
- p.setTransformSession
- ) {
- const delId = p.transformSession.cage.selectedPointId;
- p.setTransformSession((prev) => {
- if (!prev?.cage) return prev;
- if (prev.cage.closed && prev.cage.points.length <= 3) return prev;
- return {
- ...prev,
- cage: {
- ...prev.cage,
- points: prev.cage.points.filter((pt) => pt.id !== delId),
- selectedPointId: null,
- },
- };
- });
- }
- return;
- }
+ // Active TransformOverlay owns Delete/Backspace (with native Rust GPU sync)
+ if (p.transformSession?.active) return;
if (p.selection) p.handleClearSelection();
else p.handleDeleteSelectedLayer();
},
@@ -811,11 +773,11 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = Rea
}
// 3. Contextual Escape / Enter fallbacks for active sessions
+ // (TransformOverlay owns Escape / Enter while transformSession.active is true)
const key = e.key.toLowerCase();
if (key === 'escape') {
if (p.transformSession?.active) {
- e.preventDefault();
- p.handleCancelTransform();
+ return;
} else if (p.textSession) {
e.preventDefault();
p.handleCancelText();
@@ -825,22 +787,7 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = Rea
}
} else if (key === 'enter') {
if (p.transformSession?.active) {
- e.preventDefault();
- if (
- p.transformSession.mode === 'cage' &&
- p.transformSession.cage &&
- !p.transformSession.cage.closed &&
- p.transformSession.cage.points.length >= 3 &&
- p.setTransformSession
- ) {
- p.setTransformSession((prev) =>
- prev?.cage
- ? { ...prev, cage: { ...prev.cage, closed: true, phase: 'deform' } }
- : prev
- );
- return;
- }
- p.handleApplyTransform();
+ return;
}
}
};
diff --git a/src/components/LayerStylesModal.tsx b/src/components/LayerStylesModal.tsx
index aadd0b0..1a7a8a5 100644
--- a/src/components/LayerStylesModal.tsx
+++ b/src/components/LayerStylesModal.tsx
@@ -217,16 +217,32 @@ export const LayerStylesModal: React.FC<LayerStylesModalProps> = ({
const handleKeyDown = (e: KeyboardEvent) => {
if (isImeComposing(e)) return;
if (e.key === 'Escape') {
+ e.preventDefault();
+ onClose();
+ } else if (
+ e.key === 'Enter' &&
+ !e.shiftKey &&
+ !e.ctrlKey &&
+ !e.metaKey &&
+ !(e.target instanceof HTMLButtonElement) &&
+ !(e.target instanceof HTMLTextAreaElement) &&
+ !(e.target instanceof HTMLSelectElement)
+ ) {
+ e.preventDefault();
+ onApply({
+ stroke,
+ dropShadow,
+ outerGlow,
+ });
onClose();
- } else if (e.key === 'Enter' && !e.shiftKey && !e.ctrlKey && !e.metaKey) {
- handleConfirm();
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
- }, [isOpen, stroke, dropShadow, outerGlow]);
+ }, [isOpen, stroke, dropShadow, outerGlow, onApply, onClose]);
const handlePointerDown = (e: React.PointerEvent) => {
+ if ((e.target as HTMLElement | null)?.closest('button, input, select, textarea')) return;
isDraggingRef.current = true;
dragStartRef.current = {
startX: e.clientX,
@@ -234,7 +250,11 @@ export const LayerStylesModal: React.FC<LayerStylesModalProps> = ({
initX: pos.x,
initY: pos.y,
};
- (e.target as HTMLElement).setPointerCapture(e.pointerId);
+ try {
+ (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
+ } catch {
+ // Ignore synthetic/unsupported pointer capture
+ }
};
const handlePointerMove = (e: React.PointerEvent) => {
@@ -250,7 +270,7 @@ export const LayerStylesModal: React.FC<LayerStylesModalProps> = ({
const handlePointerUp = (e: React.PointerEvent) => {
isDraggingRef.current = false;
try {
- (e.target as HTMLElement).releasePointerCapture(e.pointerId);
+ (e.currentTarget as HTMLElement).releasePointerCapture(e.pointerId);
} catch {
// Ignore pointer release failure
}
@@ -293,6 +313,7 @@ export const LayerStylesModal: React.FC<LayerStylesModalProps> = ({
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
+ onPointerCancel={handlePointerUp}
className="h-10 flex items-center justify-between px-4 bg-ui-header border-b border-ui-subtle cursor-move text-xs font-medium"
>
<span id="layer-styles-modal-title" className="text-ui-primary">
diff --git a/src/components/MangaEffectsModal.tsx b/src/components/MangaEffectsModal.tsx
index b9590ff..03bfeea 100644
--- a/src/components/MangaEffectsModal.tsx
+++ b/src/components/MangaEffectsModal.tsx
@@ -26,11 +26,24 @@ export const MangaEffectsModal: React.FC<MangaEffectsModalProps> = ({
const { t } = useI18n();
const [activeTab, setActiveTab] = useState<'saturated' | 'stream'>('saturated');
+ const safeCanvasWidth = Math.max(1, canvasWidth);
+ const safeCanvasHeight = Math.max(1, canvasHeight);
+ const previewMaxW = 300;
+ const previewMaxH = 360;
+ const previewFitScale = Math.min(previewMaxW / safeCanvasWidth, previewMaxH / safeCanvasHeight);
+ const previewWidth = Math.max(40, Math.round(safeCanvasWidth * previewFitScale));
+ const previewHeight = Math.max(40, Math.round(safeCanvasHeight * previewFitScale));
+
+ const prevDimsRef = useRef<{ w: number; h: number }>({
+ w: safeCanvasWidth,
+ h: safeCanvasHeight,
+ });
+
// Saturated Lines State
const [satOptions, setSatOptions] = useState<SaturatedLinesOptions>({
- centerX: Math.round(canvasWidth * 0.5),
- centerY: Math.round(canvasHeight * 0.5),
- innerRadius: Math.round(Math.min(canvasWidth, canvasHeight) * 0.2),
+ centerX: Math.round(safeCanvasWidth * 0.5),
+ centerY: Math.round(safeCanvasHeight * 0.5),
+ innerRadius: Math.round(Math.min(safeCanvasWidth, safeCanvasHeight) * 0.2),
density: 120,
spacingJitter: 0.5,
lengthJitter: 0.35,
@@ -43,7 +56,7 @@ export const MangaEffectsModal: React.FC<MangaEffectsModalProps> = ({
const [streamOptions, setStreamOptions] = useState<StreamLinesOptions>({
angle: 0,
density: 80,
- lineLength: Math.round(Math.min(canvasWidth, canvasHeight) * 0.5),
+ lineLength: Math.round(Math.min(safeCanvasWidth, safeCanvasHeight) * 0.5),
lengthNoise: 0.4,
thickness: 3,
thicknessNoise: 0.5,
@@ -51,6 +64,27 @@ export const MangaEffectsModal: React.FC<MangaEffectsModalProps> = ({
color: '#000000',
});
+ // Re-sync default center/radius/length whenever the modal opens on a document with different dimensions
+ useEffect(() => {
+ if (!isOpen) return;
+ if (
+ prevDimsRef.current.w !== safeCanvasWidth ||
+ prevDimsRef.current.h !== safeCanvasHeight
+ ) {
+ prevDimsRef.current = { w: safeCanvasWidth, h: safeCanvasHeight };
+ setSatOptions((prev) => ({
+ ...prev,
+ centerX: Math.round(safeCanvasWidth * 0.5),
+ centerY: Math.round(safeCanvasHeight * 0.5),
+ innerRadius: Math.round(Math.min(safeCanvasWidth, safeCanvasHeight) * 0.2),
+ }));
+ setStreamOptions((prev) => ({
+ ...prev,
+ lineLength: Math.round(Math.min(safeCanvasWidth, safeCanvasHeight) * 0.5),
+ }));
+ }
+ }, [isOpen, safeCanvasWidth, safeCanvasHeight]);
+
const previewCanvasRef = useRef<HTMLCanvasElement>(null);
// Re-draw preview canvas whenever parameters change
@@ -66,39 +100,41 @@ export const MangaEffectsModal: React.FC<MangaEffectsModalProps> = ({
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Scaling ratio to fit canvas inside preview box
- const scale = canvas.width / canvasWidth;
+ const scaleX = canvas.width / safeCanvasWidth;
+ const scaleY = canvas.height / safeCanvasHeight;
+ const strokeScale = Math.max(0.001, Math.min(scaleX, scaleY));
ctx.save();
- ctx.scale(scale, scale);
+ ctx.scale(scaleX, scaleY);
if (activeTab === 'saturated') {
- renderSaturatedLines(ctx, canvasWidth, canvasHeight, satOptions);
+ renderSaturatedLines(ctx, safeCanvasWidth, safeCanvasHeight, satOptions);
// Draw faint indicator circle for center cutout
ctx.strokeStyle = '#38bdf8';
- ctx.lineWidth = 1.5 / scale;
- ctx.setLineDash([4 / scale, 4 / scale]);
+ ctx.lineWidth = 1.5 / strokeScale;
+ ctx.setLineDash([4 / strokeScale, 4 / strokeScale]);
ctx.beginPath();
ctx.arc(satOptions.centerX, satOptions.centerY, satOptions.innerRadius, 0, Math.PI * 2);
ctx.stroke();
// Crosshair at center
ctx.beginPath();
- ctx.arc(satOptions.centerX, satOptions.centerY, 3 / scale, 0, Math.PI * 2);
+ ctx.arc(satOptions.centerX, satOptions.centerY, 3 / strokeScale, 0, Math.PI * 2);
ctx.fillStyle = '#38bdf8';
ctx.fill();
} else {
- renderStreamLines(ctx, canvasWidth, canvasHeight, streamOptions);
+ renderStreamLines(ctx, safeCanvasWidth, safeCanvasHeight, streamOptions);
}
ctx.restore();
- }, [activeTab, canvasWidth, canvasHeight, satOptions, streamOptions]);
+ }, [activeTab, safeCanvasWidth, safeCanvasHeight, satOptions, streamOptions]);
useEffect(() => {
if (isOpen) {
updatePreview();
}
- }, [isOpen, updatePreview]);
+ }, [isOpen, updatePreview, previewWidth, previewHeight]);
useEffect(() => {
if (!isOpen) return;
@@ -122,14 +158,14 @@ export const MangaEffectsModal: React.FC<MangaEffectsModalProps> = ({
const canvas = previewCanvasRef.current;
if (!canvas) return;
const rect = canvas.getBoundingClientRect();
- const clickX = e.clientX - rect.left;
- const clickY = e.clientY - rect.top;
- const scale = canvasWidth / canvas.width;
+ if (rect.width <= 0 || rect.height <= 0) return;
+ const clickX = Math.max(0, Math.min(rect.width, e.clientX - rect.left));
+ const clickY = Math.max(0, Math.min(rect.height, e.clientY - rect.top));
setSatOptions((prev) => ({
...prev,
- centerX: Math.round(clickX * scale),
- centerY: Math.round(clickY * scale),
+ centerX: Math.round((clickX / rect.width) * safeCanvasWidth),
+ centerY: Math.round((clickY / rect.height) * safeCanvasHeight),
}));
};
@@ -203,8 +239,8 @@ export const MangaEffectsModal: React.FC<MangaEffectsModalProps> = ({
<div className="relative border border-ui-default rounded-ui-sm overflow-hidden bg-white">
<canvas
ref={previewCanvasRef}
- width={300}
- height={Math.round((300 * canvasHeight) / canvasWidth)}
+ width={previewWidth}
+ height={previewHeight}
onClick={handlePreviewClick}
className="cursor-crosshair block"
title={activeTab === 'saturated' ? t('Click on preview to move focus center') : undefined}
diff --git a/src/components/NavigatorPanel.tsx b/src/components/NavigatorPanel.tsx
index 0a82d1c..e0d0a1f 100644
--- a/src/components/NavigatorPanel.tsx
+++ b/src/components/NavigatorPanel.tsx
@@ -17,10 +17,11 @@ import { NavigatorPreviewMode } from '../types/workspace';
import {
isNativeCanvasActive,
renderNativeNavigatorPreview,
+ subscribeNativeCanvasActive,
subscribeNativeHistory,
subscribeNativeStrokeCommitted,
- subscribeNativeThumbnails,
} from '../utils/nativeEngineBridge';
+import { recoveryService } from '../services/recoveryService';
import { formatRotationDegrees } from '../utils/canvasUtils';
import {
applyPerceptualGrayscaleToImageData,
@@ -43,7 +44,7 @@ import {
import { IconButton, ScrubSlider, SegmentedControl, type ScrubSliderHandle } from './ui';
import { useI18n } from '../i18n';
-export const NAVIGATOR_PREVIEW_THROTTLE_MS = 120;
+export const NAVIGATOR_PREVIEW_THROTTLE_MS = 200;
const PREVIEW_PADDING = 8;
const MAX_PREVIEW_LONG_EDGE = 256;
const SLIDER_MAX = 1000;
@@ -88,19 +89,24 @@ export function viewportPointToDoc(
cam: CameraTransformState,
dimensions: CanvasDimensions
): DocPoint {
- const safeZoom = Math.max(0.0001, cam.zoom);
- const rx = vx - cam.pan.x;
- const ry = vy - cam.pan.y;
- const rad = (cam.rotation * Math.PI) / 180;
+ const safeZoom = Math.max(0.0001, Number.isFinite(cam?.zoom) ? cam.zoom : 1);
+ const panX = Number.isFinite(cam?.pan?.x) ? cam.pan.x : 0;
+ const panY = Number.isFinite(cam?.pan?.y) ? cam.pan.y : 0;
+ const rot = Number.isFinite(cam?.rotation) ? cam.rotation : 0;
+ const docW = Number.isFinite(dimensions?.width) ? dimensions.width : 1920;
+ const docH = Number.isFinite(dimensions?.height) ? dimensions.height : 1080;
+ const rx = vx - panX;
+ const ry = vy - panY;
+ const rad = (rot * Math.PI) / 180;
const cos = Math.cos(rad);
const sin = Math.sin(rad);
const unrotX = rx * cos + ry * sin;
const unrotY = -rx * sin + ry * cos;
- const fx = cam.flipX ? -1 : 1;
- const fy = cam.flipY ? -1 : 1;
+ const fx = cam?.flipX ? -1 : 1;
+ const fy = cam?.flipY ? -1 : 1;
return {
- x: dimensions.width / 2 + (fx * unrotX) / safeZoom,
- y: dimensions.height / 2 + (fy * unrotY) / safeZoom,
+ x: docW / 2 + (fx * unrotX) / safeZoom,
+ y: docH / 2 + (fy * unrotY) / safeZoom,
};
}
@@ -152,10 +158,12 @@ export function isPointInConvexQuad(
pt: DocPoint,
quad: [DocPoint, DocPoint, DocPoint, DocPoint]
): boolean {
+ if (!pt || !Array.isArray(quad) || quad.length < 4) return false;
let sign = 0;
for (let i = 0; i < 4; i++) {
const a = quad[i];
const b = quad[(i + 1) % 4];
+ if (!a || !b) return false;
const cross = (b.x - a.x) * (pt.y - a.y) - (b.y - a.y) * (pt.x - a.x);
if (Math.abs(cross) < 1e-6) continue;
const s = cross > 0 ? 1 : -1;
@@ -403,13 +411,28 @@ export const NavigatorPanel: React.FC<NavigatorPanelProps> = React.memo(
);
const activeCam = cam ?? navigation.getCameraState();
+ const sceneDims = latestSceneRef.current?.dimensions;
+ if (!activeCam || !activeCam.pan || !sceneDims) {
+ ctx.restore();
+ return;
+ }
const { vw, vh } = getMainViewportSize();
- const quad = computeViewportQuadInDoc(vw, vh, activeCam, latestSceneRef.current.dimensions);
-
- const pts = quad.map((p) => ({
- x: m.offsetX + p.x * m.scale,
- y: m.offsetY + p.y * m.scale,
- }));
+ const quad = computeViewportQuadInDoc(vw, vh, activeCam, sceneDims);
+
+ const pts = Array.isArray(quad)
+ ? quad.map((p) => ({
+ x: m.offsetX + p.x * m.scale,
+ y: m.offsetY + p.y * m.scale,
+ }))
+ : [];
+
+ if (
+ pts.length < 4 ||
+ pts.some((p) => !p || !Number.isFinite(p.x) || !Number.isFinite(p.y))
+ ) {
+ ctx.restore();
+ return;
+ }
// Red viewport frame polygon
ctx.beginPath();
@@ -616,29 +639,78 @@ export const NavigatorPanel: React.FC<NavigatorPanelProps> = React.memo(
presentPreviewToDisplay();
}, [presentPreviewToDisplay]);
+ const palettesHidden = useWorkspaceStore((s) => s.palettesHidden);
+ const palettesHiddenRef = useRef(palettesHidden);
+ palettesHiddenRef.current = palettesHidden;
+ const hasRenderedInitialRef = useRef(false);
+ const pendingRefreshRef = useRef(false);
+ const wasStageZeroRef = useRef(false);
+
+ const isNavigatorHidden = useCallback((): boolean => {
+ if (palettesHiddenRef.current) return true;
+ if (typeof document !== 'undefined' && document.hidden) return true;
+ const stage = stageRef.current;
+ if (stage && typeof stage.getBoundingClientRect === 'function') {
+ const rect = stage.getBoundingClientRect();
+ if (rect.width <= 0 || rect.height <= 0) return true;
+ }
+ return false;
+ }, []);
+
+ // Compact structural visual signature for layers — intentionally EXCLUDES `thumbnailUrl`
+ // and `maskThumbnailUrl` so async thumbnail updates NEVER trigger redundant Navigator readbacks.
+ const layersVisualSig = Array.isArray(layers)
+ ? layers
+ .map(
+ (l) =>
+ `${l.id}:${l.visible ? 1 : 0}:${l.opacity}:${l.blendMode}:${l.clipped ? 1 : 0}:${l.maskEnabled ? 1 : 0}:${l.maskLinked ? 1 : 0}:${l.parentId ?? ''}:${l.type}`
+ )
+ .join('|')
+ : '';
+
const scheduleThrottledPreview = useCallback(
- (deferSync: boolean = false, effectiveThrottleOverride?: number) => {
- const now = Date.now();
- const elapsed = now - lastPreviewTsRef.current;
+ (deferSync: boolean = true, effectiveThrottleOverride?: number) => {
const waitMs = effectiveThrottleOverride ?? throttleMs;
- if (!deferSync && elapsed >= waitMs) {
+
+ // Skip GPU readbacks while actively drawing or while the Navigator panel is collapsed/hidden;
+ // remember that a refresh is needed so it flushes once drawing stops or panel becomes visible.
+ if (recoveryService.getIsDrawingActive() || isNavigatorHidden()) {
+ pendingRefreshRef.current = true;
if (previewTimerRef.current !== null) {
clearTimeout(previewTimerRef.current);
previewTimerRef.current = null;
}
+ return;
+ }
+
+ if (!deferSync && waitMs <= 0) {
+ if (previewTimerRef.current !== null) {
+ clearTimeout(previewTimerRef.current);
+ previewTimerRef.current = null;
+ }
+ pendingRefreshRef.current = false;
+ hasRenderedInitialRef.current = true;
renderPreviewNow();
return;
}
- if (previewTimerRef.current !== null) return;
- const remaining = deferSync
- ? Math.max(16, waitMs - elapsed)
- : Math.max(16, waitMs - elapsed);
+
+ // True trailing debounce: reset timer on every burst event so rapid StrokeCommitted +
+ // HistoryChanged + layer mutations coalesce into AT MOST ONE GPU readback!
+ if (previewTimerRef.current !== null) {
+ clearTimeout(previewTimerRef.current);
+ }
previewTimerRef.current = setTimeout(() => {
previewTimerRef.current = null;
+ if (recoveryService.getIsDrawingActive() || isNavigatorHidden()) {
+ pendingRefreshRef.current = true;
+ return;
+ }
+ pendingRefreshRef.current = false;
+ hasRenderedInitialRef.current = true;
renderPreviewNow();
- }, remaining);
+ }, Math.max(16, waitMs));
},
- [renderPreviewNow, throttleMs]
+ [isNavigatorHidden, renderPreviewNow, throttleMs]
);
// Track Navigator preview stage size via ResizeObserver
@@ -648,41 +720,70 @@ export const NavigatorPanel: React.FC<NavigatorPanelProps> = React.memo(
const syncSize = () => {
const rect = el.getBoundingClientRect();
if (rect.width > 0 && rect.height > 0) {
+ const becameVisible = wasStageZeroRef.current;
+ wasStageZeroRef.current = false;
setStageSize((prev) =>
Math.abs(prev.width - rect.width) < 1 && Math.abs(prev.height - rect.height) < 1
? prev
: { width: Math.round(rect.width), height: Math.round(rect.height) }
);
+ if (becameVisible && pendingRefreshRef.current) {
+ scheduleThrottledPreview(true);
+ }
+ } else {
+ wasStageZeroRef.current = true;
}
};
syncSize();
const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(syncSize) : null;
ro?.observe(el);
return () => ro?.disconnect();
- }, []);
+ }, [scheduleThrottledPreview]);
- // Trigger throttled composite on layer/dimension/background changes
+ // Trigger initial render once on mount, and debounced composite only on structural visual changes
useEffect(() => {
- scheduleThrottledPreview();
- }, [layers, dimensions, showCheckerboard, scheduleThrottledPreview]);
+ if (!hasRenderedInitialRef.current) {
+ scheduleThrottledPreview(false, 0);
+ } else {
+ scheduleThrottledPreview(true);
+ }
+ }, [layersVisualSig, dimensions.width, dimensions.height, showCheckerboard, scheduleThrottledPreview]);
+
+ // Flush any skipped preview once palettes are unhidden
+ useEffect(() => {
+ if (!palettesHidden && pendingRefreshRef.current) {
+ scheduleThrottledPreview(true);
+ }
+ }, [palettesHidden, scheduleThrottledPreview]);
// Re-present instantly (0 recomposite!) when switching Color / Split / B&W or scrubbing split
useEffect(() => {
presentPreviewToDisplay(activePreviewMode, activeSplitRatio);
}, [activePreviewMode, activeSplitRatio, presentPreviewToDisplay]);
- // Subscribe to native Rust stroke commits, history mutations, and thumbnail refreshes
+ // Subscribe to native Rust stroke commits & history mutations (excluding redundant thumbnail
+ // events), coalesced through a single trailing debounce and paused while actively sketching.
useEffect(() => {
const triggerRefresh = () => {
scheduleThrottledPreview(true);
};
const unsubStroke = subscribeNativeStrokeCommitted(triggerRefresh);
const unsubHistory = subscribeNativeHistory(triggerRefresh);
- const unsubThumbs = subscribeNativeThumbnails(triggerRefresh);
+ const unsubDrawing = recoveryService.subscribeDrawingActive((active) => {
+ if (!active && pendingRefreshRef.current) {
+ scheduleThrottledPreview(true);
+ }
+ });
+ const unsubNativeActive = subscribeNativeCanvasActive((active) => {
+ if (active) {
+ scheduleThrottledPreview(false, 0);
+ }
+ });
return () => {
unsubStroke();
unsubHistory();
- unsubThumbs();
+ unsubDrawing();
+ unsubNativeActive();
if (previewTimerRef.current !== null) {
clearTimeout(previewTimerRef.current);
previewTimerRef.current = null;
diff --git a/src/components/PerspectiveRulerOverlay.tsx b/src/components/PerspectiveRulerOverlay.tsx
index 79f0118..6f7d50c 100644
--- a/src/components/PerspectiveRulerOverlay.tsx
+++ b/src/components/PerspectiveRulerOverlay.tsx
@@ -407,6 +407,7 @@ export const PerspectiveRulerOverlay: React.FC<PerspectiveRulerOverlayProps> = (
<>
{/* Horizon Line / Eye Level Pill Handle in Canvas Center */}
<div
+ data-native-occluder="true"
onPointerDown={startHorizonDrag}
title={t('Drag vertically to adjust Eye Level height')}
className="pointer-events-auto absolute -translate-x-1/2 -translate-y-1/2 cursor-ns-resize z-30 group"
@@ -448,6 +449,7 @@ export const PerspectiveRulerOverlay: React.FC<PerspectiveRulerOverlayProps> = (
return (
<div
key={`handle-vp-${vp.id}`}
+ data-native-occluder="true"
onPointerDown={(e) => startVpDrag(e, vp.id)}
title={t('Drag {label} Vanishing Point', { label: localizedVpLabel })}
className="pointer-events-auto absolute -translate-x-1/2 -translate-y-1/2 cursor-grab active:cursor-grabbing z-30"
@@ -477,6 +479,7 @@ export const PerspectiveRulerOverlay: React.FC<PerspectiveRulerOverlayProps> = (
return (
<div
key={`edge-vp-${vp.id}`}
+ data-native-occluder="true"
onPointerDown={(e) => startVpDrag(e, vp.id)}
title={t('Drag to reposition {label} ({dist}px off-screen)', {
label: localizedVpLabel,
@@ -500,6 +503,8 @@ export const PerspectiveRulerOverlay: React.FC<PerspectiveRulerOverlayProps> = (
{/* Floating Perspective Ruler Toolbar */}
<div
+ data-native-occluder="true"
+ onPointerDown={(e) => e.stopPropagation()}
className="pointer-events-auto absolute top-3 right-4 z-40 bg-ui-floating border border-ui-default rounded-ui-md shadow-ui-floating p-1 flex items-center space-x-1 text-[11px] text-ui-primary select-none"
>
{/* Toggle Ruler Visibility */}
diff --git a/src/components/PressureCurveEditor.tsx b/src/components/PressureCurveEditor.tsx
index a8d5f25..4698384 100644
--- a/src/components/PressureCurveEditor.tsx
+++ b/src/components/PressureCurveEditor.tsx
@@ -5,6 +5,7 @@ import {
calculatePressureOpacity,
createPressureCurvePreset,
evaluateGlobalPressureCurve,
+ normalizePressureCurve,
samplePressureCurve,
sanitizePressureCurvePoints,
} from '../utils/pressureCurve';
@@ -67,9 +68,10 @@ export const PressureCurveEditor: React.FC<PressureCurveEditorProps> = ({ value,
lastAlpha: 1,
});
- const points = useMemo(() => sanitizePressureCurvePoints(value.points), [value.points]);
+ const safeValue = useMemo(() => normalizePressureCurve(value), [value]);
+ const points = safeValue.points;
- const sampledCurve = useMemo(() => samplePressureCurve(value, 64), [value]);
+ const sampledCurve = useMemo(() => samplePressureCurve(safeValue, 64), [safeValue]);
const curvePathD = useMemo(() => {
if (sampledCurve.length === 0) return '';
@@ -89,12 +91,12 @@ export const PressureCurveEditor: React.FC<PressureCurveEditorProps> = ({ value,
const updatePoints = useCallback(
(nextPts: PressureCurvePoint[]) => {
onChange({
- enabled: value.enabled,
+ enabled: safeValue.enabled,
preset: 'custom',
points: sanitizePressureCurvePoints(nextPts),
});
},
- [onChange, value.enabled]
+ [onChange, safeValue.enabled]
);
const handleSvgPointerDown = (e: React.PointerEvent<SVGSVGElement>) => {
@@ -141,18 +143,21 @@ export const PressureCurveEditor: React.FC<PressureCurveEditorProps> = ({ value,
if (idx === null || !svgRef.current) return;
const [nx, ny] = fromClientToNorm(svgRef.current, e.clientX, e.clientY);
const next = points.map(([x, y]) => [x, y] as PressureCurvePoint);
+ if (next.length < 2 || idx < 0 || idx >= next.length) return;
if (idx === 0) {
next[0] = [0, ny];
} else if (idx === next.length - 1) {
next[next.length - 1] = [1, ny];
} else {
- const minX = next[idx - 1][0] + 0.03;
- const maxX = next[idx + 1][0] - 0.03;
+ const prevPt = next[idx - 1];
+ const nextPt = next[idx + 1];
+ const minX = (prevPt ? prevPt[0] : 0) + 0.03;
+ const maxX = (nextPt ? nextPt[0] : 1) - 0.03;
next[idx] = [Math.max(minX, Math.min(maxX, nx)), ny];
}
onChange({
- enabled: value.enabled,
+ enabled: safeValue.enabled,
preset: 'custom',
points: next,
});
@@ -244,9 +249,9 @@ export const PressureCurveEditor: React.FC<PressureCurveEditorProps> = ({ value,
const x = (e.clientX - rect.left) * scaleX;
const y = (e.clientY - rect.top) * scaleY;
const rawP = getTestRawPressure(e, (e.clientX - rect.left) / Math.max(1, rect.width));
- const mappedP = evaluateGlobalPressureCurve(rawP, value);
+ const mappedP = evaluateGlobalPressureCurve(rawP, safeValue);
const width = 1.5 + mappedP * 18;
- const alpha = calculatePressureOpacity(1.0, rawP, true, 0.12, value);
+ const alpha = calculatePressureOpacity(1.0, rawP, true, 0.12, safeValue);
testStrokeRef.current = {
active: true,
@@ -271,9 +276,9 @@ export const PressureCurveEditor: React.FC<PressureCurveEditorProps> = ({ value,
const x = (e.clientX - rect.left) * scaleX;
const y = (e.clientY - rect.top) * scaleY;
const rawP = getTestRawPressure(e, (e.clientX - rect.left) / Math.max(1, rect.width));
- const mappedP = evaluateGlobalPressureCurve(rawP, value);
+ const mappedP = evaluateGlobalPressureCurve(rawP, safeValue);
const width = 1.5 + mappedP * 18;
- const alpha = calculatePressureOpacity(1.0, rawP, true, 0.12, value);
+ const alpha = calculatePressureOpacity(1.0, rawP, true, 0.12, safeValue);
drawTestDotOrSegment(st.lastX, st.lastY, st.lastWidth, st.lastAlpha, x, y, width, alpha);
st.lastX = x;
@@ -309,8 +314,8 @@ export const PressureCurveEditor: React.FC<PressureCurveEditorProps> = ({ value,
<label className="flex items-center gap-1.5 text-[11px] text-ui-primary cursor-pointer">
<input
type="checkbox"
- checked={value.enabled}
- onChange={(e) => onChange({ ...value, enabled: e.target.checked })}
+ checked={safeValue.enabled}
+ onChange={(e) => onChange({ ...safeValue, enabled: e.target.checked })}
/>
<span>{t('Enabled')}</span>
</label>
@@ -319,12 +324,12 @@ export const PressureCurveEditor: React.FC<PressureCurveEditorProps> = ({ value,
{/* Preset Row */}
<div className="flex items-center gap-1.5">
{(['linear', 'soft', 'hard'] as const).map((preset) => {
- const active = value.preset === preset;
+ const active = safeValue.preset === preset;
return (
<button
key={preset}
type="button"
- onClick={() => onChange(createPressureCurvePreset(preset, value.enabled))}
+ onClick={() => onChange(createPressureCurvePreset(preset, safeValue.enabled))}
className={`px-2.5 py-1 rounded-ui-sm text-[11px] capitalize transition-colors cursor-pointer border ${
active
? 'bg-ui-control-active text-ui-primary border-ui-accent-border font-medium'
@@ -356,7 +361,7 @@ export const PressureCurveEditor: React.FC<PressureCurveEditorProps> = ({ value,
onPointerUp={handleSvgPointerUp}
onPointerCancel={handleSvgPointerUp}
className={`w-full h-[180px] touch-none select-none ${
- value.enabled ? 'cursor-crosshair' : 'opacity-45'
+ safeValue.enabled ? 'cursor-crosshair' : 'opacity-45'
}`}
>
{/* Plot background */}
diff --git a/src/components/RightSidebar.tsx b/src/components/RightSidebar.tsx
index aabbd46..f4b4a90 100644
--- a/src/components/RightSidebar.tsx
+++ b/src/components/RightSidebar.tsx
@@ -482,9 +482,11 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
const resetLayerFilter = () => {
setLayerFilter(DEFAULT_LAYER_FILTER_CRITERIA);
};
+ const safeHistoryList = Array.isArray(historyList) ? historyList : [];
const activeLayerHasMask = Boolean(
activeLayer &&
- (activeLayer.maskCanvas ||
+ (activeLayer.hasMask ||
+ activeLayer.maskCanvas ||
activeLayer.maskEnabled !== undefined ||
activeLayer.maskThumbnailUrl)
);
@@ -532,9 +534,12 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
});
const dropIndicatorRef = useRef<{ id: string; position: 'above' | 'below' | 'inside' } | null>(null);
const justDraggedRef = useRef<boolean>(false);
+ const activeDragCleanupRef = useRef<(() => void) | null>(null);
useEffect(() => {
return () => {
+ activeDragCleanupRef.current?.();
+ activeDragCleanupRef.current = null;
document.body.style.userSelect = '';
document.body.style.cursor = '';
};
@@ -545,6 +550,9 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
const target = e.target as HTMLElement | null;
if (target?.closest('button, input, select, textarea, [data-no-drag]')) return;
+ activeDragCleanupRef.current?.();
+ activeDragCleanupRef.current = null;
+
dragRef.current = { active: false, layerId, startX: e.clientX, startY: e.clientY };
dropIndicatorRef.current = null;
@@ -647,13 +655,20 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
setDropIndicator(nextIndicator);
};
- const handlePointerUp = () => {
+ const cleanupListeners = () => {
window.removeEventListener('pointermove', handlePointerMove);
window.removeEventListener('pointerup', handlePointerUp);
window.removeEventListener('pointercancel', handlePointerUp);
stopAutoScroll();
document.body.style.userSelect = '';
document.body.style.cursor = '';
+ if (activeDragCleanupRef.current === cleanupListeners) {
+ activeDragCleanupRef.current = null;
+ }
+ };
+
+ const handlePointerUp = () => {
+ cleanupListeners();
if (dragRef.current.active) {
justDraggedRef.current = true;
@@ -675,6 +690,7 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
setDropIndicator(null);
};
+ activeDragCleanupRef.current = cleanupListeners;
window.addEventListener('pointermove', handlePointerMove);
window.addEventListener('pointerup', handlePointerUp);
window.addEventListener('pointercancel', handlePointerUp);
@@ -738,7 +754,7 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
total: layers.length,
})
: t('{count} Layers', { count: layers.length })
- : t('{count} Steps', { count: historyList.length })}
+ : t('{count} Steps', { count: safeHistoryList.length })}
</span>
) : (
<HairlineTabs<'layers' | 'history'>
@@ -1337,7 +1353,13 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
} else {
onSelectLayer(layer.id);
}
- if (activeEditTarget === 'mask' && !layer.maskCanvas && layer.maskEnabled === undefined) {
+ if (
+ activeEditTarget === 'mask' &&
+ !layer.hasMask &&
+ !layer.maskCanvas &&
+ layer.maskEnabled === undefined &&
+ !layer.maskThumbnailUrl
+ ) {
onSelectEditTarget?.('layer');
}
}}
@@ -1579,7 +1601,8 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
</div>
)}
- {(layer.maskCanvas ||
+ {(layer.hasMask ||
+ layer.maskCanvas ||
layer.maskEnabled !== undefined ||
layer.maskThumbnailUrl) && (
<div
@@ -1702,7 +1725,7 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
</div>
{/* Tucked Collapsible Accordions for Advanced Layer Settings */}
- {activeLayer && activeLayer.type !== 'folder' && (
+ {activeLayer && !isFolderLikeLayer(activeLayer) && (
<div className="shrink-0 border-t border-ui-subtle bg-ui-panel max-h-[45%] overflow-y-auto">
{/* Accordion 1: Monochrome Expression Color & Color Threshold */}
<SectionDisclosure
@@ -2040,10 +2063,10 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
) : (
/* History Tab */
<div className="flex-1 overflow-y-auto px-1.5 py-1 space-y-0.5 min-h-0">
- {!hasOpenDocument || historyList.length === 0 ? (
+ {!hasOpenDocument || safeHistoryList.length === 0 ? (
<div className="p-4 text-center text-[11px] text-ui-muted">{t('No history')}</div>
) : (
- historyList.map((item, idx) => {
+ safeHistoryList.map((item, idx) => {
const isActive = idx === historyIndex;
const isFuture = idx > historyIndex;
return (
@@ -2094,7 +2117,8 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
const targetLayer = layers.find((l) => l.id === contextMenu.layerId);
if (!targetLayer) return null;
const hasMask = Boolean(
- targetLayer.maskCanvas ||
+ targetLayer.hasMask ||
+ targetLayer.maskCanvas ||
targetLayer.maskEnabled !== undefined ||
targetLayer.maskThumbnailUrl
);
@@ -2103,6 +2127,8 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
return (
<div
ref={contextMenuRef}
+ role="menu"
+ data-native-occluder="true"
className="fixed z-50 min-w-44 bg-ui-elevated border border-ui-default rounded-ui-md shadow-ui-popover p-1 text-[11px] text-ui-primary select-none"
style={{
left: Math.max(10, Math.min(contextMenu.x, window.innerWidth - 190)),
@@ -2174,7 +2200,7 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
<div className="my-0.5 border-t border-ui-subtle" />
- {targetLayer.type !== 'folder' && (
+ {!isFolderLikeLayer(targetLayer) && (
<>
{!hasMask ? (
<button
diff --git a/src/components/SelectionOverlay.tsx b/src/components/SelectionOverlay.tsx
index fb8e40f..95864d9 100644
--- a/src/components/SelectionOverlay.tsx
+++ b/src/components/SelectionOverlay.tsx
@@ -116,6 +116,7 @@ export const SelectionOverlay: React.FC<SelectionOverlayProps> = ({
{!selection.isDraftPreview &&
createPortal(
<div
+ data-native-occluder="true"
className="fixed bottom-10 left-1/2 -translate-x-1/2 z-50 max-w-[95vw] bg-ui-floating border border-ui-default rounded-ui-md shadow-ui-floating px-2 py-1 flex flex-wrap items-center justify-center gap-1 select-none text-[11px] text-ui-primary"
onPointerDown={(e) => e.stopPropagation()}
>
diff --git a/src/components/SpeechBalloonOverlay.tsx b/src/components/SpeechBalloonOverlay.tsx
index ec633dc..d7e15bf 100644
--- a/src/components/SpeechBalloonOverlay.tsx
+++ b/src/components/SpeechBalloonOverlay.tsx
@@ -17,7 +17,19 @@ interface SpeechBalloonOverlayProps {
onDeleteBalloon: () => void;
}
+interface SpeechBalloonOverlayInnerProps extends Omit<SpeechBalloonOverlayProps, 'balloon'> {
+ balloon: SpeechBalloon;
+}
+
export const SpeechBalloonOverlay: React.FC<SpeechBalloonOverlayProps> = ({
+ balloon,
+ ...rest
+}) => {
+ if (!balloon) return null;
+ return <SpeechBalloonOverlayInner {...rest} balloon={balloon} />;
+};
+
+const SpeechBalloonOverlayInner: React.FC<SpeechBalloonOverlayInnerProps> = ({
balloon,
zoom,
rotation = 0,
@@ -29,8 +41,6 @@ export const SpeechBalloonOverlay: React.FC<SpeechBalloonOverlayProps> = ({
}) => {
const { t, tc } = useI18n();
- if (!balloon) return null;
-
const dragRef = useRef<{
activeHandle: string | null;
startX: number;
diff --git a/src/components/StraightRulerOverlay.tsx b/src/components/StraightRulerOverlay.tsx
index baf5942..13b5703 100644
--- a/src/components/StraightRulerOverlay.tsx
+++ b/src/components/StraightRulerOverlay.tsx
@@ -451,6 +451,7 @@ export const StraightRulerOverlay: React.FC<StraightRulerOverlayProps> = ({
<div
ref={moveHandleRef}
data-testid="straight-ruler-move-handle"
+ data-native-occluder="true"
onPointerDown={(e) => startHandleDrag('move', e)}
title={t('Drag to move ruler')}
className="absolute top-0 left-0 pointer-events-auto cursor-move group"
@@ -463,6 +464,7 @@ export const StraightRulerOverlay: React.FC<StraightRulerOverlayProps> = ({
<div
ref={rotLeftHandleRef}
data-testid="straight-ruler-rotate-left"
+ data-native-occluder="true"
onPointerDown={(e) => startHandleDrag('rotate-left', e)}
title={t('Drag to rotate ruler (hold Shift for 15° snap)')}
className="absolute top-0 left-0 pointer-events-auto cursor-grab active:cursor-grabbing group"
@@ -475,6 +477,7 @@ export const StraightRulerOverlay: React.FC<StraightRulerOverlayProps> = ({
<div
ref={rotRightHandleRef}
data-testid="straight-ruler-rotate-right"
+ data-native-occluder="true"
onPointerDown={(e) => startHandleDrag('rotate-right', e)}
title={t('Drag to rotate ruler (hold Shift for 15° snap)')}
className="absolute top-0 left-0 pointer-events-auto cursor-grab active:cursor-grabbing group"
@@ -489,6 +492,7 @@ export const StraightRulerOverlay: React.FC<StraightRulerOverlayProps> = ({
{/* Compact Top-Center Ruler Control Pill */}
<div
data-testid="straight-ruler-controls"
+ data-native-occluder="true"
onPointerDown={(e) => e.stopPropagation()}
onWheel={(e) => {
if (ruler.locked) return;
diff --git a/src/components/SubToolList.tsx b/src/components/SubToolList.tsx
index f732a59..129704d 100644
--- a/src/components/SubToolList.tsx
+++ b/src/components/SubToolList.tsx
@@ -1149,10 +1149,11 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(
);
}
if (builtin) {
- if (builtin.staticTips && builtin.staticTips.length > 0) {
+ const firstStaticTip = Array.isArray(builtin.staticTips) ? builtin.staticTips[0] : undefined;
+ if (firstStaticTip?.assetPath) {
return (
<img
- src={resolveStaticBrushAssetUrl(builtin.staticTips[0].assetPath)}
+ src={resolveStaticBrushAssetUrl(firstStaticTip.assetPath)}
alt=""
draggable={false}
className={`${sizeClass} object-contain shrink-0 pointer-events-none ${
diff --git a/src/components/TonalCorrectionModal.tsx b/src/components/TonalCorrectionModal.tsx
index d112454..10ef8b9 100644
--- a/src/components/TonalCorrectionModal.tsx
+++ b/src/components/TonalCorrectionModal.tsx
@@ -184,6 +184,7 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({
// Window drag handlers
const handleDragPointerDown = (e: React.PointerEvent) => {
+ if ((e.target as HTMLElement | null)?.closest('button, input, select, textarea')) return;
isDraggingRef.current = true;
dragStartRef.current = {
startX: e.clientX,
@@ -191,7 +192,11 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({
initX: pos.x,
initY: pos.y,
};
- (e.target as HTMLElement).setPointerCapture(e.pointerId);
+ try {
+ (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
+ } catch {
+ // Ignore synthetic/unsupported pointer capture
+ }
};
const handleDragPointerMove = (e: React.PointerEvent) => {
@@ -207,7 +212,7 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({
const handleDragPointerUp = (e: React.PointerEvent) => {
isDraggingRef.current = false;
try {
- (e.target as HTMLElement).releasePointerCapture(e.pointerId);
+ (e.currentTarget as HTMLElement).releasePointerCapture(e.pointerId);
} catch {
// Ignore
}
@@ -284,7 +289,12 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({
if (e.key === 'Escape') {
e.preventDefault();
onClose();
- } else if (e.key === 'Enter' && !(e.target instanceof HTMLTextAreaElement)) {
+ } else if (
+ e.key === 'Enter' &&
+ !(e.target instanceof HTMLTextAreaElement) &&
+ !(e.target instanceof HTMLButtonElement) &&
+ !(e.target instanceof HTMLSelectElement)
+ ) {
e.preventDefault();
onApply(type, currentParams);
}
@@ -335,6 +345,7 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({
onPointerDown={handleDragPointerDown}
onPointerMove={handleDragPointerMove}
onPointerUp={handleDragPointerUp}
+ onPointerCancel={handleDragPointerUp}
className="h-10 px-4 bg-ui-header border-b border-ui-subtle flex items-center justify-between cursor-move"
>
<span id="tonal-modal-title" className="font-medium text-ui-primary">
diff --git a/src/components/TransformOverlay.tsx b/src/components/TransformOverlay.tsx
index 9d4a370..8a1c5d0 100644
--- a/src/components/TransformOverlay.tsx
+++ b/src/components/TransformOverlay.tsx
@@ -69,23 +69,30 @@ function computeAffineQuad(s: TransformSession): [Point2D, Point2D, Point2D, Poi
function buildUpdatePayload(s: TransformSession): NativeTransformUpdatePayload {
const mode = s.mode || 'affine';
if (mode === 'perspective' && s.perspectiveQuad) {
- return { kind: 'perspective', corners: s.perspectiveQuad };
+ return { mode: 'perspective', corners: s.perspectiveQuad };
}
- if (mode === 'mesh' && s.meshPoints) {
- const rows = s.meshPoints.length;
- const cols = rows > 0 ? s.meshPoints[0].length : 0;
+ if (mode === 'mesh' && s.meshPoints && s.meshPoints.length >= 2) {
+ const vRows = s.meshPoints.length;
+ const vCols = s.meshPoints[0]?.length ?? 0;
const flat: Point2D[] = [];
- for (let r = 0; r < rows; r++) {
- for (let c = 0; c < cols; c++) {
+ for (let r = 0; r < vRows; r++) {
+ for (let c = 0; c < vCols; c++) {
flat.push(s.meshPoints[r][c]);
}
}
- return { kind: 'mesh', mesh: { cols, rows, points: flat } };
+ return {
+ mode: 'mesh',
+ mesh: {
+ cols: Math.max(1, vCols - 1),
+ rows: Math.max(1, vRows - 1),
+ points: flat,
+ },
+ };
}
if (mode === 'puppet' && s.puppet) {
return {
- kind: 'puppet',
- pins: s.puppet.pins.map((p) => ({
+ mode: 'puppet',
+ puppetPins: s.puppet.pins.map((p) => ({
id: p.id,
restX: p.restX,
restY: p.restY,
@@ -98,31 +105,27 @@ function buildUpdatePayload(s: TransformSession): NativeTransformUpdatePayload {
}
if (mode === 'cage' && s.cage) {
return {
- kind: 'cage',
- restVertices: s.cage.points.map((p) => ({ x: p.restX, y: p.restY })),
- vertices: s.cage.points.map((p) => ({ x: p.x, y: p.y })),
- closed: s.cage.phase === 'deform',
+ mode: 'cage',
+ cage: {
+ restPoints: s.cage.points.map((p) => ({ x: p.restX, y: p.restY })),
+ points: s.cage.points.map((p) => ({ x: p.x, y: p.y })),
+ closed: s.cage.phase === 'deform' || Boolean(s.cage.closed),
+ },
};
}
- const origCx = s.bounds.x + s.bounds.width * 0.5;
- const origCy = s.bounds.y + s.bounds.height * 0.5;
- const curCx = s.x + s.width * 0.5;
- const curCy = s.y + s.height * 0.5;
- const sx = (s.width / Math.max(1, s.bounds.width)) * (s.flipH ? -1 : 1);
- const sy = (s.height / Math.max(1, s.bounds.height)) * (s.flipV ? -1 : 1);
return {
- kind: 'affine',
- state: {
- tx: curCx - origCx,
- ty: curCy - origCy,
- scaleX: sx,
- scaleY: sy,
+ mode: 'affine',
+ affine: {
+ x: s.x,
+ y: s.y,
+ width: Math.max(1, s.width),
+ height: Math.max(1, s.height),
rotation: (s.rotation * Math.PI) / 180,
skewX: 0,
skewY: 0,
- pivotX: 0.5,
- pivotY: 0.5,
+ flipX: Boolean(s.flipH),
+ flipY: Boolean(s.flipV),
},
};
}
@@ -153,6 +156,8 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({
const cageIdCounterRef = useRef(100);
const syncInFlightRef = useRef<boolean>(false);
const pendingPayloadRef = useRef<NativeTransformUpdatePayload | null>(null);
+ const sessionRef = useRef<TransformSession>(session);
+ sessionRef.current = session;
const flushGpuTransformUpdate = useCallback((payload: NativeTransformUpdatePayload) => {
if (syncInFlightRef.current) {
@@ -161,7 +166,9 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({
}
syncInFlightRef.current = true;
void nativeTransformUpdate(payload)
- .catch(() => {})
+ .catch((err) => {
+ console.warn('[TransformOverlay] nativeTransformUpdate failed:', err);
+ })
.finally(() => {
syncInFlightRef.current = false;
const queued = pendingPayloadRef.current;
@@ -174,11 +181,10 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({
const updateAndSync = useCallback(
(updater: (prev: TransformSession) => TransformSession) => {
- onUpdateSession((prev) => {
- const next = updater(prev);
- flushGpuTransformUpdate(buildUpdatePayload(next));
- return next;
- });
+ const next = updater(sessionRef.current);
+ sessionRef.current = next;
+ onUpdateSession(() => next);
+ flushGpuTransformUpdate(buildUpdatePayload(next));
},
[onUpdateSession, flushGpuTransformUpdate]
);
@@ -191,41 +197,72 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({
};
}, []);
- // Keyboard shortcuts: Enter = Apply, Escape = Cancel, Delete/Backspace = delete selected puppet pin
+ // Keyboard shortcuts: Enter = Close cage (if defining) or Apply, Escape = Cancel, Delete/Backspace = delete selected pin/point
useEffect(() => {
const onKeyDown = (ev: KeyboardEvent) => {
const target = ev.target as HTMLElement | null;
if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA')) return;
if (ev.key === 'Enter') {
ev.preventDefault();
+ const cur = sessionRef.current;
+ if (
+ cur.mode === 'cage' &&
+ cur.cage &&
+ cur.cage.phase !== 'deform' &&
+ !cur.cage.closed &&
+ cur.cage.points.length >= 3
+ ) {
+ updateAndSync((prev) =>
+ prev.cage
+ ? { ...prev, cage: { ...prev.cage, phase: 'deform', closed: true } }
+ : prev
+ );
+ return;
+ }
onApply();
} else if (ev.key === 'Escape') {
ev.preventDefault();
onCancel();
- } else if (
- (ev.key === 'Delete' || ev.key === 'Backspace') &&
- session.mode === 'puppet' &&
- session.puppet?.selectedPinId
- ) {
- ev.preventDefault();
- const delId = session.puppet.selectedPinId;
- updateAndSync((prev) => {
- if (!prev.puppet) return prev;
- const remaining = prev.puppet.pins.filter((p) => p.id !== delId);
- return {
- ...prev,
- puppet: {
- ...prev.puppet,
- pins: remaining,
- selectedPinId: remaining[0]?.id ?? null,
- },
- };
- });
+ } else if (ev.key === 'Delete' || ev.key === 'Backspace') {
+ const cur = sessionRef.current;
+ if (cur.mode === 'puppet' && cur.puppet?.selectedPinId) {
+ ev.preventDefault();
+ const delId = cur.puppet.selectedPinId;
+ updateAndSync((prev) => {
+ if (!prev.puppet) return prev;
+ const remaining = prev.puppet.pins.filter((p) => p.id !== delId);
+ return {
+ ...prev,
+ puppet: {
+ ...prev.puppet,
+ pins: remaining,
+ selectedPinId: remaining[0]?.id ?? null,
+ },
+ };
+ });
+ } else if (cur.mode === 'cage' && cur.cage?.selectedPointId) {
+ ev.preventDefault();
+ const delId = cur.cage.selectedPointId;
+ updateAndSync((prev) => {
+ if (!prev.cage) return prev;
+ const isClosed = prev.cage.phase === 'deform' || Boolean(prev.cage.closed);
+ if (isClosed && prev.cage.points.length <= 3) return prev;
+ const remaining = prev.cage.points.filter((pt) => pt.id !== delId);
+ return {
+ ...prev,
+ cage: {
+ ...prev.cage,
+ points: remaining,
+ selectedPointId: null,
+ },
+ };
+ });
+ }
}
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
- }, [onApply, onCancel, session.mode, session.puppet?.selectedPinId, updateAndSync]);
+ }, [onApply, onCancel, updateAndSync]);
const invZoom = 1 / Math.max(0.05, zoom || 1);
const mode: TransformMode = session.mode || 'affine';
@@ -467,7 +504,7 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({
const first = cagePoints[0];
if (Math.hypot(first.x - pt.x, first.y - pt.y) <= 14 * invZoom) {
updateAndSync((prev) =>
- prev.cage ? { ...prev, cage: { ...prev.cage, phase: 'deform' } } : prev
+ prev.cage ? { ...prev, cage: { ...prev.cage, phase: 'deform', closed: true } } : prev
);
return;
}
@@ -800,7 +837,7 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({
if (!cageClosed && idx === 0 && cagePoints.length >= 3) {
e.stopPropagation();
updateAndSync((prev) =>
- prev.cage ? { ...prev, cage: { ...prev.cage, phase: 'deform' } } : prev
+ prev.cage ? { ...prev, cage: { ...prev.cage, phase: 'deform', closed: true } } : prev
);
return;
}
@@ -832,6 +869,7 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({
{/* Floating Transform Mode & Action Toolbar */}
<div
+ data-native-occluder="true"
onPointerDown={(e) => e.stopPropagation()}
className="absolute z-45 pointer-events-auto flex items-center gap-1 px-2 py-1 rounded-ui-md bg-ui-floating border border-ui-default shadow-ui-floating text-[11px] text-ui-primary whitespace-nowrap"
style={{
diff --git a/src/components/canvasArea/CanvasViewportHud.tsx b/src/components/canvasArea/CanvasViewportHud.tsx
index 169faf2..46f0f1a 100644
--- a/src/components/canvasArea/CanvasViewportHud.tsx
+++ b/src/components/canvasArea/CanvasViewportHud.tsx
@@ -1,7 +1,7 @@
import React from 'react';
import { Smartphone, Archive } from 'lucide-react';
import { TipOutline } from '../../utils/brushOutline';
-import { toolStoreActions, useToolStore } from '../../stores';
+import { toolStoreActions, useNativeDiagnostics, useToolStore } from '../../stores';
import { StraightRulerOverlay } from '../StraightRulerOverlay';
import { PerspectiveRulerOverlay } from '../PerspectiveRulerOverlay';
import { SmartphoneViewportSimulator } from '../SmartphoneViewportSimulator';
@@ -10,6 +10,110 @@ import { CanvasAreaProps } from './types';
import { useI18n } from '../../i18n';
import type { NativeEngineDiagnostics } from '../../utils/nativeEngineBridge';
+interface NativeGpuPerfHudProps {
+ onClearNativeCanvas?: () => void;
+}
+
+/**
+ * Isolated leaf component that subscribes to 4 Hz `native-engine://diagnostics` updates via
+ * `useSyncExternalStore` ONLY while mounted. Keeps `CanvasArea` and `CanvasViewportHud` at
+ * zero re-renders during strokes, and omits `data-native-occluder` with fixed-width numeric
+ * columns so changing FPS/latency digits never trigger `setNativeOccludedRects` IPC.
+ */
+const NativeGpuPerfHud: React.FC<NativeGpuPerfHudProps> = React.memo(({ onClearNativeCanvas }) => {
+ const { t } = useI18n();
+ const nativeDiagnostics = useNativeDiagnostics();
+
+ const renderFpsReadout = () => {
+ if (!nativeDiagnostics) {
+ return (
+ <>
+ <span className="inline-block w-[46px] text-right text-ui-primary">-- FPS</span>
+ <span className="inline-block w-[38px] text-right text-ui-muted">--</span>
+ </>
+ );
+ }
+ const frameMs = nativeDiagnostics.frameTimeMs;
+ const safeActiveFps =
+ nativeDiagnostics.fps < 15 && frameMs > 0 && frameMs < 20
+ ? Math.min(240, Math.round(1000 / Math.max(0.5, frameMs)))
+ : Math.round(nativeDiagnostics.fps);
+ if (nativeDiagnostics.isIdle) {
+ return (
+ <>
+ <span
+ className="inline-block w-[46px] text-right text-ui-muted"
+ title={
+ safeActiveFps > 0
+ ? `On-demand idle (last active: ${safeActiveFps} FPS)`
+ : 'On-demand idle'
+ }
+ >
+ Idle
+ </span>
+ <span className="inline-block w-[38px] text-right text-ui-muted">
+ {frameMs > 0 ? `${frameMs.toFixed(1)}ms` : '--'}
+ </span>
+ </>
+ );
+ }
+ return (
+ <>
+ <span className="inline-block w-[46px] text-right text-ui-primary">{`${safeActiveFps} FPS`}</span>
+ <span className="inline-block w-[38px] text-right text-ui-muted">{`${frameMs.toFixed(1)}ms`}</span>
+ </>
+ );
+ };
+
+ return (
+ <div
+ data-testid="native-gpu-perf-hud"
+ className="pointer-events-none absolute bottom-2.5 right-3 z-40 flex items-center gap-2 px-2.5 py-1 rounded-ui-md bg-ui-floating border border-ui-default shadow-ui-floating text-[10px] font-ui-mono tabular-nums text-ui-secondary select-none"
+ title={
+ nativeDiagnostics
+ ? `${nativeDiagnostics.adapterName} · ${nativeDiagnostics.compositionMode} · ${nativeDiagnostics.presentMode} (latency=${nativeDiagnostics.maxFrameLatency})`
+ : 'Native DX12 Engine'
+ }
+ >
+ <span className="inline-flex items-center gap-1 text-ui-primary font-medium">
+ <span className="w-1.5 h-1.5 rounded-full bg-ui-success" />
+ {nativeDiagnostics?.backend || 'DX12'}
+ </span>
+ <span className="max-w-[160px] truncate text-ui-muted">
+ {nativeDiagnostics?.adapterName || 'Initializing GPU...'}
+ </span>
+ <span className="text-ui-subtle">|</span>
+ {renderFpsReadout()}
+ <span className="text-ui-subtle">|</span>
+ <span
+ className="inline-block w-[68px] text-right text-ui-primary"
+ title="Input-to-present latency"
+ >
+ {nativeDiagnostics
+ ? `I2P ${nativeDiagnostics.inputToPresentMs.toFixed(2)}ms`
+ : 'I2P --'}
+ </span>
+ {onClearNativeCanvas && (
+ <>
+ <span className="text-ui-subtle">|</span>
+ <button
+ type="button"
+ onPointerDown={(e) => e.stopPropagation()}
+ onWheel={(e) => e.stopPropagation()}
+ onClick={onClearNativeCanvas}
+ className="pointer-events-auto px-1.5 py-0.5 rounded-ui-xs bg-ui-control hover:bg-ui-control-hover text-ui-primary border border-ui-subtle transition-colors cursor-pointer"
+ title={t('Clear test GPU stroke canvas')}
+ >
+ {t('Clear')}
+ </button>
+ </>
+ )}
+ </div>
+ );
+});
+
+NativeGpuPerfHud.displayName = 'NativeGpuPerfHud';
+
export interface CanvasViewportHudProps {
canvasProps: CanvasAreaProps;
cursorRingRef: React.RefObject<HTMLDivElement | null>;
@@ -29,6 +133,7 @@ export interface CanvasViewportHudProps {
thicknessRatio?: number;
tipOutline: TipOutline | null;
isResizingBrush: boolean;
+ liveResizePreview?: { size: number; hardness: number } | null;
resizePreviewX: number;
resizePreviewY: number;
quickPalettePos: { x: number; y: number } | null;
@@ -57,12 +162,12 @@ export const CanvasViewportHud: React.FC<CanvasViewportHudProps> = ({
thicknessRatio = 1.0,
tipOutline,
isResizingBrush,
+ liveResizePreview = null,
resizePreviewX,
resizePreviewY,
quickPalettePos,
setQuickPalettePos,
nativeCanvasActive = false,
- nativeDiagnostics = null,
onClearNativeCanvas,
}) => {
const { t } = useI18n();
@@ -299,28 +404,36 @@ export const CanvasViewportHud: React.FC<CanvasViewportHudProps> = ({
) : (
<>
{/* Outer diameter & hardness preview circle */}
- <div
- className={`w-full h-full ${isSquare ? 'rounded-none' : 'rounded-full'} border-2 border-white shadow-[0_0_0_1px_rgba(0,0,0,0.8),0_4px_16px_rgba(0,0,0,0.5)] transition-[width,height] duration-75`}
- style={{
- background:
- (brushSettings.hardness ?? 1.0) < 0.98
- ? `radial-gradient(circle, rgba(239, 68, 68, 0.45) 0%, rgba(239, 68, 68, 0.45) ${Math.round(
- (brushSettings.hardness ?? 1.0) * 100
- )}%, rgba(239, 68, 68, 0.05) 100%)`
- : 'rgba(239, 68, 68, 0.38)',
- }}
- />
+ {(() => {
+ const previewHardness =
+ liveResizePreview?.hardness ?? brushSettings.hardness ?? 1.0;
+ return (
+ <>
+ <div
+ className={`w-full h-full ${isSquare ? 'rounded-none' : 'rounded-full'} border-2 border-white shadow-[0_0_0_1px_rgba(0,0,0,0.8),0_4px_16px_rgba(0,0,0,0.5)] transition-[width,height] duration-75`}
+ style={{
+ background:
+ previewHardness < 0.98
+ ? `radial-gradient(circle, rgba(239, 68, 68, 0.45) 0%, rgba(239, 68, 68, 0.45) ${Math.round(
+ previewHardness * 100
+ )}%, rgba(239, 68, 68, 0.05) 100%)`
+ : 'rgba(239, 68, 68, 0.38)',
+ }}
+ />
- {/* Inner hardness boundary indicator if soft brush */}
- {(brushSettings.hardness ?? 1.0) < 0.98 && (
- <div
- className={`absolute ${isSquare ? 'rounded-none' : 'rounded-full'} border border-dashed border-white/80 pointer-events-none`}
- style={{
- width: `${Math.max(2, cursorWidth * (brushSettings.hardness ?? 1.0))}px`,
- height: `${Math.max(2, cursorHeight * (brushSettings.hardness ?? 1.0))}px`,
- }}
- />
- )}
+ {/* Inner hardness boundary indicator if soft brush */}
+ {previewHardness < 0.98 && (
+ <div
+ className={`absolute ${isSquare ? 'rounded-none' : 'rounded-full'} border border-dashed border-white/80 pointer-events-none`}
+ style={{
+ width: `${Math.max(2, cursorWidth * previewHardness)}px`,
+ height: `${Math.max(2, cursorHeight * previewHardness)}px`,
+ }}
+ />
+ )}
+ </>
+ );
+ })()}
</>
)}
@@ -332,8 +445,13 @@ export const CanvasViewportHud: React.FC<CanvasViewportHudProps> = ({
<div className="flex items-center gap-2 text-[11px] font-ui-mono tabular-nums font-medium text-ui-primary">
<span>
{t('Size {size}px', {
- size:
- tool === 'liquify' && liquifySettings
+ size: liveResizePreview
+ ? tool === 'liquify' ||
+ tool === 'retouch' ||
+ (tool === 'fill' && fillSettings?.method === 'paint-unfilled')
+ ? Math.round(liveResizePreview.size)
+ : liveResizePreview.size
+ : tool === 'liquify' && liquifySettings
? liquifySettings.size
: tool === 'retouch' && retouchSettings
? retouchSettings.size
@@ -348,8 +466,9 @@ export const CanvasViewportHud: React.FC<CanvasViewportHudProps> = ({
<span className="text-ui-muted">·</span>
<span>
{t('Hard {value}%', {
- value:
- tool === 'retouch' && retouchSettings
+ value: liveResizePreview
+ ? Math.round(liveResizePreview.hardness * 100)
+ : tool === 'retouch' && retouchSettings
? retouchSettings.hardness
: Math.round((brushSettings.hardness ?? 1.0) * 100),
})}
@@ -488,55 +607,8 @@ export const CanvasViewportHud: React.FC<CanvasViewportHudProps> = ({
/>
)}
- {/* Native Rust + wgpu (DX12) Perf HUD Readout (Phase 1 Vertical Slice) */}
- {nativeCanvasActive && (
- <div
- data-testid="native-gpu-perf-hud"
- data-native-occluder="true"
- onPointerDown={(e) => e.stopPropagation()}
- onWheel={(e) => e.stopPropagation()}
- className="absolute bottom-2.5 right-3 z-40 flex items-center gap-2 px-2.5 py-1 rounded-ui-md bg-ui-floating border border-ui-default shadow-ui-floating text-[10px] font-ui-mono tabular-nums text-ui-secondary select-none"
- title={
- nativeDiagnostics
- ? `${nativeDiagnostics.adapterName} · ${nativeDiagnostics.compositionMode} · ${nativeDiagnostics.presentMode} (latency=${nativeDiagnostics.maxFrameLatency})`
- : 'Native DX12 Engine'
- }
- >
- <span className="inline-flex items-center gap-1 text-ui-primary font-medium">
- <span className="w-1.5 h-1.5 rounded-full bg-ui-success" />
- {nativeDiagnostics?.backend || 'DX12'}
- </span>
- <span className="max-w-[160px] truncate text-ui-muted">
- {nativeDiagnostics?.adapterName || 'Initializing GPU...'}
- </span>
- <span className="text-ui-subtle">|</span>
- <span className="text-ui-primary">
- {nativeDiagnostics ? `${Math.round(nativeDiagnostics.fps)} FPS` : '-- FPS'}
- </span>
- <span className="text-ui-muted">
- {nativeDiagnostics ? `${nativeDiagnostics.frameTimeMs.toFixed(1)}ms` : '--'}
- </span>
- <span className="text-ui-subtle">|</span>
- <span className="text-ui-primary" title="Input-to-present latency">
- {nativeDiagnostics
- ? `I2P ${nativeDiagnostics.inputToPresentMs.toFixed(2)}ms`
- : 'I2P --'}
- </span>
- {onClearNativeCanvas && (
- <>
- <span className="text-ui-subtle">|</span>
- <button
- type="button"
- onClick={onClearNativeCanvas}
- className="px-1.5 py-0.5 rounded-ui-xs bg-ui-control hover:bg-ui-control-hover text-ui-primary border border-ui-subtle transition-colors cursor-pointer"
- title={t('Clear test GPU stroke canvas')}
- >
- {t('Clear')}
- </button>
- </>
- )}
- </div>
- )}
+ {/* Native Rust + wgpu (DX12) Perf HUD Readout (isolated external store subscriber) */}
+ {nativeCanvasActive && <NativeGpuPerfHud onClearNativeCanvas={onClearNativeCanvas} />}
{/* 2D Frame-by-Frame Animation Timeline Scrubber Dock */}
{animationTimeline && onUpdateAnimationTimeline && (
diff --git a/src/components/canvasArea/useCanvasEffects.ts b/src/components/canvasArea/useCanvasEffects.ts
index e50a2f6..4f64127 100644
--- a/src/components/canvasArea/useCanvasEffects.ts
+++ b/src/components/canvasArea/useCanvasEffects.ts
@@ -4,8 +4,7 @@ import { ModifierAction } from '../../types/settings';
import { getBrushTipOutline, resolveBrushTipImage, TipOutline } from '../../utils/brushOutline';
import { computeTipStampDimensions, isNaturalPaintBrush } from '../../utils/brushMath';
import { preloadTipImage } from '../../utils/brushStorage';
-import { shouldSuppressDomPointerEvent, subscribeNativeTablet } from '../../utils/nativeTabletInput';
-import { isNativeStrokeTool } from '../../utils/nativeEngineBridge';
+import { isNativeStrokeTool, setNativeCursor } from '../../utils/nativeEngineBridge';
import { useUiStore } from '../../stores';
import {
computeEffectiveCursorAngleDeg,
@@ -126,6 +125,11 @@ export function useCanvasEffects({
setTipOutline(null);
}, [activeTipImage, brushSettings.customTipDataUrl, brushSettings.preset]);
+ const [liveResizePreview, setLiveResizePreview] = useState<{
+ size: number;
+ hardness: number;
+ } | null>(null);
+
const isBrushOrEraser = tool === 'brush' || tool === 'decoration' || tool === 'eraser';
const isPaintUnfilled = tool === 'fill' && fillSettings?.method === 'paint-unfilled';
const isCustomTip = Boolean(
@@ -133,7 +137,7 @@ export function useCanvasEffects({
);
const isSquare = isBrushOrEraser && brushSettings.preset === 'square-digital' && !tipOutline;
- const activeToolSize =
+ const baseActiveToolSize =
tool === 'liquify' && liquifySettings
? liquifySettings.size
: tool === 'retouch' && retouchSettings
@@ -141,6 +145,8 @@ export function useCanvasEffects({
: isPaintUnfilled
? Math.max(2, Math.min(300, fillSettings?.brushSize ?? 24))
: brushSettings.size;
+ const activeToolSize =
+ isResizingBrush && liveResizePreview ? liveResizePreview.size : baseActiveToolSize;
const cursorBaseWidth = Math.max(4, activeToolSize * liveZoom);
const thicknessRatio = isBrushOrEraser ? (brushSettings.thickness ?? 1.0) : 1.0;
const thicknessVertical = Boolean(brushSettings.thicknessVertical && isBrushOrEraser);
@@ -294,6 +300,8 @@ export function useCanvasEffects({
!isPaintUnfilled);
const shouldHideCursorRingRef = useRef(shouldHideCursorRing);
shouldHideCursorRingRef.current = shouldHideCursorRing;
+ const nativeCanvasActiveRef = useRef(nativeCanvasActive);
+ nativeCanvasActiveRef.current = nativeCanvasActive;
const cursorToolRef = useRef(tool);
cursorToolRef.current = tool;
@@ -301,11 +309,15 @@ export function useCanvasEffects({
((x: number, y: number, tiltX?: number, tiltY?: number, twist?: number) => void) | null
>(null);
- // Lightweight visibility toggle when Space/Shift/Alt/pan/rotate/tool changes (ZERO listener teardown!)
+ // Lightweight visibility toggle when Space/Shift/Alt/pan/rotate/tool/nativeCanvasActive changes
+ // (hides DOM cursor ring ONCE on transition instead of mutating style.display on every pointermove)
useEffect(() => {
- if (!cursorRingRef.current) return;
+ const ring = cursorRingRef.current;
+ if (!ring) return;
if (shouldHideCursorRing) {
- cursorRingRef.current.style.display = 'none';
+ if (ring.style.display !== 'none') {
+ ring.style.display = 'none';
+ }
} else if (lastPointerPosRef.current && showRingAtLocalPosRef.current) {
showRingAtLocalPosRef.current(lastPointerPosRef.current.x, lastPointerPosRef.current.y);
}
@@ -315,9 +327,15 @@ export function useCanvasEffects({
const viewport = viewportRef.current;
if (!viewport) return;
- let cachedRect: DOMRect | null = viewport.getBoundingClientRect();
+ let cachedRect: DOMRect | null = nativeCanvasActiveRef.current
+ ? null
+ : viewport.getBoundingClientRect();
const updateRect = () => {
- if (viewport) cachedRect = viewport.getBoundingClientRect();
+ if (viewport && !nativeCanvasActiveRef.current) {
+ cachedRect = viewport.getBoundingClientRect();
+ } else {
+ cachedRect = null;
+ }
};
let ringRafId: number | null = null;
@@ -434,10 +452,23 @@ export function useCanvasEffects({
twist?: number,
immediate: boolean = false
) => {
+ // When native DX12 canvas owns the cursor & stroke, skip all DOM layout reads & style writes.
+ if (nativeCanvasActiveRef.current && isNativeStrokeTool(cursorToolRef.current)) {
+ return;
+ }
const ring = cursorRingRef.current;
if (!ring) return;
- if (forceRefreshRect || !cachedRect) updateRect();
+ if (shouldHideCursorRingRef.current) {
+ if (ring.style.display !== 'none') {
+ ring.style.display = 'none';
+ }
+ return;
+ }
+
+ if (forceRefreshRect || !cachedRect) {
+ cachedRect = viewport.getBoundingClientRect();
+ }
if (!cachedRect) return;
const x = clientX - cachedRect.left;
@@ -447,17 +478,14 @@ export function useCanvasEffects({
lastPointerPosRef.current = null;
lastDirAnchorRef.current = null;
hasDynamicDirRef.current = false;
- ring.style.display = 'none';
+ if (ring.style.display !== 'none') {
+ ring.style.display = 'none';
+ }
return;
}
lastPointerPosRef.current = { x, y };
- if (shouldHideCursorRingRef.current) {
- ring.style.display = 'none';
- return;
- }
-
if (immediate) {
showRingAtLocalPos(x, y, tiltX, tiltY, twist);
} else {
@@ -466,22 +494,14 @@ export function useCanvasEffects({
};
const handleWindowPointerMove = (e: PointerEvent) => {
- const curTool = cursorToolRef.current;
- if (
- (curTool === 'brush' || curTool === 'decoration' || curTool === 'eraser') &&
- shouldSuppressDomPointerEvent(e.pointerType, e.clientX, e.clientY)
- ) {
+ if (nativeCanvasActiveRef.current && isNativeStrokeTool(cursorToolRef.current)) {
return;
}
updateCursorRingCoords(e.clientX, e.clientY, false, e.tiltX, e.tiltY, e.twist, false);
};
const handleViewportPointerEnterOrDown = (e: PointerEvent) => {
- const curTool = cursorToolRef.current;
- if (
- (curTool === 'brush' || curTool === 'decoration' || curTool === 'eraser') &&
- shouldSuppressDomPointerEvent(e.pointerType, e.clientX, e.clientY)
- ) {
+ if (nativeCanvasActiveRef.current && isNativeStrokeTool(cursorToolRef.current)) {
return;
}
updateCursorRingCoords(e.clientX, e.clientY, true, e.tiltX, e.tiltY, e.twist, true);
@@ -495,7 +515,7 @@ export function useCanvasEffects({
lastPointerPosRef.current = null;
lastDirAnchorRef.current = null;
hasDynamicDirRef.current = false;
- if (cursorRingRef.current) {
+ if (cursorRingRef.current && cursorRingRef.current.style.display !== 'none') {
cursorRingRef.current.style.display = 'none';
}
};
@@ -505,31 +525,11 @@ export function useCanvasEffects({
viewport.addEventListener('pointerenter', handleViewportPointerEnterOrDown, { passive: true });
viewport.addEventListener('pointerleave', handlePointerLeave, { passive: true });
- // Keep brush ring in sync with native WinTab / Windows Ink packets (XP-Pen / Wacom)
- const unsubscribeNativeTablet = subscribeNativeTablet((batch) => {
- if (batch.length === 0) return;
- const last = batch[batch.length - 1];
- if (last.phase === 4) {
- handlePointerLeave();
- return;
- }
- updateCursorRingCoords(
- last.clientX,
- last.clientY,
- false,
- last.tiltX,
- last.tiltY,
- last.twist,
- false
- );
- });
-
return () => {
showRingAtLocalPosRef.current = null;
if (ringRafId !== null && typeof cancelAnimationFrame === 'function') {
cancelAnimationFrame(ringRafId);
}
- unsubscribeNativeTablet();
window.removeEventListener('resize', updateRect);
window.removeEventListener('scroll', updateRect, true);
ro?.disconnect();
@@ -569,16 +569,40 @@ export function useCanvasEffects({
};
}, [quickPalettePos, setIsResizingBrush, setQuickPalettePos]);
- // Handle active brush resizing window drag listeners
+ // Handle active brush resizing window drag listeners.
+ // During Ctrl+Alt+Drag, update ONLY the lightweight local on-canvas preview (and native GPU
+ // cursor size) at 60 Hz — committing to the global tool store & full 90-field native brush
+ // config ONCE on pointer-up so BrushPreview & RightSidebar never thrash mid-drag.
useEffect(() => {
- if (!isResizingBrush) return;
+ if (!isResizingBrush) {
+ setLiveResizePreview(null);
+ return;
+ }
let rafId: number | null = null;
let pendingSize = resizeStartSettingsRef.current.size;
let pendingHardness = resizeStartSettingsRef.current.hardness;
+ let hasChanged = false;
+ setLiveResizePreview({ size: pendingSize, hardness: pendingHardness });
- const commitResize = () => {
+ const flushPreview = () => {
rafId = null;
+ setLiveResizePreview({ size: pendingSize, hardness: pendingHardness });
+ if (nativeCanvasActiveRef.current && isNativeStrokeTool(tool)) {
+ const cfg = cursorConfigRef.current;
+ void setNativeCursor({
+ size: Math.max(0.5, pendingSize),
+ thicknessRatio: Math.max(0.05, Math.min(1.0, cfg.thicknessRatio || 1.0)),
+ thicknessVertical: cfg.thicknessVertical,
+ tipAngleDeg: cfg.tipAngleDeg,
+ isSquare: isSquare,
+ visible: false,
+ });
+ }
+ };
+
+ const commitFinalSettings = () => {
+ if (!hasChanged) return;
if (tool === 'liquify' && onUpdateLiquifySettings) {
onUpdateLiquifySettings({ size: Math.round(pendingSize) });
} else if (tool === 'retouch' && onUpdateRetouchSettings) {
@@ -598,8 +622,10 @@ export function useCanvasEffects({
const finishResize = () => {
if (rafId !== null) {
cancelAnimationFrame(rafId);
- commitResize();
+ rafId = null;
}
+ commitFinalSettings();
+ setLiveResizePreview(null);
setIsResizingBrush(false);
};
@@ -615,9 +641,10 @@ export function useCanvasEffects({
const baseSize = Math.max(0.5, resizeStartSettingsRef.current.size);
const rawSize = baseSize * Math.exp(dx * 0.006) + dx * 0.15;
const clampedSize = Math.max(0.5, Math.min(1000, rawSize));
- pendingSize = clampedSize < 10 ? Math.round(clampedSize * 10) / 10 : Math.round(clampedSize);
+ const nextSize =
+ clampedSize < 10 ? Math.round(clampedSize * 10) / 10 : Math.round(clampedSize);
- pendingHardness = Math.max(
+ const nextHardness = Math.max(
0.05,
Math.min(
1.0,
@@ -625,8 +652,13 @@ export function useCanvasEffects({
)
);
+ if (nextSize === pendingSize && nextHardness === pendingHardness) return;
+ pendingSize = nextSize;
+ pendingHardness = nextHardness;
+ hasChanged = true;
+
if (rafId === null) {
- rafId = requestAnimationFrame(commitResize);
+ rafId = requestAnimationFrame(flushPreview);
}
};
@@ -653,7 +685,17 @@ export function useCanvasEffects({
document.body.style.cursor = '';
document.body.style.userSelect = '';
};
- }, [isResizingBrush, isPaintUnfilled, onUpdateBrushSettings, onUpdateFillSettings, onUpdateLiquifySettings, onUpdateRetouchSettings, tool, setIsResizingBrush]);
+ }, [
+ isResizingBrush,
+ isPaintUnfilled,
+ isSquare,
+ onUpdateBrushSettings,
+ onUpdateFillSettings,
+ onUpdateLiquifySettings,
+ onUpdateRetouchSettings,
+ tool,
+ setIsResizingBrush,
+ ]);
return {
tipOutline,
@@ -667,6 +709,7 @@ export function useCanvasEffects({
cursorWidth,
cursorHeight,
totalAngleDeg,
+ liveResizePreview,
cursorConfigRef,
lastPointerPosRef,
cursorRingRef,
diff --git a/src/components/canvasArea/useCanvasPointerHandlers.ts b/src/components/canvasArea/useCanvasPointerHandlers.ts
index 7534dd9..5bf0810 100644
--- a/src/components/canvasArea/useCanvasPointerHandlers.ts
+++ b/src/components/canvasArea/useCanvasPointerHandlers.ts
@@ -1,4 +1,4 @@
-import React, { useRef } from 'react';
+import React, { useEffect, useRef } from 'react';
import {
BrushSettings,
CanvasDimensions,
@@ -11,10 +11,10 @@ import { ModifierAction } from '../../types/settings';
import { CanvasNavigationHandle } from '../../hooks/useCanvasNavigation';
import { screenToCanvas } from '../../utils/canvasUtils';
import { resolvePointerModifierAction } from '../../utils/shortcutManager';
-import { shouldSuppressDomPointerEvent } from '../../utils/nativeTabletInput';
import { isNativeStrokeTool } from '../../utils/nativeEngineBridge';
import { isWorkspaceInteractionActive } from '../../utils/workspacePointerGuard';
import { artworkTimeTracker } from '../../utils/artworkTimeTracker';
+import { recoveryService } from '../../services/recoveryService';
import { toolStoreActions, uiStoreActions, useToolStore, useUiStore } from '../../stores';
import { extractCoalescedEvents, extractPredictedEvents } from './types';
@@ -118,12 +118,23 @@ export function useCanvasPointerHandlers({
};
};
+ const modifierEyedropperCleanupRef = useRef<(() => void) | null>(null);
+
+ useEffect(() => {
+ return () => {
+ modifierEyedropperCleanupRef.current?.();
+ modifierEyedropperCleanupRef.current = null;
+ };
+ }, []);
+
// Start continuous eyedropper sampling for modifier buttons (e.g. Right Click / Barrel Button)
const startModifierEyedropper = (e: React.PointerEvent) => {
if (!onSampleColor || !viewportRef.current) return;
e.preventDefault();
e.stopPropagation();
+ modifierEyedropperCleanupRef.current?.();
+
let lastClientX = e.clientX;
let lastClientY = e.clientY;
@@ -155,17 +166,29 @@ export function useCanvasPointerHandlers({
lastClientY = ev.clientY;
sampleAtClient(lastClientX, lastClientY, false);
};
+ const cleanup = () => {
+ window.removeEventListener('pointermove', handleMove);
+ window.removeEventListener('pointerup', handleUp);
+ window.removeEventListener('pointercancel', handleCancel);
+ window.removeEventListener('blur', handleCancel);
+ if (modifierEyedropperCleanupRef.current === cleanup) {
+ modifierEyedropperCleanupRef.current = null;
+ }
+ };
const handleUp = (ev: PointerEvent) => {
lastClientX = ev.clientX;
lastClientY = ev.clientY;
sampleAtClient(lastClientX, lastClientY, true);
- window.removeEventListener('pointermove', handleMove);
- window.removeEventListener('pointerup', handleUp);
- window.removeEventListener('pointercancel', handleUp);
+ cleanup();
+ };
+ const handleCancel = () => {
+ cleanup();
};
+ modifierEyedropperCleanupRef.current = cleanup;
window.addEventListener('pointermove', handleMove, { passive: true });
window.addEventListener('pointerup', handleUp);
- window.addEventListener('pointercancel', handleUp);
+ window.addEventListener('pointercancel', handleCancel);
+ window.addEventListener('blur', handleCancel);
};
// Open floating Quick Palette near cursor when mapped to 'quick-palette'
@@ -344,18 +367,11 @@ export function useCanvasPointerHandlers({
}
// When native DX12 `ink-engine` owns Brush/Decoration/Eraser strokes directly via lock-free SPSC
- // rings (WinTab/Windows Ink/native mouse), skip JS stroke dispatch completely (zero IPC).
+ // rings (WinTab/Windows Ink/native mouse), notify recoveryService of active native drawing so
+ // checkpoints, timelapse readbacks & scratch-disk walks pause, then skip JS stroke dispatch.
const isNativeOwned = nativeStrokeOwned ?? (nativeCanvasActive && isNativeStrokeTool(tool));
if (isNativeOwned) {
- return;
- }
-
- // Native WinTab / Windows Ink channel owns pen brush/eraser strokes; skip duplicate DOM
- // pen events AND WinTab CXO_SYSTEM-synthesized mouse events (which carry constant pressure=0.5).
- if (
- (tool === 'brush' || tool === 'decoration' || tool === 'eraser') &&
- shouldSuppressDomPointerEvent(e.pointerType, e.clientX, e.clientY)
- ) {
+ recoveryService.notifyNativeStrokeStart();
return;
}
@@ -384,14 +400,6 @@ export function useCanvasPointerHandlers({
if (isNativeOwned && activeDomPointerIdRef.current !== e.pointerId) {
return;
}
- const isTrackedDomStroke = activeDomPointerIdRef.current === e.pointerId;
- if (
- !isTrackedDomStroke &&
- (tool === 'brush' || tool === 'decoration' || tool === 'eraser') &&
- shouldSuppressDomPointerEvent(e.pointerType, e.clientX, e.clientY)
- ) {
- return;
- }
const coalesced = extractCoalescedEvents(e);
const predicted = extractPredictedEvents(e);
(e as any).coalescedEvents = coalesced;
@@ -409,6 +417,7 @@ export function useCanvasPointerHandlers({
activeDomPointerIdRef.current = null;
}
if (nativeCanvasActive && isNativeStrokeTool(tool) && !isTrackedDomStroke) {
+ recoveryService.notifyNativeStrokeEnd();
if (tempEraserPrevToolRef.current !== null) {
const prev = tempEraserPrevToolRef.current;
tempEraserPrevToolRef.current = null;
@@ -416,16 +425,8 @@ export function useCanvasPointerHandlers({
}
return;
}
- if (
- isTrackedDomStroke ||
- !(
- (tool === 'brush' || tool === 'decoration' || tool === 'eraser') &&
- shouldSuppressDomPointerEvent(e.pointerType, e.clientX, e.clientY)
- )
- ) {
- onPointerUp(e);
- uiStoreActions.setIsDrawing(false);
- }
+ onPointerUp(e);
+ uiStoreActions.setIsDrawing(false);
try {
const target = e.currentTarget as HTMLElement | null;
if (target?.hasPointerCapture?.(e.pointerId)) {
diff --git a/src/hooks/drawing/useBrushStrokeSession.ts b/src/hooks/drawing/useBrushStrokeSession.ts
index 25a9e06..b8e00a6 100644
--- a/src/hooks/drawing/useBrushStrokeSession.ts
+++ b/src/hooks/drawing/useBrushStrokeSession.ts
@@ -19,7 +19,6 @@ import { artworkTimeTracker } from '../../utils/artworkTimeTracker';
import { screenToCanvas } from '../../utils/canvasUtils';
import { enforceColorMode } from '../../utils/colorUtils';
import { subscribeNativeStrokeCommitted } from '../../utils/nativeEngineBridge';
-import { clearNativePenContact } from '../../utils/nativeTabletInput';
import { commitVectorStrokeOrErase } from './useVectorDrawing';
import { LastStrokeEndState, PushHistoryStepFn } from './types';
@@ -292,7 +291,9 @@ export function useBrushStrokeSession(
const handleFocusLoss = () => {
if (isDrawingRef.current) {
abortActiveStroke();
- clearNativePenContact();
+ }
+ if (recoveryService.getIsDrawingActive()) {
+ recoveryService.notifyNativeStrokeEnd();
}
};
window.addEventListener('blur', handleFocusLoss);
@@ -304,8 +305,30 @@ export function useBrushStrokeSession(
// Subscribe to committed native Rust DX12 strokes for artwork stats, Shift+click anchor & collab sync
useEffect(() => {
const unsubCommitted = subscribeNativeStrokeCommitted((ev) => {
+ const curDocId = paramsRef.current.activeSessionId;
+ if (curDocId && ev.docId && ev.docId !== curDocId) return;
artworkTimeTracker.recordArtworkAction();
- const pts: Point[] = (ev.points || []).map((p) => ({
+ const rawPts = ev.points;
+ if (rawPts && rawPts.length > 0) {
+ const rawLast = rawPts[rawPts.length - 1];
+ paramsRef.current.lastStrokeEndRef.current = {
+ x: rawLast.x,
+ y: rawLast.y,
+ pressure: rawLast.pressure,
+ width: rawLast.width,
+ layerId: ev.layerId,
+ };
+ }
+ // Avoid allocating/mapping point arrays when not in a multiplayer session
+ if (!multiplayerService.isConnected()) return;
+ if (!rawPts || rawPts.length === 0) return;
+
+ const onStart = paramsRef.current.onCollabStrokeStartRef.current;
+ const onChunk = paramsRef.current.onCollabStrokeChunkRef.current;
+ const onFinish = paramsRef.current.onCollabStrokeFinishRef.current;
+ if (!onStart || !onFinish) return;
+
+ const pts: Point[] = rawPts.map((p) => ({
x: p.x,
y: p.y,
pressure: p.pressure,
@@ -316,34 +339,18 @@ export function useBrushStrokeSession(
timestamp: p.timestampMs,
isCorner: p.isCorner,
}));
- if (pts.length > 0) {
- const last = pts[pts.length - 1];
- paramsRef.current.lastStrokeEndRef.current = {
- x: last.x,
- y: last.y,
- pressure: last.pressure,
- width: last.width,
- layerId: ev.layerId,
- };
- const onStart = paramsRef.current.onCollabStrokeStartRef.current;
- const onChunk = paramsRef.current.onCollabStrokeChunkRef.current;
- const onFinish = paramsRef.current.onCollabStrokeFinishRef.current;
- if (onStart && onFinish) {
- const strokeId = ev.entryId || `native-${Date.now()}`;
- const bs = getBrushSettings();
- const tool = getTool();
- onStart(strokeId, ev.layerId, bs, tool, pts[0]);
- if (pts.length > 2 && onChunk) {
- onChunk(strokeId, pts.slice(1, -1));
- }
- onFinish(strokeId, ev.layerId, last, ev.dirtyRect);
- if (multiplayerService.isConnected()) {
- multiplayerService.streamNativeDirtyRectTiles(ev.layerId, ev.dirtyRect, {
- strokeId,
- });
- }
- }
+ const last = pts[pts.length - 1];
+ const strokeId = ev.entryId || `native-${Date.now()}`;
+ const bs = getBrushSettings();
+ const tool = getTool();
+ onStart(strokeId, ev.layerId, bs, tool, pts[0]);
+ if (pts.length > 2 && onChunk) {
+ onChunk(strokeId, pts.slice(1, -1));
}
+ onFinish(strokeId, ev.layerId, last, ev.dirtyRect);
+ multiplayerService.streamNativeDirtyRectTiles(ev.layerId, ev.dirtyRect, {
+ strokeId,
+ });
});
return () => {
unsubCommitted();
diff --git a/src/hooks/drawing/useDrawingHistory.ts b/src/hooks/drawing/useDrawingHistory.ts
index 3887d46..53c5b89 100644
--- a/src/hooks/drawing/useDrawingHistory.ts
+++ b/src/hooks/drawing/useDrawingHistory.ts
@@ -15,6 +15,7 @@ import { multiplayerService } from '../../services/multiplayerService';
import {
clearNativeLayer,
fromNativeLayerNodeMeta,
+ getHistorySnapshotEntries,
nativeGetHistory,
nativeJumpHistory,
nativePushHistoryMeta,
@@ -27,7 +28,9 @@ import {
NativeHistoryStateSnapshot,
requestNativeThumbnails,
subscribeNativeHistory,
+ subscribeNativeStrokeCommitted,
} from '../../utils/nativeEngineBridge';
+import { recoveryService } from '../../services/recoveryService';
import { documentStoreActions } from '../../stores';
import {
ApplyDocumentStateDeltaFn,
@@ -110,7 +113,9 @@ export function useDrawingHistory({
abortActiveStrokeRef,
}: UseDrawingHistoryParams): UseDrawingHistoryResult {
const activeSessionIdRef = useRef<string | null>(activeSessionId ?? null);
+ const initializedHistoryDocRef = useRef<string | null>(null);
const historyIndexRef = useRef<number>(-1);
+ const lastHistorySigRef = useRef<string>('');
const pendingHistoryTasksRef = useRef<Array<() => void>>([]);
const [historyList, setHistoryList] = useState<HistoryItemMeta[]>([]);
@@ -118,17 +123,38 @@ export function useDrawingHistory({
const [canUndo, setCanUndo] = useState(false);
const [canRedo, setCanRedo] = useState(false);
- const applyNativeHistorySnapshot = useCallback((snap: NativeHistoryStateSnapshot) => {
- historyIndexRef.current = snap.index;
- setHistoryIndex(snap.index);
- setCanUndo(snap.canUndo);
- setCanRedo(snap.canRedo);
- setHistoryList(snap.items);
- }, []);
+ const applyNativeHistorySnapshot = useCallback(
+ (snap: NativeHistoryStateSnapshot | null | undefined) => {
+ if (!snap || typeof snap !== 'object') return;
+ const entries = getHistorySnapshotEntries(snap);
+ const safeIndex =
+ typeof snap.index === 'number' && Number.isFinite(snap.index)
+ ? snap.index
+ : entries.length - 1;
+ const lastEntryId = entries.length > 0 ? entries[entries.length - 1]?.id ?? '' : '';
+ const currentEntryId =
+ safeIndex >= 0 && safeIndex < entries.length ? entries[safeIndex]?.id ?? '' : '';
+ const nextCanUndo = Boolean(snap.canUndo);
+ const nextCanRedo = Boolean(snap.canRedo);
+ const sig = `${safeIndex}|${entries.length}|${lastEntryId}|${currentEntryId}|${nextCanUndo ? 1 : 0}|${nextCanRedo ? 1 : 0}`;
+ if (sig === lastHistorySigRef.current) return;
+ lastHistorySigRef.current = sig;
+
+ historyIndexRef.current = safeIndex;
+ setHistoryIndex(safeIndex);
+ setCanUndo(nextCanUndo);
+ setCanRedo(nextCanRedo);
+ setHistoryList(entries);
+ },
+ []
+ );
const applyNativeMutationResult = useCallback(
(res: NativeHistoryMutationResult | null, direction: 'undo' | 'redo' = 'redo') => {
- if (!res) return;
+ if (!res || !res.doc) return;
+ if (activeSessionIdRef.current && res.doc.id && res.doc.id !== activeSessionIdRef.current) {
+ return;
+ }
applyNativeHistorySnapshot(res.doc.history);
if (res.documentStateDelta) {
onApplyDocumentStateDeltaRef?.current?.(res.documentStateDelta, direction);
@@ -159,6 +185,14 @@ export function useDrawingHistory({
if (res.changedLayerIds.length > 0) {
void requestNativeThumbnails(res.doc.id, res.changedLayerIds);
}
+ if (
+ res.changedLayerIds.length > 0 ||
+ res.dimensionsChanged ||
+ res.layersChanged ||
+ res.documentStateDelta
+ ) {
+ documentStoreActions.markDocumentDirty(res.doc.id, true);
+ }
},
[
activeLayerIdRef,
@@ -170,12 +204,28 @@ export function useDrawingHistory({
]
);
- // Subscribe to live Rust CoW history updates (strokes, fills, transforms, liquify, filters, selections)
+ // Subscribe to live Rust CoW history updates & committed native strokes so history,
+ // undo/redo buttons, and the dirty-document (`*`) indicator always stay synchronized.
useEffect(() => {
- return subscribeNativeHistory((ev) => {
+ const unsubHistory = subscribeNativeHistory((ev) => {
if (activeSessionIdRef.current && ev.docId !== activeSessionIdRef.current) return;
applyNativeHistorySnapshot(ev.history);
});
+ const unsubStroke = subscribeNativeStrokeCommitted((ev) => {
+ const targetDocId = ev.docId || activeSessionIdRef.current;
+ if (activeSessionIdRef.current && ev.docId && ev.docId !== activeSessionIdRef.current) return;
+ if (ev.history) {
+ applyNativeHistorySnapshot(ev.history);
+ }
+ if (targetDocId) {
+ documentStoreActions.markDocumentDirty(targetDocId, true);
+ recoveryService.notifyNativeStrokeCommitted(targetDocId);
+ }
+ });
+ return () => {
+ unsubHistory();
+ unsubStroke();
+ };
}, [applyNativeHistorySnapshot]);
const pushHistoryStep = useCallback<PushHistoryStepFn>(
@@ -191,13 +241,13 @@ export function useDrawingHistory({
_peerId?: string | number,
_strokeId?: string,
_isMaskEdit?: boolean,
- layerTreeDelta?: LayerTreeDelta,
+ _layerTreeDelta?: LayerTreeDelta,
documentStateDelta?: DocumentStateDelta
) => {
const docId = activeSessionIdRef.current;
if (!docId) return;
// Rust owns all raster/layer CoW history; forward compact metadata deltas (rulers, timeline, selection)
- if (documentStateDelta && !explicitTileDeltas?.length && !layerTreeDelta) {
+ if (documentStateDelta && !explicitTileDeltas?.length) {
void nativePushHistoryMeta({
docId,
actionType,
@@ -205,9 +255,13 @@ export function useDrawingHistory({
layerId: targetLayerId || null,
documentStateDelta,
coalesceKey: documentStateDelta.coalesceKey,
- }).then((snap) => {
- if (snap) applyNativeHistorySnapshot(snap);
- });
+ })
+ .then((snap) => {
+ if (snap && activeSessionIdRef.current === docId) {
+ applyNativeHistorySnapshot(snap);
+ }
+ })
+ .catch((err) => console.warn('[History] Native pushHistoryMeta failed:', err));
}
},
[applyNativeHistorySnapshot]
@@ -361,12 +415,15 @@ export function useDrawingHistory({
if (dims.width <= 0 || dims.height <= 0) return;
const docId = activeSessionIdRef.current;
if (!docId) return;
- void clearNativeLayer(docId, activeLayerId, true).then((snap) => {
- if (snap) {
- applyNativeHistorySnapshot(snap.history);
- void requestNativeThumbnails(docId, [activeLayerId]);
- }
- });
+ void clearNativeLayer(docId, activeLayerId, true)
+ .then((snap) => {
+ if (snap && activeSessionIdRef.current === docId) {
+ applyNativeHistorySnapshot(snap.history);
+ documentStoreActions.markDocumentDirty(docId, true);
+ void requestNativeThumbnails(docId, [activeLayerId]);
+ }
+ })
+ .catch((err) => console.warn('[History] Native clearCanvas failed:', err));
}, [activeLayerId, activeLayerLocked, applyNativeHistorySnapshot, dimensionsRef]);
const resetHistory = useCallback(
@@ -374,6 +431,7 @@ export function useDrawingHistory({
flushPendingHistoryTasks();
const docId = targetDocumentId ?? activeSessionIdRef.current;
if (!docId) {
+ lastHistorySigRef.current = '';
historyIndexRef.current = -1;
setHistoryList([]);
setHistoryIndex(-1);
@@ -381,28 +439,36 @@ export function useDrawingHistory({
setCanRedo(false);
return;
}
- void nativeResetHistory(docId, t('New Document')).then((snap) => {
- if (snap && (!targetDocumentId || targetDocumentId === activeSessionIdRef.current)) {
- applyNativeHistorySnapshot(snap);
- }
- });
+ lastHistorySigRef.current = '';
+ void nativeResetHistory(docId, t('New Document'))
+ .then((snap) => {
+ if (snap && (!targetDocumentId || targetDocumentId === activeSessionIdRef.current)) {
+ applyNativeHistorySnapshot(snap);
+ }
+ })
+ .catch((err) => console.warn('[History] Native resetHistory failed:', err));
},
[applyNativeHistorySnapshot, flushPendingHistoryTasks]
);
- // Sync history list from Rust whenever the active document tab changes
+ // Sync history list from Rust whenever the active document tab changes (including initial mount)
useEffect(() => {
- const prevDocId = activeSessionIdRef.current;
const nextDocId = activeSessionId ?? null;
- if (prevDocId === nextDocId) return;
+ const prevDocId = activeSessionIdRef.current;
+ const alreadyInitialized = initializedHistoryDocRef.current === nextDocId;
+ if (prevDocId === nextDocId && alreadyInitialized) return;
- flushPendingHistoryTasks();
- if (isDrawingRef.current) {
- abortActiveStrokeRef.current();
+ if (prevDocId !== nextDocId) {
+ flushPendingHistoryTasks();
+ if (isDrawingRef.current) {
+ abortActiveStrokeRef.current();
+ }
+ lastStrokeEndRef.current = null;
}
activeSessionIdRef.current = nextDocId;
- lastStrokeEndRef.current = null;
+ initializedHistoryDocRef.current = nextDocId;
+ lastHistorySigRef.current = '';
if (!nextDocId) {
historyIndexRef.current = -1;
@@ -413,11 +479,13 @@ export function useDrawingHistory({
return;
}
- void nativeGetHistory(nextDocId).then((snap) => {
- if (snap && activeSessionIdRef.current === nextDocId) {
- applyNativeHistorySnapshot(snap);
- }
- });
+ void nativeGetHistory(nextDocId)
+ .then((snap) => {
+ if (snap && activeSessionIdRef.current === nextDocId) {
+ applyNativeHistorySnapshot(snap);
+ }
+ })
+ .catch(() => {});
}, [
abortActiveStrokeRef,
activeSessionId,
diff --git a/src/hooks/drawing/useRetouchTool.ts b/src/hooks/drawing/useRetouchTool.ts
index 32a10e2..defd61b 100644
--- a/src/hooks/drawing/useRetouchTool.ts
+++ b/src/hooks/drawing/useRetouchTool.ts
@@ -84,31 +84,42 @@ export function useRetouchTool({
useEffect(() => {
let prevTool = useToolStore.getState().tool;
- return useToolStore.subscribe(() => {
+ const unsub = useToolStore.subscribe(() => {
const curTool = useToolStore.getState().tool;
if (prevTool === 'retouch' && curTool !== 'retouch') {
if (isActiveRef.current) {
isActiveRef.current = false;
- void nativeRetouchCancel(documentStore.getActiveDocumentId());
+ const docId = documentStore.getActiveDocumentId();
+ stepChainRef.current = stepChainRef.current
+ .then(() => nativeRetouchCancel(docId))
+ .catch(() => {});
}
setIsPickingCloneSource(false);
setLiveSamplePos(null);
}
prevTool = curTool;
});
+ return () => {
+ unsub();
+ if (isActiveRef.current) {
+ isActiveRef.current = false;
+ const docId = documentStore.getActiveDocumentId();
+ stepChainRef.current = stepChainRef.current
+ .then(() => nativeRetouchCancel(docId))
+ .catch(() => {});
+ }
+ };
}, [setIsPickingCloneSource]);
const queueNativeStep = useCallback(
- (from: Point2D, to: Point2D, pressure: number, sourceOrigin: [number, number] | null) => {
+ (_from: Point2D, to: Point2D, pressure: number, sourceOrigin: [number, number] | null) => {
const { retouchSettings, primaryColor } = useToolStore.getState();
const docId = documentStore.getActiveDocumentId();
const params = {
- fromX: from.x,
- fromY: from.y,
- toX: to.x,
- toY: to.y,
+ x: to.x,
+ y: to.y,
pressure: Math.max(0.05, Math.min(1, pressure || 1.0)),
- sourceOrigin,
+ cloneSource: sourceOrigin,
settings: {
kind: retouchSettings.mode,
size: retouchSettings.size,
@@ -128,7 +139,7 @@ export function useRetouchTool({
};
stepChainRef.current = stepChainRef.current
.then(() => nativeRetouchStep(params, docId))
- .catch(() => {});
+ .catch((err) => console.warn('[Retouch] nativeRetouchStep failed:', err));
},
[]
);
diff --git a/src/hooks/drawing/useSelectionTools.ts b/src/hooks/drawing/useSelectionTools.ts
index 1508d03..4280ea6 100644
--- a/src/hooks/drawing/useSelectionTools.ts
+++ b/src/hooks/drawing/useSelectionTools.ts
@@ -20,6 +20,7 @@ import {
SelectionTileSnapshot,
} from '../../utils/selectionUtils';
import {
+ fromNativeLayerNodeMeta,
isNativeCanvasActive,
nativeDeselect,
nativeSelectAll,
@@ -48,7 +49,7 @@ import {
type NativeTransformSessionSnapshot,
type NativeWandReferMode,
} from '../../utils/nativeEngineBridge';
-import { useToolStore } from '../../stores';
+import { useDocumentStore, useToolStore } from '../../stores';
import { t } from '../../i18n';
import { PushHistoryStepFn } from './types';
@@ -57,61 +58,89 @@ export function nativeTransformSnapshotToSession(
fallbackLayerId: string,
isSelection: boolean
): TransformSession {
- const cols = Math.max(2, snap.mesh.cols || 4);
- const rows = Math.max(2, snap.mesh.rows || 4);
+ const srcBounds = snap.sourceBounds ?? { x: 0, y: 0, width: 1, height: 1 };
+ const safeW = Math.max(1, srcBounds.width || 1);
+ const safeH = Math.max(1, srcBounds.height || 1);
+
+ // Rust MeshState stores cell counts (cols, rows) with (rows + 1) * (cols + 1) control points,
+ // while TS TransformSession stores vertex grid counts (meshCols, meshRows).
+ const cellCols = Math.max(1, snap.mesh?.cols || 3);
+ const cellRows = Math.max(1, snap.mesh?.rows || 3);
+ const vCols = cellCols + 1;
+ const vRows = cellRows + 1;
+ const rawMeshPoints = Array.isArray(snap.mesh?.points) ? snap.mesh.points : [];
const meshPoints: Point2D[][] = [];
- for (let r = 0; r < rows; r++) {
+ for (let r = 0; r < vRows; r++) {
const row: Point2D[] = [];
- for (let c = 0; c < cols; c++) {
- const pt = snap.mesh.points[r * cols + c] ?? {
- x: snap.bounds.x + (c / Math.max(1, cols - 1)) * snap.bounds.width,
- y: snap.bounds.y + (r / Math.max(1, rows - 1)) * snap.bounds.height,
+ for (let c = 0; c < vCols; c++) {
+ const pt = rawMeshPoints[r * vCols + c] ?? {
+ x: srcBounds.x + (c / Math.max(1, cellCols)) * safeW,
+ y: srcBounds.y + (r / Math.max(1, cellRows)) * safeH,
};
row.push({ x: pt.x, y: pt.y });
}
meshPoints.push(row);
}
- const scaleX = snap.affine.scaleX || 1;
- const scaleY = snap.affine.scaleY || 1;
- const flipH = scaleX < 0;
- const flipV = scaleY < 0;
- const absW = Math.max(1, snap.bounds.width * Math.abs(scaleX));
- const absH = Math.max(1, snap.bounds.height * Math.abs(scaleY));
- const cx = snap.bounds.x + snap.bounds.width * 0.5 + snap.affine.tx;
- const cy = snap.bounds.y + snap.bounds.height * 0.5 + snap.affine.ty;
+ const aff = snap.affine ?? {
+ x: srcBounds.x,
+ y: srcBounds.y,
+ width: safeW,
+ height: safeH,
+ rotation: 0,
+ skewX: 0,
+ skewY: 0,
+ flipX: false,
+ flipY: false,
+ };
+ const targetLayerIds =
+ Array.isArray(snap.targetLayerIds) && snap.targetLayerIds.length > 0
+ ? [...snap.targetLayerIds]
+ : [fallbackLayerId];
+ const rawCorners = Array.isArray(snap.corners) && snap.corners.length === 4 ? snap.corners : null;
+ const rawPins = Array.isArray(snap.puppet?.pins) ? snap.puppet.pins : [];
+ const rawCagePoints = Array.isArray(snap.cage?.points) ? snap.cage.points : [];
+ const rawCageRest = Array.isArray(snap.cage?.restPoints) ? snap.cage.restPoints : [];
+ const cageClosed = Boolean(snap.cage?.closed);
return {
active: snap.active,
nativeGpuActive: true,
- layerId: snap.layerIds[0] || fallbackLayerId,
- layerIds: snap.layerIds.length > 0 ? [...snap.layerIds] : [fallbackLayerId],
+ layerId: targetLayerIds[0] || fallbackLayerId,
+ layerIds: targetLayerIds,
bounds: {
- x: snap.bounds.x,
- y: snap.bounds.y,
- width: Math.max(1, snap.bounds.width),
- height: Math.max(1, snap.bounds.height),
+ x: srcBounds.x,
+ y: srcBounds.y,
+ width: safeW,
+ height: safeH,
},
- x: cx - absW * 0.5,
- y: cy - absH * 0.5,
- width: absW,
- height: absH,
- rotation: (snap.affine.rotation * 180) / Math.PI,
- flipH,
- flipV,
+ x: Number.isFinite(aff.x) ? aff.x : srcBounds.x,
+ y: Number.isFinite(aff.y) ? aff.y : srcBounds.y,
+ width: Math.max(1, Number.isFinite(aff.width) ? aff.width : safeW),
+ height: Math.max(1, Number.isFinite(aff.height) ? aff.height : safeH),
+ rotation: ((Number.isFinite(aff.rotation) ? aff.rotation : 0) * 180) / Math.PI,
+ flipH: Boolean(aff.flipX),
+ flipV: Boolean(aff.flipY),
isSelection,
- mode: snap.mode,
- perspectiveQuad: [
- { x: snap.corners[0].x, y: snap.corners[0].y },
- { x: snap.corners[1].x, y: snap.corners[1].y },
- { x: snap.corners[2].x, y: snap.corners[2].y },
- { x: snap.corners[3].x, y: snap.corners[3].y },
- ],
- meshCols: cols,
- meshRows: rows,
+ mode: snap.mode ?? 'affine',
+ perspectiveQuad: rawCorners
+ ? [
+ { x: rawCorners[0].x, y: rawCorners[0].y },
+ { x: rawCorners[1].x, y: rawCorners[1].y },
+ { x: rawCorners[2].x, y: rawCorners[2].y },
+ { x: rawCorners[3].x, y: rawCorners[3].y },
+ ]
+ : [
+ { x: srcBounds.x, y: srcBounds.y },
+ { x: srcBounds.x + safeW, y: srcBounds.y },
+ { x: srcBounds.x + safeW, y: srcBounds.y + safeH },
+ { x: srcBounds.x, y: srcBounds.y + safeH },
+ ],
+ meshCols: vCols,
+ meshRows: vRows,
meshPoints,
puppet: {
- pins: snap.puppet.pins.map((p) => ({
+ pins: rawPins.map((p) => ({
id: p.id,
restX: p.restX,
restY: p.restY,
@@ -120,18 +149,19 @@ export function nativeTransformSnapshotToSession(
rotation: p.rotation,
depth: p.depth,
})),
- selectedPinId: snap.puppet.pins[0]?.id ?? null,
+ selectedPinId: rawPins[0]?.id ?? null,
rigidity: 'normal',
density: 'normal',
expansion: 6,
- showMesh: true,
+ showMesh: snap.showMesh !== false,
},
cage: {
- phase: snap.cage.closed ? 'deform' : 'define',
- points: snap.cage.vertices.map((v, idx) => ({
+ phase: cageClosed ? 'deform' : 'define',
+ closed: cageClosed,
+ points: rawCagePoints.map((v, idx) => ({
id: `cage-${idx}`,
- restX: snap.cage.restVertices[idx]?.x ?? v.x,
- restY: snap.cage.restVertices[idx]?.y ?? v.y,
+ restX: rawCageRest[idx]?.x ?? v.x,
+ restY: rawCageRest[idx]?.y ?? v.y,
x: v.x,
y: v.y,
})),
@@ -220,8 +250,10 @@ export function useSelectionTools({
selectedLayerIds,
flushPendingHistoryTasks,
updateLayerThumbnail,
+ onSyncNativeLayers,
showToast,
}: UseSelectionToolsParams): UseSelectionToolsResult {
+ const activeDocumentId = useDocumentStore((s) => s.activeDocumentId);
const [selection, setSelection] = useState<CanvasSelection | null>(null);
const [transformSession, setTransformSession] = useState<TransformSession | null>(null);
@@ -242,28 +274,46 @@ export function useSelectionTools({
const isMountedRef = useRef<boolean>(true);
// Keep React selection action-bar metadata synchronized with native Rust SparseSelectionMask
- // (including SelectPen / SelectEraser strokes painted directly in DX12!)
+ // (including SelectPen / SelectEraser strokes painted directly in DX12 and document tab switches!)
useEffect(() => {
isMountedRef.current = true;
const unsub = subscribeNativeSelectionChanged((ev) => {
if (!isMountedRef.current) return;
- const activeDocId = documentStore.getActiveDocumentId();
- if (activeDocId && ev.docId && ev.docId !== activeDocId) return;
+ const curDocId = documentStore.getActiveDocumentId();
+ if (curDocId && ev.docId && ev.docId !== curDocId) return;
setSelection(selectionMetaToCanvasSelection(ev.selection));
});
- if (isNativeCanvasActive()) {
- void nativeSelectionGetState(documentStore.getActiveDocumentId())
- .then((meta) => {
- if (isMountedRef.current && meta) setSelection(selectionMetaToCanvasSelection(meta));
- })
- .catch(() => {});
- }
return () => {
isMountedRef.current = false;
unsub();
};
}, []);
+ useEffect(() => {
+ selectRectStartRef.current = null;
+ lassoPointsRef.current = [];
+ selectionDragRef.current = null;
+ if (!activeDocumentId) {
+ setSelection(null);
+ return;
+ }
+ if (!isNativeCanvasActive()) {
+ setSelection(null);
+ return;
+ }
+ let cancelled = false;
+ void nativeSelectionGetState(activeDocumentId)
+ .then((meta) => {
+ if (!cancelled && isMountedRef.current && documentStore.getActiveDocumentId() === activeDocumentId) {
+ setSelection(selectionMetaToCanvasSelection(meta));
+ }
+ })
+ .catch(() => {});
+ return () => {
+ cancelled = true;
+ };
+ }, [activeDocumentId]);
+
const restoreSelectionFromHistory = useCallback((sel: CanvasSelection | null) => {
selectRectStartRef.current = null;
lassoPointsRef.current = [];
@@ -369,13 +419,27 @@ export function useSelectionTools({
void nativeSelectionMoveToNewLayer(newId, activeLayerId, docId)
.then((snap) => {
if (snap) {
+ if (Array.isArray(snap.layers) && snap.layers.length > 0) {
+ onSyncNativeLayers?.(
+ snap.layers.map(fromNativeLayerNodeMeta),
+ snap.activeLayerId ?? newId
+ );
+ }
updateLayerThumbnail(activeLayerId, true);
updateLayerThumbnail(newId, true);
showToast(t('Moved selection to new layer'));
}
})
.catch(() => {});
- }, [selection, activeLayer, activeLayerId, flushPendingHistoryTasks, updateLayerThumbnail, showToast]);
+ }, [
+ selection,
+ activeLayer,
+ activeLayerId,
+ flushPendingHistoryTasks,
+ onSyncNativeLayers,
+ updateLayerThumbnail,
+ showToast,
+ ]);
const handleCopySelectionToNewLayer = useCallback(() => {
if (!selection) return;
@@ -387,12 +451,26 @@ export function useSelectionTools({
.then((ok) => (ok ? nativeSelectionPaste(newId, docId) : null))
.then((snap) => {
if (snap) {
+ if (Array.isArray(snap.layers) && snap.layers.length > 0) {
+ onSyncNativeLayers?.(
+ snap.layers.map(fromNativeLayerNodeMeta),
+ snap.activeLayerId ?? newId
+ );
+ }
updateLayerThumbnail(newId, true);
showToast(t('Copied selection to new layer'));
}
})
.catch(() => {});
- }, [selection, activeLayer, activeLayerId, flushPendingHistoryTasks, updateLayerThumbnail, showToast]);
+ }, [
+ selection,
+ activeLayer,
+ activeLayerId,
+ flushPendingHistoryTasks,
+ onSyncNativeLayers,
+ updateLayerThumbnail,
+ showToast,
+ ]);
const handleFillSelectionColor = useCallback(() => {
if (!activeLayer || activeLayer.type !== 'raster' || activeLayer.locked) {
diff --git a/src/hooks/drawing/useShapeAndFillTools.ts b/src/hooks/drawing/useShapeAndFillTools.ts
index 7302b31..01336d5 100644
--- a/src/hooks/drawing/useShapeAndFillTools.ts
+++ b/src/hooks/drawing/useShapeAndFillTools.ts
@@ -421,7 +421,9 @@ export function useShapeAndFillTools({
cancelAnimationFrame(liquifyRafIdRef.current);
liquifyRafIdRef.current = null;
}
- void nativeLiquifyCancel();
+ liquifyChainRef.current = liquifyChainRef.current
+ .then(() => nativeLiquifyCancel())
+ .catch(() => {});
}
if (prevTool !== curTool && curTool !== 'text' && curTool !== 'object') {
if (textDragRef.current) {
@@ -460,6 +462,12 @@ export function useShapeAndFillTools({
cancelAnimationFrame(liquifyRafIdRef.current);
liquifyRafIdRef.current = null;
}
+ if (isLiquifyingRef.current) {
+ isLiquifyingRef.current = false;
+ liquifyChainRef.current = liquifyChainRef.current
+ .then(() => nativeLiquifyCancel())
+ .catch(() => {});
+ }
};
}, [commitTextSession]);
@@ -525,15 +533,18 @@ export function useShapeAndFillTools({
fromY: from.y,
toX: to.x,
toY: to.y,
- mode: ls.mode,
- size: ls.size,
- strength: Math.max(0.01, Math.min(1, ls.strength / 100)),
- hardness: Math.max(0, Math.min(1, ls.hardness / 100)),
pressure: Math.max(0.05, Math.min(1, pressure || 1.0)),
- usePressure: Boolean(ls.usePressure),
+ settings: {
+ mode: ls.mode,
+ size: ls.size,
+ strength: Math.max(0.01, Math.min(1, ls.strength / 100)),
+ hardness: Math.max(0, Math.min(1, ls.hardness / 100)),
+ usePressure: Boolean(ls.usePressure),
+ multiLayer: Boolean(ls.multiLayer),
+ },
})
)
- .catch(() => {});
+ .catch((err) => console.warn('[Liquify] nativeLiquifyStepGpu failed:', err));
},
[]
);
@@ -610,8 +621,18 @@ export function useShapeAndFillTools({
if (tool === 'liquify') {
e.preventDefault();
- flushPendingHistoryTasks?.();
const isMulti = Boolean(liquifySettings.multiLayer);
+ if (
+ !isMulti &&
+ (!activeLayer ||
+ activeLayer.type !== 'raster' ||
+ activeLayer.locked ||
+ !isLayerEffectivelyVisible(activeLayer))
+ ) {
+ showToast?.(t('Select an unlocked, visible raster layer to use Liquify'));
+ return true;
+ }
+ flushPendingHistoryTasks?.();
const targetIds = isMulti
? selectedLayerIds.length > 1
? selectedLayerIds
@@ -724,7 +745,7 @@ export function useShapeAndFillTools({
closeGap: fillSettings.closeGap ?? 0,
areaScale: fillSettings.areaScale ?? 0,
antiAlias: fillSettings.antiAlias ?? true,
- opacity: isTransparentInk ? 0 : Math.max(0, Math.min(1, fillSettings.opacity ?? 1)),
+ opacity: Math.max(0, Math.min(1, fillSettings.opacity ?? 1)),
referMode: mapFillReferMode(fillSettings.method),
layerId: targetLayerId,
},
@@ -1082,7 +1103,7 @@ export function useShapeAndFillTools({
const docId = documentStore.getActiveDocumentId();
const isTransparentInk = useToolStore.getState().isTransparentColor;
const fillColor = isTransparentInk ? '#00000000' : primaryColor;
- const fillOpacity = isTransparentInk ? 0 : Math.max(0, Math.min(1, fillSettings.opacity ?? 1));
+ const fillOpacity = Math.max(0, Math.min(1, fillSettings.opacity ?? 1));
const targetLayerId = activeLayerId;
const opPromise =
diff --git a/src/hooks/layerManager/layerTreeOps.ts b/src/hooks/layerManager/layerTreeOps.ts
index 1d42634..6b09e87 100644
--- a/src/hooks/layerManager/layerTreeOps.ts
+++ b/src/hooks/layerManager/layerTreeOps.ts
@@ -133,7 +133,20 @@ export function computeBatchDeleteLayers(
}
}
- const nextLayers = layers.filter((l) => !allToDelete.has(l.id));
+ const nextLayers = layers
+ .filter((l) => !allToDelete.has(l.id))
+ .map((l) => {
+ if (!l.parentId || !allToDelete.has(l.parentId)) return l;
+ // Reparent any preserved child whose parent folder was deleted to the nearest surviving ancestor (or root)
+ let curParent: string | null = l.parentId;
+ let depth = 0;
+ while (curParent && allToDelete.has(curParent) && depth < 64) {
+ const parentNode = layers.find((p) => p.id === curParent);
+ curParent = parentNode?.parentId ?? null;
+ depth++;
+ }
+ return { ...l, parentId: curParent };
+ });
const nextActive = nextLayers.find((l) => l.type === 'raster') || nextLayers[0];
const nextActiveId = nextActive ? nextActive.id : '';
@@ -207,8 +220,9 @@ export function computeMergeFolderLayers(
monoThreshold: folder.monoThreshold ?? 128,
monoExpressBlack: folder.monoExpressBlack ?? true,
monoExpressWhite: folder.monoExpressWhite ?? true,
- ...(folder.maskCanvas
+ ...(folder.hasMask || folder.maskCanvas
? {
+ hasMask: true,
maskCanvas: folder.maskCanvas,
maskEnabled: folder.maskEnabled,
maskLinked: folder.maskLinked,
diff --git a/src/hooks/layerManager/useLayerCollabSync.ts b/src/hooks/layerManager/useLayerCollabSync.ts
index 34b23b3..01bcda2 100644
--- a/src/hooks/layerManager/useLayerCollabSync.ts
+++ b/src/hooks/layerManager/useLayerCollabSync.ts
@@ -98,30 +98,29 @@ export function useLayerCollabSync(
const deleteRemoteLayer = useCallback(
(layerId: string, onCommitted?: (nextLayers: LayerItem[]) => void) => {
const docId = activeSessionIdRef.current;
- setLayers((prev) => {
- const res = computeBatchDeleteLayers(prev, [layerId], activeLayerIdRef.current);
- if (res.deletedIds.length === 0) {
- onCommitted?.(prev);
- return prev;
- }
- for (const delId of res.deletedIds) {
- const timer = thumbDebounceTimersRef.current.get(delId);
- if (timer) {
- clearTimeout(timer);
- thumbDebounceTimersRef.current.delete(delId);
- }
- }
- if (res.deletedIds.includes(activeLayerIdRef.current)) {
- setActiveLayerId(res.nextActiveId);
- } else {
- setSelectedLayerIds((prevSel) => prevSel.filter((sid) => !res.deletedIds.includes(sid)));
+ const prev = layersRef.current;
+ const res = computeBatchDeleteLayers(prev, [layerId], activeLayerIdRef.current);
+ if (res.deletedIds.length === 0) {
+ onCommitted?.(prev);
+ return;
+ }
+ for (const delId of res.deletedIds) {
+ const timer = thumbDebounceTimersRef.current.get(delId);
+ if (timer) {
+ clearTimeout(timer);
+ thumbDebounceTimersRef.current.delete(delId);
}
- layersRef.current = res.nextLayers;
- onCommitted?.(res.nextLayers);
- return res.nextLayers;
- });
+ }
+ layersRef.current = res.nextLayers;
+ setLayers(res.nextLayers);
+ if (res.deletedIds.includes(activeLayerIdRef.current)) {
+ setActiveLayerId(res.nextActiveId);
+ } else {
+ setSelectedLayerIds((prevSel) => prevSel.filter((sid) => !res.deletedIds.includes(sid)));
+ }
+ onCommitted?.(res.nextLayers);
if (docId) {
- void deleteNativeLayer(docId, layerId, false);
+ void deleteNativeLayer(docId, layerId, false).catch(() => {});
}
},
[
@@ -144,59 +143,62 @@ export function useLayerCollabSync(
) => {
const dims = dimensionsRef.current;
const docId = activeSessionIdRef.current;
+ const prev = layersRef.current;
+ let found = false;
let needsTextBalloonRender: LayerItem | null = null;
let needsVectorRender: LayerItem | null = null;
- let nextSnapshot: LayerItem[] | null = null;
- setLayers((prev) => {
- let found = false;
- const next = prev.map((l) => {
- if (l.id !== layerId) return l;
- found = true;
- const updated = applyRemoteLayerPatch(l, patch, clearedFields, dims);
- if (
- (updated.type === 'text' &&
- updated.textData &&
- !deepEqualWireValue(l.textData, updated.textData)) ||
- (updated.type === 'balloon' &&
- updated.balloonData &&
- !deepEqualWireValue(l.balloonData, updated.balloonData))
- ) {
- needsTextBalloonRender = updated;
- }
- if (
- updated.type === 'vector' &&
- patch.vectorStrokes !== undefined &&
- !areVectorStrokesEqual(l.vectorStrokes, updated.vectorStrokes)
- ) {
- needsVectorRender = updated;
- }
- return updated;
- });
- if (!found) {
- onCommitted?.(prev);
- return prev;
+ const next = prev.map((l) => {
+ if (l.id !== layerId) return l;
+ found = true;
+ const updated = applyRemoteLayerPatch(l, patch, clearedFields, dims);
+ if (
+ (updated.type === 'text' &&
+ updated.textData &&
+ !deepEqualWireValue(l.textData, updated.textData)) ||
+ (updated.type === 'balloon' &&
+ updated.balloonData &&
+ !deepEqualWireValue(l.balloonData, updated.balloonData))
+ ) {
+ needsTextBalloonRender = updated;
}
- layersRef.current = next;
- nextSnapshot = next;
- onCommitted?.(next);
- return next;
+ if (
+ updated.type === 'vector' &&
+ patch.vectorStrokes !== undefined &&
+ !areVectorStrokesEqual(l.vectorStrokes, updated.vectorStrokes)
+ ) {
+ needsVectorRender = updated;
+ }
+ return updated;
});
- if (docId && nextSnapshot) {
- void syncNativeLayers(docId, nextSnapshot, activeLayerIdRef.current);
+ if (!found) {
+ onCommitted?.(prev);
+ return;
}
- if (needsTextBalloonRender) {
- syncVectorObjectLayerToGrid(needsTextBalloonRender, dims, docId);
- updateLayerThumbnail?.(layerId, true);
- } else if (needsVectorRender) {
- const vr = needsVectorRender as LayerItem;
- void nativeRasterizeVectorLayer(
- vr.id,
- toNativeVectorStrokes(vr.vectorStrokes || []),
- false,
- docId
- ).then(() => updateLayerThumbnail?.(layerId, true));
+
+ layersRef.current = next;
+ setLayers(next);
+ onCommitted?.(next);
+
+ if (docId) {
+ void syncNativeLayers(docId, next, activeLayerIdRef.current)
+ .then(() => {
+ if (needsTextBalloonRender) {
+ syncVectorObjectLayerToGrid(needsTextBalloonRender, dims, docId);
+ updateLayerThumbnail?.(layerId, true);
+ } else if (needsVectorRender) {
+ const vr = needsVectorRender as LayerItem;
+ return nativeRasterizeVectorLayer(
+ vr.id,
+ toNativeVectorStrokes(vr.vectorStrokes || []),
+ false,
+ docId
+ ).then(() => updateLayerThumbnail?.(layerId, true));
+ }
+ return undefined;
+ })
+ .catch(() => {});
}
},
[activeLayerIdRef, activeSessionIdRef, dimensionsRef, layersRef, setLayers, updateLayerThumbnail]
@@ -210,61 +212,59 @@ export function useLayerCollabSync(
) => {
const dims = dimensionsRef.current;
const docId = activeSessionIdRef.current;
- let toRenderTextBalloon: LayerItem[] = [];
- let toRenderVector: LayerItem[] = [];
- let committedNext: LayerItem[] | null = null;
+ const prev = layersRef.current;
+ const mergeResult = mergeRemoteLayerTree(prev, wireLayers, removedLayerIds, dims);
- setLayers((prev) => {
- const mergeResult = mergeRemoteLayerTree(prev, wireLayers, removedLayerIds, dims);
-
- for (const remId of mergeResult.removedIds) {
- const timer = thumbDebounceTimersRef.current.get(remId);
- if (timer) {
- clearTimeout(timer);
- thumbDebounceTimersRef.current.delete(remId);
- }
+ for (const remId of mergeResult.removedIds) {
+ const timer = thumbDebounceTimersRef.current.get(remId);
+ if (timer) {
+ clearTimeout(timer);
+ thumbDebounceTimersRef.current.delete(remId);
}
+ }
- toRenderTextBalloon = mergeResult.toRenderTextBalloon;
- toRenderVector = mergeResult.toRenderVector;
+ const toRenderTextBalloon = mergeResult.toRenderTextBalloon;
+ const toRenderVector = mergeResult.toRenderVector;
+ const next = mergeResult.nextLayers;
+ const mergedIds = new Set(next.map((l) => l.id));
- const next = mergeResult.nextLayers;
- const mergedIds = new Set(next.map((l) => l.id));
+ layersRef.current = next;
+ setLayers(next);
- if (!mergedIds.has(activeLayerIdRef.current)) {
- const fallback =
- next.find((l) => l.type === 'raster' && !isBackgroundLayerId(l.id))?.id ||
- next[0]?.id ||
- '';
- setActiveLayerId(fallback);
- } else {
- setSelectedLayerIds((prevSel) => {
- const filtered = prevSel.filter((id) => mergedIds.has(id));
- return filtered.length > 0 ? filtered : [activeLayerIdRef.current];
- });
- }
+ let nextActiveId = activeLayerIdRef.current;
+ if (!mergedIds.has(activeLayerIdRef.current)) {
+ const fallback =
+ next.find((l) => l.type === 'raster' && !isBackgroundLayerId(l.id))?.id ||
+ next[0]?.id ||
+ '';
+ nextActiveId = fallback;
+ setActiveLayerId(fallback);
+ } else {
+ setSelectedLayerIds((prevSel) => {
+ const filtered = prevSel.filter((id) => mergedIds.has(id));
+ return filtered.length > 0 ? filtered : [activeLayerIdRef.current];
+ });
+ }
- layersRef.current = next;
- committedNext = next;
- onCommitted?.(next);
- return next;
- });
+ onCommitted?.(next);
- if (docId && committedNext) {
- void syncNativeLayers(docId, committedNext, activeLayerIdRef.current).then(() => {
- for (const layer of toRenderTextBalloon) {
- syncVectorObjectLayerToGrid(layer, dims, docId);
- updateLayerThumbnail?.(layer.id, true);
- }
- for (const layer of toRenderVector) {
- void nativeRasterizeVectorLayer(
- layer.id,
- toNativeVectorStrokes(layer.vectorStrokes || []),
- false,
- docId
- ).then(() => updateLayerThumbnail?.(layer.id, true));
- }
- });
+ if (docId) {
+ void syncNativeLayers(docId, next, nextActiveId)
+ .then(() => {
+ for (const layer of toRenderTextBalloon) {
+ syncVectorObjectLayerToGrid(layer, dims, docId);
+ updateLayerThumbnail?.(layer.id, true);
+ }
+ for (const layer of toRenderVector) {
+ void nativeRasterizeVectorLayer(
+ layer.id,
+ toNativeVectorStrokes(layer.vectorStrokes || []),
+ false,
+ docId
+ ).then(() => updateLayerThumbnail?.(layer.id, true));
+ }
+ })
+ .catch(() => {});
}
},
[
diff --git a/src/hooks/layerManager/useLayerCrud.ts b/src/hooks/layerManager/useLayerCrud.ts
index b9dd41b..5acb3fb 100644
--- a/src/hooks/layerManager/useLayerCrud.ts
+++ b/src/hooks/layerManager/useLayerCrud.ts
@@ -108,7 +108,14 @@ export function useLayerCrud(ctx: LayerManagerContext) {
};
let nextLayers = beforeLayers;
- const insertIndex = currentActiveIdx >= 0 ? currentActiveIdx : 0;
+ const insertIndex =
+ currentActiveIdx >= 0
+ ? currentActiveLayer &&
+ isFolderLikeLayer(currentActiveLayer) &&
+ initialParentId === currentActiveLayer.id
+ ? currentActiveIdx + 1
+ : currentActiveIdx
+ : 0;
if (!beforeLayers.some((l) => l.id === id)) {
nextLayers = [...beforeLayers];
nextLayers.splice(insertIndex, 0, createdLayer);
@@ -263,7 +270,9 @@ export function useLayerCrud(ctx: LayerManagerContext) {
layersRef.current = res.nextLayers;
setLayers(res.nextLayers);
+ let nextActiveForNative = beforeActiveLayerId;
if (res.deletedIds.includes(beforeActiveLayerId)) {
+ nextActiveForNative = res.nextActiveId;
setActiveLayerId(res.nextActiveId);
} else {
setSelectedLayerIds((prevSelected) =>
@@ -272,7 +281,22 @@ export function useLayerCrud(ctx: LayerManagerContext) {
}
const docId = activeSessionIdRef.current;
if (docId) {
- void deleteNativeLayer(docId, id, true);
+ const deletedTarget = prev.find((l) => l.id === id);
+ const targetWasFolder = isFolderLikeLayer(deletedTarget);
+ const preservedDescendant =
+ targetWasFolder &&
+ res.nextLayers.some((l) => {
+ const old = prev.find((p) => p.id === l.id);
+ return old && old.parentId !== l.parentId;
+ });
+ if (preservedDescendant) {
+ void syncNativeLayers(docId, res.nextLayers, nextActiveForNative, {
+ recordHistory: true,
+ historyLabel: t('Delete Layer'),
+ }).catch(() => {});
+ } else {
+ void deleteNativeLayer(docId, id, true).catch(() => {});
+ }
}
},
[
@@ -305,7 +329,10 @@ export function useLayerCrud(ctx: LayerManagerContext) {
setActiveLayerId(res.nextActiveId);
const docId = activeSessionIdRef.current;
if (docId) {
- void syncNativeLayers(docId, res.nextLayers, res.nextActiveId);
+ void syncNativeLayers(docId, res.nextLayers, res.nextActiveId, {
+ recordHistory: true,
+ historyLabel: t('Delete Layers'),
+ }).catch(() => {});
}
}, [
activeLayerIdRef,
@@ -328,7 +355,10 @@ export function useLayerCrud(ctx: LayerManagerContext) {
setActiveLayerId(res.newFolder.id);
const docId = activeSessionIdRef.current;
if (docId) {
- void syncNativeLayers(docId, res.nextLayers, res.newFolder.id);
+ void syncNativeLayers(docId, res.nextLayers, res.newFolder.id, {
+ recordHistory: true,
+ historyLabel: t('Group Layers'),
+ }).catch(() => {});
}
}, [activeLayerIdRef, activeSessionIdRef, layersRef, selectedLayerIdsRef, setActiveLayerId, setLayers]);
diff --git a/src/hooks/layerManager/useLayerDocumentOps.ts b/src/hooks/layerManager/useLayerDocumentOps.ts
index fd7d5bd..868e072 100644
--- a/src/hooks/layerManager/useLayerDocumentOps.ts
+++ b/src/hooks/layerManager/useLayerDocumentOps.ts
@@ -205,17 +205,21 @@ export function useLayerDocumentOps(
name: 'Untitled*',
dimensions: _dims,
colorMode: _mode,
- backgroundHex: backgroundColor,
+ backgroundHex: typeof backgroundColor === 'string' && backgroundColor ? backgroundColor : '#ffffff',
defaultToneFrequency: defaultToneFrequencyRef.current,
- }).then((snap) => {
- if (!snap || activeSessionIdRef.current !== docId) return;
- const bgMeta = snap.layers.find((l) => l.id === bgId);
- if (bgMeta?.thumbnailUrl) {
- setLayers((prev) =>
- prev.map((l) => (l.id === bgId ? { ...l, thumbnailUrl: bgMeta.thumbnailUrl! } : l))
- );
- }
- });
+ })
+ .then((snap) => {
+ if (!snap || !Array.isArray(snap.layers) || activeSessionIdRef.current !== docId) return;
+ const bgMeta = snap.layers.find((l) => l && l.id === bgId);
+ if (bgMeta?.thumbnailUrl) {
+ setLayers((prev) =>
+ prev.map((l) => (l.id === bgId ? { ...l, thumbnailUrl: bgMeta.thumbnailUrl! } : l))
+ );
+ }
+ })
+ .catch(() => {
+ // Ignore transient native bridge creation failures; JS layer state remains valid
+ });
const initialLayers: LayerItem[] = [
{
@@ -288,14 +292,15 @@ export function useLayerDocumentOps(
activeSessionIdRef.current = docId;
}
+ const topRaster = doc.layers.find((l) => l.type === 'raster');
+ const initialActiveId = topRaster ? topRaster.id : doc.layers[0]?.id || '';
if (!skipIngest && docId) {
- void syncNativeLayers(docId, doc.layers, doc.layers[0]?.id ?? null);
+ void syncNativeLayers(docId, doc.layers, initialActiveId || null).catch(() => {});
}
setLayers(doc.layers);
layersRef.current = doc.layers;
- const topRaster = doc.layers.find((l) => l.type === 'raster');
- setActiveLayerId(topRaster ? topRaster.id : doc.layers[0]?.id || '');
+ setActiveLayerId(initialActiveId);
},
[activeSessionIdRef, dimensionsRef, layersRef, setActiveLayerId, setLayers, thumbDebounceTimersRef]
);
diff --git a/src/hooks/layerManager/useLayerEffects.ts b/src/hooks/layerManager/useLayerEffects.ts
index 5781424..2c9005e 100644
--- a/src/hooks/layerManager/useLayerEffects.ts
+++ b/src/hooks/layerManager/useLayerEffects.ts
@@ -317,12 +317,18 @@ export function useLayerEffects(
],
},
};
- void nativeImageOpApply(op, id, docId).then(() =>
- updateNativeLayer(docId, id, {
- recordHistory: false,
- }).then(() => syncNativeLayers(docId, next, activeLayerIdRef.current))
- );
- updateLayerThumbnail(id, true);
+ void nativeImageOpApply(op, id, docId)
+ .then(() =>
+ updateNativeLayer(docId, id, {
+ layerColorEnabled: false,
+ recordHistory: false,
+ })
+ )
+ .then(() => syncNativeLayers(docId, next, activeLayerIdRef.current))
+ .then(() => {
+ updateLayerThumbnail(id, true);
+ })
+ .catch(() => {});
}
const layerTreeDelta = createLayerTreeSnapshotDelta(
diff --git a/src/hooks/layerManager/useLayerPropertiesAndMasks.ts b/src/hooks/layerManager/useLayerPropertiesAndMasks.ts
index 454ce24..d135cf1 100644
--- a/src/hooks/layerManager/useLayerPropertiesAndMasks.ts
+++ b/src/hooks/layerManager/useLayerPropertiesAndMasks.ts
@@ -127,19 +127,20 @@ export function useLayerPropertiesAndMasks(
const toggleCollapse = useCallback(
(id: string) => {
- setLayers((prev) => {
- const next = prev.map((l) => (l.id === id ? { ...l, collapsed: !l.collapsed } : l));
- layersRef.current = next;
- const docId = activeSessionIdRef.current;
- const updated = next.find((l) => l.id === id);
- if (docId && updated) {
- void updateNativeLayer(docId, id, {
- collapsed: Boolean(updated.collapsed),
- recordHistory: false,
- });
- }
- return next;
- });
+ const prev = layersRef.current;
+ const target = prev.find((l) => l.id === id);
+ if (!target) return;
+ const nextCollapsed = !target.collapsed;
+ const next = prev.map((l) => (l.id === id ? { ...l, collapsed: nextCollapsed } : l));
+ layersRef.current = next;
+ setLayers(next);
+ const docId = activeSessionIdRef.current;
+ if (docId) {
+ void updateNativeLayer(docId, id, {
+ collapsed: nextCollapsed,
+ recordHistory: false,
+ });
+ }
},
[activeSessionIdRef, layersRef, setLayers]
);
@@ -268,13 +269,14 @@ export function useLayerPropertiesAndMasks(
const prev = layersRef.current;
const target = prev.find((l) => l.id === layerId);
if (!target || (!target.hasMask && !target.maskCanvas)) return;
- const next = prev.map((l) => (l.id === layerId ? { ...l, maskEnabled: !l.maskEnabled } : l));
+ const nextEnabled = target.maskEnabled === false;
+ const next = prev.map((l) => (l.id === layerId ? { ...l, maskEnabled: nextEnabled } : l));
layersRef.current = next;
setLayers(next);
const docId = activeSessionIdRef.current;
if (docId) {
void updateNativeLayer(docId, layerId, {
- maskEnabled: !target.maskEnabled,
+ maskEnabled: nextEnabled,
recordHistory: true,
historyLabel: t('Toggle Layer Mask'),
});
@@ -288,13 +290,14 @@ export function useLayerPropertiesAndMasks(
const prev = layersRef.current;
const target = prev.find((l) => l.id === layerId);
if (!target || (!target.hasMask && !target.maskCanvas)) return;
- const next = prev.map((l) => (l.id === layerId ? { ...l, maskLinked: !l.maskLinked } : l));
+ const nextLinked = target.maskLinked === false;
+ const next = prev.map((l) => (l.id === layerId ? { ...l, maskLinked: nextLinked } : l));
layersRef.current = next;
setLayers(next);
const docId = activeSessionIdRef.current;
if (docId) {
void updateNativeLayer(docId, layerId, {
- maskLinked: !target.maskLinked,
+ maskLinked: nextLinked,
recordHistory: true,
historyLabel: t('Toggle Mask Link'),
});
@@ -414,7 +417,12 @@ export function useLayerPropertiesAndMasks(
adjustmentData: defaultData,
};
- const insertIndex = activeIdx >= 0 ? activeIdx : 0;
+ const insertIndex =
+ activeIdx >= 0
+ ? activeLayer && isFolderLikeLayer(activeLayer)
+ ? activeIdx + 1
+ : activeIdx
+ : 0;
const next = [...prev];
next.splice(insertIndex, 0, newLayer);
layersRef.current = next;
diff --git a/src/hooks/layerManager/useLayerResize.ts b/src/hooks/layerManager/useLayerResize.ts
index 990b9fe..7890355 100644
--- a/src/hooks/layerManager/useLayerResize.ts
+++ b/src/hooks/layerManager/useLayerResize.ts
@@ -410,22 +410,27 @@ export function useLayerResize(ctx: LayerManagerContext) {
scaleContent,
bgHex: backgroundColor,
recordHistory: true,
- }).then(async () => {
- await syncNativeLayers(docId, nextLayers, curActiveLayerId);
- for (const layer of nextLayers) {
- if ((layer.type === 'text' && layer.textData) || (layer.type === 'balloon' && layer.balloonData)) {
- syncVectorObjectLayerToGrid(layer, newDims, docId);
- } else if (layer.type === 'vector' && layer.vectorStrokes && layer.vectorStrokes.length > 0) {
- await nativeRasterizeVectorLayer(
- layer.id,
- toNativeVectorStrokes(layer.vectorStrokes),
- false,
- docId
- );
+ })
+ .then(async () => {
+ if (activeSessionIdRef.current !== docId) return;
+ await syncNativeLayers(docId, nextLayers, curActiveLayerId);
+ for (const layer of nextLayers) {
+ if ((layer.type === 'text' && layer.textData) || (layer.type === 'balloon' && layer.balloonData)) {
+ await syncVectorObjectLayerToGrid(layer, newDims, docId, false);
+ } else if (layer.type === 'vector' && layer.vectorStrokes && layer.vectorStrokes.length > 0) {
+ await nativeRasterizeVectorLayer(
+ layer.id,
+ toNativeVectorStrokes(layer.vectorStrokes),
+ false,
+ docId
+ );
+ }
+ }
+ if (activeSessionIdRef.current === docId) {
+ await requestNativeThumbnails(docId, nextLayers.map((l) => l.id));
}
- }
- await requestNativeThumbnails(docId, nextLayers.map((l) => l.id));
- });
+ })
+ .catch((err) => console.warn('[LayerResize] Native canvas resize failed:', err));
}
return {
diff --git a/src/hooks/layerManager/useLayerSpecialLayers.ts b/src/hooks/layerManager/useLayerSpecialLayers.ts
index 1d69823..b5131e8 100644
--- a/src/hooks/layerManager/useLayerSpecialLayers.ts
+++ b/src/hooks/layerManager/useLayerSpecialLayers.ts
@@ -80,10 +80,14 @@ export function useLayerSpecialLayers(
layersRef.current = nextLayers;
setLayers(nextLayers);
if (docId) {
- void syncNativeLayers(docId, nextLayers, activeLayerIdRef.current);
+ void syncNativeLayers(docId, nextLayers, activeLayerIdRef.current)
+ .then(() => syncVectorObjectLayerToGrid(updated, dims, docId, true))
+ .then(() => updateLayerThumbnail(editingLayerId, true))
+ .catch(() => {});
+ } else {
+ void syncVectorObjectLayerToGrid(updated, dims, docId, true);
+ updateLayerThumbnail(editingLayerId, true);
}
- syncVectorObjectLayerToGrid(updated, dims, docId);
- updateLayerThumbnail(editingLayerId, true);
return updated;
}
}
@@ -105,10 +109,14 @@ export function useLayerSpecialLayers(
layersRef.current = nextLayers;
setLayers(nextLayers);
if (docId) {
- void syncNativeLayers(docId, nextLayers, created.id);
+ void syncNativeLayers(docId, nextLayers, created.id)
+ .then(() => syncVectorObjectLayerToGrid(withData, dims, docId, false))
+ .then(() => updateLayerThumbnail(created.id, true))
+ .catch(() => {});
+ } else {
+ void syncVectorObjectLayerToGrid(withData, dims, docId, false);
+ updateLayerThumbnail(created.id, true);
}
- syncVectorObjectLayerToGrid(withData, dims, docId);
- updateLayerThumbnail(created.id, true);
recordLayerHistory(
t('Add Text Layer'),
created.id,
@@ -153,10 +161,14 @@ export function useLayerSpecialLayers(
layersRef.current = nextLayers;
setLayers(nextLayers);
if (docId) {
- void syncNativeLayers(docId, nextLayers, activeLayerIdRef.current);
+ void syncNativeLayers(docId, nextLayers, activeLayerIdRef.current)
+ .then(() => syncVectorObjectLayerToGrid(updated, dims, docId, true))
+ .then(() => updateLayerThumbnail(editingLayerId, true))
+ .catch(() => {});
+ } else {
+ void syncVectorObjectLayerToGrid(updated, dims, docId, true);
+ updateLayerThumbnail(editingLayerId, true);
}
- syncVectorObjectLayerToGrid(updated, dims, docId);
- updateLayerThumbnail(editingLayerId, true);
return updated;
}
}
@@ -178,10 +190,14 @@ export function useLayerSpecialLayers(
layersRef.current = nextLayers;
setLayers(nextLayers);
if (docId) {
- void syncNativeLayers(docId, nextLayers, created.id);
+ void syncNativeLayers(docId, nextLayers, created.id)
+ .then(() => syncVectorObjectLayerToGrid(withData, dims, docId, false))
+ .then(() => updateLayerThumbnail(created.id, true))
+ .catch(() => {});
+ } else {
+ void syncVectorObjectLayerToGrid(withData, dims, docId, false);
+ updateLayerThumbnail(created.id, true);
}
- syncVectorObjectLayerToGrid(withData, dims, docId);
- updateLayerThumbnail(created.id, true);
recordLayerHistory(
t('Add Speech Balloon'),
created.id,
diff --git a/src/hooks/useAppMenuSections.tsx b/src/hooks/useAppMenuSections.tsx
index 1ea8b7d..96ed24c 100644
--- a/src/hooks/useAppMenuSections.tsx
+++ b/src/hooks/useAppMenuSections.tsx
@@ -703,24 +703,24 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
submenu: [
{
id: 'layer-mask-add',
- label: activeLayer?.maskCanvas
+ label: Boolean(activeLayer?.hasMask || activeLayer?.maskCanvas)
? t('Mask Already Present')
: t('Add Layer Mask (Reveal All)'),
- disabled: Boolean(activeLayer?.maskCanvas),
+ disabled: Boolean(activeLayer?.hasMask || activeLayer?.maskCanvas),
onClick: () => addLayerMask(activeLayerId),
},
{
id: 'layer-mask-delete',
label: t('Delete Layer Mask'),
danger: true,
- disabled: !activeLayer?.maskCanvas,
+ disabled: !Boolean(activeLayer?.hasMask || activeLayer?.maskCanvas),
onClick: () => removeLayerMask(activeLayerId),
},
{
id: 'layer-mask-toggle',
label:
activeLayer?.maskEnabled === false ? t('Enable Layer Mask') : t('Disable Layer Mask'),
- disabled: !activeLayer?.maskCanvas,
+ disabled: !Boolean(activeLayer?.hasMask || activeLayer?.maskCanvas),
onClick: () => toggleLayerMask(activeLayerId),
},
{
@@ -729,7 +729,7 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectio
activeLayer?.maskLinked === false
? t('Link Mask to Layer')
: t('Unlink Mask from Layer'),
- disabled: !activeLayer?.maskCanvas,
+ disabled: !Boolean(activeLayer?.hasMask || activeLayer?.maskCanvas),
onClick: () => toggleMaskLinked(activeLayerId),
},
],
diff --git a/src/hooks/useCanvasNavigation.ts b/src/hooks/useCanvasNavigation.ts
index 877fe19..9dfd319 100644
--- a/src/hooks/useCanvasNavigation.ts
+++ b/src/hooks/useCanvasNavigation.ts
@@ -11,7 +11,7 @@ export const MIN_ZOOM = 0.01; // 1%
export const MAX_ZOOM = 32.0; // 3200%
/** Debounce window (ms) before committing high-frequency camera updates to React UI state. */
-export const NAV_STATE_COMMIT_DEBOUNCE_MS = 140;
+export const NAV_STATE_COMMIT_DEBOUNCE_MS = 120;
/** Custom DOM event name dispatched on window whenever live camera transform changes. */
export const CAMERA_CHANGE_EVENT = 'ink-camera-change';
@@ -457,11 +457,11 @@ export function useCanvasNavigation({
broadcastCameraImmediate(source);
commitNavStateImmediate();
} else {
- broadcastCameraImmediate(source);
+ scheduleCameraBroadcast(source);
scheduleNavStateCommit();
}
},
- [broadcastCameraImmediate, commitNavStateImmediate, scheduleNavStateCommit]
+ [broadcastCameraImmediate, commitNavStateImmediate, scheduleCameraBroadcast, scheduleNavStateCommit]
);
const setRotation = useCallback(
diff --git a/src/hooks/useCollabSync.ts b/src/hooks/useCollabSync.ts
index 1ca2e2a..669dbe9 100644
--- a/src/hooks/useCollabSync.ts
+++ b/src/hooks/useCollabSync.ts
@@ -67,6 +67,7 @@ import {
nativeCollabRemoteStrokeFinish,
nativeCollabRemoteStrokeStart,
nativeRasterizeVectorLayer,
+ setNativeCollabPointsEnabled,
} from '../utils/nativeEngineBridge';
import {
documentStoreActions,
@@ -1337,6 +1338,14 @@ export function useCollabSync({
}
}, [layers, mp.isConnected, mp.myRole]);
+ // Only stream full committed stroke point arrays from Rust when multiplayer is connected
+ useEffect(() => {
+ void setNativeCollabPointsEnabled(Boolean(mp.isConnected));
+ return () => {
+ void setNativeCollabPointsEnabled(false);
+ };
+ }, [mp.isConnected]);
+
// Reactive document-level state broadcaster: Perspective Ruler, Straight Ruler, Animation Timeline
useEffect(() => {
const state = useDocumentStore.getState();
@@ -1408,20 +1417,18 @@ export function useCollabSync({
(finalHostName: string) => {
const hostPeerId = mp.myPeer.id;
- // Stamp ownership on host's existing non-background layers to protect them from accidental guest deletion
- setLayers((prev) => {
- const next = prev.map((l) => {
- if (l.id === 'layer-bg' || l.id.startsWith('layer-bg')) return l;
- if (l.ownerPeerId !== undefined) return l;
- return { ...l, ownerPeerId: hostPeerId, ownerPeerName: finalHostName };
- });
- layersRef.current = next;
- return next;
+ // Stamp ownership synchronously so any subsequent renameLayer reads the stamped layersRef
+ const stamped = layersRef.current.map((l) => {
+ if (l.id === 'layer-bg' || l.id.startsWith('layer-bg')) return l;
+ if (l.ownerPeerId !== undefined) return l;
+ return { ...l, ownerPeerId: hostPeerId, ownerPeerName: finalHostName };
});
+ layersRef.current = stamped;
+ setLayers(stamped);
const defaultLayer =
- layersRef.current.find((l) => l.id === activeLayerId) ||
- layersRef.current.find(
+ stamped.find((l) => l.id === activeLayerId) ||
+ stamped.find(
(l) => l.type === 'raster' && l.id !== 'layer-bg' && !l.id.startsWith('layer-bg')
);
if (
@@ -1431,7 +1438,7 @@ export function useCollabSync({
) {
const hostLayerName = getNextCollabLayerName(
finalHostName,
- layersRef.current.filter((l) => l.id !== defaultLayer.id)
+ stamped.filter((l) => l.id !== defaultLayer.id)
);
renameLayer(defaultLayer.id, hostLayerName);
}
diff --git a/src/hooks/useLayerManager.ts b/src/hooks/useLayerManager.ts
index f303034..987eed5 100644
--- a/src/hooks/useLayerManager.ts
+++ b/src/hooks/useLayerManager.ts
@@ -9,6 +9,7 @@ import {
import { recoveryService } from '../services/recoveryService';
import { documentStoreActions } from '../stores';
import {
+ setNativeActiveLayer,
subscribeNativeThumbnails,
syncNativeLayers,
} from '../utils/nativeEngineBridge';
@@ -164,6 +165,10 @@ export function useLayerManager({
} else {
setSelectedLayerIds([]);
}
+ const docId = activeSessionIdRef.current;
+ if (docId) {
+ void setNativeActiveLayer(docId, id || null);
+ }
},
[setSelectedLayerIds]
);
@@ -183,6 +188,10 @@ export function useLayerManager({
setActiveLayerIdState(res.nextActiveId);
activeLayerIdRef.current = res.nextActiveId;
setSelectedLayerIds(res.nextSelectedIds);
+ const docId = activeSessionIdRef.current;
+ if (docId) {
+ void setNativeActiveLayer(docId, res.nextActiveId || null);
+ }
},
[setSelectedLayerIds]
);
@@ -336,6 +345,7 @@ export function useLayerManager({
return {
layers,
+ layersRef,
setLayers,
activeLayerId,
setActiveLayerId,
diff --git a/src/hooks/useMultiplayer.ts b/src/hooks/useMultiplayer.ts
index 5c7ce72..1a15e3c 100644
--- a/src/hooks/useMultiplayer.ts
+++ b/src/hooks/useMultiplayer.ts
@@ -1809,11 +1809,25 @@ export function useMultiplayer({
) {
existing.msg = {
...existing.msg,
+ rawPacket: undefined,
version: tMsg.version,
seq: tMsg.seq,
senderId: tMsg.senderId,
};
} else {
+ // Flush the pending full tile first so we never drop it when a sub-rect patch can't merge in-place
+ pendingTileBatchRef.current.delete(tileKey);
+ const fullWire =
+ existing.msg.rawPacket ??
+ serializeWireTilePacket({
+ layerId: existing.msg.layerId,
+ tileX: existing.msg.tileX,
+ tileY: existing.msg.tileY,
+ format: existing.msg.format,
+ version: existing.msg.version,
+ data: existing.msg.data,
+ });
+ void nativeCollabApplyTileDelta(existing.msg.layerId, fullWire, true).catch(() => {});
pendingTileBatchRef.current.set(tileKey, { kind: 'subrects', patches: [tMsg] });
}
} else if (existing?.kind === 'subrects') {
diff --git a/src/hooks/useNativeEngineViewport.ts b/src/hooks/useNativeEngineViewport.ts
index bcd49df..4e81948 100644
--- a/src/hooks/useNativeEngineViewport.ts
+++ b/src/hooks/useNativeEngineViewport.ts
@@ -7,18 +7,20 @@ import {
useDocumentStore,
useToolStore,
useUiStore,
+ useUpdaterStore,
useWorkspaceStore,
} from '../stores';
-import { DEFAULT_INTERFACE_SCALE } from '../utils/interfaceScale';
+import {
+ DEFAULT_INTERFACE_SCALE,
+ INTERFACE_SCALE_APPLIED_EVENT,
+} from '../utils/interfaceScale';
import {
canNativeEngineHandleBrush,
classifyNativeTool,
clearNativeCanvas,
- getNativeDiagnostics,
initNativeEngineBridge,
isNativeCanvasActive,
isNativeStrokeTool,
- NativeEngineDiagnostics,
NativeUiRect,
NativeWheelNavMode,
parseCssColorToRgba,
@@ -34,10 +36,11 @@ import {
setNativeViewport,
subscribeNativeCamera,
subscribeNativeCanvasActive,
- subscribeNativeDiagnostics,
subscribeNativePointerStat,
+ subscribeNativeViewportInvalidated,
syncNativeFullBrushConfig,
} from '../utils/nativeEngineBridge';
+import { recoveryService } from '../services/recoveryService';
export interface UseNativeEngineViewportParams {
viewportRef: React.RefObject<HTMLDivElement | null>;
@@ -72,6 +75,7 @@ const OCCLUDER_SELECTOR = [
'[role="dialog"]',
'[aria-modal="true"]',
'[role="menu"]',
+ '[role="listbox"]',
'[data-chrome-floating="true"]',
'[data-testid="floating-brush-pill"]',
'[data-testid="quick-brush-panel"]',
@@ -80,8 +84,223 @@ const OCCLUDER_SELECTOR = [
'[data-testid^="focus-hud"]',
'[data-testid*="popover"]',
'[data-testid*="modal"]',
+ '[data-testid*="context-menu"]',
+ '[data-testid*="dropdown"]',
+ '.shadow-ui-popover',
+].join(',');
+
+const OCCLUDER_MUTATION_THROTTLE_MS = 80;
+
+const MODAL_SELECTOR = '[role="dialog"],[aria-modal="true"],[data-testid*="modal"]';
+const IGNORED_MUTATION_ANCESTOR_SELECTOR = [
+ '[data-testid="status-bar"]',
+ '[data-chrome-bar="status"]',
+ '[data-testid="native-gpu-perf-hud"]',
+ '[data-testid="canvas-interaction-surface"]',
+ '[data-testid="brush-cursor-ring"]',
+ '[data-testid="canvas-artboard"]',
].join(',');
+function isElementNode(node: Node | null | undefined): node is Element {
+ return Boolean(node && node.nodeType === 1);
+}
+
+function getAttrSafe(el: Element, name: string): string | null {
+ return typeof el.getAttribute === 'function' ? el.getAttribute(name) : null;
+}
+
+function isIgnoredMutationTarget(node: Node | null | undefined): boolean {
+ if (!isElementNode(node)) return false;
+ if (typeof node.closest === 'function') {
+ return Boolean(node.closest(IGNORED_MUTATION_ANCESTOR_SELECTOR));
+ }
+ let cur: Node | null = node;
+ while (isElementNode(cur)) {
+ const tid = getAttrSafe(cur, 'data-testid');
+ if (
+ tid === 'status-bar' ||
+ tid === 'native-gpu-perf-hud' ||
+ tid === 'canvas-interaction-surface' ||
+ tid === 'brush-cursor-ring' ||
+ tid === 'canvas-artboard' ||
+ getAttrSafe(cur, 'data-chrome-bar') === 'status'
+ ) {
+ return true;
+ }
+ cur = cur.parentNode;
+ }
+ return false;
+}
+
+function matchesModalElement(el: Element): boolean {
+ if (typeof el.matches === 'function') {
+ try {
+ if (el.matches(MODAL_SELECTOR)) return true;
+ } catch {
+ // Fall through to attribute check
+ }
+ }
+ const role = getAttrSafe(el, 'role');
+ const ariaModal = getAttrSafe(el, 'aria-modal');
+ const tid = getAttrSafe(el, 'data-testid') || '';
+ return role === 'dialog' || ariaModal === 'true' || tid.includes('modal');
+}
+
+function matchesOccluderElement(el: Element): boolean {
+ if (typeof el.matches === 'function') {
+ try {
+ if (el.matches(OCCLUDER_SELECTOR)) return true;
+ } catch {
+ // Fall through to attribute check
+ }
+ }
+ if (
+ getAttrSafe(el, 'data-native-occluder') === 'true' ||
+ getAttrSafe(el, 'data-chrome-floating') === 'true' ||
+ getAttrSafe(el, 'aria-modal') === 'true'
+ ) {
+ return true;
+ }
+ const role = getAttrSafe(el, 'role');
+ if (role === 'dialog' || role === 'menu' || role === 'listbox') return true;
+ const tid = getAttrSafe(el, 'data-testid') || '';
+ if (
+ tid === 'floating-brush-pill' ||
+ tid === 'quick-brush-panel' ||
+ tid === 'collab-room-overlay' ||
+ tid === 'collab-follow-banner' ||
+ tid.startsWith('focus-hud') ||
+ tid.includes('popover') ||
+ tid.includes('modal') ||
+ tid.includes('context-menu') ||
+ tid.includes('dropdown')
+ ) {
+ return true;
+ }
+ return false;
+}
+
+function hasOccluderAncestor(el: Element): boolean {
+ if (typeof el.closest === 'function') {
+ try {
+ return Boolean(el.closest(OCCLUDER_SELECTOR));
+ } catch {
+ // Fall through
+ }
+ }
+ let cur: Node | null = el;
+ while (isElementNode(cur)) {
+ if (matchesOccluderElement(cur)) return true;
+ cur = cur.parentNode;
+ }
+ return false;
+}
+
+function nodeContainsOccluder(node: Node): { occluder: boolean; modal: boolean } {
+ if (!isElementNode(node)) return { occluder: false, modal: false };
+ const directModal = matchesModalElement(node);
+ if (directModal) return { occluder: true, modal: true };
+ const directOccluder = matchesOccluderElement(node);
+ if (typeof node.querySelector === 'function') {
+ try {
+ if (node.querySelector(MODAL_SELECTOR)) return { occluder: true, modal: true };
+ if (directOccluder || node.querySelector(OCCLUDER_SELECTOR)) {
+ return { occluder: true, modal: false };
+ }
+ } catch {
+ // Fall through
+ }
+ }
+ return { occluder: directOccluder, modal: false };
+}
+
+/**
+ * Filters `document.body` MutationRecords so high-frequency DOM writes (StatusBar 30 Hz
+ * pressure bar, cursor ring, artboard transforms, perf HUD) NEVER trigger `querySelectorAll`
+ * + `getComputedStyle` + `getBoundingClientRect` forced reflows.
+ */
+export function classifyOccluderMutations(
+ records?: ReadonlyArray<MutationRecord>
+): { shouldScan: boolean; isModalEvent: boolean } {
+ if (!records || records.length === 0) {
+ return { shouldScan: true, isModalEvent: false };
+ }
+ let shouldScan = false;
+ let isModalEvent = false;
+ for (let i = 0; i < records.length; i++) {
+ const rec = records[i];
+ if (!rec) continue;
+ if (rec.type === 'attributes') {
+ if (rec.attributeName === 'style') continue;
+ if (isIgnoredMutationTarget(rec.target)) continue;
+ if (rec.attributeName === 'aria-modal') {
+ shouldScan = true;
+ isModalEvent = true;
+ break;
+ }
+ if (
+ rec.attributeName === 'data-native-occluder' ||
+ rec.attributeName === 'data-chrome-floating'
+ ) {
+ shouldScan = true;
+ continue;
+ }
+ if (isElementNode(rec.target) && hasOccluderAncestor(rec.target)) {
+ shouldScan = true;
+ if (matchesModalElement(rec.target)) {
+ isModalEvent = true;
+ break;
+ }
+ }
+ } else if (rec.type === 'childList') {
+ if (isIgnoredMutationTarget(rec.target)) continue;
+ const checkList = (nodes: NodeList | undefined) => {
+ if (!nodes) return;
+ for (let j = 0; j < nodes.length; j++) {
+ const res = nodeContainsOccluder(nodes[j]);
+ if (res.occluder) shouldScan = true;
+ if (res.modal) {
+ isModalEvent = true;
+ return;
+ }
+ }
+ };
+ checkList(rec.addedNodes);
+ if (isModalEvent) break;
+ checkList(rec.removedNodes);
+ if (isModalEvent) break;
+ if (!shouldScan && isElementNode(rec.target) && hasOccluderAncestor(rec.target)) {
+ shouldScan = true;
+ }
+ }
+ }
+ return { shouldScan, isModalEvent };
+}
+
+const PHYS_EDGE_EPS = 1e-3;
+
+/**
+ * Converts a CSS DOMRect into integer physical pixel bounds with outward epsilon-guarded
+ * floor/ceil rounding so fractional DPR (`1.25`, `1.5`) and WebView zoom (`0.85..1.25`)
+ * never leave 1px transparent cutout border seams while preserving exact integer bounds.
+ */
+export function computePhysicalPixelRect(
+ rect: { left: number; top: number; right: number; bottom: number },
+ dpr: number
+): { xPx: number; yPx: number; widthPx: number; heightPx: number } {
+ const safeDpr = Number.isFinite(dpr) && dpr > 0.05 ? dpr : 1;
+ const xPx = Math.max(0, Math.floor(rect.left * safeDpr + PHYS_EDGE_EPS));
+ const yPx = Math.max(0, Math.floor(rect.top * safeDpr + PHYS_EDGE_EPS));
+ const rightPx = Math.max(xPx, Math.ceil(rect.right * safeDpr - PHYS_EDGE_EPS));
+ const bottomPx = Math.max(yPx, Math.ceil(rect.bottom * safeDpr - PHYS_EDGE_EPS));
+ return {
+ xPx,
+ yPx,
+ widthPx: Math.max(0, rightPx - xPx),
+ heightPx: Math.max(0, bottomPx - yPx),
+ };
+}
+
function isEditableElement(el: Element | null): boolean {
if (!el) return false;
const tag = el.tagName;
@@ -117,10 +336,11 @@ export function useNativeEngineViewport({
flipY,
}: UseNativeEngineViewportParams) {
const [nativeActive, setNativeActive] = useState<boolean>(() => isNativeCanvasActive());
- const [diagnostics, setDiagnostics] = useState<NativeEngineDiagnostics | null>(null);
const [textInputFocused, setTextInputFocused] = useState<boolean>(false);
const [workspaceInteracting, setWorkspaceInteracting] = useState<boolean>(false);
+ const [hasDomModal, setHasDomModal] = useState<boolean>(false);
+ const appView = useUiStore((s) => s.appView);
const interfaceScale = useUiStore(
(s) => s.appSettings.interfaceScale ?? DEFAULT_INTERFACE_SCALE
);
@@ -129,9 +349,16 @@ export function useNativeEngineViewport({
const wheelModeRaw = useUiStore((s) => s.appSettings.modifierKeys?.mouseWheel ?? 'zoom');
const globalPressureCurve = useUiStore((s) => s.appSettings.pressureCurve);
const isWebtoonMode = useUiStore((s) => s.isWebtoonMode);
- const isModalOpen = useUiStore(
- (s) => selectIsAnyModalOpen(s) || s.isAppearanceStudioOpen || s.is3DLayerOpen
+ const isUpdaterModalOpen = useUpdaterStore((s) => s.isModalOpen);
+ const isUiModalOpen = useUiStore(
+ (s) =>
+ selectIsAnyModalOpen(s) ||
+ s.isBrushStudioModalOpen ||
+ s.isAppearanceStudioOpen ||
+ s.is3DLayerOpen
);
+ const isModalOpen = isUiModalOpen || isUpdaterModalOpen || hasDomModal;
+ const isWorkspaceVisible = hasOpenDocument && appView === 'workspace';
const secondaryColor = useToolStore((s) => s.secondaryColor);
const straightRuler = useDocumentStore((s) => s.straightRuler);
const perspectiveRuler = useDocumentStore((s) => s.perspectiveRuler);
@@ -139,6 +366,8 @@ export function useNativeEngineViewport({
const floatingPanelsCount = useWorkspaceStore((s) => s.layout.floatingPanels?.length ?? 0);
const palettesHidden = useWorkspaceStore((s) => s.palettesHidden);
+ const nativeActiveRef = useRef(nativeActive);
+ nativeActiveRef.current = nativeActive;
const applyingNativeCameraRef = useRef(false);
const lastViewportSigRef = useRef<string>('');
const lastOccludedSigRef = useRef<string>('');
@@ -148,7 +377,7 @@ export function useNativeEngineViewport({
const nativeStrokeOwned =
nativeActive &&
- hasOpenDocument &&
+ isWorkspaceVisible &&
canNativeEngineHandleBrush(tool, brushSettings, activeLayer, isMaskMode);
// Detect native Windows DX12 DirectComposition engine once on desktop
@@ -160,11 +389,6 @@ export function useNativeEngineViewport({
void initNativeEngineBridge().then((active) => {
if (mounted) {
setNativeActive(active);
- if (active) {
- void getNativeDiagnostics().then((diag) => {
- if (mounted && diag) setDiagnostics(diag);
- });
- }
}
});
return () => {
@@ -173,11 +397,11 @@ export function useNativeEngineViewport({
};
}, []);
- // Toggle transparent WebView2 cutout attribute on :root while document is open
+ // Toggle transparent WebView2 cutout attribute on :root strictly while workspace document is visible
useEffect(() => {
if (typeof document === 'undefined' || !document.documentElement) return;
const root = document.documentElement;
- if (nativeActive && hasOpenDocument) {
+ if (nativeActive && isWorkspaceVisible) {
if (typeof root.setAttribute === 'function') {
root.setAttribute('data-native-canvas', 'true');
} else if (root.dataset) {
@@ -198,24 +422,29 @@ export function useNativeEngineViewport({
}
}
};
- }, [nativeActive, hasOpenDocument]);
+ }, [nativeActive, isWorkspaceVisible]);
- // Hide DirectComposition visual whenever CanvasArea unmounts or document closes
+ // Hide DirectComposition visual whenever appView !== 'workspace' or !hasOpenDocument
+ useEffect(() => {
+ if (!nativeActive || isWorkspaceVisible) return;
+ lastViewportSigRef.current = '';
+ lastOccludedSigRef.current = '';
+ void setNativeViewport({
+ xPx: 0,
+ yPx: 0,
+ widthPx: 0,
+ heightPx: 0,
+ dpr: typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1,
+ visible: false,
+ });
+ }, [nativeActive, isWorkspaceVisible]);
+
+ // Always hide DirectComposition visual when CanvasArea unmounts (e.g. switching to WelcomeScreen)
useEffect(() => {
- if (!nativeActive) return;
- if (!hasOpenDocument) {
- lastViewportSigRef.current = '';
- void setNativeViewport({
- xPx: 0,
- yPx: 0,
- widthPx: 0,
- heightPx: 0,
- dpr: typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1,
- visible: false,
- });
- }
return () => {
+ if (!nativeActiveRef.current) return;
lastViewportSigRef.current = '';
+ lastOccludedSigRef.current = '';
void setNativeViewport({
xPx: 0,
yPx: 0,
@@ -225,7 +454,7 @@ export function useNativeEngineViewport({
visible: false,
});
};
- }, [nativeActive, hasOpenDocument]);
+ }, []);
// Track text-input focus and workspace splitter/drag guard on document
useEffect(() => {
@@ -253,30 +482,33 @@ export function useNativeEngineViewport({
};
}, [nativeActive]);
- // Observe canvas viewport physical bounds (ResizeObserver + DPR + interfaceScale + layout)
- // AND occluded UI rects (modals, popovers, context menus, FloatingBrushPill, floating docks)
+ // Observe canvas viewport physical bounds (ResizeObserver + DPR + interfaceScale + WM_DPICHANGED + layout)
+ // AND occluded UI rects (modals, popovers, dropdowns, context menus, FloatingBrushPill, floating docks)
useEffect(() => {
- if (!nativeActive || !hasOpenDocument) return;
+ if (!nativeActive || !isWorkspaceVisible) {
+ setHasDomModal(false);
+ return;
+ }
const viewport = viewportRef.current;
if (!viewport || typeof window === 'undefined') return;
let rafId: number | null = null;
+ let throttleTimer: ReturnType<typeof setTimeout> | null = null;
+ let lastOccluderScanMs = 0;
+ let deferredAfterDrawing = false;
let dprMql: MediaQueryList | null = null;
let scaleTimer: ReturnType<typeof setTimeout> | null = null;
+ let settleTimer: ReturnType<typeof setTimeout> | null = null;
const pushViewportAndOccluders = () => {
rafId = null;
+ lastOccluderScanMs = typeof performance !== 'undefined' ? performance.now() : Date.now();
const vp = viewportRef.current;
if (!vp) return;
const dpr = window.devicePixelRatio || 1;
const rect = vp.getBoundingClientRect();
- const leftPx = Math.round(rect.left * dpr);
- const topPx = Math.round(rect.top * dpr);
- const rightPx = Math.round(rect.right * dpr);
- const bottomPx = Math.round(rect.bottom * dpr);
- const widthPx = Math.max(0, rightPx - leftPx);
- const heightPx = Math.max(0, bottomPx - topPx);
+ const { xPx: leftPx, yPx: topPx, widthPx, heightPx } = computePhysicalPixelRect(rect, dpr);
const visible = widthPx > 0 && heightPx > 0;
const vpSig = `${leftPx},${topPx},${widthPx},${heightPx},${dpr.toFixed(4)},${visible ? 1 : 0}`;
@@ -295,6 +527,7 @@ export function useNativeEngineViewport({
// Compute physical-pixel UI occlusion rects overlapping the canvas viewport
const occluded: NativeUiRect[] = [];
let occSig = '';
+ let detectedDomModal = false;
if (visible) {
const nodes = document.querySelectorAll(OCCLUDER_SELECTOR);
for (let i = 0; i < nodes.length; i++) {
@@ -311,6 +544,9 @@ export function useNativeEngineViewport({
}
const r = el.getBoundingClientRect();
if (r.width <= 0 || r.height <= 0) continue;
+ if (el.getAttribute('aria-modal') === 'true') {
+ detectedDomModal = true;
+ }
// Only include elements that overlap the viewport bounds
if (
r.right <= rect.left ||
@@ -320,16 +556,14 @@ export function useNativeEngineViewport({
) {
continue;
}
- const x = Math.round(r.left * dpr);
- const y = Math.round(r.top * dpr);
- const w = Math.max(0, Math.round(r.right * dpr) - x);
- const h = Math.max(0, Math.round(r.bottom * dpr) - y);
+ const { xPx: x, yPx: y, widthPx: w, heightPx: h } = computePhysicalPixelRect(r, dpr);
if (w > 0 && h > 0) {
occluded.push({ x, y, width: w, height: h });
occSig += `${x},${y},${w},${h};`;
}
}
}
+ setHasDomModal((prev) => (prev === detectedDomModal ? prev : detectedDomModal));
if (occSig !== lastOccludedSigRef.current) {
lastOccludedSigRef.current = occSig;
@@ -342,8 +576,56 @@ export function useNativeEngineViewport({
rafId = requestAnimationFrame(pushViewportAndOccluders);
};
- const handleDprChange = () => {
+ const scheduleThrottledOccluderSync = (isModalEvent: boolean) => {
+ // Skip routine occluder rescans during active strokes unless a modal opens
+ if (recoveryService.getIsDrawingActive() && !isModalEvent) {
+ deferredAfterDrawing = true;
+ return;
+ }
+ if (isModalEvent) {
+ if (throttleTimer !== null) {
+ clearTimeout(throttleTimer);
+ throttleTimer = null;
+ }
+ scheduleSync();
+ return;
+ }
+ const now = typeof performance !== 'undefined' ? performance.now() : Date.now();
+ const elapsed = now - lastOccluderScanMs;
+ if (elapsed >= OCCLUDER_MUTATION_THROTTLE_MS) {
+ if (throttleTimer !== null) {
+ clearTimeout(throttleTimer);
+ throttleTimer = null;
+ }
+ scheduleSync();
+ return;
+ }
+ if (throttleTimer === null) {
+ throttleTimer = setTimeout(() => {
+ throttleTimer = null;
+ if (recoveryService.getIsDrawingActive()) {
+ deferredAfterDrawing = true;
+ return;
+ }
+ scheduleSync();
+ }, Math.max(16, OCCLUDER_MUTATION_THROTTLE_MS - elapsed));
+ }
+ };
+
+ const forceResyncWithSettle = () => {
+ lastViewportSigRef.current = '';
+ lastOccludedSigRef.current = '';
scheduleSync();
+ if (settleTimer !== null) clearTimeout(settleTimer);
+ settleTimer = setTimeout(() => {
+ settleTimer = null;
+ lastViewportSigRef.current = '';
+ scheduleSync();
+ }, 60);
+ };
+
+ const handleDprChange = () => {
+ forceResyncWithSettle();
attachDprListener();
};
@@ -362,7 +644,7 @@ export function useNativeEngineViewport({
pushViewportAndOccluders();
attachDprListener();
// Re-sync after async Tauri setZoom() settles when interfaceScale changes
- scaleTimer = setTimeout(scheduleSync, 80);
+ scaleTimer = setTimeout(forceResyncWithSettle, 80);
const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(scheduleSync) : null;
ro?.observe(viewport);
@@ -370,33 +652,62 @@ export function useNativeEngineViewport({
ro?.observe(document.body);
}
- const mo = new MutationObserver(scheduleSync);
+ const mo = new MutationObserver((records) => {
+ const { shouldScan, isModalEvent } = classifyOccluderMutations(records);
+ if (!shouldScan) return;
+ scheduleThrottledOccluderSync(isModalEvent);
+ });
+ // Do NOT observe `style` mutations across `document.body` — StatusBar 30 Hz pressure bars,
+ // cursor rings, and artboard pan/zoom transforms would otherwise cause 30–60 Hz forced reflows!
mo.observe(document.body, {
childList: true,
subtree: true,
attributes: true,
- attributeFilter: ['style', 'class', 'data-native-occluder', 'data-chrome-floating'],
+ attributeFilter: [
+ 'class',
+ 'role',
+ 'aria-modal',
+ 'data-native-occluder',
+ 'data-chrome-floating',
+ ],
});
+ const unsubDrawing = recoveryService.subscribeDrawingActive((active) => {
+ if (!active && deferredAfterDrawing) {
+ deferredAfterDrawing = false;
+ scheduleSync();
+ }
+ });
+ const unsubInvalidated = subscribeNativeViewportInvalidated(forceResyncWithSettle);
window.addEventListener('resize', scheduleSync);
+ window.addEventListener(INTERFACE_SCALE_APPLIED_EVENT, forceResyncWithSettle);
+ window.visualViewport?.addEventListener('resize', scheduleSync);
return () => {
if (rafId !== null) cancelAnimationFrame(rafId);
+ if (throttleTimer !== null) clearTimeout(throttleTimer);
if (scaleTimer !== null) clearTimeout(scaleTimer);
+ if (settleTimer !== null) clearTimeout(settleTimer);
dprMql?.removeEventListener?.('change', handleDprChange);
ro?.disconnect();
mo.disconnect();
+ unsubDrawing();
+ unsubInvalidated();
window.removeEventListener('resize', scheduleSync);
+ window.removeEventListener(INTERFACE_SCALE_APPLIED_EVENT, forceResyncWithSettle);
+ window.visualViewport?.removeEventListener('resize', scheduleSync);
};
}, [
nativeActive,
- hasOpenDocument,
+ isWorkspaceVisible,
viewportRef,
interfaceScale,
palettesHidden,
floatingPanelsCount,
openPopover,
- isModalOpen,
+ isUiModalOpen,
+ isUpdaterModalOpen,
+ workspaceInteracting,
]);
// Sync document size
@@ -419,9 +730,11 @@ export function useNativeEngineViewport({
return () => cancelAnimationFrame(raf);
}, [nativeActive, hasOpenDocument, themePreset, appearance, showCheckerboard]);
- // Sync full Phase 4 CSP BrushSettings, FG/BG colors & content-hashed tip/paper textures ONLY on change
+ // Sync full Phase 4 CSP BrushSettings, FG/BG colors & content-hashed tip/paper textures ONLY on change.
+ // Skip during interactive Ctrl+Alt+Drag brush resize so 60 Hz size/hardness preview never runs
+ // a 90-field JSON.stringify + full NativeBrushConfig IPC; final config syncs once on pointer-up.
useEffect(() => {
- if (!nativeActive || !hasOpenDocument) return;
+ if (!nativeActive || !hasOpenDocument || isResizingBrush) return;
let sig = '';
try {
sig = JSON.stringify([
@@ -547,7 +860,16 @@ export function useNativeEngineViewport({
(tool === 'eraser' || Boolean(brushSettings.isTransparentInk)) &&
isBackgroundLayerId(activeLayer?.id ?? '');
void syncNativeFullBrushConfig(tool, brushSettings, primaryColor, secondaryColor, isBgEraser);
- }, [nativeActive, hasOpenDocument, tool, primaryColor, secondaryColor, brushSettings, activeLayer?.id]);
+ }, [
+ nativeActive,
+ hasOpenDocument,
+ isResizingBrush,
+ tool,
+ primaryColor,
+ secondaryColor,
+ brushSettings,
+ activeLayer?.id,
+ ]);
// Sync non-destructive layer mask painting mode into native Rust engine
useEffect(() => {
@@ -614,7 +936,7 @@ export function useNativeEngineViewport({
// Sync interaction policy (tool classification, wheel mode, focus & modal guards)
useEffect(() => {
- if (!nativeActive || !hasOpenDocument) return;
+ if (!nativeActive || !isWorkspaceVisible) return;
const wheelMode: NativeWheelNavMode =
wheelModeRaw === 'scroll'
? 'scroll'
@@ -624,7 +946,7 @@ export function useNativeEngineViewport({
void setNativePolicy({
activeTool: classifyNativeTool(tool),
- nativeStrokeEnabled: nativeStrokeOwned,
+ nativeStrokeEnabled: nativeStrokeOwned && !isResizingBrush,
wheelMode,
isWebtoonMode,
textInputFocused,
@@ -633,9 +955,10 @@ export function useNativeEngineViewport({
});
}, [
nativeActive,
- hasOpenDocument,
+ isWorkspaceVisible,
tool,
nativeStrokeOwned,
+ isResizingBrush,
wheelModeRaw,
isWebtoonMode,
textInputFocused,
@@ -701,13 +1024,21 @@ export function useNativeEngineViewport({
};
}, [nativeActive, hasOpenDocument, navigation]);
- // Subscribe to throttled GPU diagnostics (~4Hz) and pointer stats (~30Hz) from Rust
+ // Subscribe to throttled pointer stats (~30Hz) from Rust and forward active-pressure
+ // transitions into `recoveryService` so native strokes pause checkpoints, timelapse & disk walks.
+ // (4 Hz GPU diagnostics are consumed solely by the isolated `NativeGpuPerfHud` leaf store.)
useEffect(() => {
if (!nativeActive || !hasOpenDocument) return;
- const unsubDiag = subscribeNativeDiagnostics((diag) => {
- setDiagnostics(diag);
- });
+ let wasPressureDown = false;
const unsubStat = subscribeNativePointerStat((stat) => {
+ const pressureDown = typeof stat.pressure === 'number' && stat.pressure > 0.001;
+ if (pressureDown) {
+ wasPressureDown = true;
+ recoveryService.notifyNativeStrokeStart();
+ } else if (wasPressureDown) {
+ wasPressureDown = false;
+ recoveryService.notifyNativeStrokeEnd();
+ }
if (typeof window !== 'undefined') {
window.dispatchEvent(
new CustomEvent('canvas-pointer-stat', {
@@ -721,7 +1052,10 @@ export function useNativeEngineViewport({
}
});
return () => {
- unsubDiag();
+ if (wasPressureDown) {
+ wasPressureDown = false;
+ recoveryService.notifyNativeStrokeEnd();
+ }
unsubStat();
};
}, [nativeActive, hasOpenDocument]);
@@ -731,9 +1065,8 @@ export function useNativeEngineViewport({
}, []);
return {
- nativeActive: nativeActive && hasOpenDocument,
+ nativeActive: nativeActive && isWorkspaceVisible,
nativeStrokeOwned,
- diagnostics,
onClearNativeCanvas: handleClearNativeCanvas,
};
}
diff --git a/src/hooks/useTonalAndFilterActions.ts b/src/hooks/useTonalAndFilterActions.ts
index a9e8622..e717b8d 100644
--- a/src/hooks/useTonalAndFilterActions.ts
+++ b/src/hooks/useTonalAndFilterActions.ts
@@ -286,7 +286,7 @@ export function useTonalAndFilterActions({
uiStoreActions.setTonalModalState({
...current,
histograms: {
- rgb: new Uint32Array(h.luminance),
+ rgb: new Uint32Array(h.rgb ?? h.luminance),
r: new Uint32Array(h.r),
g: new Uint32Array(h.g),
b: new Uint32Array(h.b),
@@ -410,14 +410,24 @@ export function useTonalAndFilterActions({
const handleApplyMangaEffects = useCallback(
(type: 'saturated' | 'stream', options: SaturatedLinesOptions | StreamLinesOptions) => {
- if (!activeLayerId || activeLayer?.locked || dimensions.width <= 0 || dimensions.height <= 0) {
+ if (!activeLayerId || !activeLayer || dimensions.width <= 0 || dimensions.height <= 0) {
+ return;
+ }
+ if (activeLayer.type !== 'raster' || activeLayer.locked) {
+ showToast(t('Select an unlocked raster layer to apply manga effects.'));
return;
}
const docId = documentStore.getActiveDocumentId();
if (!docId) return;
- // Render in bounded 512x512 chunks (never allocates a full-doc canvas) and ingest directly into Rust tiles
+ // Render in bounded 512x512 DOM canvas chunks (never allocates a full-doc DOM canvas).
+ // For documents up to 16 MP (e.g. 4096x4096), assemble into one atomic RGBA buffer so Undo/Redo
+ // covers the entire canvas in a single history step instead of only the first 512x512 chunk.
const CHUNK = 512;
+ const totalPixels = dimensions.width * dimensions.height;
+ const useSingleAtomicIngest = totalPixels <= 16_777_216;
+ const fullRgba = useSingleAtomicIngest ? new Uint8Array(totalPixels * 4) : null;
+
const chunkCanvas = document.createElement('canvas');
chunkCanvas.width = Math.min(CHUNK, dimensions.width);
chunkCanvas.height = Math.min(CHUNK, dimensions.height);
@@ -429,6 +439,7 @@ export function useTonalAndFilterActions({
const tasks: Array<() => Promise<unknown>> = [];
const effectTypeLabel = tc('mangaEffect', type);
+ const targetLayerId = activeLayerId;
try {
for (let cy = 0; cy < dimensions.height; cy += CHUNK) {
const ch = Math.min(CHUNK, dimensions.height - cy);
@@ -459,34 +470,65 @@ export function useTonalAndFilterActions({
cCtx.restore();
const img = cCtx.getImageData(0, 0, cw, ch);
- const bytes = new Uint8Array(img.data.buffer.slice(0));
- const isFirst = tasks.length === 0;
- tasks.push(() =>
- ingestNativeDirtyRect({
- docId,
- layerId: activeLayerId,
- x: cx,
- y: cy,
- width: cw,
- height: ch,
- bytes,
- recordHistory: isFirst,
- actionType: 'brush',
- label: t('Manga Effect ({type})', { type: effectTypeLabel }),
- })
- );
+ if (fullRgba) {
+ const rowBytes = cw * 4;
+ for (let row = 0; row < ch; row++) {
+ const srcOff = row * rowBytes;
+ const dstOff = ((cy + row) * dimensions.width + cx) * 4;
+ fullRgba.set(img.data.subarray(srcOff, srcOff + rowBytes), dstOff);
+ }
+ } else {
+ const bytes = new Uint8Array(img.data.buffer.slice(0));
+ const isFirst = tasks.length === 0;
+ tasks.push(() =>
+ ingestNativeDirtyRect({
+ docId,
+ layerId: targetLayerId,
+ x: cx,
+ y: cy,
+ width: cw,
+ height: ch,
+ bytes,
+ recordHistory: isFirst,
+ actionType: 'brush',
+ label: t('Manga Effect ({type})', { type: effectTypeLabel }),
+ })
+ );
+ }
}
}
} finally {
releaseTemporaryCanvas(chunkCanvas);
}
+ if (fullRgba) {
+ tasks.push(() =>
+ ingestNativeDirtyRect({
+ docId,
+ layerId: targetLayerId,
+ x: 0,
+ y: 0,
+ width: dimensions.width,
+ height: dimensions.height,
+ bytes: fullRgba,
+ recordHistory: true,
+ actionType: 'brush',
+ label: t('Manga Effect ({type})', { type: effectTypeLabel }),
+ })
+ );
+ }
+
void (async () => {
- for (const run of tasks) {
- await run();
+ try {
+ for (const run of tasks) {
+ await run();
+ }
+ updateLayerThumbnail(targetLayerId, true);
+ showToast(t('Applied manga {type} lines', { type: effectTypeLabel }));
+ } catch (err) {
+ console.error('[MangaEffects] Failed to apply manga effects:', err);
+ showToast(t('Failed to apply manga effects.'));
}
- updateLayerThumbnail(activeLayerId, true);
- showToast(t('Applied manga {type} lines', { type: effectTypeLabel }));
})();
},
[activeLayerId, activeLayer, dimensions.width, dimensions.height, updateLayerThumbnail, showToast]
@@ -546,16 +588,18 @@ export function useTonalAndFilterActions({
const handleApplyExpressionColor = useCallback(
(layerId: string) => {
const result = applyExpressionColorOfPreview(layerId);
- if (result && result.tileDeltas.length > 0) {
- pushHistoryStepRef.current?.(
- 'expression-color',
- t('Apply Expression Color'),
- null,
- null,
- layerId,
- undefined,
- result.tileDeltas
- );
+ if (result) {
+ if (result.tileDeltas.length > 0) {
+ pushHistoryStepRef.current?.(
+ 'expression-color',
+ t('Apply Expression Color'),
+ null,
+ null,
+ layerId,
+ undefined,
+ result.tileDeltas
+ );
+ }
showToast(t('Applied expression color to layer'));
}
},
diff --git a/src/i18n/ja/settings.ts b/src/i18n/ja/settings.ts
index a512aee..434c136 100644
--- a/src/i18n/ja/settings.ts
+++ b/src/i18n/ja/settings.ts
@@ -817,10 +817,10 @@ export const JA_SETTINGS: TranslationDictionary = {
'GPU Brush Acceleration': 'GPUブラシアクセラレーション',
'Baked Layer Stack Cache': 'レイヤースタックキャッシュ',
'GPU Tile Cache (VRAM)': 'GPUタイルキャッシュ (VRAM)',
- 'Low (32 MB)': '低 (32 MB)',
- 'Balanced (64 MB)': '標準 (64 MB)',
- 'High (128 MB)': '高 (128 MB)',
- 'Ultra (256 MB)': '最高 (256 MB)',
+ 'Low (128 MB)': '低 (128 MB)',
+ 'Balanced (256 MB)': '標準 (256 MB)',
+ 'High (512 MB)': '高 (512 MB)',
+ 'Ultra (1024 MB)': '最高 (1024 MB)',
'{count} slices': '{count} スライス',
'Viewport Resolution (HiDPI)': 'ビューポート解像度 (HiDPI)',
'Viewport Resolution Scaling': 'ビューポート解像度スケーリング',
diff --git a/src/main.tsx b/src/main.tsx
index 1ba3ece..b5d8d35 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -12,41 +12,164 @@ interface Props {
interface State {
hasError: boolean;
error: Error | null;
+ componentStack: string | null;
+ copied: boolean;
}
-class ErrorBoundary extends Component<Props, State> {
+export class ErrorBoundary extends Component<Props, State> {
+ private copyTimer: ReturnType<typeof setTimeout> | null = null;
+
public state: State = {
hasError: false,
error: null,
+ componentStack: null,
+ copied: false,
};
public static getDerivedStateFromError(error: Error): State {
- return { hasError: true, error };
+ return {
+ hasError: true,
+ error,
+ componentStack: null,
+ copied: false,
+ };
}
public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error("Uncaught runtime error:", error, errorInfo);
+ const stack = errorInfo?.componentStack?.trim() || null;
+ if (stack) {
+ this.setState({ componentStack: stack });
+ }
+ }
+
+ public componentWillUnmount() {
+ if (this.copyTimer !== null) {
+ clearTimeout(this.copyTimer);
+ this.copyTimer = null;
+ }
+ }
+
+ private buildErrorDetailsText(): string {
+ const err = this.state.error;
+ const sections: string[] = [];
+ sections.push(
+ `Error: ${err?.name || "Error"}: ${err?.message || "An unexpected error occurred."}`
+ );
+ if (err?.stack) {
+ sections.push(`\nStack Trace:\n${err.stack.trim()}`);
+ }
+ if (this.state.componentStack) {
+ sections.push(`\nComponent Stack:\n${this.state.componentStack}`);
+ }
+ return sections.join("\n");
}
+ private handleCopyDetails = async () => {
+ const details = this.buildErrorDetailsText();
+ let ok = false;
+ try {
+ if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
+ await navigator.clipboard.writeText(details);
+ ok = true;
+ }
+ } catch {
+ ok = false;
+ }
+ if (!ok && typeof document !== "undefined") {
+ try {
+ const ta = document.createElement("textarea");
+ ta.value = details;
+ ta.style.position = "fixed";
+ ta.style.opacity = "0";
+ document.body.appendChild(ta);
+ ta.select();
+ ok = document.execCommand("copy");
+ document.body.removeChild(ta);
+ } catch {
+ ok = false;
+ }
+ }
+ if (ok) {
+ this.setState({ copied: true });
+ if (this.copyTimer !== null) clearTimeout(this.copyTimer);
+ this.copyTimer = setTimeout(() => {
+ this.copyTimer = null;
+ this.setState({ copied: false });
+ }, 2000);
+ }
+ };
+
public render() {
if (this.state.hasError) {
+ const errorStack = this.state.error?.stack?.trim() || null;
+ const componentStack = this.state.componentStack;
+
return (
<div className="flex flex-col items-center justify-center w-screen h-screen bg-[#1e1e1e] text-[#cccccc] p-8 text-center font-sans select-none">
- <div className="bg-[#252525] border border-red-500/40 rounded-lg p-6 max-w-lg shadow-2xl">
- <h2 className="text-lg font-bold text-red-400 mb-2">{t('Graphics Editor Encountered an Error')}</h2>
- <p className="text-xs text-[#888888] mb-4 font-mono break-all">
+ <div className="bg-[#252525] border border-red-500/40 rounded-lg p-6 max-w-xl w-full shadow-2xl">
+ <h2 className="text-lg font-bold text-red-400 mb-2">
+ {t('Graphics Editor Encountered an Error')}
+ </h2>
+ <p className="text-xs text-[#a0a0a0] mb-4 font-mono break-all select-text">
{this.state.error?.message || t('An unexpected error occurred.')}
</p>
- <button
- onClick={() => {
- this.setState({ hasError: false, error: null });
- markIntentionalReload();
- window.location.reload();
- }}
- className="px-4 py-1.5 bg-blue-600 hover:bg-blue-500 text-white rounded text-xs font-medium transition-colors"
- >
- {t('Reload Editor')}
- </button>
+
+ {(errorStack || componentStack) && (
+ <details className="text-left mb-4 bg-[#1a1a1a] border border-white/10 rounded p-2.5">
+ <summary className="text-[11px] font-medium text-[#b0b0b0] hover:text-white cursor-pointer select-none">
+ {t('Error Details & Stack Trace')}
+ </summary>
+ <div className="mt-2 space-y-2 max-h-56 overflow-auto select-text">
+ {errorStack && (
+ <div>
+ <div className="text-[10px] uppercase tracking-wider text-[#888888] mb-0.5">
+ {t('Stack Trace')}
+ </div>
+ <pre className="text-[10px] leading-relaxed text-[#d4d4d4] font-mono whitespace-pre-wrap break-words">
+ {errorStack}
+ </pre>
+ </div>
+ )}
+ {componentStack && (
+ <div>
+ <div className="text-[10px] uppercase tracking-wider text-[#888888] mb-0.5">
+ {t('Component Stack')}
+ </div>
+ <pre className="text-[10px] leading-relaxed text-[#9ca3af] font-mono whitespace-pre-wrap break-words">
+ {componentStack}
+ </pre>
+ </div>
+ )}
+ </div>
+ </details>
+ )}
+
+ <div className="flex items-center justify-center gap-2">
+ <button
+ type="button"
+ onClick={this.handleCopyDetails}
+ className="px-3.5 py-1.5 bg-[#333333] hover:bg-[#3f3f3f] border border-white/10 text-[#e0e0e0] rounded text-xs font-medium transition-colors cursor-pointer"
+ >
+ {this.state.copied ? t('Copied Error Details') : t('Copy Error Details')}
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ this.setState({
+ hasError: false,
+ error: null,
+ componentStack: null,
+ copied: false,
+ });
+ markIntentionalReload();
+ window.location.reload();
+ }}
+ className="px-4 py-1.5 bg-blue-600 hover:bg-blue-500 text-white rounded text-xs font-medium transition-colors cursor-pointer"
+ >
+ {t('Reload Editor')}
+ </button>
+ </div>
</div>
</div>
);
@@ -56,10 +179,13 @@ class ErrorBoundary extends Component<Props, State> {
}
}
-ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
- <React.StrictMode>
- <ErrorBoundary>
- <App />
- </ErrorBoundary>
- </React.StrictMode>,
-);
+const rootElement = typeof document !== "undefined" ? document.getElementById("root") : null;
+if (rootElement) {
+ ReactDOM.createRoot(rootElement).render(
+ <React.StrictMode>
+ <ErrorBoundary>
+ <App />
+ </ErrorBoundary>
+ </React.StrictMode>,
+ );
+}
diff --git a/src/services/bake3DService.ts b/src/services/bake3DService.ts
index 5f2a74e..b7d259c 100644
--- a/src/services/bake3DService.ts
+++ b/src/services/bake3DService.ts
@@ -381,64 +381,65 @@ export async function bake3DToRasterLayer(options: Bake3DOptions): Promise<Bake3
}
}
- // Clamp & verify offscreen renderer size against GPU + Chromium DrawingBuffer limits
- configureSafeBakeRendererSize(offscreenRenderer, targetWidth, targetHeight);
- offscreenRenderer.setClearColor(0x000000, 0);
- if (activeRenderer && 'toneMapping' in activeRenderer && 'toneMapping' in offscreenRenderer) {
- offscreenRenderer.toneMapping = activeRenderer.toneMapping;
- offscreenRenderer.toneMappingExposure = activeRenderer.toneMappingExposure;
- }
- if (offscreenRenderer.shadowMap && activeRenderer?.shadowMap) {
- offscreenRenderer.shadowMap.enabled = activeRenderer.shadowMap.enabled;
- offscreenRenderer.shadowMap.type = activeRenderer.shadowMap.type;
- }
+ let rasterCanvas: HTMLCanvasElement;
+ let dataUrl: string;
+ try {
+ // Clamp & verify offscreen renderer size against GPU + Chromium DrawingBuffer limits
+ configureSafeBakeRendererSize(offscreenRenderer, targetWidth, targetHeight);
+ offscreenRenderer.setClearColor(0x000000, 0);
+ if (activeRenderer && 'toneMapping' in activeRenderer && 'toneMapping' in offscreenRenderer) {
+ offscreenRenderer.toneMapping = activeRenderer.toneMapping;
+ offscreenRenderer.toneMappingExposure = activeRenderer.toneMappingExposure;
+ }
+ if (offscreenRenderer.shadowMap && activeRenderer?.shadowMap) {
+ offscreenRenderer.shadowMap.enabled = activeRenderer.shadowMap.enabled;
+ offscreenRenderer.shadowMap.type = activeRenderer.shadowMap.type;
+ }
- // Synchronize camera projection aspect ratio & world matrix with document geometry
- if (typeof camera.updateMatrixWorld === 'function') {
- camera.updateMatrixWorld(true);
- }
- const renderCamera = camera.clone();
- if ('aspect' in renderCamera) {
- (renderCamera as THREE.PerspectiveCamera).aspect = targetWidth / targetHeight;
- (renderCamera as THREE.PerspectiveCamera).updateProjectionMatrix();
- } else if ('left' in renderCamera) {
- (renderCamera as THREE.OrthographicCamera).updateProjectionMatrix();
- }
- if (typeof renderCamera.updateMatrixWorld === 'function') {
- renderCamera.updateMatrixWorld(true);
- }
+ // Synchronize camera projection aspect ratio & world matrix with document geometry
+ if (typeof camera.updateMatrixWorld === 'function') {
+ camera.updateMatrixWorld(true);
+ }
+ const renderCamera = camera.clone();
+ if ('aspect' in renderCamera) {
+ (renderCamera as THREE.PerspectiveCamera).aspect = targetWidth / targetHeight;
+ (renderCamera as THREE.PerspectiveCamera).updateProjectionMatrix();
+ } else if ('left' in renderCamera) {
+ (renderCamera as THREE.OrthographicCamera).updateProjectionMatrix();
+ }
+ if (typeof renderCamera.updateMatrixWorld === 'function') {
+ renderCamera.updateMatrixWorld(true);
+ }
- offscreenRenderer.render(scene, renderCamera);
+ offscreenRenderer.render(scene, renderCamera);
- // 2. Transfer WebGL frame buffer to standard 2D document layer
- const rasterCanvas = document.createElement('canvas');
- rasterCanvas.width = targetWidth;
- rasterCanvas.height = targetHeight;
+ // 2. Transfer WebGL frame buffer to standard 2D document layer
+ rasterCanvas = document.createElement('canvas');
+ rasterCanvas.width = targetWidth;
+ rasterCanvas.height = targetHeight;
- const ctx = rasterCanvas.getContext('2d', { willReadFrequently: false });
- if (!ctx) {
- if (!reusedActiveRenderer) {
- disposeThreeResources(null, offscreenRenderer);
+ const ctx = rasterCanvas.getContext('2d', { willReadFrequently: false });
+ if (!ctx) {
+ throw new Error(t('Unable to create 2D canvas context for 3D rasterization'));
}
- throw new Error(t('Unable to create 2D canvas context for 3D rasterization'));
- }
-
- ctx.drawImage(offscreenRenderer.domElement, 0, 0, targetWidth, targetHeight);
- const dataUrl = rasterCanvas.toDataURL('image/png');
- // 3. Memory Cleanup: Free offscreen WebGL context; preserve live scene if disposeOnComplete=false
- if (disposeOnComplete) {
- disposeThreeResources(scene, offscreenRenderer);
- if (activeRenderer && !reusedActiveRenderer) {
- disposeThreeResources(null, activeRenderer);
- }
- } else if (reusedActiveRenderer) {
- offscreenRenderer.setPixelRatio(savedActivePixelRatio);
- if (savedActiveSize.x > 0 && savedActiveSize.y > 0) {
- offscreenRenderer.setSize(savedActiveSize.x, savedActiveSize.y, false);
+ ctx.drawImage(offscreenRenderer.domElement, 0, 0, targetWidth, targetHeight);
+ dataUrl = rasterCanvas.toDataURL('image/png');
+ } finally {
+ // 3. Memory Cleanup: Free offscreen WebGL context; preserve live scene if disposeOnComplete=false
+ if (disposeOnComplete) {
+ disposeThreeResources(scene, offscreenRenderer);
+ if (activeRenderer && !reusedActiveRenderer) {
+ disposeThreeResources(null, activeRenderer);
+ }
+ } else if (reusedActiveRenderer) {
+ offscreenRenderer.setPixelRatio(savedActivePixelRatio);
+ if (savedActiveSize.x > 0 && savedActiveSize.y > 0) {
+ offscreenRenderer.setSize(savedActiveSize.x, savedActiveSize.y, false);
+ }
+ } else {
+ disposeThreeResources(null, offscreenRenderer);
}
- } else {
- disposeThreeResources(null, offscreenRenderer);
}
// 4. Construct standard document raster layer
@@ -770,106 +771,154 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<Bak
type: THREE.UnsignedByteType,
});
+ let lineTarget: THREE.WebGLRenderTarget | null = null;
+ let quadGeo: THREE.PlaneGeometry | null = null;
+ let sobelMaterial: THREE.ShaderMaterial | null = null;
+ let displayMaterial: THREE.ShaderMaterial | null = null;
+ let lineCanvas!: HTMLCanvasElement;
+ let diffData!: Uint8ClampedArray;
+
try {
- for (const mesh of savedMaterials.keys()) {
- mesh.material = normalMat;
- }
+ try {
+ for (const mesh of savedMaterials.keys()) {
+ mesh.material = normalMat;
+ }
- offscreenRenderer.setRenderTarget(targetA);
- offscreenRenderer.clear();
- offscreenRenderer.render(scene, renderCamera);
+ offscreenRenderer.setRenderTarget(targetA);
+ offscreenRenderer.clear();
+ offscreenRenderer.render(scene, renderCamera);
+
+ // 2. Offscreen Render Target B: Diffuse Lighting Buffer
+ for (const [mesh, origMat] of savedMaterials.entries()) {
+ mesh.material = origMat;
+ }
- // 2. Offscreen Render Target B: Diffuse Lighting Buffer
- for (const [mesh, origMat] of savedMaterials.entries()) {
- mesh.material = origMat;
+ offscreenRenderer.setRenderTarget(targetB);
+ offscreenRenderer.clear();
+ offscreenRenderer.render(scene, renderCamera);
+ } finally {
+ for (const [mesh, origMat] of savedMaterials.entries()) {
+ mesh.material = origMat;
+ }
+ for (const helper of hiddenHelpers) {
+ helper.visible = true;
+ }
}
- offscreenRenderer.setRenderTarget(targetB);
+ // 3. GLSL Fragment Sobel Edge Detection Pass over Target A (Normals + Depth)
+ lineTarget = new THREE.WebGLRenderTarget(renderWidth, renderHeight, {
+ minFilter: THREE.NearestFilter,
+ magFilter: THREE.NearestFilter,
+ format: THREE.RGBAFormat,
+ type: THREE.UnsignedByteType,
+ });
+
+ const postScene = new THREE.Scene();
+ const postCamera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
+ quadGeo = new THREE.PlaneGeometry(2, 2);
+
+ sobelMaterial = new THREE.ShaderMaterial({
+ vertexShader: sobelVertexShader,
+ fragmentShader: sobelFragmentShader,
+ uniforms: {
+ tNormal: { value: targetA.texture },
+ tDepth: { value: targetA.depthTexture },
+ uResolution: { value: new THREE.Vector2(renderWidth, renderHeight) },
+ uThreshold: { value: lineThreshold },
+ uLineWidth: { value: lineWidth },
+ uCameraNear: { value: cameraNear },
+ uCameraFar: { value: cameraFar },
+ uIsPerspective: { value: isPerspective },
+ uAntiAliasing: { value: antiAliasing ? 1 : 0 },
+ },
+ depthTest: false,
+ depthWrite: false,
+ transparent: true,
+ });
+
+ const sobelQuad = new THREE.Mesh(quadGeo, sobelMaterial);
+ postScene.add(sobelQuad);
+
+ offscreenRenderer.setRenderTarget(lineTarget);
offscreenRenderer.clear();
- offscreenRenderer.render(scene, renderCamera);
- } finally {
- for (const [mesh, origMat] of savedMaterials.entries()) {
- mesh.material = origMat;
- }
- for (const helper of hiddenHelpers) {
- helper.visible = true;
+ offscreenRenderer.render(postScene, postCamera);
+
+ // Transfer rendered line target to lineCanvas at target document dimensions
+ lineCanvas = document.createElement('canvas');
+ lineCanvas.width = targetWidth;
+ lineCanvas.height = targetHeight;
+ const lineCtx = lineCanvas.getContext('2d', { willReadFrequently: true });
+ if (!lineCtx) {
+ throw new Error(t('Unable to create 2D canvas context for 3D rasterization'));
}
- }
- // 3. GLSL Fragment Sobel Edge Detection Pass over Target A (Normals + Depth)
- const lineTarget = new THREE.WebGLRenderTarget(renderWidth, renderHeight, {
- minFilter: THREE.NearestFilter,
- magFilter: THREE.NearestFilter,
- format: THREE.RGBAFormat,
- type: THREE.UnsignedByteType,
- });
+ displayMaterial = new THREE.ShaderMaterial({
+ vertexShader: displayVertexShader,
+ fragmentShader: displayFragmentShader,
+ uniforms: { tSource: { value: lineTarget.texture } },
+ depthTest: false,
+ depthWrite: false,
+ transparent: true,
+ });
+ sobelQuad.material = displayMaterial;
- const postScene = new THREE.Scene();
- const postCamera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
- const quadGeo = new THREE.PlaneGeometry(2, 2);
-
- const sobelMaterial = new THREE.ShaderMaterial({
- vertexShader: sobelVertexShader,
- fragmentShader: sobelFragmentShader,
- uniforms: {
- tNormal: { value: targetA.texture },
- tDepth: { value: targetA.depthTexture },
- uResolution: { value: new THREE.Vector2(renderWidth, renderHeight) },
- uThreshold: { value: lineThreshold },
- uLineWidth: { value: lineWidth },
- uCameraNear: { value: cameraNear },
- uCameraFar: { value: cameraFar },
- uIsPerspective: { value: isPerspective },
- uAntiAliasing: { value: antiAliasing ? 1 : 0 },
- },
- depthTest: false,
- depthWrite: false,
- transparent: true,
- });
+ offscreenRenderer.setRenderTarget(null);
+ offscreenRenderer.clear();
+ offscreenRenderer.render(postScene, postCamera);
+ lineCtx.imageSmoothingEnabled = false;
+ lineCtx.drawImage(offscreenRenderer.domElement, 0, 0, targetWidth, targetHeight);
- const sobelQuad = new THREE.Mesh(quadGeo, sobelMaterial);
- postScene.add(sobelQuad);
-
- offscreenRenderer.setRenderTarget(lineTarget);
- offscreenRenderer.clear();
- offscreenRenderer.render(postScene, postCamera);
-
- // Transfer rendered line target to lineCanvas at target document dimensions
- const lineCanvas = document.createElement('canvas');
- lineCanvas.width = targetWidth;
- lineCanvas.height = targetHeight;
- const lineCtx = lineCanvas.getContext('2d', { willReadFrequently: true })!;
-
- const displayMaterial = new THREE.ShaderMaterial({
- vertexShader: displayVertexShader,
- fragmentShader: displayFragmentShader,
- uniforms: { tSource: { value: lineTarget.texture } },
- depthTest: false,
- depthWrite: false,
- transparent: true,
- });
- sobelQuad.material = displayMaterial;
-
- offscreenRenderer.setRenderTarget(null);
- offscreenRenderer.clear();
- offscreenRenderer.render(postScene, postCamera);
- lineCtx.imageSmoothingEnabled = false;
- lineCtx.drawImage(offscreenRenderer.domElement, 0, 0, targetWidth, targetHeight);
-
- // 4. Capture Diffuse Lighting Buffer for Shadow Tier Posterization
- displayMaterial.uniforms.tSource.value = targetB.texture;
- offscreenRenderer.setRenderTarget(null);
- offscreenRenderer.clear();
- offscreenRenderer.render(postScene, postCamera);
-
- const diffuseCanvas = document.createElement('canvas');
- diffuseCanvas.width = renderWidth;
- diffuseCanvas.height = renderHeight;
- const diffCtx = diffuseCanvas.getContext('2d', { willReadFrequently: true })!;
- diffCtx.imageSmoothingEnabled = false;
- diffCtx.drawImage(offscreenRenderer.domElement, 0, 0, renderWidth, renderHeight);
- const diffImageData = diffCtx.getImageData(0, 0, renderWidth, renderHeight);
- const diffData = diffImageData.data;
+ // 4. Capture Diffuse Lighting Buffer for Shadow Tier Posterization
+ displayMaterial.uniforms.tSource.value = targetB.texture;
+ offscreenRenderer.setRenderTarget(null);
+ offscreenRenderer.clear();
+ offscreenRenderer.render(postScene, postCamera);
+
+ const diffuseCanvas = document.createElement('canvas');
+ diffuseCanvas.width = renderWidth;
+ diffuseCanvas.height = renderHeight;
+ const diffCtx = diffuseCanvas.getContext('2d', { willReadFrequently: true });
+ if (!diffCtx) {
+ throw new Error(t('Unable to create 2D canvas context for 3D rasterization'));
+ }
+ diffCtx.imageSmoothingEnabled = false;
+ diffCtx.drawImage(offscreenRenderer.domElement, 0, 0, renderWidth, renderHeight);
+ const diffImageData = diffCtx.getImageData(0, 0, renderWidth, renderHeight);
+ diffData = diffImageData.data;
+ } finally {
+ // Immediate Cleanup of Offscreen WebGL Resources even if rendering/readback throws
+ normalMat.dispose();
+ quadGeo?.dispose();
+ sobelMaterial?.dispose();
+ displayMaterial?.dispose();
+ targetA.texture.dispose();
+ targetA.depthTexture?.dispose();
+ targetA.dispose();
+ targetB.texture.dispose();
+ targetB.dispose();
+ lineTarget?.texture.dispose();
+ lineTarget?.dispose();
+
+ if (effectiveDisposeOnComplete) {
+ disposeThreeResources(scene, offscreenRenderer);
+ if (activeRenderer && !reusedActiveRenderer) {
+ disposeThreeResources(null, activeRenderer);
+ }
+ } else if (reusedActiveRenderer) {
+ offscreenRenderer.setRenderTarget(null);
+ offscreenRenderer.setPixelRatio(savedActivePixelRatio);
+ if (savedActiveSize.x > 0 && savedActiveSize.y > 0) {
+ offscreenRenderer.setSize(savedActiveSize.x, savedActiveSize.y, false);
+ }
+ } else {
+ try {
+ if (typeof offscreenRenderer.forceContextLoss === 'function') {
+ offscreenRenderer.forceContextLoss();
+ }
+ } catch {}
+ offscreenRenderer.dispose();
+ }
+ }
// Group Folder Name Resolution
const rawModelName = modelName || baseLayerName || 'Model';
@@ -1100,39 +1149,6 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<Bak
parentId: null,
};
- // 8. Immediate Cleanup of Offscreen WebGL Resources
- normalMat.dispose();
- quadGeo.dispose();
- sobelMaterial.dispose();
- displayMaterial.dispose();
- targetA.texture.dispose();
- targetA.depthTexture?.dispose();
- targetA.dispose();
- targetB.texture.dispose();
- targetB.dispose();
- lineTarget.texture.dispose();
- lineTarget.dispose();
-
- if (effectiveDisposeOnComplete) {
- disposeThreeResources(scene, offscreenRenderer);
- if (activeRenderer && !reusedActiveRenderer) {
- disposeThreeResources(null, activeRenderer);
- }
- } else if (reusedActiveRenderer) {
- offscreenRenderer.setRenderTarget(null);
- offscreenRenderer.setPixelRatio(savedActivePixelRatio);
- if (savedActiveSize.x > 0 && savedActiveSize.y > 0) {
- offscreenRenderer.setSize(savedActiveSize.x, savedActiveSize.y, false);
- }
- } else {
- try {
- if (typeof offscreenRenderer.forceContextLoss === 'function') {
- offscreenRenderer.forceContextLoss();
- }
- } catch {}
- offscreenRenderer.dispose();
- }
-
// Render and Stack Hierarchy:
// Folder containing: 3D Outline on top, then Deep shadow tones below, then Light shadow tone
// In `layers` stack: [folderLayer, lineLayer, toneLayerDeep, ..., toneLayerLight]
diff --git a/src/services/multiplayerService.ts b/src/services/multiplayerService.ts
index 8a566ff..0f04a53 100644
--- a/src/services/multiplayerService.ts
+++ b/src/services/multiplayerService.ts
@@ -164,7 +164,7 @@ const CAMERA_SYNC_THROTTLE_MS = 50;
const MASK_FLAG_FULL_REPLACE = 0x01;
const MASK_FLAG_LZ4 = 0x02;
const MASK_FLAG_SOLID_FILL = 0x04;
-const MAX_MASK_DECODE_BYTES = 4 * 1024 * 1024; // 4 MB safety ceiling per mask packet
+const MAX_MASK_DECODE_BYTES = 64 * 1024 * 1024; // 64 MB safety ceiling per mask packet (up to 8192×8192 alpha mask)
const MAX_BINARY_PACKET_BYTES = 16 * 1024 * 1024;
const MAX_JSON_MESSAGE_CHARS = 8 * 1024 * 1024;
diff --git a/src/services/recoveryService.ts b/src/services/recoveryService.ts
index cd48943..4973fc5 100644
--- a/src/services/recoveryService.ts
+++ b/src/services/recoveryService.ts
@@ -359,10 +359,20 @@ export function isTauriEnvironment(): boolean {
);
}
+const NATIVE_DRAWING_IDLE_GRACE_MS = 1500;
+const NATIVE_STROKE_SAFETY_TIMEOUT_MS = 8000;
+
class RecoveryService {
private currentSessionId: string | null = null;
+ private sessionInitializedOnDisk: boolean = false;
private dirtySinceCheckpoint: boolean = false;
+ private dirtySeq: number = 0;
+ private strokesSinceCheckpoint: number = 0;
private isDrawingActive: boolean = false;
+ private nativeStrokeInProgress: boolean = false;
+ private nativeDrawingGraceTimer: ReturnType<typeof setTimeout> | null = null;
+ private nativeStrokeSafetyTimer: ReturnType<typeof setTimeout> | null = null;
+ private drawingActiveListeners: Set<(active: boolean) => void> = new Set();
private checkpointGeneration: number = 0;
private idleCheckpointTimer: ReturnType<typeof setTimeout> | null = null;
private layerMutationDebounceTimer: ReturnType<typeof setTimeout> | null = null;
@@ -400,17 +410,114 @@ class RecoveryService {
return this.isDrawingActive;
}
+ /**
+ * Subscribes to drawing-activity transitions (`true` while actively sketching or inside the
+ * post-stroke grace window, `false` once idle) so background subsystems (Navigator preview,
+ * occluder rescans, BrushPreview GPU queue) can flush deferred work cleanly when idle.
+ */
+ public subscribeDrawingActive(listener: (active: boolean) => void): () => void {
+ this.drawingActiveListeners.add(listener);
+ return () => {
+ this.drawingActiveListeners.delete(listener);
+ };
+ }
+
+ private emitDrawingActive(active: boolean): void {
+ for (const listener of Array.from(this.drawingActiveListeners)) {
+ try {
+ listener(active);
+ } catch {
+ // Ignore subscriber errors
+ }
+ }
+ }
+
+ private clearNativeDrawingTimers(): void {
+ if (this.nativeDrawingGraceTimer) {
+ clearTimeout(this.nativeDrawingGraceTimer);
+ this.nativeDrawingGraceTimer = null;
+ }
+ if (this.nativeStrokeSafetyTimer) {
+ clearTimeout(this.nativeStrokeSafetyTimer);
+ this.nativeStrokeSafetyTimer = null;
+ }
+ }
+
public setDrawingActive(active: boolean): void {
+ const prev = this.isDrawingActive;
+ if (!active) {
+ this.nativeStrokeInProgress = false;
+ this.clearNativeDrawingTimers();
+ }
this.isDrawingActive = active;
- artworkTimeTracker.setDrawingActive(active);
+ if (prev !== active) {
+ artworkTimeTracker.setDrawingActive(active);
+ this.emitDrawingActive(active);
+ }
if (active) {
if (this.idleCheckpointTimer) {
clearTimeout(this.idleCheckpointTimer);
this.idleCheckpointTimer = null;
}
} else if (this.dirtySinceCheckpoint && this.currentSessionId && isTauriEnvironment()) {
- this.resetIdleCheckpointTimer(this.currentSessionId);
+ if (this.strokesSinceCheckpoint >= CHECKPOINT_STROKE_THRESHOLD) {
+ this.strokesSinceCheckpoint = 0;
+ void this.triggerCheckpoint(this.currentSessionId);
+ } else {
+ this.resetIdleCheckpointTimer(this.currentSessionId);
+ }
+ }
+ }
+
+ /**
+ * Marks the start or ongoing continuation of a native DX12 stroke (triggered by unoccluded
+ * pointer-down or in-contact native pointer-stat packets). Sets a safety timeout fallback so
+ * a missed pointer-up/window-blur can never leave background tasks paused indefinitely.
+ */
+ public notifyNativeStrokeStart(safetyTimeoutMs: number = NATIVE_STROKE_SAFETY_TIMEOUT_MS): void {
+ this.nativeStrokeInProgress = true;
+ if (this.nativeDrawingGraceTimer) {
+ clearTimeout(this.nativeDrawingGraceTimer);
+ this.nativeDrawingGraceTimer = null;
+ }
+ if (this.nativeStrokeSafetyTimer) {
+ clearTimeout(this.nativeStrokeSafetyTimer);
+ }
+ this.nativeStrokeSafetyTimer = setTimeout(() => {
+ this.nativeStrokeSafetyTimer = null;
+ if (this.nativeStrokeInProgress) {
+ this.notifyNativeStrokeEnd(NATIVE_DRAWING_IDLE_GRACE_MS);
+ }
+ }, Math.max(500, safetyTimeoutMs));
+
+ if (!this.isDrawingActive) {
+ this.setDrawingActive(true);
+ }
+ }
+
+ /**
+ * Marks pen-up / commit of a native DX12 stroke while keeping `isDrawingActive === true` for
+ * an idle grace window (`1500ms` default) so rapid hatching/sketching is never interrupted by
+ * checkpoints, timelapse readbacks, or 2-second scratch-disk walks.
+ */
+ public notifyNativeStrokeEnd(graceMs: number = NATIVE_DRAWING_IDLE_GRACE_MS): void {
+ this.nativeStrokeInProgress = false;
+ if (this.nativeStrokeSafetyTimer) {
+ clearTimeout(this.nativeStrokeSafetyTimer);
+ this.nativeStrokeSafetyTimer = null;
}
+ if (!this.isDrawingActive) {
+ this.setDrawingActive(true);
+ }
+ if (this.nativeDrawingGraceTimer) {
+ clearTimeout(this.nativeDrawingGraceTimer);
+ }
+ this.nativeDrawingGraceTimer = setTimeout(() => {
+ this.nativeDrawingGraceTimer = null;
+ if (!this.nativeStrokeInProgress) {
+ this.setDrawingActive(false);
+ }
+ }, Math.max(0, graceMs));
}
/**
@@ -421,21 +528,27 @@ class RecoveryService {
manifestProvider: () => DocumentManifest | null,
_thumbnailProvider?: () => Promise<Uint8Array | null>
): Promise<void> {
- const isSameSession = this.currentSessionId === sessionId;
+ const isSameActiveSession =
+ this.currentSessionId === sessionId && this.sessionInitializedOnDisk;
this.currentSessionId = sessionId;
this.manifestProvider = manifestProvider;
- if (isSameSession) {
+ if (isSameActiveSession) {
return;
}
this.checkpointGeneration++;
this.dirtySinceCheckpoint = false;
+ this.strokesSinceCheckpoint = 0;
if (this.idleCheckpointTimer) {
clearTimeout(this.idleCheckpointTimer);
this.idleCheckpointTimer = null;
}
+ if (this.layerMutationDebounceTimer) {
+ clearTimeout(this.layerMutationDebounceTimer);
+ this.layerMutationDebounceTimer = null;
+ }
if (!isTauriEnvironment()) return;
@@ -453,11 +566,38 @@ class RecoveryService {
sessionId,
manifestJson,
});
+ if (this.currentSessionId === sessionId) {
+ this.sessionInitializedOnDisk = true;
+ }
} catch (err) {
console.warn('[RecoveryService] Failed to init session in Rust backend:', err);
}
}
+ /**
+ * Notifies the recovery service when a native DX12 raster stroke commits so raster-only
+ * drawing sessions trigger idle and periodic recovery checkpoints even without layer mutations.
+ */
+ public notifyNativeStrokeCommitted(sessionId?: string | null): void {
+ // Keep drawing active across rapid native sketching bursts for the idle grace window so
+ // checkpoints, timelapse captures, and scratch-disk walks never fire mid-sketching.
+ this.notifyNativeStrokeEnd();
+
+ const activeId = sessionId || this.currentSessionId;
+ if (!activeId || !isTauriEnvironment()) return;
+
+ this.dirtySinceCheckpoint = true;
+ this.dirtySeq++;
+ this.strokesSinceCheckpoint++;
+
+ if (!this.isDrawingActive && this.strokesSinceCheckpoint >= CHECKPOINT_STROKE_THRESHOLD) {
+ this.strokesSinceCheckpoint = 0;
+ void this.triggerCheckpoint(activeId);
+ } else if (!this.isDrawingActive) {
+ this.resetIdleCheckpointTimer(activeId);
+ }
+ }
+
private async dispatchWalEntryAsync(
sessionId: string,
entryType: number,
@@ -502,7 +642,7 @@ class RecoveryService {
const gen = this.checkpointGeneration;
- if (vectorDelta && vectorDelta.after && vectorDelta.after.length > 0) {
+ if (vectorDelta && Array.isArray(vectorDelta.after)) {
const afterStrokes = vectorDelta.after;
this.enqueueWalTask(async () => {
if (this.checkpointGeneration !== gen) return;
@@ -522,6 +662,7 @@ class RecoveryService {
}
this.dirtySinceCheckpoint = true;
+ this.dirtySeq++;
this.resetIdleCheckpointTimer(activeId);
}
@@ -579,6 +720,7 @@ class RecoveryService {
);
this.dirtySinceCheckpoint = true;
+ this.dirtySeq++;
this.resetIdleCheckpointTimer(activeId);
}
@@ -609,10 +751,15 @@ class RecoveryService {
}
this.isCheckpointing = true;
+ const capturedDirtySeq = this.dirtySeq;
if (this.idleCheckpointTimer) {
clearTimeout(this.idleCheckpointTimer);
this.idleCheckpointTimer = null;
}
+ if (this.layerMutationDebounceTimer) {
+ clearTimeout(this.layerMutationDebounceTimer);
+ this.layerMutationDebounceTimer = null;
+ }
try {
await this.walQueue;
@@ -626,7 +773,13 @@ class RecoveryService {
: null;
const manifestJson = safeManifest ? JSON.stringify(safeManifest) : undefined;
await nativeRecoveryCheckpoint(activeId, activeId, manifestJson);
- this.dirtySinceCheckpoint = false;
+ this.checkpointGeneration++;
+ this.sessionInitializedOnDisk = true;
+ if (this.dirtySeq === capturedDirtySeq) {
+ this.dirtySinceCheckpoint = false;
+ } else {
+ this.resetIdleCheckpointTimer(activeId);
+ }
}
} catch (err) {
console.warn('[RecoveryService] Checkpoint failed:', err);
@@ -652,6 +805,10 @@ class RecoveryService {
this.layerMutationDebounceTimer = null;
}
this.dirtySinceCheckpoint = false;
+ this.strokesSinceCheckpoint = 0;
+ if (this.currentSessionId === activeId) {
+ this.sessionInitializedOnDisk = false;
+ }
if (isTauriEnvironment()) {
try {
diff --git a/src/stores/index.ts b/src/stores/index.ts
index 78cf178..3ca9ac6 100644
--- a/src/stores/index.ts
+++ b/src/stores/index.ts
@@ -59,6 +59,12 @@ export type { AutoActionStoreState } from './useAutoActionStore';
export { useUpdaterStore, updaterStoreActions } from './useUpdaterStore';
export type { UpdaterStoreState, UpdaterStatus } from './useUpdaterStore';
+export {
+ useNativeDiagnostics,
+ getNativeDiagnosticsSnapshot,
+ resetNativeDiagnosticsStore,
+} from './nativeDiagnosticsStore';
+
export {
useColorSetsStore,
colorSetsStoreActions,
diff --git a/src/stores/nativeDiagnosticsStore.ts b/src/stores/nativeDiagnosticsStore.ts
new file mode 100644
index 0000000..3addbfa
--- /dev/null
+++ b/src/stores/nativeDiagnosticsStore.ts
@@ -0,0 +1,95 @@
+import { useSyncExternalStore } from 'react';
+import {
+ getNativeDiagnostics,
+ isNativeCanvasActive,
+ NativeEngineDiagnostics,
+ subscribeNativeCanvasActive,
+ subscribeNativeDiagnostics,
+} from '../utils/nativeEngineBridge';
+
+type Listener = () => void;
+
+let currentDiagnostics: NativeEngineDiagnostics | null = null;
+const listeners = new Set<Listener>();
+let unsubDiag: (() => void) | null = null;
+let unsubActive: (() => void) | null = null;
+let generation = 0;
+
+function emitChange(): void {
+ for (const listener of listeners) {
+ listener();
+ }
+}
+
+function attachNativeSubscriptions(): void {
+ if (unsubDiag !== null) return;
+ const gen = ++generation;
+
+ const fetchInitial = () => {
+ if (!isNativeCanvasActive()) return;
+ void getNativeDiagnostics().then((diag) => {
+ if (gen !== generation || !diag || listeners.size === 0) return;
+ currentDiagnostics = diag;
+ emitChange();
+ });
+ };
+
+ unsubDiag = subscribeNativeDiagnostics((diag) => {
+ currentDiagnostics = diag;
+ emitChange();
+ });
+
+ unsubActive = subscribeNativeCanvasActive((active) => {
+ if (active) {
+ fetchInitial();
+ } else if (currentDiagnostics !== null) {
+ currentDiagnostics = null;
+ emitChange();
+ }
+ });
+
+ fetchInitial();
+}
+
+function detachNativeSubscriptions(): void {
+ generation++;
+ unsubDiag?.();
+ unsubDiag = null;
+ unsubActive?.();
+ unsubActive = null;
+}
+
+function subscribe(listener: Listener): () => void {
+ listeners.add(listener);
+ if (listeners.size === 1) {
+ attachNativeSubscriptions();
+ }
+ return () => {
+ listeners.delete(listener);
+ if (listeners.size === 0) {
+ detachNativeSubscriptions();
+ }
+ };
+}
+
+export function getNativeDiagnosticsSnapshot(): NativeEngineDiagnostics | null {
+ return currentDiagnostics;
+}
+
+/**
+ * Isolated external-store hook consumed ONLY by the `NativeGpuPerfHud` leaf component.
+ * Keeps 4 Hz `native-engine://diagnostics` updates completely out of `CanvasArea` React state
+ * and unsubscribes automatically whenever the perf HUD is unmounted.
+ */
+export function useNativeDiagnostics(): NativeEngineDiagnostics | null {
+ return useSyncExternalStore(subscribe, getNativeDiagnosticsSnapshot, () => null);
+}
+
+/**
+ * Resets cached diagnostics and tears down active listeners (for deterministic unit tests).
+ */
+export function resetNativeDiagnosticsStore(): void {
+ detachNativeSubscriptions();
+ listeners.clear();
+ currentDiagnostics = null;
+}
diff --git a/src/stores/useAutoActionStore.ts b/src/stores/useAutoActionStore.ts
index 545d71b..ac9f0a8 100644
--- a/src/stores/useAutoActionStore.ts
+++ b/src/stores/useAutoActionStore.ts
@@ -18,12 +18,13 @@ export interface AutoActionStoreState {
}
const createInitialAutoActionState = (): AutoActionStoreState => {
- const sets = loadAutoActionSets();
+ const rawSets = loadAutoActionSets();
+ const sets = Array.isArray(rawSets) ? rawSets : [];
const activeSet = sets[0];
return {
sets,
activeSetId: activeSet?.id ?? 'set-manga-default',
- selectedActionId: activeSet?.actions[0]?.id ?? null,
+ selectedActionId: Array.isArray(activeSet?.actions) ? (activeSet.actions[0]?.id ?? null) : null,
isRecording: false,
recordingActionId: null,
isPlaying: false,
@@ -43,7 +44,7 @@ export const autoActionStoreActions = {
if (!found) return;
useAutoActionStore.setState({
activeSetId: setId,
- selectedActionId: found.actions[0]?.id ?? null,
+ selectedActionId: Array.isArray(found.actions) ? (found.actions[0]?.id ?? null) : null,
});
},
@@ -69,18 +70,24 @@ export const autoActionStoreActions = {
createAction(name?: string, setId?: string): AutoAction {
const state = useAutoActionStore.getState();
const targetSetId = setId ?? state.activeSetId;
- const targetSet = state.sets.find((s) => s.id === targetSetId) ?? state.sets[0];
- const cleanName =
- name?.trim() || `Auto Action ${(targetSet?.actions.length ?? 0) + 1}`;
+ let targetSet = state.sets.find((s) => s.id === targetSetId) ?? state.sets[0];
+ if (!targetSet) {
+ targetSet = autoActionStoreActions.createSet('Default Actions');
+ }
+ const existingActions = Array.isArray(targetSet.actions) ? targetSet.actions : [];
+ const cleanName = name?.trim() || `Auto Action ${existingActions.length + 1}`;
const action: AutoAction = {
id: `action-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`,
name: cleanName,
steps: [],
createdAt: Date.now(),
};
+ const resolvedSetId = targetSet.id;
useAutoActionStore.setState((prev) => {
const sets = prev.sets.map((s) =>
- s.id === targetSet.id ? { ...s, actions: [...s.actions, action] } : s
+ s.id === resolvedSetId
+ ? { ...s, actions: [...(Array.isArray(s.actions) ? s.actions : []), action] }
+ : s
);
persist(sets);
return { sets, selectedActionId: action.id };
@@ -92,7 +99,7 @@ export const autoActionStoreActions = {
useAutoActionStore.setState((prev) => {
const sets = prev.sets.map((s) => ({
...s,
- actions: s.actions.filter((a) => a.id !== actionId),
+ actions: (Array.isArray(s.actions) ? s.actions : []).filter((a) => a.id !== actionId),
}));
persist(sets);
const isRecTarget = prev.recordingActionId === actionId;
@@ -138,8 +145,10 @@ export const autoActionStoreActions = {
useAutoActionStore.setState((prev) => {
const sets = prev.sets.map((s) => ({
...s,
- actions: s.actions.map((a) =>
- a.id === prev.recordingActionId ? { ...a, steps: [...a.steps, step] } : a
+ actions: (Array.isArray(s.actions) ? s.actions : []).map((a) =>
+ a.id === prev.recordingActionId
+ ? { ...a, steps: [...(Array.isArray(a.steps) ? a.steps : []), step] }
+ : a
),
}));
persist(sets);
@@ -151,11 +160,11 @@ export const autoActionStoreActions = {
useAutoActionStore.setState((prev) => {
const sets = prev.sets.map((s) => ({
...s,
- actions: s.actions.map((a) =>
+ actions: (Array.isArray(s.actions) ? s.actions : []).map((a) =>
a.id === actionId
? {
...a,
- steps: a.steps.map((st) =>
+ steps: (Array.isArray(a.steps) ? a.steps : []).map((st) =>
st.id === stepId ? { ...st, enabled: st.enabled === false } : st
),
}
@@ -171,9 +180,12 @@ export const autoActionStoreActions = {
useAutoActionStore.setState((prev) => {
const sets = prev.sets.map((s) => ({
...s,
- actions: s.actions.map((a) =>
+ actions: (Array.isArray(s.actions) ? s.actions : []).map((a) =>
a.id === actionId
- ? { ...a, steps: a.steps.filter((st) => st.id !== stepId) }
+ ? {
+ ...a,
+ steps: (Array.isArray(a.steps) ? a.steps : []).filter((st) => st.id !== stepId),
+ }
: a
),
}));
@@ -183,11 +195,12 @@ export const autoActionStoreActions = {
},
replaceSets(sets: AutoActionSet[]): void {
- persist(sets);
+ const safeSets = Array.isArray(sets) ? sets : [];
+ persist(safeSets);
useAutoActionStore.setState({
- sets,
- activeSetId: sets[0]?.id ?? '',
- selectedActionId: sets[0]?.actions[0]?.id ?? null,
+ sets: safeSets,
+ activeSetId: safeSets[0]?.id ?? '',
+ selectedActionId: Array.isArray(safeSets[0]?.actions) ? (safeSets[0].actions[0]?.id ?? null) : null,
isRecording: false,
recordingActionId: null,
});
diff --git a/src/stores/useColorSetsStore.ts b/src/stores/useColorSetsStore.ts
index c0dc123..3a8a165 100644
--- a/src/stores/useColorSetsStore.ts
+++ b/src/stores/useColorSetsStore.ts
@@ -286,9 +286,10 @@ function sanitizeColorSets(raw: unknown): ColorSet[] {
export function createInitialColorSetsState(): ColorSetsStoreState {
const defaults = createDefaultColorSets();
+ const fallbackSetId = defaults[0]?.id ?? 'set-atelier-neutrals';
const fallback: ColorSetsStoreState = {
sets: defaults,
- activeSetId: defaults[0].id,
+ activeSetId: fallbackSetId,
setsColumns: 6,
historyColumns: 6,
showInlineSlidersBelowWheel: false,
@@ -298,13 +299,13 @@ export function createInitialColorSetsState(): ColorSetsStoreState {
const raw = safeLocalStorageGetItem(COLOR_SETS_STORAGE_KEY);
if (!raw) return fallback;
const parsed = JSON.parse(raw) as Record<string, unknown>;
- if (!parsed || typeof parsed !== 'object') return fallback;
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return fallback;
const sets = sanitizeColorSets(parsed.sets);
const activeSetId =
typeof parsed.activeSetId === 'string' && sets.some((s) => s.id === parsed.activeSetId)
? parsed.activeSetId
- : sets[0].id;
+ : (sets[0]?.id ?? fallbackSetId);
return {
sets,
@@ -552,7 +553,7 @@ export const colorSetsStoreActions = {
const nextSets = state.sets.filter((s) => s.id !== setId);
const nextActiveId =
state.activeSetId === setId
- ? nextSets[Math.min(idx, nextSets.length - 1)].id
+ ? (nextSets[Math.min(idx, nextSets.length - 1)]?.id ?? '')
: state.activeSetId;
useColorSetsStore.setState({
sets: nextSets,
diff --git a/src/stores/useSubToolGroupStore.ts b/src/stores/useSubToolGroupStore.ts
index eb14582..c6de80e 100644
--- a/src/stores/useSubToolGroupStore.ts
+++ b/src/stores/useSubToolGroupStore.ts
@@ -81,8 +81,9 @@ function stripBrushFromCustomGroups(
): CustomSubToolGroup[] {
return groups.map((g) => {
if (g.id === keepGroupId) return g;
- const filtered = g.brushIds.filter((id) => id !== normBrushId);
- if (filtered.length === g.brushIds.length) return g;
+ const brushIds = Array.isArray(g.brushIds) ? g.brushIds : [];
+ const filtered = brushIds.filter((id) => id !== normBrushId);
+ if (filtered.length === brushIds.length) return g;
return {
...g,
brushIds: filtered,
@@ -297,9 +298,10 @@ export const subToolGroupStoreActions = {
const nextBuiltinOrders = stripBrushFromBuiltinOrders(state.builtinGroupOrders, norm);
const nextGroups = state.groups.map((g) => {
- const without = g.brushIds.filter((id) => id !== norm);
+ const brushIds = Array.isArray(g.brushIds) ? g.brushIds : [];
+ const without = brushIds.filter((id) => id !== norm);
if (g.id !== targetGroupId) {
- if (without.length === g.brushIds.length) return g;
+ if (without.length === brushIds.length) return g;
return {
...g,
brushIds: without,
@@ -374,7 +376,7 @@ export const subToolGroupStoreActions = {
// Case 2: Custom group
const targetGroup = state.groups.find((g) => g.id === groupId);
- if (!targetGroup) return;
+ if (!targetGroup || !Array.isArray(targetGroup.brushIds)) return;
const origFromIdx = targetGroup.brushIds.indexOf(fromId);
const origToIdx = targetGroup.brushIds.indexOf(toId);
if (origToIdx < 0) return;
@@ -406,8 +408,9 @@ export const subToolGroupStoreActions = {
let changed = false;
const nextGroups = prev.groups.map((g) => {
- const filtered = g.brushIds.filter((id) => id !== norm && id !== presetId);
- if (filtered.length === g.brushIds.length) return g;
+ const brushIds = Array.isArray(g.brushIds) ? g.brushIds : [];
+ const filtered = brushIds.filter((id) => id !== norm && id !== presetId);
+ if (filtered.length === brushIds.length) return g;
changed = true;
return {
...g,
@@ -449,7 +452,7 @@ export const subToolGroupStoreActions = {
const norm = normalizeBrushIdForGroup(presetId);
if (!norm) return;
const state = useSubToolGroupStore.getState();
- const owner = state.groups.find((g) => g.brushIds.includes(norm));
+ const owner = state.groups.find((g) => Array.isArray(g.brushIds) && g.brushIds.includes(norm));
if (!owner || owner.lastActiveBrushId === norm) return;
useSubToolGroupStore.setState({
groups: state.groups.map((g) =>
diff --git a/src/stores/useSubViewStore.ts b/src/stores/useSubViewStore.ts
index 40f45b3..9b04e53 100644
--- a/src/stores/useSubViewStore.ts
+++ b/src/stores/useSubViewStore.ts
@@ -136,18 +136,26 @@ function isSafeImageSrc(src: unknown): src is string {
return false;
}
+let cachedSubViewDbPromise: Promise<IDBDatabase> | null = null;
+let cachedSubViewIdbFactory: IDBFactory | null = null;
+
function openSubViewDB(): Promise<IDBDatabase> {
- return new Promise((resolve, reject) => {
- const idb =
- typeof indexedDB !== 'undefined'
- ? indexedDB
- : typeof window !== 'undefined'
- ? window.indexedDB
- : undefined;
- if (!idb) {
- reject(new Error('IndexedDB is not available'));
- return;
- }
+ const idb =
+ typeof indexedDB !== 'undefined'
+ ? indexedDB
+ : typeof window !== 'undefined'
+ ? window.indexedDB
+ : undefined;
+ if (!idb) {
+ cachedSubViewDbPromise = null;
+ cachedSubViewIdbFactory = null;
+ return Promise.reject(new Error('IndexedDB is not available'));
+ }
+ if (cachedSubViewDbPromise && cachedSubViewIdbFactory === idb) {
+ return cachedSubViewDbPromise;
+ }
+ cachedSubViewIdbFactory = idb;
+ cachedSubViewDbPromise = new Promise<IDBDatabase>((resolve, reject) => {
const req = idb.open(SUB_VIEW_DB_NAME, SUB_VIEW_DB_VERSION);
req.onupgradeneeded = (e) => {
const db = (e.target as IDBOpenDBRequest).result;
@@ -155,9 +163,26 @@ function openSubViewDB(): Promise<IDBDatabase> {
db.createObjectStore(SUB_VIEW_IMAGE_STORE, { keyPath: 'id' });
}
};
- req.onsuccess = () => resolve(req.result);
- req.onerror = () => reject(req.error);
+ req.onsuccess = () => {
+ const db = req.result;
+ db.onclose = () => {
+ cachedSubViewDbPromise = null;
+ cachedSubViewIdbFactory = null;
+ };
+ db.onversionchange = () => {
+ db.close();
+ cachedSubViewDbPromise = null;
+ cachedSubViewIdbFactory = null;
+ };
+ resolve(db);
+ };
+ req.onerror = () => {
+ cachedSubViewDbPromise = null;
+ cachedSubViewIdbFactory = null;
+ reject(req.error);
+ };
});
+ return cachedSubViewDbPromise;
}
export async function saveSubViewImageToIdb(id: string, src: string): Promise<void> {
@@ -170,6 +195,7 @@ export async function saveSubViewImageToIdb(id: string, src: string): Promise<vo
req.onerror = () => reject(req.error);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
+ tx.onabort = () => reject(tx.error ?? new Error('IndexedDB transaction aborted'));
});
} catch (err) {
handleIndexedDbError(err, 'References image');
@@ -185,6 +211,7 @@ export async function deleteSubViewImageFromIdb(id: string): Promise<void> {
tx.objectStore(SUB_VIEW_IMAGE_STORE).delete(id);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
+ tx.onabort = () => reject(tx.error ?? new Error('IndexedDB transaction aborted'));
});
} catch {
// Ignore delete failures when IDB is unavailable
@@ -199,6 +226,7 @@ export async function clearSubViewImagesFromIdb(): Promise<void> {
tx.objectStore(SUB_VIEW_IMAGE_STORE).clear();
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
+ tx.onabort = () => reject(tx.error ?? new Error('IndexedDB transaction aborted'));
});
} catch {
// Ignore clear failures when IDB is unavailable
diff --git a/src/stores/useToolStore.ts b/src/stores/useToolStore.ts
index b7093cb..07fb62a 100644
--- a/src/stores/useToolStore.ts
+++ b/src/stores/useToolStore.ts
@@ -146,12 +146,13 @@ function persistRecentColors(colors: string[]): void {
}
function pushColorHistory(prev: string[], rawColor: string): { list: string[]; changed: boolean } {
+ const safePrev = Array.isArray(prev) ? prev.filter((c): c is string => typeof c === 'string') : [];
const normalized = normalizeHistoryHex(rawColor);
- if (!normalized) return { list: prev, changed: false };
- if (prev.length > 0 && prev[0].toLowerCase() === normalized) {
- return { list: prev, changed: false };
+ if (!normalized) return { list: safePrev, changed: false };
+ if (safePrev.length > 0 && safePrev[0].toLowerCase() === normalized) {
+ return { list: safePrev, changed: false };
}
- const filtered = prev.filter((c) => c.toLowerCase() !== normalized);
+ const filtered = safePrev.filter((c) => c.toLowerCase() !== normalized);
return {
list: [normalized, ...filtered].slice(0, MAX_COLOR_HISTORY),
changed: true,
@@ -195,7 +196,12 @@ function loadInitialLiquifySettings(): LiquifySettings {
try {
if (typeof localStorage !== 'undefined') {
const saved = localStorage.getItem('ink_studio_liquify_settings');
- if (saved) return { ...defaults, ...(JSON.parse(saved) as Partial<LiquifySettings>) };
+ if (saved) {
+ const parsed = JSON.parse(saved);
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
+ return { ...defaults, ...(parsed as Partial<LiquifySettings>) };
+ }
+ }
}
} catch {
// Ignore storage errors
@@ -207,7 +213,12 @@ function loadInitialShapeSettings(): ShapeSettings {
try {
if (typeof localStorage !== 'undefined') {
const saved = localStorage.getItem('ink_studio_shape_settings');
- if (saved) return { ...DEFAULT_SHAPE_SETTINGS, ...(JSON.parse(saved) as Partial<ShapeSettings>) };
+ if (saved) {
+ const parsed = JSON.parse(saved);
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
+ return { ...DEFAULT_SHAPE_SETTINGS, ...(parsed as Partial<ShapeSettings>) };
+ }
+ }
}
} catch {
// Ignore storage errors
@@ -231,15 +242,28 @@ function loadInitialGradientSettings(): GradientSettings {
if (typeof localStorage !== 'undefined') {
const saved = localStorage.getItem('ink_studio_gradient_settings');
if (saved) {
- const parsed = JSON.parse(saved) as Partial<GradientSettings>;
- return {
- ...DEFAULT_GRADIENT_SETTINGS,
- ...parsed,
- stops:
- Array.isArray(parsed.stops) && parsed.stops.length >= 2
- ? parsed.stops
- : DEFAULT_GRADIENT_SETTINGS.stops.map((s) => ({ ...s })),
- };
+ const parsed = JSON.parse(saved);
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
+ const rec = parsed as Partial<GradientSettings>;
+ const validStops = Array.isArray(rec.stops)
+ ? rec.stops.filter(
+ (s): s is GradientSettings['stops'][number] =>
+ Boolean(s) &&
+ typeof s === 'object' &&
+ typeof s.color === 'string' &&
+ typeof s.offset === 'number' &&
+ Number.isFinite(s.offset)
+ )
+ : [];
+ return {
+ ...DEFAULT_GRADIENT_SETTINGS,
+ ...rec,
+ stops:
+ validStops.length >= 2
+ ? validStops
+ : DEFAULT_GRADIENT_SETTINGS.stops.map((s) => ({ ...s })),
+ };
+ }
}
}
} catch {
@@ -255,7 +279,12 @@ function loadInitialRetouchSettings(): RetouchSettings {
try {
if (typeof localStorage !== 'undefined') {
const saved = localStorage.getItem('ink_studio_retouch_settings');
- if (saved) return { ...DEFAULT_RETOUCH_SETTINGS, ...(JSON.parse(saved) as Partial<RetouchSettings>) };
+ if (saved) {
+ const parsed = JSON.parse(saved);
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
+ return { ...DEFAULT_RETOUCH_SETTINGS, ...(parsed as Partial<RetouchSettings>) };
+ }
+ }
}
} catch {
// Ignore storage errors
@@ -267,7 +296,12 @@ function loadInitialPenSettings(): PenToolSettings {
try {
if (typeof localStorage !== 'undefined') {
const saved = localStorage.getItem('ink_studio_pen_settings');
- if (saved) return { ...DEFAULT_PEN_SETTINGS, ...(JSON.parse(saved) as Partial<PenToolSettings>) };
+ if (saved) {
+ const parsed = JSON.parse(saved);
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
+ return { ...DEFAULT_PEN_SETTINGS, ...(parsed as Partial<PenToolSettings>) };
+ }
+ }
}
} catch {
// Ignore storage errors
diff --git a/src/stores/useUiStore.ts b/src/stores/useUiStore.ts
index 9661466..e3d05c6 100644
--- a/src/stores/useUiStore.ts
+++ b/src/stores/useUiStore.ts
@@ -358,7 +358,7 @@ export const uiStoreActions = {
};
applyAppearanceToDocument(nextAppearance, {
themePreset: nextSettings.themePreset,
- legacyAccent: nextAppearance.accent,
+ legacyAccent: nextModernAccent,
});
useUiStore.setState({ appSettings: nextSettings });
if (options.persist !== false) {
@@ -384,7 +384,7 @@ export const uiStoreActions = {
};
applyAppearanceToDocument(nextAppearance, {
themePreset: nextSettings.themePreset,
- legacyAccent: nextAppearance.accent,
+ legacyAccent: nextModernAccent,
});
useUiStore.setState({ appSettings: nextSettings });
if (options.persist !== false) {
diff --git a/src/types/settings.ts b/src/types/settings.ts
index 2c98aad..ebde068 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -76,6 +76,7 @@ export function resolveModernAccentColor(accent: ModernAccentColor, customColor?
}
export function hexToRgb(hex: string): { r: number; g: number; b: number } | null {
+ if (typeof hex !== 'string') return null;
const clean = hex.replace('#', '').trim();
if (clean.length === 3) {
const r = parseInt(clean[0] + clean[0], 16);
@@ -477,7 +478,9 @@ export function loadAppSettings(): AppSettings {
const raw = localStorage.getItem(SETTINGS_KEY);
const storedNickname = localStorage.getItem(NICKNAME_STORAGE_KEY) || '';
if (raw) {
- const parsed = JSON.parse(raw);
+ const parsedRaw = JSON.parse(raw);
+ if (parsedRaw && typeof parsedRaw === 'object' && !Array.isArray(parsedRaw)) {
+ const parsed = parsedRaw as Record<string, any>;
const validLanguage: AppLanguage = sanitizeAppLanguage(parsed.language);
const validTheme: ThemePreset = 'modern';
const validAccent: ModernAccentColor = [
@@ -638,11 +641,33 @@ export function loadAppSettings(): AppSettings {
typeof parsed.collabTurnCredential === 'string' && !parsed.collabTurnCredential.includes('\0')
? parsed.collabTurnCredential.trim().slice(0, 256)
: DEFAULT_APP_SETTINGS.collabTurnCredential;
+ const validDefaultWidth: number =
+ typeof parsed.defaultWidth === 'number' && Number.isFinite(parsed.defaultWidth) && parsed.defaultWidth >= 1
+ ? Math.round(parsed.defaultWidth)
+ : DEFAULT_APP_SETTINGS.defaultWidth;
+ const validDefaultHeight: number =
+ typeof parsed.defaultHeight === 'number' && Number.isFinite(parsed.defaultHeight) && parsed.defaultHeight >= 1
+ ? Math.round(parsed.defaultHeight)
+ : DEFAULT_APP_SETTINGS.defaultHeight;
+ const validDefaultDpi: number =
+ typeof parsed.defaultDpi === 'number' && Number.isFinite(parsed.defaultDpi) && parsed.defaultDpi >= 1
+ ? Math.round(parsed.defaultDpi)
+ : DEFAULT_APP_SETTINGS.defaultDpi;
+ const validDefaultColorMode: CanvasColorMode =
+ parsed.defaultColorMode === 'color' ||
+ parsed.defaultColorMode === 'grayscale' ||
+ parsed.defaultColorMode === 'monochrome'
+ ? parsed.defaultColorMode
+ : DEFAULT_APP_SETTINGS.defaultColorMode;
+ const validDefaultBgColor: string =
+ typeof parsed.defaultBgColor === 'string' && parsed.defaultBgColor.trim().length > 0
+ ? parsed.defaultBgColor
+ : DEFAULT_APP_SETTINGS.defaultBgColor;
return {
...DEFAULT_APP_SETTINGS,
...parsed,
- userName: parsed.userName !== undefined ? parsed.userName : storedNickname,
- hasPromptedName: parsed.hasPromptedName !== undefined ? parsed.hasPromptedName : true,
+ userName: typeof parsed.userName === 'string' ? parsed.userName : storedNickname,
+ hasPromptedName: typeof parsed.hasPromptedName === 'boolean' ? parsed.hasPromptedName : true,
language: validLanguage,
themePreset: validTheme,
modernAccent: validAccent,
@@ -650,6 +675,11 @@ export function loadAppSettings(): AppSettings {
uiTone: validTone,
appearance: validAppearance,
interfaceScale: validInterfaceScale,
+ defaultWidth: validDefaultWidth,
+ defaultHeight: validDefaultHeight,
+ defaultDpi: validDefaultDpi,
+ defaultColorMode: validDefaultColorMode,
+ defaultBgColor: validDefaultBgColor,
quickShapeEnabled: validQuickShapeEnabled,
maxHistorySteps: validMaxHistorySteps,
collabSignalingUrl: validCollabSignalingUrl,
@@ -681,6 +711,7 @@ export function loadAppSettings(): AppSettings {
modifierKeys: sanitizeModifierKeys(parsed.modifierKeys),
pressureCurve: sanitizePressureCurve(parsed.pressureCurve),
};
+ }
} else if (storedNickname) {
return {
...DEFAULT_APP_SETTINGS,
diff --git a/src/utils/__tests__/ipcContractsRegression.test.ts b/src/utils/__tests__/ipcContractsRegression.test.ts
new file mode 100644
index 0000000..82c8a40
--- /dev/null
+++ b/src/utils/__tests__/ipcContractsRegression.test.ts
@@ -0,0 +1,333 @@
+import { describe, it, expect } from 'vitest';
+import {
+ buildNativeBrushConfigPayload,
+ getHistorySnapshotEntries,
+ type NativeHistoryStateSnapshot,
+ type NativeTransformSessionSnapshot,
+} from '../nativeEngineBridge';
+import { nativeTransformSnapshotToSession } from '../../hooks/drawing/useSelectionTools';
+import {
+ createDefaultGradientMesh,
+ DEFAULT_GRADIENT_SETTINGS,
+ toNativeFilterSpec,
+ toNativeGradientParams,
+ toNativeTonalSpec,
+} from '../toolConfigs';
+import {
+ computeBatchDeleteLayers,
+ computeMergeFolderLayers,
+} from '../../hooks/layerManager/layerTreeOps';
+import { importAutoActionSetsJson } from '../autoActionEngine';
+import { parseLegacySoraV1Json } from '../legacySoraMigrator';
+import type { BrushSettings, LayerItem } from '../../types/editor';
+
+describe('IPC contracts and bug-audit regression suite', () => {
+ describe('HistoryStateSnapshot entries vs items contract (App.tsx crash fix)', () => {
+ it('extracts Rust-serialized entries without throwing', () => {
+ const rustSnap: NativeHistoryStateSnapshot = {
+ entries: [
+ {
+ id: 'h-0',
+ type: 'initial',
+ label: 'New Canvas',
+ timestamp: 1700000000000,
+ timeFormatted: '12:00:00',
+ thumbnailUrl: '',
+ },
+ {
+ id: 'h-1',
+ type: 'brush',
+ label: 'Brush Stroke',
+ timestamp: 1700000005000,
+ timeFormatted: '12:00:05',
+ thumbnailUrl: '',
+ },
+ ],
+ index: 1,
+ canUndo: true,
+ canRedo: false,
+ };
+ const entries = getHistorySnapshotEntries(rustSnap);
+ expect(entries).toHaveLength(2);
+ expect(entries[0]?.label).toBe('New Canvas');
+ expect(entries[1]?.id).toBe('h-1');
+ });
+
+ it('falls back to legacy items or empty array safely on malformed snapshots', () => {
+ const legacy = {
+ items: [
+ {
+ id: 'h-legacy',
+ type: 'brush',
+ label: 'Legacy Step',
+ timestamp: 1,
+ timeFormatted: '00:00:01',
+ thumbnailUrl: '',
+ },
+ ],
+ index: 0,
+ canUndo: false,
+ canRedo: false,
+ } as unknown as NativeHistoryStateSnapshot;
+ expect(getHistorySnapshotEntries(legacy)).toHaveLength(1);
+ expect(getHistorySnapshotEntries(null)).toEqual([]);
+ expect(getHistorySnapshotEntries(undefined)).toEqual([]);
+ expect(getHistorySnapshotEntries({} as NativeHistoryStateSnapshot)).toEqual([]);
+ });
+ });
+
+ describe('TransformSessionSnapshot Rust <-> TS schema alignment', () => {
+ it('hydrates exact Rust TransformSessionSnapshot JSON including cell-to-vertex mesh stride and cage state', () => {
+ // Exact wire shape emitted by crates/ink-engine/src/tools/transform.rs
+ const rustSnap: NativeTransformSessionSnapshot = {
+ active: true,
+ docId: 'doc-1',
+ mode: 'mesh',
+ showMesh: true,
+ targetLayerIds: ['layer-1', 'layer-2'],
+ sourceBounds: { x: 100, y: 50, width: 200, height: 100 },
+ affine: {
+ x: 110,
+ y: 60,
+ width: 240,
+ height: 120,
+ rotation: 0.25,
+ skewX: 0.1,
+ skewY: -0.05,
+ flipX: true,
+ flipY: false,
+ },
+ corners: [
+ { x: 100, y: 50 },
+ { x: 300, y: 50 },
+ { x: 300, y: 150 },
+ { x: 100, y: 150 },
+ ],
+ mesh: {
+ // 2x2 cells => 3x3 = 9 vertices
+ cols: 2,
+ rows: 2,
+ points: [
+ { x: 100, y: 50 },
+ { x: 200, y: 50 },
+ { x: 300, y: 50 },
+ { x: 100, y: 100 },
+ { x: 215, y: 105 },
+ { x: 300, y: 100 },
+ { x: 100, y: 150 },
+ { x: 200, y: 150 },
+ { x: 300, y: 150 },
+ ],
+ },
+ puppet: {
+ pins: [
+ { id: 'p1', restX: 120, restY: 80, x: 140, y: 90, rotation: 0, depth: 0 },
+ ],
+ meshVertices: [],
+ meshTriangles: [],
+ },
+ cage: {
+ points: [
+ { x: 100, y: 50 },
+ { x: 300, y: 50 },
+ { x: 200, y: 150 },
+ ],
+ restPoints: [
+ { x: 100, y: 50 },
+ { x: 300, y: 50 },
+ { x: 200, y: 150 },
+ ],
+ closed: true,
+ },
+ };
+
+ const session = nativeTransformSnapshotToSession(rustSnap, 'fallback', false);
+ expect(session.active).toBe(true);
+ expect(session.layerId).toBe('layer-1');
+ expect(session.layerIds).toEqual(['layer-1', 'layer-2']);
+ expect(session.bounds).toEqual({ x: 100, y: 50, width: 200, height: 100 });
+ expect(session.x).toBe(110);
+ expect(session.y).toBe(60);
+ expect(session.width).toBe(240);
+ expect(session.height).toBe(120);
+ expect(session.flipH).toBe(true);
+ expect(session.flipV).toBe(false);
+ // 2 cells -> 3 vertices per axis
+ expect(session.meshCols).toBe(3);
+ expect(session.meshRows).toBe(3);
+ expect(session.meshPoints).toHaveLength(3);
+ expect(session.meshPoints?.[1]?.[1]).toEqual({ x: 215, y: 105 });
+ expect(session.cage?.phase).toBe('deform');
+ expect(session.cage?.points).toHaveLength(3);
+ expect(session.puppet?.pins).toHaveLength(1);
+ });
+ });
+
+ describe('Gradient mesh cell count & dragged node UV mapping', () => {
+ it('emits cell counts (cols-1, rows-1) and non-uniform UVs for dragged nodes', () => {
+ const bounds = { x: 0, y: 0, width: 400, height: 200 };
+ const mesh = createDefaultGradientMesh(bounds, 3, 3, '#ff0000', '#0000ff');
+ // Drag center node (index 4) to (300, 150) => u = 0.75, v = 0.75
+ mesh.nodes[4] = { ...mesh.nodes[4], x: 300, y: 150 };
+
+ const params = toNativeGradientParams({
+ settings: { ...DEFAULT_GRADIENT_SETTINGS, type: 'mesh' },
+ start: { x: 0, y: 0 },
+ end: { x: 400, y: 200 },
+ primaryColor: '#ff0000',
+ secondaryColor: '#0000ff',
+ mesh,
+ });
+
+ expect(params.mesh).toBeDefined();
+ expect(params.mesh?.cols).toBe(2);
+ expect(params.mesh?.rows).toBe(2);
+ expect(params.mesh?.nodes).toHaveLength(9);
+ expect(params.mesh?.nodes[4]?.u).toBeCloseTo(0.75, 4);
+ expect(params.mesh?.nodes[4]?.v).toBeCloseTo(0.75, 4);
+ });
+ });
+
+ describe('Filter & Tonal spec sanitization', () => {
+ it('clamps binarization threshold to u8 and film-grain seed to u32', () => {
+ const tonal = toNativeTonalSpec('binarization', { threshold: 999 });
+ expect(tonal).toEqual({ kind: 'binarization', threshold: 255 });
+
+ const tonalNeg = toNativeTonalSpec('binarization', { threshold: -50 });
+ expect(tonalNeg).toEqual({ kind: 'binarization', threshold: 0 });
+
+ const level = toNativeTonalSpec('level-correction', {
+ inputMin: 12,
+ inputMax: 240,
+ gamma: 1.25,
+ outputMin: 5,
+ outputMax: 250,
+ });
+ expect(level).toEqual({
+ kind: 'level-correction',
+ inBlack: 12,
+ inWhite: 240,
+ gamma: 1.25,
+ outBlack: 5,
+ outWhite: 250,
+ });
+
+ const filter = toNativeFilterSpec('film-grain', {
+ intensity: 25,
+ size: 1.5,
+ monochromatic: true,
+ seed: -42,
+ });
+ expect(filter.kind).toBe('film-grain');
+ if (filter.kind === 'film-grain') {
+ expect(filter.seed).toBeGreaterThanOrEqual(0);
+ expect(Number.isInteger(filter.seed)).toBe(true);
+ }
+ });
+ });
+
+ describe('Brush config naturalPaint.penetrationCurve sanitization', () => {
+ it('converts array penetrationCurve into a finite scalar for Rust f32 deserialization', async () => {
+ const brushSettings = {
+ size: 20,
+ opacity: 1,
+ flow: 1,
+ hardness: 0.9,
+ spacing: 0.1,
+ naturalPaint: {
+ enabled: true,
+ penetrationCurve: [0, 0.25, 0.5, 0.75, 1] as unknown as number,
+ },
+ } as unknown as BrushSettings;
+
+ const payload = await buildNativeBrushConfigPayload(
+ 'brush',
+ brushSettings,
+ '#112233',
+ '#ffffff'
+ );
+ const np = payload.naturalPaint as Record<string, unknown>;
+ expect(typeof np.penetrationCurve).toBe('number');
+ expect(Number.isFinite(np.penetrationCurve)).toBe(true);
+ });
+ });
+
+ describe('Layer tree ops: mask metadata preservation & batch delete reparenting', () => {
+ it('preserves hasMask on merged folder raster layer even without maskCanvas', () => {
+ const layers: LayerItem[] = [
+ {
+ id: 'folder-1',
+ name: 'Group',
+ type: 'folder',
+ visible: true,
+ opacity: 0.8,
+ blendMode: 'pass-through',
+ locked: false,
+ collapsed: false,
+ parentId: null,
+ hasMask: true,
+ maskEnabled: true,
+ maskLinked: true,
+ },
+ {
+ id: 'child-1',
+ name: 'Ink',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ collapsed: false,
+ parentId: 'folder-1',
+ },
+ ];
+
+ const merged = computeMergeFolderLayers(layers, 'folder-1', 'merged-1');
+ expect(merged).not.toBeNull();
+ const mergedLayer = merged!.nextLayers.find((l) => l.id === 'merged-1');
+ expect(mergedLayer?.hasMask).toBe(true);
+ expect(mergedLayer?.blendMode).toBe('normal');
+ });
+
+ it('reparents preserved raster child to null when its parent folder is deleted in batch delete', () => {
+ const layers: LayerItem[] = [
+ {
+ id: 'folder-1',
+ name: 'Folder',
+ type: 'folder',
+ visible: true,
+ opacity: 1,
+ blendMode: 'pass-through',
+ locked: false,
+ collapsed: false,
+ parentId: null,
+ },
+ {
+ id: 'raster-only',
+ name: 'Only Raster',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ collapsed: false,
+ parentId: 'folder-1',
+ },
+ ];
+
+ const res = computeBatchDeleteLayers(layers, ['folder-1', 'raster-only'], 'raster-only');
+ expect(res.nextLayers).toHaveLength(1);
+ expect(res.nextLayers[0]?.id).toBe('raster-only');
+ expect(res.nextLayers[0]?.parentId).toBeNull();
+ });
+ });
+
+ describe('Malformed JSON safety in importers', () => {
+ it('throws descriptive errors instead of raw SyntaxError on corrupt JSON', () => {
+ expect(() => importAutoActionSetsJson('{corrupt')).toThrow('Invalid Auto Actions JSON format');
+ expect(() => parseLegacySoraV1Json('{corrupt')).toThrow(
+ 'Invalid legacy .sora project payload: malformed JSON'
+ );
+ });
+ });
+});
diff --git a/src/utils/__tests__/nativePerformanceRegressions.test.tsx b/src/utils/__tests__/nativePerformanceRegressions.test.tsx
new file mode 100644
index 0000000..98effda
--- /dev/null
+++ b/src/utils/__tests__/nativePerformanceRegressions.test.tsx
@@ -0,0 +1,941 @@
+import { act, useRef } from 'react';
+import { createRoot, Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { BrushSettings, CanvasDimensions, DocumentTab, LayerItem } from '../../types/editor';
+import type { CanvasAreaProps } from '../../components/canvasArea/types';
+import {
+ documentStoreActions,
+ resetNativeDiagnosticsStore,
+ uiStoreActions,
+ useDocumentStore,
+ useToolStore,
+ useUpdaterStore,
+ useWorkspaceStore,
+} from '../../stores';
+import { recoveryService } from '../../services/recoveryService';
+import { globalTimelapseManager } from '../timelapseEngine';
+
+const mockBridge = vi.hoisted(() => ({
+ nativeActive: true,
+ setNativeViewport: vi.fn(async () => {}),
+ setNativeOccludedRects: vi.fn(async () => {}),
+ setNativePolicy: vi.fn(async () => {}),
+ setNativeCamera: vi.fn(async () => {}),
+ setNativeDocument: vi.fn(async () => {}),
+ setNativeAppearance: vi.fn(async () => {}),
+ setNativeCursor: vi.fn(async () => {}),
+ setNativeMaskMode: vi.fn(async () => {}),
+ setNativeRulers: vi.fn(async () => {}),
+ setNativePressureCurve: vi.fn(async () => {}),
+ syncNativeFullBrushConfig: vi.fn(async () => {}),
+ requestNativeThumbnails: vi.fn(async () => {}),
+ renderNativeNavigatorPreview: vi.fn(async () => ({
+ width: 64,
+ height: 64,
+ rgba: new Uint8ClampedArray(64 * 64 * 4),
+ })),
+ diagnosticsListeners: new Set<(diag: any) => void>(),
+ pointerStatListeners: new Set<(stat: any) => void>(),
+ strokeCommittedListeners: new Set<(ev: any) => void>(),
+ historyListeners: new Set<(ev: any) => void>(),
+ thumbnailsListeners: new Set<(ev: any) => void>(),
+}));
+
+vi.mock('../nativeEngineBridge', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../nativeEngineBridge')>();
+ return {
+ ...actual,
+ isNativeCanvasActive: () => mockBridge.nativeActive,
+ initNativeEngineBridge: async () => mockBridge.nativeActive,
+ getNativeDiagnostics: async () => null,
+ canNativeEngineHandleBrush: () => true,
+ setNativeViewport: (...args: any[]) => (mockBridge.setNativeViewport as any)(...args),
+ setNativeOccludedRects: (...args: any[]) => (mockBridge.setNativeOccludedRects as any)(...args),
+ setNativePolicy: (...args: any[]) => (mockBridge.setNativePolicy as any)(...args),
+ setNativeCamera: (...args: any[]) => (mockBridge.setNativeCamera as any)(...args),
+ setNativeDocument: (...args: any[]) => (mockBridge.setNativeDocument as any)(...args),
+ setNativeAppearance: (...args: any[]) => (mockBridge.setNativeAppearance as any)(...args),
+ setNativeCursor: (...args: any[]) => (mockBridge.setNativeCursor as any)(...args),
+ setNativeMaskMode: (...args: any[]) => (mockBridge.setNativeMaskMode as any)(...args),
+ setNativeRulers: (...args: any[]) => (mockBridge.setNativeRulers as any)(...args),
+ setNativePressureCurve: (...args: any[]) => (mockBridge.setNativePressureCurve as any)(...args),
+ syncNativeFullBrushConfig: (...args: any[]) =>
+ (mockBridge.syncNativeFullBrushConfig as any)(...args),
+ requestNativeThumbnails: (...args: any[]) =>
+ (mockBridge.requestNativeThumbnails as any)(...args),
+ renderNativeNavigatorPreview: (...args: any[]) =>
+ (mockBridge.renderNativeNavigatorPreview as any)(...args),
+ nativeGetHistory: async () => null,
+ subscribeNativeCanvasActive: () => () => {},
+ subscribeNativeCamera: () => () => {},
+ subscribeNativeViewportInvalidated: () => () => {},
+ subscribeNativeDiagnostics: (cb: (diag: any) => void) => {
+ mockBridge.diagnosticsListeners.add(cb);
+ return () => mockBridge.diagnosticsListeners.delete(cb);
+ },
+ subscribeNativePointerStat: (cb: (stat: any) => void) => {
+ mockBridge.pointerStatListeners.add(cb);
+ return () => mockBridge.pointerStatListeners.delete(cb);
+ },
+ subscribeNativeStrokeCommitted: (cb: (ev: any) => void) => {
+ mockBridge.strokeCommittedListeners.add(cb);
+ return () => mockBridge.strokeCommittedListeners.delete(cb);
+ },
+ subscribeNativeHistory: (cb: (ev: any) => void) => {
+ mockBridge.historyListeners.add(cb);
+ return () => mockBridge.historyListeners.delete(cb);
+ },
+ subscribeNativeThumbnails: (cb: (ev: any) => void) => {
+ mockBridge.thumbnailsListeners.add(cb);
+ return () => mockBridge.thumbnailsListeners.delete(cb);
+ },
+ };
+});
+
+import {
+ classifyOccluderMutations,
+ useNativeEngineViewport,
+} from '../../hooks/useNativeEngineViewport';
+import { useDrawingHistory, UseDrawingHistoryResult } from '../../hooks/drawing/useDrawingHistory';
+import { CanvasViewportHud } from '../../components/canvasArea/CanvasViewportHud';
+import { NavigatorPanel } from '../../components/NavigatorPanel';
+import type { CanvasNavigationHandle } from '../../hooks/useCanvasNavigation';
+
+// Minimal DOM harness matching repo Vitest node environment
+interface MiniNode {
+ nodeType: number;
+ nodeName: string;
+ parentNode: MiniElement | null;
+ ownerDocument: MiniDocument;
+}
+
+class MiniTextNode implements MiniNode {
+ public nodeType = 3;
+ public nodeName = '#text';
+ public parentNode: MiniElement | null = null;
+ constructor(
+ public nodeValue: string,
+ public ownerDocument: MiniDocument
+ ) {}
+}
+
+class MiniCommentNode implements MiniNode {
+ public nodeType = 8;
+ public nodeName = '#comment';
+ public parentNode: MiniElement | null = null;
+ constructor(
+ public nodeValue: string,
+ public ownerDocument: MiniDocument
+ ) {}
+}
+
+function createMock2DCtx() {
+ return {
+ save: vi.fn(),
+ restore: vi.fn(),
+ setTransform: vi.fn(),
+ clearRect: vi.fn(),
+ fillRect: vi.fn(),
+ strokeRect: vi.fn(),
+ beginPath: vi.fn(),
+ moveTo: vi.fn(),
+ lineTo: vi.fn(),
+ closePath: vi.fn(),
+ fill: vi.fn(),
+ stroke: vi.fn(),
+ translate: vi.fn(),
+ rotate: vi.fn(),
+ scale: vi.fn(),
+ drawImage: vi.fn(),
+ createImageData: (w: number, h: number) => ({
+ data: new Uint8ClampedArray(w * h * 4),
+ width: w,
+ height: h,
+ }),
+ putImageData: vi.fn(),
+ imageSmoothingEnabled: true,
+ fillStyle: '',
+ strokeStyle: '',
+ lineWidth: 1,
+ globalAlpha: 1,
+ };
+}
+
+class MiniElement extends EventTarget implements MiniNode {
+ public nodeType = 1;
+ public nodeName: string;
+ public tagName: string;
+ public namespaceURI = 'http://www.w3.org/1999/xhtml';
+ public parentNode: MiniElement | null = null;
+ public childNodes: MiniNode[] = [];
+ public style: Record<string, string> = {};
+ public className = '';
+ public isContentEditable = false;
+ public width = 200;
+ public height = 120;
+ public clientWidth = 200;
+ public clientHeight = 120;
+ public rect = { left: 240, top: 64, right: 1200, bottom: 784, width: 960, height: 720 };
+ private attrs = new Map<string, string>();
+ private mockCtx: ReturnType<typeof createMock2DCtx> | null = null;
+
+ constructor(
+ tag: string,
+ public ownerDocument: MiniDocument
+ ) {
+ super();
+ this.nodeName = tag.toUpperCase();
+ this.tagName = tag.toUpperCase();
+ }
+
+ get firstChild(): MiniNode | null {
+ return this.childNodes[0] ?? null;
+ }
+
+ get textContent(): string {
+ return this.childNodes
+ .map((c) =>
+ c instanceof MiniTextNode ? c.nodeValue : c instanceof MiniElement ? c.textContent : ''
+ )
+ .join('');
+ }
+
+ set textContent(val: string) {
+ this.childNodes = val ? [new MiniTextNode(val, this.ownerDocument)] : [];
+ }
+
+ appendChild<T extends MiniNode>(child: T): T {
+ if (child.parentNode) child.parentNode.removeChild(child);
+ child.parentNode = this;
+ this.childNodes.push(child);
+ return child;
+ }
+
+ removeChild<T extends MiniNode>(child: T): T {
+ const idx = this.childNodes.indexOf(child);
+ if (idx >= 0) {
+ this.childNodes.splice(idx, 1);
+ child.parentNode = null;
+ }
+ return child;
+ }
+
+ insertBefore<T extends MiniNode>(newNode: T, refNode: MiniNode | null): T {
+ if (newNode.parentNode) newNode.parentNode.removeChild(newNode);
+ newNode.parentNode = this;
+ if (!refNode) {
+ this.childNodes.push(newNode);
+ return newNode;
+ }
+ const idx = this.childNodes.indexOf(refNode);
+ if (idx < 0) this.childNodes.push(newNode);
+ else this.childNodes.splice(idx, 0, newNode);
+ return newNode;
+ }
+
+ setAttribute(k: string, v: string) {
+ this.attrs.set(k, String(v));
+ }
+ getAttribute(k: string): string | null {
+ return this.attrs.get(k) ?? null;
+ }
+ removeAttribute(k: string) {
+ this.attrs.delete(k);
+ }
+ hasAttribute(k: string): boolean {
+ return this.attrs.has(k);
+ }
+ getBoundingClientRect() {
+ return { ...this.rect, x: this.rect.left, y: this.rect.top };
+ }
+ getContext(type: string) {
+ if (type === '2d') {
+ if (!this.mockCtx) this.mockCtx = createMock2DCtx();
+ return this.mockCtx;
+ }
+ return null;
+ }
+ findByAttr(attr: string, val: string): MiniElement | null {
+ if (this.getAttribute(attr) === val) return this;
+ for (const c of this.childNodes) {
+ if (c instanceof MiniElement) {
+ const hit = c.findByAttr(attr, val);
+ if (hit) return hit;
+ }
+ }
+ return null;
+ }
+}
+
+class MiniDocument extends EventTarget {
+ public nodeType = 9;
+ public nodeName = '#document';
+ public defaultView: any;
+ public body: MiniElement;
+ public documentElement: MiniElement;
+ public activeElement: MiniElement | null = null;
+ public hidden = false;
+ public occluders: MiniElement[] = [];
+
+ constructor(win: any) {
+ super();
+ this.defaultView = win;
+ this.documentElement = new MiniElement('html', this);
+ this.body = new MiniElement('body', this);
+ this.documentElement.appendChild(this.body);
+ }
+
+ createElement(tag: string) {
+ return new MiniElement(tag, this);
+ }
+ createElementNS(_ns: string, tag: string) {
+ return new MiniElement(tag, this);
+ }
+ createTextNode(text: string) {
+ return new MiniTextNode(text, this);
+ }
+ createComment(text: string) {
+ return new MiniCommentNode(text, this);
+ }
+ querySelectorAll(_selector: string) {
+ return this.occluders;
+ }
+}
+
+class RecordingMutationObserver {
+ public static instances: RecordingMutationObserver[] = [];
+ public observedTarget: Node | null = null;
+ public observedOptions: MutationObserverInit | null = null;
+ private cb: MutationCallback;
+ constructor(cb: MutationCallback) {
+ this.cb = cb;
+ RecordingMutationObserver.instances.push(this);
+ }
+ observe(target: Node, options?: MutationObserverInit) {
+ this.observedTarget = target;
+ this.observedOptions = options ?? null;
+ }
+ disconnect() {}
+ takeRecords(): MutationRecord[] {
+ return [];
+ }
+ emit(records: Partial<MutationRecord>[]) {
+ this.cb(records as MutationRecord[], this as unknown as MutationObserver);
+ }
+}
+
+function makeDoc(id: string): DocumentTab {
+ return {
+ id,
+ name: 'PerfTest',
+ isDirty: false,
+ dimensions: { width: 1024, height: 1024, dpi: 300 },
+ colorMode: 'color',
+ layers: [
+ {
+ id: 'layer-1',
+ name: 'Layer 1',
+ type: 'raster',
+ visible: true,
+ opacity: 100,
+ blendMode: 'normal',
+ locked: false,
+ alphaLocked: false,
+ clipped: false,
+ parentId: null,
+ },
+ ],
+ activeLayerId: 'layer-1',
+ };
+}
+
+function createMockNavHandle(): CanvasNavigationHandle {
+ const panRef = { current: { x: 400, y: 300 } };
+ const zoomRef = { current: 1 };
+ const rotationRef = { current: 0 };
+ const flipXRef = { current: false };
+ const flipYRef = { current: false };
+ return {
+ panRef,
+ zoomRef,
+ rotationRef,
+ flipXRef,
+ flipYRef,
+ getCameraState: () => ({
+ pan: { ...panRef.current },
+ zoom: zoomRef.current,
+ rotation: rotationRef.current,
+ flipX: flipXRef.current,
+ flipY: flipYRef.current,
+ }),
+ subscribeCamera: () => () => {},
+ setPanLive: vi.fn(),
+ setZoomLive: vi.fn(),
+ rotateBy: vi.fn(),
+ commitCameraState: vi.fn(),
+ };
+}
+
+describe('Native Engine Bridge Performance Regressions', () => {
+ let prevGlobals: Record<string, unknown>;
+ let miniWin: any;
+ let miniDoc: MiniDocument;
+ let hostEl: MiniElement;
+ let root: Root | null = null;
+ let pendingRafs: Map<number, FrameRequestCallback>;
+ let nextRafId: number;
+
+ const flushRaf = () => {
+ const callbacks = Array.from(pendingRafs.values());
+ pendingRafs.clear();
+ for (const cb of callbacks) cb(0);
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetNativeDiagnosticsStore();
+ recoveryService.setDrawingActive(false);
+ mockBridge.nativeActive = true;
+ mockBridge.diagnosticsListeners.clear();
+ mockBridge.pointerStatListeners.clear();
+ mockBridge.strokeCommittedListeners.clear();
+ mockBridge.historyListeners.clear();
+ mockBridge.thumbnailsListeners.clear();
+ RecordingMutationObserver.instances = [];
+ pendingRafs = new Map();
+ nextRafId = 1;
+
+ const g = globalThis as Record<string, unknown>;
+ prevGlobals = {
+ window: g.window,
+ document: g.document,
+ HTMLElement: g.HTMLElement,
+ HTMLIFrameElement: g.HTMLIFrameElement,
+ Element: g.Element,
+ Node: g.Node,
+ getComputedStyle: g.getComputedStyle,
+ MutationObserver: g.MutationObserver,
+ requestAnimationFrame: g.requestAnimationFrame,
+ cancelAnimationFrame: g.cancelAnimationFrame,
+ IS_REACT_ACT_ENVIRONMENT: g.IS_REACT_ACT_ENVIRONMENT,
+ };
+
+ const fakeGetComputedStyle = (el: MiniElement) => ({
+ display: el.style?.display ?? 'block',
+ visibility: el.style?.visibility ?? 'visible',
+ pointerEvents: el.style?.pointerEvents ?? 'auto',
+ opacity: el.style?.opacity ?? '1',
+ getPropertyValue: () => '#18181b',
+ });
+
+ const FakeIFrame = class HTMLIFrameElement {};
+ miniWin = Object.assign(new EventTarget(), {
+ devicePixelRatio: 1,
+ HTMLElement: MiniElement,
+ HTMLIFrameElement: FakeIFrame,
+ Element: MiniElement,
+ Node: MiniElement,
+ matchMedia: () => ({
+ matches: true,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ }),
+ getComputedStyle: fakeGetComputedStyle,
+ });
+ miniDoc = new MiniDocument(miniWin);
+ miniWin.document = miniDoc;
+ hostEl = miniDoc.createElement('div');
+ miniDoc.body.appendChild(hostEl);
+
+ g.window = miniWin;
+ g.document = miniDoc;
+ g.HTMLElement = MiniElement;
+ g.HTMLIFrameElement = FakeIFrame;
+ g.Element = MiniElement;
+ g.Node = MiniElement;
+ g.getComputedStyle = fakeGetComputedStyle;
+ g.MutationObserver = RecordingMutationObserver;
+ g.requestAnimationFrame = (cb: FrameRequestCallback) => {
+ const id = nextRafId++;
+ pendingRafs.set(id, cb);
+ return id;
+ };
+ g.cancelAnimationFrame = (id: number) => {
+ pendingRafs.delete(id);
+ };
+ g.IS_REACT_ACT_ENVIRONMENT = true;
+
+ uiStoreActions.setAppView('workspace');
+ uiStoreActions.setBrushStudioModalOpen(false);
+ useUpdaterStore.setState({ isModalOpen: false });
+ useWorkspaceStore.setState({ palettesHidden: false });
+ const doc = makeDoc('doc-perf-1');
+ documentStoreActions.setDocuments([doc]);
+ documentStoreActions.setActiveDocumentId(doc.id);
+ });
+
+ afterEach(async () => {
+ vi.useRealTimers();
+ recoveryService.setDrawingActive(false);
+ resetNativeDiagnosticsStore();
+ if (root) {
+ await act(async () => {
+ root?.unmount();
+ });
+ root = null;
+ }
+ const g = globalThis as Record<string, unknown>;
+ for (const [k, v] of Object.entries(prevGlobals)) {
+ if (v === undefined) delete g[k];
+ else g[k] = v;
+ }
+ });
+
+ it('1. emitting 10 native-engine://diagnostics events causes 0 re-renders of CanvasArea subtree while updating NativeGpuPerfHud leaf without data-native-occluder', () => {
+ const viewportEl = miniDoc.createElement('div');
+ const brushSettings: BrushSettings = { ...useToolStore.getState().brushSettings };
+ const layer = useDocumentStore.getState().documents[0].layers[0];
+ let canvasAreaRenderCount = 0;
+
+ function SimulatedCanvasArea() {
+ canvasAreaRenderCount += 1;
+ const vpRef = useRef<HTMLDivElement | null>(viewportEl as any);
+ const cursorRingRef = useRef<HTMLDivElement | null>(null);
+ const pointerStatRef = useRef<HTMLDivElement | null>(null);
+ const { nativeActive, onClearNativeCanvas } = useNativeEngineViewport({
+ viewportRef: vpRef,
+ dimensions: { width: 1024, height: 1024, dpi: 300 },
+ showCheckerboard: true,
+ hasOpenDocument: true,
+ tool: 'brush',
+ brushSettings,
+ primaryColor: '#111111',
+ activeLayer: layer,
+ isMaskMode: false,
+ isSquare: false,
+ thicknessRatio: 1,
+ thicknessVertical: false,
+ tipAngleDeg: 0,
+ isResizingBrush: false,
+ isSpaceDown: false,
+ isPanning: false,
+ isRotating: false,
+ isZoomDragging: false,
+ isRotateModifier: false,
+ pan: { x: 0, y: 0 },
+ zoom: 1,
+ rotation: 0,
+ flipX: false,
+ flipY: false,
+ });
+
+ return (
+ <CanvasViewportHud
+ canvasProps={
+ {
+ viewportRef: vpRef,
+ dimensions: { width: 1024, height: 1024, dpi: 300 },
+ brushSettings,
+ onUpdateBrushSettings: () => {},
+ zoom: 1,
+ pan: { x: 0, y: 0 },
+ rotation: 0,
+ isSpaceDown: false,
+ isShiftDown: false,
+ isRotateModifier: false,
+ isPanning: false,
+ isRotating: false,
+ isHovering: false,
+ cursorPos: null,
+ onStartPan: () => {},
+ onStartRotate: () => {},
+ onPointerDown: () => {},
+ onPointerMove: () => {},
+ onPointerUp: () => {},
+ onPointerEnter: () => {},
+ onPointerLeave: () => {},
+ layers: [layer],
+ activeLayerId: layer.id,
+ } as unknown as CanvasAreaProps
+ }
+ cursorRingRef={cursorRingRef}
+ pointerStatRef={pointerStatRef}
+ livePan={{ x: 0, y: 0 }}
+ liveZoom={1}
+ liveRotation={0}
+ liveFlipX={false}
+ liveFlipY={false}
+ cursorWidth={20}
+ cursorHeight={20}
+ totalAngleDeg={0}
+ isCustomTip={false}
+ isSquare={false}
+ tipOutline={null}
+ isResizingBrush={false}
+ resizePreviewX={0}
+ resizePreviewY={0}
+ quickPalettePos={null}
+ setQuickPalettePos={() => {}}
+ nativeCanvasActive={nativeActive}
+ onClearNativeCanvas={onClearNativeCanvas}
+ />
+ );
+ }
+
+ root = createRoot(hostEl as any);
+ act(() => {
+ root!.render(<SimulatedCanvasArea />);
+ });
+
+ const rendersAfterMount = canvasAreaRenderCount;
+ expect(mockBridge.diagnosticsListeners.size).toBe(1);
+
+ const hudEl = hostEl.findByAttr('data-testid', 'native-gpu-perf-hud');
+ expect(hudEl).not.toBeNull();
+ // Perf HUD must NOT have data-native-occluder="true" so digit changes never trigger occlusion IPC
+ expect(hudEl!.getAttribute('data-native-occluder')).toBeNull();
+
+ // Emit 10 rapid 4 Hz diagnostics updates
+ act(() => {
+ for (let i = 1; i <= 10; i++) {
+ const diag = {
+ ready: true,
+ adapterName: 'RTX 4090',
+ backend: 'DX12',
+ presentMode: 'Immediate',
+ fps: 120 + i,
+ frameTimeMs: 4.2,
+ inputToPresentMs: 2.1 + i * 0.1,
+ swapchainWidth: 1920,
+ swapchainHeight: 1080,
+ docWidth: 1024,
+ docHeight: 1024,
+ activeStrokeDabs: i * 10,
+ totalFramesRendered: i * 30,
+ deviceLostRecoveries: 0,
+ maxFrameLatency: 1,
+ compositionMode: 'DirectComposition',
+ isIdle: false,
+ };
+ for (const cb of mockBridge.diagnosticsListeners) cb(diag);
+ }
+ });
+
+ // Zero CanvasArea re-renders across all 10 diagnostics events!
+ expect(canvasAreaRenderCount).toBe(rendersAfterMount);
+ // Leaf HUD reflects the latest 10th diagnostics snapshot directly
+ expect(hudEl!.textContent).toContain('130 FPS');
+ expect(hudEl!.textContent).toContain('I2P 3.10ms');
+ });
+
+ it('2. mutating StatusBar pressure bar style.width does NOT trigger setNativeOccludedRects', () => {
+ const viewportEl = miniDoc.createElement('div');
+ const brushSettings: BrushSettings = { ...useToolStore.getState().brushSettings };
+ const layer = useDocumentStore.getState().documents[0].layers[0];
+
+ function ViewportHarness() {
+ const vpRef = useRef<HTMLDivElement | null>(viewportEl as any);
+ useNativeEngineViewport({
+ viewportRef: vpRef,
+ dimensions: { width: 1024, height: 1024, dpi: 300 },
+ showCheckerboard: true,
+ hasOpenDocument: true,
+ tool: 'brush',
+ brushSettings,
+ primaryColor: '#111111',
+ activeLayer: layer,
+ isMaskMode: false,
+ isSquare: false,
+ thicknessRatio: 1,
+ thicknessVertical: false,
+ tipAngleDeg: 0,
+ isResizingBrush: false,
+ isSpaceDown: false,
+ isPanning: false,
+ isRotating: false,
+ isZoomDragging: false,
+ isRotateModifier: false,
+ pan: { x: 0, y: 0 },
+ zoom: 1,
+ rotation: 0,
+ flipX: false,
+ flipY: false,
+ });
+ return null;
+ }
+
+ root = createRoot(hostEl as any);
+ act(() => {
+ root!.render(<ViewportHarness />);
+ });
+
+ // Find the body MutationObserver registered by useNativeEngineViewport
+ const bodyObserver = RecordingMutationObserver.instances.find(
+ (inst) => inst.observedTarget === (miniDoc.body as unknown as Node)
+ );
+ expect(bodyObserver).toBeDefined();
+ // `style` MUST NOT be observed across document.body
+ expect(bodyObserver!.observedOptions?.attributeFilter).not.toContain('style');
+
+ const statusBar = miniDoc.createElement('footer');
+ statusBar.setAttribute('data-testid', 'status-bar');
+ statusBar.setAttribute('data-chrome-bar', 'status');
+ const pressureBar = miniDoc.createElement('div');
+ statusBar.appendChild(pressureBar);
+ miniDoc.body.appendChild(statusBar);
+
+ const floatingPill = miniDoc.createElement('div');
+ floatingPill.setAttribute('data-testid', 'floating-brush-pill');
+ floatingPill.setAttribute('data-native-occluder', 'true');
+ floatingPill.rect = { left: 300, top: 300, right: 420, bottom: 360, width: 120, height: 60 };
+ miniDoc.occluders = [floatingPill];
+ mockBridge.setNativeOccludedRects.mockClear();
+
+ // Simulate 30 Hz StatusBar pressure bar style.width + class mutations
+ act(() => {
+ for (let i = 0; i < 30; i++) {
+ pressureBar.style.width = `${i * 3}%`;
+ bodyObserver!.emit([
+ {
+ type: 'attributes',
+ attributeName: 'style',
+ target: pressureBar as unknown as Node,
+ },
+ {
+ type: 'attributes',
+ attributeName: 'class',
+ target: pressureBar as unknown as Node,
+ },
+ ]);
+ }
+ flushRaf();
+ });
+
+ expect(mockBridge.setNativeOccludedRects).not.toHaveBeenCalled();
+
+ // Direct classifier verification for StatusBar vs modal opening
+ expect(
+ classifyOccluderMutations([
+ {
+ type: 'attributes',
+ attributeName: 'style',
+ target: pressureBar as unknown as Node,
+ } as MutationRecord,
+ ])
+ ).toEqual({ shouldScan: false, isModalEvent: false });
+
+ const modalEl = miniDoc.createElement('div');
+ modalEl.setAttribute('role', 'dialog');
+ modalEl.setAttribute('aria-modal', 'true');
+ modalEl.rect = { left: 400, top: 200, right: 800, bottom: 600, width: 400, height: 400 };
+ miniDoc.occluders = [floatingPill, modalEl];
+
+ // Even during an active stroke, opening a modal MUST trigger an immediate occluder rescan
+ recoveryService.setDrawingActive(true);
+ act(() => {
+ bodyObserver!.emit([
+ {
+ type: 'childList',
+ target: miniDoc.body as unknown as Node,
+ addedNodes: [modalEl] as unknown as NodeList,
+ removedNodes: [] as unknown as NodeList,
+ },
+ ]);
+ flushRaf();
+ });
+
+ expect(mockBridge.setNativeOccludedRects).toHaveBeenCalledTimes(1);
+ expect(mockBridge.setNativeOccludedRects).toHaveBeenLastCalledWith([
+ { x: 300, y: 300, width: 120, height: 60 },
+ { x: 400, y: 200, width: 400, height: 400 },
+ ]);
+ });
+
+ it('3. rapid StrokeCommitted + HistoryChanged + ThumbnailsUpdated trigger at most 1 debounced Navigator preview and 1 history state update', () => {
+ vi.useFakeTimers();
+ const activeDoc = useDocumentStore.getState().documents[0];
+ const dims: CanvasDimensions = activeDoc.dimensions;
+ const nav = createMockNavHandle();
+ const vpRef = { current: { clientWidth: 800, clientHeight: 600 } as HTMLDivElement };
+
+ let historyRenderCount = 0;
+ let latestHistory: UseDrawingHistoryResult | null = null;
+
+ function CombinedHarness({ layers }: { layers: LayerItem[] }) {
+ historyRenderCount += 1;
+ const dimsRef = useRef(dims);
+ const layerIdRef = useRef('layer-1');
+ const colorModeRef = useRef(activeDoc.colorMode);
+ const layersRef = useRef<LayerItem[] | undefined>(layers);
+ const isDrawingRef = useRef(false);
+ const lastStrokeEndRef = useRef(null);
+ const abortRef = useRef(() => {});
+ const maskThumbRef = useRef<((id: string) => void) | undefined>(undefined);
+
+ latestHistory = useDrawingHistory({
+ activeSessionId: activeDoc.id,
+ activeLayerId: 'layer-1',
+ activeLayerLocked: false,
+ dimensions: dims,
+ dimensionsRef: dimsRef,
+ activeLayerIdRef: layerIdRef,
+ colorModeRef,
+ layersRef,
+ onUpdateLayerThumbnail: () => {},
+ onUpdateMaskThumbnailRef: maskThumbRef,
+ isDrawingRef,
+ lastStrokeEndRef,
+ abortActiveStrokeRef: abortRef,
+ });
+
+ return (
+ <NavigatorPanel
+ viewportRef={vpRef}
+ navigation={nav}
+ dimensions={dims}
+ layers={layers}
+ showCheckerboard={false}
+ zoom={1}
+ rotation={0}
+ flipX={false}
+ flipY={false}
+ onZoomIn={() => {}}
+ onZoomOut={() => {}}
+ onFitToScreen={() => {}}
+ onZoomActualSize={() => {}}
+ onRotateLeft={() => {}}
+ onRotateRight={() => {}}
+ onResetRotation={() => {}}
+ onToggleFlipHorizontal={() => {}}
+ onToggleFlipVertical={() => {}}
+ throttleMs={200}
+ />
+ );
+ }
+
+ root = createRoot(hostEl as any);
+ act(() => {
+ root!.render(<CombinedHarness layers={activeDoc.layers} />);
+ });
+
+ // Initial mount rendered Navigator preview once
+ expect(mockBridge.renderNativeNavigatorPreview).toHaveBeenCalledTimes(1);
+ mockBridge.renderNativeNavigatorPreview.mockClear();
+ const rendersBeforeStroke = historyRenderCount;
+
+ const historySnap = {
+ entries: [
+ {
+ id: 'stroke-42',
+ type: 'stroke',
+ label: 'Brush Stroke',
+ timestamp: 1000,
+ timeFormatted: '00:01',
+ thumbnailUrl: '',
+ },
+ ],
+ index: 0,
+ canUndo: true,
+ canRedo: false,
+ };
+
+ // Emit StrokeCommitted + duplicate HistoryChanged + ThumbnailsUpdated in rapid succession
+ act(() => {
+ for (const cb of mockBridge.strokeCommittedListeners) {
+ cb({
+ docId: activeDoc.id,
+ layerId: 'layer-1',
+ entryId: 'stroke-42',
+ dirtyRect: { x: 0, y: 0, width: 64, height: 64 },
+ history: historySnap,
+ points: [],
+ });
+ }
+ for (const cb of mockBridge.historyListeners) {
+ cb({ docId: activeDoc.id, history: historySnap });
+ }
+ for (const cb of mockBridge.thumbnailsListeners) {
+ cb({ docId: activeDoc.id, updates: [{ layerId: 'layer-1', thumbnailUrl: 'data:image/png;base64,AA==' }] });
+ }
+ });
+
+ // History state updated EXACTLY ONCE despite receiving both StrokeCommitted and HistoryChanged!
+ expect(historyRenderCount - rendersBeforeStroke).toBe(1);
+ expect(latestHistory!.historyList).toHaveLength(1);
+ expect(latestHistory!.canUndo).toBe(true);
+
+ // Updating layer thumbnailUrl prop must NOT trigger another Navigator GPU readback
+ act(() => {
+ root!.render(
+ <CombinedHarness
+ layers={[{ ...activeDoc.layers[0], thumbnailUrl: 'data:image/png;base64,BBBB' }]}
+ />
+ );
+ });
+
+ // During the 1500ms native stroke grace window, Navigator GPU readback is deferred
+ expect(recoveryService.getIsDrawingActive()).toBe(true);
+ expect(mockBridge.renderNativeNavigatorPreview).toHaveBeenCalledTimes(0);
+
+ // Advance past the 1500ms grace window + 200ms trailing debounce -> AT MOST 1 Navigator readback!
+ act(() => {
+ vi.advanceTimersByTime(1800);
+ });
+ expect(mockBridge.renderNativeNavigatorPreview).toHaveBeenCalledTimes(1);
+ });
+
+ it('4. native stroke activity sets recoveryService.getIsDrawingActive() === true and suppresses checkpoints & timelapse until idle', async () => {
+ vi.useFakeTimers();
+ (miniWin as any).__TAURI_INTERNALS__ = {};
+ const triggerCheckpointSpy = vi
+ .spyOn(recoveryService as any, 'triggerCheckpoint')
+ .mockResolvedValue(undefined);
+
+ const docId = 'doc-perf-guard';
+ await recoveryService.initSession(docId, () => null);
+ globalTimelapseManager.setRecording(docId, true, 'GuardTest');
+
+ const captureContext = {
+ isDrawingActive: () => recoveryService.getIsDrawingActive(),
+ documentName: 'GuardTest',
+ };
+
+ // Simulate rapid hatching burst of 30 native strokes (exceeding CHECKPOINT_STROKE_THRESHOLD=25),
+ // each 200ms apart (well within the 1500ms idle grace window).
+ for (let i = 0; i < 30; i++) {
+ recoveryService.notifyNativeStrokeStart();
+ expect(recoveryService.getIsDrawingActive()).toBe(true);
+
+ // Timelapse capture mid-stroke MUST be deferred (returns false)
+ const captured = await globalTimelapseManager.captureKeyframe(
+ docId,
+ useDocumentStore.getState().documents[0].layers,
+ { width: 1024, height: 1024, dpi: 300 },
+ false,
+ captureContext
+ );
+ expect(captured).toBe(false);
+
+ recoveryService.notifyNativeStrokeCommitted(docId);
+ expect(recoveryService.getIsDrawingActive()).toBe(true);
+ vi.advanceTimersByTime(200);
+ }
+
+ // Even after 30 strokes, ZERO recovery checkpoints fired mid-sketching!
+ expect(recoveryService.getIsDrawingActive()).toBe(true);
+ expect(triggerCheckpointSpy).not.toHaveBeenCalled();
+
+ // Wait 1400ms (still inside 1500ms grace window from last stroke: 200ms already passed -> 1300ms left)
+ vi.advanceTimersByTime(1200);
+ expect(recoveryService.getIsDrawingActive()).toBe(true);
+ expect(triggerCheckpointSpy).not.toHaveBeenCalled();
+
+ // Pass the 1500ms idle grace window -> drawing becomes idle & deferred checkpoint flushes!
+ vi.advanceTimersByTime(200);
+ expect(recoveryService.getIsDrawingActive()).toBe(false);
+ expect(triggerCheckpointSpy).toHaveBeenCalledTimes(1);
+
+ await globalTimelapseManager.removeSession(docId);
+ triggerCheckpointSpy.mockRestore();
+ });
+});
diff --git a/src/utils/__tests__/nativeViewportAndStrokeSync.test.tsx b/src/utils/__tests__/nativeViewportAndStrokeSync.test.tsx
new file mode 100644
index 0000000..e34ec8f
--- /dev/null
+++ b/src/utils/__tests__/nativeViewportAndStrokeSync.test.tsx
@@ -0,0 +1,670 @@
+import { act, useRef } from 'react';
+import { createRoot, Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { BrushSettings, DocumentTab, LayerItem } from '../../types/editor';
+import {
+ documentStoreActions,
+ uiStoreActions,
+ useDocumentStore,
+ useToolStore,
+ useUpdaterStore,
+} from '../../stores';
+import { INTERFACE_SCALE_APPLIED_EVENT } from '../interfaceScale';
+
+const mockBridge = vi.hoisted(() => ({
+ nativeActive: true,
+ setNativeViewport: vi.fn(async () => {}),
+ setNativeOccludedRects: vi.fn(async () => {}),
+ setNativePolicy: vi.fn(async () => {}),
+ setNativeCamera: vi.fn(async () => {}),
+ setNativeDocument: vi.fn(async () => {}),
+ setNativeAppearance: vi.fn(async () => {}),
+ setNativeCursor: vi.fn(async () => {}),
+ setNativeMaskMode: vi.fn(async () => {}),
+ setNativeRulers: vi.fn(async () => {}),
+ setNativePressureCurve: vi.fn(async () => {}),
+ syncNativeFullBrushConfig: vi.fn(async () => {}),
+ requestNativeThumbnails: vi.fn(async () => {}),
+ nativeUndo: vi.fn(async (docId: string) => ({
+ doc: {
+ id: docId,
+ dimensions: { width: 1024, height: 1024, dpi: 300 },
+ layers: [],
+ activeLayerId: 'layer-1',
+ history: {
+ items: [{ id: 's1', type: 'stroke', label: 'Brush Stroke', timestamp: 1, timeFormatted: '00:00', thumbnailUrl: '' }],
+ currentIndex: -1,
+ canUndo: false,
+ canRedo: true,
+ },
+ },
+ layersChanged: false,
+ dimensionsChanged: false,
+ changedLayerIds: ['layer-1'],
+ })),
+ nativeRedo: vi.fn(async (docId: string) => ({
+ doc: {
+ id: docId,
+ dimensions: { width: 1024, height: 1024, dpi: 300 },
+ layers: [],
+ activeLayerId: 'layer-1',
+ history: {
+ items: [{ id: 's1', type: 'stroke', label: 'Brush Stroke', timestamp: 1, timeFormatted: '00:00', thumbnailUrl: '' }],
+ currentIndex: 0,
+ canUndo: true,
+ canRedo: false,
+ },
+ },
+ layersChanged: false,
+ dimensionsChanged: false,
+ changedLayerIds: ['layer-1'],
+ })),
+ viewportInvalidatedListeners: new Set<() => void>(),
+ strokeCommittedListeners: new Set<(ev: any) => void>(),
+ historyListeners: new Set<(ev: any) => void>(),
+}));
+
+vi.mock('../nativeEngineBridge', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../nativeEngineBridge')>();
+ return {
+ ...actual,
+ isNativeCanvasActive: () => mockBridge.nativeActive,
+ initNativeEngineBridge: async () => mockBridge.nativeActive,
+ getNativeDiagnostics: async () => null,
+ canNativeEngineHandleBrush: () => true,
+ setNativeViewport: (...args: any[]) => (mockBridge.setNativeViewport as any)(...args),
+ setNativeOccludedRects: (...args: any[]) => (mockBridge.setNativeOccludedRects as any)(...args),
+ setNativePolicy: (...args: any[]) => (mockBridge.setNativePolicy as any)(...args),
+ setNativeCamera: (...args: any[]) => (mockBridge.setNativeCamera as any)(...args),
+ setNativeDocument: (...args: any[]) => (mockBridge.setNativeDocument as any)(...args),
+ setNativeAppearance: (...args: any[]) => (mockBridge.setNativeAppearance as any)(...args),
+ setNativeCursor: (...args: any[]) => (mockBridge.setNativeCursor as any)(...args),
+ setNativeMaskMode: (...args: any[]) => (mockBridge.setNativeMaskMode as any)(...args),
+ setNativeRulers: (...args: any[]) => (mockBridge.setNativeRulers as any)(...args),
+ setNativePressureCurve: (...args: any[]) => (mockBridge.setNativePressureCurve as any)(...args),
+ syncNativeFullBrushConfig: (...args: any[]) =>
+ (mockBridge.syncNativeFullBrushConfig as any)(...args),
+ requestNativeThumbnails: (...args: any[]) =>
+ (mockBridge.requestNativeThumbnails as any)(...args),
+ nativeGetHistory: async () => null,
+ nativeUndo: (...args: any[]) => (mockBridge.nativeUndo as any)(...args),
+ nativeRedo: (...args: any[]) => (mockBridge.nativeRedo as any)(...args),
+ subscribeNativeCanvasActive: () => () => {},
+ subscribeNativeCamera: () => () => {},
+ subscribeNativeDiagnostics: () => () => {},
+ subscribeNativePointerStat: () => () => {},
+ subscribeNativeViewportInvalidated: (cb: () => void) => {
+ mockBridge.viewportInvalidatedListeners.add(cb);
+ return () => mockBridge.viewportInvalidatedListeners.delete(cb);
+ },
+ subscribeNativeStrokeCommitted: (cb: (ev: any) => void) => {
+ mockBridge.strokeCommittedListeners.add(cb);
+ return () => mockBridge.strokeCommittedListeners.delete(cb);
+ },
+ subscribeNativeHistory: (cb: (ev: any) => void) => {
+ mockBridge.historyListeners.add(cb);
+ return () => mockBridge.historyListeners.delete(cb);
+ },
+ };
+});
+
+import {
+ computePhysicalPixelRect,
+ useNativeEngineViewport,
+} from '../../hooks/useNativeEngineViewport';
+import {
+ useDrawingHistory,
+ UseDrawingHistoryResult,
+} from '../../hooks/drawing/useDrawingHistory';
+
+// Minimal DOM harness matching repo Vitest node environment
+interface MiniNode {
+ nodeType: number;
+ nodeName: string;
+ parentNode: MiniElement | null;
+ ownerDocument: MiniDocument;
+}
+
+class MiniTextNode implements MiniNode {
+ public nodeType = 3;
+ public nodeName = '#text';
+ public nodeValue: string;
+ public parentNode: MiniElement | null = null;
+ public ownerDocument: MiniDocument;
+ constructor(text: string, ownerDocument: MiniDocument) {
+ this.nodeValue = text;
+ this.ownerDocument = ownerDocument;
+ }
+}
+
+class MiniCommentNode implements MiniNode {
+ public nodeType = 8;
+ public nodeName = '#comment';
+ public nodeValue: string;
+ public parentNode: MiniElement | null = null;
+ public ownerDocument: MiniDocument;
+ constructor(text: string, ownerDocument: MiniDocument) {
+ this.nodeValue = text;
+ this.ownerDocument = ownerDocument;
+ }
+}
+
+class MiniElement extends EventTarget implements MiniNode {
+ public nodeType = 1;
+ public nodeName: string;
+ public tagName: string;
+ public namespaceURI = 'http://www.w3.org/1999/xhtml';
+ public ownerDocument: MiniDocument;
+ public parentNode: MiniElement | null = null;
+ public childNodes: MiniNode[] = [];
+ public style: Record<string, string> = {};
+ public className = '';
+ public isContentEditable = false;
+ public rect = { left: 240, top: 68, right: 1200, bottom: 800, width: 960, height: 732 };
+ private attrs = new Map<string, string>();
+
+ constructor(tag: string, ownerDocument: MiniDocument) {
+ super();
+ this.nodeName = tag.toUpperCase();
+ this.tagName = tag.toUpperCase();
+ this.ownerDocument = ownerDocument;
+ }
+
+ get firstChild(): MiniNode | null {
+ return this.childNodes[0] ?? null;
+ }
+
+ appendChild<T extends MiniNode>(child: T): T {
+ if (child.parentNode) child.parentNode.removeChild(child);
+ child.parentNode = this;
+ this.childNodes.push(child);
+ return child;
+ }
+
+ removeChild<T extends MiniNode>(child: T): T {
+ const idx = this.childNodes.indexOf(child);
+ if (idx >= 0) {
+ this.childNodes.splice(idx, 1);
+ child.parentNode = null;
+ }
+ return child;
+ }
+
+ insertBefore<T extends MiniNode>(newNode: T, refNode: MiniNode | null): T {
+ if (newNode.parentNode) newNode.parentNode.removeChild(newNode);
+ newNode.parentNode = this;
+ if (!refNode) {
+ this.childNodes.push(newNode);
+ return newNode;
+ }
+ const idx = this.childNodes.indexOf(refNode);
+ if (idx < 0) this.childNodes.push(newNode);
+ else this.childNodes.splice(idx, 0, newNode);
+ return newNode;
+ }
+
+ setAttribute(k: string, v: string) {
+ this.attrs.set(k, String(v));
+ }
+ getAttribute(k: string): string | null {
+ return this.attrs.get(k) ?? null;
+ }
+ removeAttribute(k: string) {
+ this.attrs.delete(k);
+ }
+ hasAttribute(k: string): boolean {
+ return this.attrs.has(k);
+ }
+ getBoundingClientRect() {
+ return { ...this.rect, x: this.rect.left, y: this.rect.top };
+ }
+}
+
+class MiniDocument extends EventTarget {
+ public nodeType = 9;
+ public nodeName = '#document';
+ public defaultView: any;
+ public body: MiniElement;
+ public documentElement: MiniElement;
+ public activeElement: MiniElement | null = null;
+ public occluders: MiniElement[] = [];
+
+ constructor(win: any) {
+ super();
+ this.defaultView = win;
+ this.documentElement = new MiniElement('html', this);
+ this.body = new MiniElement('body', this);
+ this.documentElement.appendChild(this.body);
+ }
+
+ createElement(tag: string) {
+ return new MiniElement(tag, this);
+ }
+ createElementNS(_ns: string, tag: string) {
+ return new MiniElement(tag, this);
+ }
+ createTextNode(text: string) {
+ return new MiniTextNode(text, this);
+ }
+ createComment(text: string) {
+ return new MiniCommentNode(text, this);
+ }
+ querySelectorAll(_selector: string) {
+ return this.occluders;
+ }
+}
+
+class MiniMutationObserver {
+ public static instances: MiniMutationObserver[] = [];
+ private cb: () => void;
+ constructor(cb: () => void) {
+ this.cb = cb;
+ MiniMutationObserver.instances.push(this);
+ }
+ observe() {}
+ disconnect() {}
+ trigger() {
+ this.cb();
+ }
+}
+
+function makeDoc(id: string): DocumentTab {
+ return {
+ id,
+ name: 'Untitled',
+ isDirty: false,
+ dimensions: { width: 1024, height: 1024, dpi: 300 },
+ colorMode: 'color',
+ layers: [
+ {
+ id: 'layer-1',
+ name: 'Layer 1',
+ type: 'raster',
+ visible: true,
+ opacity: 100,
+ blendMode: 'normal',
+ locked: false,
+ alphaLocked: false,
+ clipped: false,
+ parentId: null,
+ },
+ ],
+ activeLayerId: 'layer-1',
+ };
+}
+
+describe('DirectComposition physical-pixel alignment, occlusion & StrokeCommitted sync', () => {
+ let prevWindow: any;
+ let prevDocument: any;
+ let prevMutationObserver: any;
+ let prevRaf: any;
+ let prevCancelRaf: any;
+ let prevActEnv: any;
+ let prevHtmlElement: any;
+ let prevHtmlIFrameElement: any;
+ let prevElement: any;
+ let prevNode: any;
+ let prevGetComputedStyle: any;
+ let miniWin: any;
+ let miniDoc: MiniDocument;
+ let hostEl: MiniElement;
+ let root: Root | null = null;
+
+ let pendingRafs: Map<number, FrameRequestCallback>;
+ let nextRafId: number;
+ const flushRaf = () => {
+ const callbacks = Array.from(pendingRafs.values());
+ pendingRafs.clear();
+ for (const cb of callbacks) cb(0);
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockBridge.nativeActive = true;
+ mockBridge.viewportInvalidatedListeners.clear();
+ mockBridge.strokeCommittedListeners.clear();
+ mockBridge.historyListeners.clear();
+ MiniMutationObserver.instances = [];
+ pendingRafs = new Map();
+ nextRafId = 1;
+
+ prevWindow = (globalThis as any).window;
+ prevDocument = (globalThis as any).document;
+ prevMutationObserver = (globalThis as any).MutationObserver;
+ prevRaf = (globalThis as any).requestAnimationFrame;
+ prevCancelRaf = (globalThis as any).cancelAnimationFrame;
+ prevActEnv = (globalThis as any).IS_REACT_ACT_ENVIRONMENT;
+ prevHtmlElement = (globalThis as any).HTMLElement;
+ prevHtmlIFrameElement = (globalThis as any).HTMLIFrameElement;
+ prevElement = (globalThis as any).Element;
+ prevNode = (globalThis as any).Node;
+ prevGetComputedStyle = (globalThis as any).getComputedStyle;
+
+ const fakeGetComputedStyle = (el: MiniElement) => ({
+ display: el.style?.display ?? 'block',
+ visibility: el.style?.visibility ?? 'visible',
+ pointerEvents: el.style?.pointerEvents ?? 'auto',
+ opacity: el.style?.opacity ?? '1',
+ getPropertyValue: () => '#18181b',
+ });
+
+ const FakeIFrame = class HTMLIFrameElement {};
+ miniWin = Object.assign(new EventTarget(), {
+ devicePixelRatio: 1.25,
+ HTMLElement: MiniElement,
+ HTMLIFrameElement: FakeIFrame,
+ Element: MiniElement,
+ Node: MiniElement,
+ matchMedia: () => ({
+ matches: true,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ }),
+ getComputedStyle: fakeGetComputedStyle,
+ });
+ miniDoc = new MiniDocument(miniWin);
+ miniWin.document = miniDoc;
+ hostEl = miniDoc.createElement('div');
+ miniDoc.body.appendChild(hostEl);
+
+ (globalThis as any).window = miniWin;
+ (globalThis as any).document = miniDoc;
+ (globalThis as any).HTMLElement = MiniElement;
+ (globalThis as any).HTMLIFrameElement = FakeIFrame;
+ (globalThis as any).Element = MiniElement;
+ (globalThis as any).Node = MiniElement;
+ (globalThis as any).getComputedStyle = fakeGetComputedStyle;
+ (globalThis as any).MutationObserver = MiniMutationObserver;
+ (globalThis as any).requestAnimationFrame = (cb: FrameRequestCallback) => {
+ const id = nextRafId++;
+ pendingRafs.set(id, cb);
+ return id;
+ };
+ (globalThis as any).cancelAnimationFrame = (id: number) => {
+ pendingRafs.delete(id);
+ };
+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+ uiStoreActions.setAppView('workspace');
+ uiStoreActions.setBrushStudioModalOpen(false);
+ useUpdaterStore.setState({ isModalOpen: false });
+ const doc = makeDoc('doc-sync-1');
+ documentStoreActions.setDocuments([doc]);
+ documentStoreActions.setActiveDocumentId(doc.id);
+ });
+
+ afterEach(async () => {
+ if (root) {
+ await act(async () => {
+ root?.unmount();
+ });
+ root = null;
+ }
+ (globalThis as any).window = prevWindow;
+ (globalThis as any).document = prevDocument;
+ (globalThis as any).HTMLElement = prevHtmlElement;
+ (globalThis as any).HTMLIFrameElement = prevHtmlIFrameElement;
+ (globalThis as any).Element = prevElement;
+ (globalThis as any).Node = prevNode;
+ (globalThis as any).getComputedStyle = prevGetComputedStyle;
+ (globalThis as any).MutationObserver = prevMutationObserver;
+ (globalThis as any).requestAnimationFrame = prevRaf;
+ (globalThis as any).cancelAnimationFrame = prevCancelRaf;
+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = prevActEnv;
+ });
+
+ it('computes exact outward-covered physical pixels across DPR 1.0..2.0 and interfaceScale 0.85..1.25 with zero 1px seams', () => {
+ const osDprs = [1.0, 1.25, 1.5, 2.0];
+ const interfaceScales = [0.85, 0.9, 1.0, 1.15, 1.25];
+
+ // Exact integer physical bounds must never expand by +1px even under IEEE-754 float noise
+ expect(
+ computePhysicalPixelRect({ left: 240, top: 64, right: 1200, bottom: 784 }, 1.25)
+ ).toEqual({ xPx: 300, yPx: 80, widthPx: 1200, heightPx: 900 });
+ expect(
+ computePhysicalPixelRect({ left: 240, top: 64, right: 1200, bottom: 784 }, 1.5)
+ ).toEqual({ xPx: 360, yPx: 96, widthPx: 1440, heightPx: 1080 });
+ expect(
+ computePhysicalPixelRect({ left: 240.8, top: 64.0, right: 1200.0, bottom: 784.0 }, 1.25)
+ ).toEqual({ xPx: 301, yPx: 80, widthPx: 1199, heightPx: 900 });
+
+ // Minimize / collapsed viewport must yield 0x0 without negative dimensions
+ expect(computePhysicalPixelRect({ left: 0, top: 0, right: 0, bottom: 0 }, 1.5)).toEqual({
+ xPx: 0,
+ yPx: 0,
+ widthPx: 0,
+ heightPx: 0,
+ });
+
+ // Across every (osDpr, interfaceScale) pair, the physical box must completely cover the
+ // fractional CSS cutout (no 1px transparent border seam) with <= 1px overhang per edge.
+ const cssRect = { left: 241.33, top: 67.67, right: 1283.42, bottom: 811.79 };
+ for (const osDpr of osDprs) {
+ for (const scale of interfaceScales) {
+ const effDpr = osDpr * scale;
+ const phys = computePhysicalPixelRect(cssRect, effDpr);
+ expect(phys.xPx).toBeLessThanOrEqual(cssRect.left * effDpr + 1e-3);
+ expect(phys.yPx).toBeLessThanOrEqual(cssRect.top * effDpr + 1e-3);
+ expect(phys.xPx + phys.widthPx).toBeGreaterThanOrEqual(cssRect.right * effDpr - 1e-3);
+ expect(phys.yPx + phys.heightPx).toBeGreaterThanOrEqual(cssRect.bottom * effDpr - 1e-3);
+ expect(cssRect.left * effDpr - phys.xPx).toBeLessThan(1.0 + 1e-3);
+ expect(phys.xPx + phys.widthPx - cssRect.right * effDpr).toBeLessThan(1.0 + 1e-3);
+ }
+ }
+ });
+
+ it('syncs historyList, canUndo, and document isDirty (*) when Rust emits StrokeCommitted and during undo/redo', async () => {
+ let latest: UseDrawingHistoryResult | null = null;
+ const activeDoc = useDocumentStore.getState().documents[0];
+
+ function Harness() {
+ const dimsRef = useRef(activeDoc.dimensions);
+ const layerIdRef = useRef('layer-1');
+ const colorModeRef = useRef(activeDoc.colorMode);
+ const layersRef = useRef<LayerItem[] | undefined>(activeDoc.layers);
+ const isDrawingRef = useRef(false);
+ const lastStrokeEndRef = useRef(null);
+ const abortRef = useRef(() => {});
+ const maskThumbRef = useRef<((id: string) => void) | undefined>(undefined);
+
+ latest = useDrawingHistory({
+ activeSessionId: activeDoc.id,
+ activeLayerId: 'layer-1',
+ activeLayerLocked: false,
+ dimensions: activeDoc.dimensions,
+ dimensionsRef: dimsRef,
+ activeLayerIdRef: layerIdRef,
+ colorModeRef,
+ layersRef,
+ onUpdateLayerThumbnail: () => {},
+ onUpdateMaskThumbnailRef: maskThumbRef,
+ isDrawingRef,
+ lastStrokeEndRef,
+ abortActiveStrokeRef: abortRef,
+ });
+ return null;
+ }
+
+ root = createRoot(hostEl as any);
+ act(() => {
+ root!.render(<Harness />);
+ });
+
+ expect(useDocumentStore.getState().documents[0].isDirty).toBe(false);
+ expect(latest!.canUndo).toBe(false);
+
+ // Emit StrokeCommitted from Rust engine
+ act(() => {
+ for (const cb of mockBridge.strokeCommittedListeners) {
+ cb({
+ docId: activeDoc.id,
+ layerId: 'layer-1',
+ history: {
+ items: [{ id: 's1', type: 'stroke', label: 'Brush Stroke', timestamp: 123, timeFormatted: '00:00', thumbnailUrl: '' }],
+ currentIndex: 0,
+ canUndo: true,
+ canRedo: false,
+ },
+ });
+ }
+ });
+
+ expect(latest!.canUndo).toBe(true);
+ expect(latest!.canRedo).toBe(false);
+ expect(latest!.historyList).toHaveLength(1);
+ expect(latest!.historyList[0].label).toBe('Brush Stroke');
+ expect(useDocumentStore.getState().documents[0].isDirty).toBe(true);
+
+ // Reset dirty flag to verify Undo also marks document dirty and updates canUndo/canRedo
+ documentStoreActions.markDocumentDirty(activeDoc.id, false);
+ await act(async () => {
+ latest!.undo();
+ await Promise.resolve();
+ });
+ expect(mockBridge.nativeUndo).toHaveBeenCalledTimes(1);
+ expect(latest!.canUndo).toBe(false);
+ expect(latest!.canRedo).toBe(true);
+ expect(useDocumentStore.getState().documents[0].isDirty).toBe(true);
+
+ // Redo restores stroke history state
+ await act(async () => {
+ latest!.redo();
+ await Promise.resolve();
+ });
+ expect(mockBridge.nativeRedo).toHaveBeenCalledTimes(1);
+ expect(latest!.canUndo).toBe(true);
+ expect(latest!.canRedo).toBe(false);
+ });
+
+ it('hides DirectComposition on WelcomeScreen/no-doc, re-syncs on ViewportInvalidated & scale, and tracks modals/occluders', () => {
+ const viewportEl = miniDoc.createElement('div');
+ viewportEl.rect = { left: 240, top: 64, right: 1200, bottom: 784, width: 960, height: 720 };
+
+ const floatingPill = miniDoc.createElement('div');
+ floatingPill.setAttribute('data-testid', 'floating-brush-pill');
+ floatingPill.setAttribute('data-native-occluder', 'true');
+ floatingPill.rect = { left: 500, top: 700, right: 780, bottom: 756, width: 280, height: 56 };
+ miniDoc.occluders = [floatingPill];
+
+ const brushSettings: BrushSettings = { ...useToolStore.getState().brushSettings };
+ const layer = useDocumentStore.getState().documents[0].layers[0];
+
+ function ViewportHarness({ hasOpenDocument }: { hasOpenDocument: boolean }) {
+ const vpRef = useRef<HTMLDivElement | null>(viewportEl as any);
+ useNativeEngineViewport({
+ viewportRef: vpRef,
+ dimensions: { width: 1024, height: 1024, dpi: 300 },
+ showCheckerboard: true,
+ hasOpenDocument,
+ tool: 'brush',
+ brushSettings,
+ primaryColor: '#111111',
+ activeLayer: layer,
+ isMaskMode: false,
+ isSquare: false,
+ thicknessRatio: 1,
+ thicknessVertical: false,
+ tipAngleDeg: 0,
+ isResizingBrush: false,
+ isSpaceDown: false,
+ isPanning: false,
+ isRotating: false,
+ isZoomDragging: false,
+ isRotateModifier: false,
+ pan: { x: 0, y: 0 },
+ zoom: 1,
+ rotation: 0,
+ flipX: false,
+ flipY: false,
+ });
+ return null;
+ }
+
+ root = createRoot(hostEl as any);
+ act(() => {
+ root!.render(<ViewportHarness hasOpenDocument={true} />);
+ });
+
+ // Initial workspace mount activates transparent cutout and pushes exact physical rect + FloatingBrushPill occluder
+ expect(miniDoc.documentElement.getAttribute('data-native-canvas')).toBe('true');
+ expect(mockBridge.setNativeViewport).toHaveBeenLastCalledWith({
+ xPx: 300,
+ yPx: 80,
+ widthPx: 1200,
+ heightPx: 900,
+ dpr: 1.25,
+ visible: true,
+ });
+ expect(mockBridge.setNativeOccludedRects).toHaveBeenLastCalledWith([
+ { x: 625, y: 875, width: 350, height: 70 },
+ ]);
+
+ // WM_DPICHANGED / restore invalidation re-syncs even if CSS dimensions stay identical
+ mockBridge.setNativeViewport.mockClear();
+ miniWin.devicePixelRatio = 1.5;
+ act(() => {
+ for (const cb of mockBridge.viewportInvalidatedListeners) cb();
+ flushRaf();
+ });
+ expect(mockBridge.setNativeViewport).toHaveBeenLastCalledWith({
+ xPx: 360,
+ yPx: 96,
+ widthPx: 1440,
+ heightPx: 1080,
+ dpr: 1.5,
+ visible: true,
+ });
+
+ // Interface scale change event triggers fresh alignment push
+ mockBridge.setNativeViewport.mockClear();
+ miniWin.devicePixelRatio = 1.875; // 1.5 * 1.25 interfaceScale
+ act(() => {
+ miniWin.dispatchEvent(new Event(INTERFACE_SCALE_APPLIED_EVENT));
+ flushRaf();
+ });
+ expect(mockBridge.setNativeViewport).toHaveBeenLastCalledWith({
+ xPx: 450,
+ yPx: 120,
+ widthPx: 1800,
+ heightPx: 1350,
+ dpr: 1.875,
+ visible: true,
+ });
+
+ // Opening Brush Studio modal pauses native engine via modalOpen: true
+ mockBridge.setNativePolicy.mockClear();
+ act(() => {
+ uiStoreActions.setBrushStudioModalOpen(true);
+ });
+ expect(mockBridge.setNativePolicy).toHaveBeenLastCalledWith(
+ expect.objectContaining({ modalOpen: true })
+ );
+ act(() => {
+ uiStoreActions.setBrushStudioModalOpen(false);
+ });
+
+ // Switching to WelcomeScreen ('home') hides DirectComposition visual & removes cutout attribute
+ mockBridge.setNativeViewport.mockClear();
+ act(() => {
+ uiStoreActions.setAppView('home');
+ });
+ expect(miniDoc.documentElement.getAttribute('data-native-canvas')).toBeNull();
+ expect(mockBridge.setNativeViewport).toHaveBeenLastCalledWith(
+ expect.objectContaining({ widthPx: 0, heightPx: 0, visible: false })
+ );
+
+ // Returning to workspace restores visible: true; closing document hides again
+ act(() => {
+ uiStoreActions.setAppView('workspace');
+ });
+ expect(miniDoc.documentElement.getAttribute('data-native-canvas')).toBe('true');
+ mockBridge.setNativeViewport.mockClear();
+ act(() => {
+ root!.render(<ViewportHarness hasOpenDocument={false} />);
+ });
+ expect(miniDoc.documentElement.getAttribute('data-native-canvas')).toBeNull();
+ expect(mockBridge.setNativeViewport).toHaveBeenLastCalledWith(
+ expect.objectContaining({ widthPx: 0, heightPx: 0, visible: false })
+ );
+ });
+});
diff --git a/src/utils/__tests__/newCanvasCrashRegression.test.tsx b/src/utils/__tests__/newCanvasCrashRegression.test.tsx
new file mode 100644
index 0000000..6a1104b
--- /dev/null
+++ b/src/utils/__tests__/newCanvasCrashRegression.test.tsx
@@ -0,0 +1,1004 @@
+import React, { act } from 'react';
+import { createRoot, Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { CanvasArea } from '../../components/CanvasArea';
+import { SpeechBalloonOverlay } from '../../components/SpeechBalloonOverlay';
+import { DockGroupView, renderPanelIcon } from '../../components/DockWorkspace';
+import { FloatingPanelWindow } from '../../components/FloatingPanelWindow';
+import { PressureCurveEditor } from '../../components/PressureCurveEditor';
+import {
+ useDocumentLifecycle,
+ UseDocumentLifecycleParams,
+} from '../../components/DocumentLifecycleManager';
+import { ErrorBoundary } from '../../main';
+import {
+ documentStoreActions,
+ toolStoreActions,
+ uiStoreActions,
+ useDocumentStore,
+ useToolStore,
+ useUiStore,
+ useWorkspaceStore,
+} from '../../stores';
+import {
+ COLOR_SETS_STORAGE_KEY,
+ createInitialColorSetsState,
+} from '../../stores/useColorSetsStore';
+import {
+ autoActionStoreActions,
+ useAutoActionStore,
+} from '../../stores/useAutoActionStore';
+import {
+ BrushSettings,
+ LayerItem,
+ NewCanvasOptions,
+ SpeechBalloon,
+} from '../../types/editor';
+import { loadAppSettings } from '../../types/settings';
+import {
+ resetBrushSettingsCache,
+ getEffectiveBrushSettings,
+ loadAllSavedBrushSettings,
+} from '../brushPresetManager';
+import { evaluateFastSpline, getCompiledCurveLut } from '../brushMath';
+import { enforceColorMode, hexToRgb, isValidHex, parseRgba } from '../colorUtils';
+import {
+ isLinearPressureCurve,
+ normalizePressureCurve,
+ sanitizePressureCurvePoints,
+} from '../pressureCurve';
+import {
+ buildNativeBrushConfigPayload,
+ createNativeDocument,
+ parseCssColorToRgba,
+ setNativePressureCurve,
+ syncNativeFullBrushConfig,
+} from '../nativeEngineBridge';
+import {
+ buildGradientMapLut,
+ buildMonotonicCubicSplineLut,
+ createDefaultGradientMesh,
+ resolveGradientStops,
+} from '../toolConfigs';
+import {
+ WORKSPACE_STORAGE_KEY,
+ loadWorkspaceState,
+} from '../workspacePresets';
+import type {
+ DockColumn,
+ DockGroup,
+ FloatingPanelState,
+} from '../../types/workspace';
+import {
+ computeViewportQuadInDoc,
+ isPointInConvexQuad,
+} from '../../components/NavigatorPanel';
+
+vi.mock('../recentDocumentsManager', () => ({
+ saveRecentDocument: vi.fn().mockResolvedValue(undefined),
+}));
+
+// Minimal in-memory Storage implementation for legacy/corrupt localStorage tests
+function createMemoryStorage(): Storage {
+ const store = new Map<string, string>();
+ return {
+ get length() {
+ return store.size;
+ },
+ clear() {
+ store.clear();
+ },
+ getItem(key: string) {
+ return store.has(key) ? store.get(key)! : null;
+ },
+ key(index: number) {
+ return Array.from(store.keys())[index] ?? null;
+ },
+ removeItem(key: string) {
+ store.delete(key);
+ },
+ setItem(key: string, value: string) {
+ store.set(key, String(value));
+ },
+ };
+}
+
+function createStubCanvas2DContext(canvas: MiniEl) {
+ return {
+ canvas,
+ save: vi.fn(),
+ restore: vi.fn(),
+ scale: vi.fn(),
+ translate: vi.fn(),
+ rotate: vi.fn(),
+ transform: vi.fn(),
+ setTransform: vi.fn(),
+ clearRect: vi.fn(),
+ fillRect: vi.fn(),
+ strokeRect: vi.fn(),
+ beginPath: vi.fn(),
+ closePath: vi.fn(),
+ moveTo: vi.fn(),
+ lineTo: vi.fn(),
+ bezierCurveTo: vi.fn(),
+ quadraticCurveTo: vi.fn(),
+ arc: vi.fn(),
+ ellipse: vi.fn(),
+ rect: vi.fn(),
+ fill: vi.fn(),
+ stroke: vi.fn(),
+ clip: vi.fn(),
+ drawImage: vi.fn(),
+ fillText: vi.fn(),
+ strokeText: vi.fn(),
+ measureText: vi.fn(() => ({ width: 20 })),
+ setLineDash: vi.fn(),
+ createLinearGradient: vi.fn(() => ({ addColorStop: vi.fn() })),
+ createRadialGradient: vi.fn(() => ({ addColorStop: vi.fn() })),
+ getImageData: vi.fn(() => ({ data: new Uint8ClampedArray(16), width: 2, height: 2 })),
+ putImageData: vi.fn(),
+ fillStyle: '#000000',
+ strokeStyle: '#000000',
+ lineWidth: 1,
+ lineCap: 'round',
+ lineJoin: 'round',
+ globalAlpha: 1,
+ globalCompositeOperation: 'source-over',
+ font: '12px sans-serif',
+ textAlign: 'left',
+ textBaseline: 'alphabetic',
+ imageSmoothingEnabled: true,
+ imageSmoothingQuality: 'high',
+ };
+}
+
+class MiniText {
+ public nodeType = 3;
+ public nodeName = '#text';
+ public parentNode: MiniEl | null = null;
+ constructor(
+ public nodeValue: string,
+ public ownerDocument: MiniDoc
+ ) {}
+}
+
+class MiniComment {
+ public nodeType = 8;
+ public nodeName = '#comment';
+ public parentNode: MiniEl | null = null;
+ constructor(
+ public nodeValue: string,
+ public ownerDocument: MiniDoc
+ ) {}
+}
+
+class MiniEl extends EventTarget {
+ public nodeType = 1;
+ public nodeName: string;
+ public tagName: string;
+ public namespaceURI: string;
+ public parentNode: MiniEl | null = null;
+ public childNodes: Array<MiniEl | MiniText | MiniComment> = [];
+ public style: Record<string, string> = {};
+ public className = '';
+ public disabled = false;
+ public value = '';
+ public checked = false;
+ public width = 300;
+ public height = 150;
+ public clientWidth = 1024;
+ public clientHeight = 768;
+ public offsetWidth = 1024;
+ public offsetHeight = 768;
+ public scrollLeft = 0;
+ public scrollTop = 0;
+ public dataset: Record<string, string> = {};
+ public isContentEditable = false;
+ private attrs = new Map<string, string>();
+ private ctx2d: ReturnType<typeof createStubCanvas2DContext> | null = null;
+
+ constructor(
+ tag: string,
+ public ownerDocument: MiniDoc,
+ namespaceURI = 'http://www.w3.org/1999/xhtml'
+ ) {
+ super();
+ this.nodeName = tag.toUpperCase();
+ this.tagName = tag.toUpperCase();
+ this.namespaceURI = namespaceURI;
+ }
+
+ get firstChild() {
+ return this.childNodes[0] ?? null;
+ }
+
+ get textContent(): string {
+ return this.childNodes
+ .map((c) => (c instanceof MiniText ? c.nodeValue : c instanceof MiniEl ? c.textContent : ''))
+ .join('');
+ }
+
+ set textContent(val: string) {
+ this.childNodes = val ? [new MiniText(String(val), this.ownerDocument)] : [];
+ }
+
+ appendChild<T extends MiniEl | MiniText | MiniComment>(child: T): T {
+ if (child.parentNode) child.parentNode.removeChild(child);
+ child.parentNode = this;
+ this.childNodes.push(child);
+ return child;
+ }
+
+ removeChild<T extends MiniEl | MiniText | MiniComment>(child: T): T {
+ const idx = this.childNodes.indexOf(child);
+ if (idx >= 0) {
+ this.childNodes.splice(idx, 1);
+ child.parentNode = null;
+ }
+ return child;
+ }
+
+ insertBefore<T extends MiniEl | MiniText | MiniComment>(
+ node: T,
+ ref: MiniEl | MiniText | MiniComment | null
+ ): T {
+ if (node.parentNode) node.parentNode.removeChild(node);
+ node.parentNode = this;
+ const idx = ref ? this.childNodes.indexOf(ref) : -1;
+ if (idx >= 0) this.childNodes.splice(idx, 0, node);
+ else this.childNodes.push(node);
+ return node;
+ }
+
+ setAttribute(k: string, v: string) {
+ this.attrs.set(k, String(v));
+ }
+
+ getAttribute(k: string): string | null {
+ return this.attrs.get(k) ?? null;
+ }
+
+ removeAttribute(k: string) {
+ this.attrs.delete(k);
+ }
+
+ getBoundingClientRect(): DOMRect {
+ return {
+ left: 0,
+ top: 0,
+ right: this.clientWidth,
+ bottom: this.clientHeight,
+ width: this.clientWidth,
+ height: this.clientHeight,
+ x: 0,
+ y: 0,
+ toJSON: () => ({}),
+ };
+ }
+
+ getContext(type: string) {
+ if (type === '2d') {
+ if (!this.ctx2d) this.ctx2d = createStubCanvas2DContext(this);
+ return this.ctx2d;
+ }
+ return null;
+ }
+
+ contains(target: unknown): boolean {
+ if (target === this) return true;
+ for (const c of this.childNodes) {
+ if (c === target) return true;
+ if (c instanceof MiniEl && c.contains(target)) return true;
+ }
+ return false;
+ }
+
+ closest(_selector: string): MiniEl | null {
+ return null;
+ }
+
+ querySelector(_selector: string): MiniEl | null {
+ return null;
+ }
+
+ querySelectorAll(_selector: string): MiniEl[] {
+ return [];
+ }
+
+ focus() {}
+ blur() {}
+ select() {}
+ setPointerCapture() {}
+ releasePointerCapture() {}
+ hasPointerCapture() {
+ return false;
+ }
+
+ findAllByTag(tag: string): MiniEl[] {
+ const upper = tag.toUpperCase();
+ const out: MiniEl[] = [];
+ if (this.tagName === upper) out.push(this);
+ for (const c of this.childNodes) {
+ if (c instanceof MiniEl) out.push(...c.findAllByTag(tag));
+ }
+ return out;
+ }
+}
+
+class MiniDoc extends EventTarget {
+ public nodeType = 9;
+ public nodeName = '#document';
+ public defaultView: unknown = globalThis;
+ public documentElement: MiniEl;
+ public body: MiniEl;
+ public activeElement: MiniEl;
+
+ constructor() {
+ super();
+ this.documentElement = new MiniEl('html', this);
+ this.body = new MiniEl('body', this);
+ this.documentElement.appendChild(this.body);
+ this.activeElement = this.body;
+ }
+
+ createElement(tag: string): MiniEl {
+ return new MiniEl(tag, this);
+ }
+
+ createElementNS(ns: string, tag: string): MiniEl {
+ return new MiniEl(tag, this, ns);
+ }
+
+ createTextNode(val: string): MiniText {
+ return new MiniText(val, this);
+ }
+
+ createComment(val: string): MiniComment {
+ return new MiniComment(val, this);
+ }
+
+ getElementById(_id: string): MiniEl | null {
+ return null;
+ }
+
+ querySelector(_selector: string): MiniEl | null {
+ return null;
+ }
+
+ querySelectorAll(_selector: string): MiniEl[] {
+ return [];
+ }
+
+ execCommand(_cmd: string): boolean {
+ return true;
+ }
+}
+
+class StubResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+describe('Create New Canvas crash & Rules-of-Hooks regressions', () => {
+ let root: Root | null = null;
+ let container: MiniEl | null = null;
+ let miniDoc: MiniDoc | null = null;
+ let storage: Storage;
+ const savedGlobals: Record<string, unknown> = {};
+ const globalKeys = [
+ 'IS_REACT_ACT_ENVIRONMENT',
+ 'document',
+ 'window',
+ 'addEventListener',
+ 'removeEventListener',
+ 'dispatchEvent',
+ 'HTMLElement',
+ 'HTMLCanvasElement',
+ 'HTMLIFrameElement',
+ 'SVGElement',
+ 'Element',
+ 'Node',
+ 'ResizeObserver',
+ 'requestAnimationFrame',
+ 'cancelAnimationFrame',
+ 'devicePixelRatio',
+ 'innerWidth',
+ 'innerHeight',
+ 'getComputedStyle',
+ 'matchMedia',
+ 'localStorage',
+ ];
+
+ const baseLayer: LayerItem = {
+ id: 'layer-1',
+ name: 'Layer 1',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ parentId: null,
+ };
+
+ const baseBrushSettings: BrushSettings = {
+ preset: 'g-pen',
+ size: 12,
+ minSizeFactor: 0.04,
+ color: '#000000',
+ secondaryColor: '#ffffff',
+ opacity: 1,
+ flow: 1,
+ spacing: 0.05,
+ grain: 0,
+ usePressure: true,
+ smoothing: true,
+ stabilization: 10,
+ hardness: 1,
+ };
+
+ beforeEach(() => {
+ const g = globalThis as Record<string, unknown>;
+ for (const k of globalKeys) {
+ savedGlobals[k] = g[k];
+ }
+
+ storage = createMemoryStorage();
+ miniDoc = new MiniDoc();
+ const winEvents = new EventTarget();
+ g.IS_REACT_ACT_ENVIRONMENT = true;
+ g.document = miniDoc;
+ g.window = globalThis;
+ g.addEventListener = winEvents.addEventListener.bind(winEvents);
+ g.removeEventListener = winEvents.removeEventListener.bind(winEvents);
+ g.dispatchEvent = winEvents.dispatchEvent.bind(winEvents);
+ g.HTMLElement = MiniEl;
+ g.HTMLCanvasElement = MiniEl;
+ g.HTMLIFrameElement = class HTMLIFrameElement {};
+ g.SVGElement = MiniEl;
+ g.Element = MiniEl;
+ g.Node = MiniText;
+ g.ResizeObserver = StubResizeObserver;
+ g.requestAnimationFrame = (cb: FrameRequestCallback) =>
+ setTimeout(() => cb(performance.now()), 0) as unknown as number;
+ g.cancelAnimationFrame = (id: number) => clearTimeout(id);
+ g.devicePixelRatio = 1;
+ g.innerWidth = 1440;
+ g.innerHeight = 900;
+ g.getComputedStyle = () => ({ getPropertyValue: () => '' });
+ g.matchMedia = () => ({
+ matches: false,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ });
+ g.localStorage = storage;
+
+ container = miniDoc.createElement('div');
+ miniDoc.body.appendChild(container);
+ root = createRoot(container as unknown as HTMLElement);
+
+ resetBrushSettingsCache();
+ documentStoreActions.setDocuments([]);
+ documentStoreActions.setActiveDocumentId(null);
+ documentStoreActions.setSavedFileInfo(null);
+ uiStoreActions.setAppView('home');
+ useWorkspaceStore.setState({ palettesHidden: false });
+ });
+
+ afterEach(() => {
+ if (root) {
+ act(() => {
+ root?.unmount();
+ });
+ }
+ root = null;
+ container = null;
+ miniDoc = null;
+ resetBrushSettingsCache();
+
+ const g = globalThis as Record<string, unknown>;
+ for (const k of globalKeys) {
+ if (savedGlobals[k] === undefined) {
+ delete g[k];
+ } else {
+ g[k] = savedGlobals[k];
+ }
+ }
+ });
+
+ it('transitions CanvasArea from hasOpenDocument={false} to hasOpenDocument={true} and back with zero React hook errors', () => {
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const viewportRef = React.createRef<HTMLDivElement>();
+ const interactionRef = React.createRef<HTMLDivElement>();
+
+ const makeCanvasProps = (hasOpenDocument: boolean) => ({
+ viewportRef,
+ interactionRef,
+ dimensions: { width: 1200, height: 800, dpi: 300 },
+ brushSettings: baseBrushSettings,
+ onUpdateBrushSettings: vi.fn(),
+ zoom: 1,
+ pan: { x: 0, y: 0 },
+ rotation: 0,
+ isSpaceDown: false,
+ isShiftDown: false,
+ isRotateModifier: false,
+ isPanning: false,
+ isRotating: false,
+ onStartPan: vi.fn(),
+ onStartRotate: vi.fn(),
+ isHovering: false,
+ cursorPos: null,
+ onPointerDown: vi.fn(),
+ onPointerMove: vi.fn(),
+ onPointerUp: vi.fn(),
+ onPointerEnter: vi.fn(),
+ onPointerLeave: vi.fn(),
+ layers: [baseLayer],
+ activeLayerId: baseLayer.id,
+ getEffectiveOpacity: () => 1,
+ isLayerEffectivelyVisible: () => true,
+ hasOpenDocument,
+ });
+
+ try {
+ expect(() => {
+ act(() => {
+ root!.render(React.createElement(CanvasArea, makeCanvasProps(false)));
+ });
+ }).not.toThrow();
+
+ // Welcome -> Workspace transition (previously crashed with React #310 "Rendered more hooks than during the previous render")
+ expect(() => {
+ act(() => {
+ root!.render(React.createElement(CanvasArea, makeCanvasProps(true)));
+ });
+ }).not.toThrow();
+
+ // Workspace -> Welcome -> Workspace round-trip
+ expect(() => {
+ act(() => {
+ root!.render(React.createElement(CanvasArea, makeCanvasProps(false)));
+ });
+ act(() => {
+ root!.render(React.createElement(CanvasArea, makeCanvasProps(true)));
+ });
+ }).not.toThrow();
+
+ const hookErrors = errorSpy.mock.calls.filter((call) =>
+ String(call[0] ?? '').toLowerCase().includes('more hooks')
+ );
+ expect(hookErrors).toHaveLength(0);
+ } finally {
+ errorSpy.mockRestore();
+ }
+ });
+
+ it('transitions SpeechBalloonOverlay across balloon={null} -> valid balloon -> null with zero React hook errors', () => {
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ const sampleBalloon: SpeechBalloon = {
+ id: 'balloon-1',
+ shape: 'ellipse',
+ bounds: { x: 100, y: 100, width: 220, height: 120 },
+ tail: {
+ start: { x: 180, y: 220, pressure: 0.5, width: 2 },
+ control1: { x: 170, y: 260, pressure: 0.5, width: 2 },
+ control2: { x: 140, y: 280, pressure: 0.5, width: 2 },
+ tip: { x: 120, y: 310, pressure: 0.5, width: 2 },
+ },
+ fillColor: '#ffffff',
+ strokeColor: '#000000',
+ strokeWidth: 3,
+ text: 'Hello!',
+ fontFamily: 'sans-serif',
+ fontSize: 20,
+ vertical: false,
+ };
+
+ const baseProps = {
+ zoom: 1,
+ onUpdateBalloon: vi.fn(),
+ onConfirmBalloon: vi.fn(),
+ onDeleteBalloon: vi.fn(),
+ };
+
+ try {
+ expect(() => {
+ act(() => {
+ root!.render(
+ React.createElement(SpeechBalloonOverlay, { ...baseProps, balloon: null })
+ );
+ });
+ }).not.toThrow();
+
+ expect(() => {
+ act(() => {
+ root!.render(
+ React.createElement(SpeechBalloonOverlay, { ...baseProps, balloon: sampleBalloon })
+ );
+ });
+ }).not.toThrow();
+
+ expect(() => {
+ act(() => {
+ root!.render(
+ React.createElement(SpeechBalloonOverlay, { ...baseProps, balloon: null })
+ );
+ });
+ }).not.toThrow();
+
+ const hookErrors = errorSpy.mock.calls.filter((call) =>
+ String(call[0] ?? '').toLowerCase().includes('more hooks')
+ );
+ expect(hookErrors).toHaveLength(0);
+ } finally {
+ errorSpy.mockRestore();
+ }
+ });
+
+ it('handles handleCreateNewCanvas and workspace/store hydration with corrupted legacy localStorage payloads without throwing', () => {
+ // Seed corrupted / legacy pre-migration localStorage entries across every affected subsystem
+ storage.setItem(
+ 'ink_studio_app_settings',
+ JSON.stringify({
+ userName: 'Artist',
+ // Missing pressureCurve on purpose in first check, plus malformed canvas defaults
+ defaultWidth: null,
+ defaultHeight: 'bad',
+ defaultDpi: NaN,
+ defaultBgColor: 12345,
+ })
+ );
+ storage.setItem(
+ WORKSPACE_STORAGE_KEY,
+ JSON.stringify({
+ version: 1,
+ activePresetId: 'custom',
+ layout: {
+ leftDocks: [
+ {
+ id: 'col-empty',
+ width: 240,
+ groups: [{ id: 'grp-empty', panelIds: [], activePanelId: '', heightRatio: 1 }],
+ },
+ ],
+ rightDocks: [{ id: 'col-bad', width: 260, groups: null }],
+ floatingPanels: [
+ {
+ id: 'fp-empty',
+ panelIds: [],
+ activePanelId: '',
+ x: 100,
+ y: 100,
+ width: 240,
+ height: 240,
+ collapsed: false,
+ zIndex: 1,
+ },
+ ],
+ },
+ })
+ );
+ storage.setItem(
+ 'ink_studio_brush_settings_by_id',
+ JSON.stringify({
+ 'g-pen': {
+ size: Number.NaN,
+ pressureCurve: [null, undefined, 'corrupt'],
+ velocityCurve: 'not-an-array',
+ sizeSensor: {
+ usePressure: true,
+ pressureCurve: [undefined],
+ },
+ dualBrushConfig: 'invalid',
+ },
+ })
+ );
+ storage.setItem(
+ COLOR_SETS_STORAGE_KEY,
+ JSON.stringify({
+ sets: [{ id: 'bad', name: '', swatches: [{ hex: null }, { hex: '#zzzzzz' }] }],
+ activeSetId: 'nonexistent',
+ })
+ );
+ storage.setItem('ink_studio_color_history', JSON.stringify([null, 42, '#zzzzzz', 'bad']));
+ storage.setItem('ink_studio_gradient_settings', JSON.stringify({ stops: [null, undefined] }));
+
+ // 1. Hydrating app settings, workspace layout, brush settings, and color sets must never throw
+ const loadedSettings = loadAppSettings();
+ expect(loadedSettings.pressureCurve.points.length).toBeGreaterThanOrEqual(2);
+ expect(loadedSettings.defaultWidth).toBeGreaterThan(0);
+ expect(typeof loadedSettings.defaultBgColor).toBe('string');
+
+ const loadedWorkspace = loadWorkspaceState();
+ expect(loadedWorkspace.layout.leftDocks.length + loadedWorkspace.layout.rightDocks.length).toBeGreaterThan(0);
+
+ resetBrushSettingsCache();
+ const savedBrushes = loadAllSavedBrushSettings();
+ expect(savedBrushes['g-pen']?.pressureCurve).toBeUndefined();
+ const effectiveGPen = getEffectiveBrushSettings('g-pen');
+ expect(Number.isFinite(effectiveGPen.size)).toBe(true);
+
+ const colorSetsState = createInitialColorSetsState();
+ expect(colorSetsState.sets.length).toBeGreaterThan(0);
+ expect(colorSetsState.activeSetId).toBeTruthy();
+
+ // Also verify PressureCurveEditor, DockGroupView, and FloatingPanelWindow survive malformed props directly
+ expect(() => {
+ act(() => {
+ root!.render(
+ React.createElement(PressureCurveEditor, {
+ value: undefined as unknown as Parameters<typeof PressureCurveEditor>[0]['value'],
+ onChange: vi.fn(),
+ })
+ );
+ });
+ }).not.toThrow();
+
+ const emptyGroup: DockGroup = {
+ id: 'corrupt-grp',
+ panelIds: [],
+ activePanelId: '' as unknown as DockGroup['activePanelId'],
+ heightRatio: 1,
+ };
+ const emptyCol: DockColumn = {
+ id: 'corrupt-col',
+ width: 240,
+ collapsed: false,
+ groups: [emptyGroup],
+ };
+ expect(() => {
+ act(() => {
+ root!.render(
+ React.createElement(DockGroupView, {
+ side: 'left',
+ col: emptyCol,
+ group: emptyGroup,
+ groupIndex: 0,
+ themePreset: 'modern',
+ draggingPanelId: null,
+ onStartDragPanel: vi.fn(),
+ onEndDragPanel: vi.fn(),
+ renderPanelBody: () => null,
+ })
+ );
+ });
+ }).not.toThrow();
+
+ const emptyFloating: FloatingPanelState = {
+ id: 'corrupt-float',
+ panelIds: [],
+ activePanelId: '' as unknown as FloatingPanelState['activePanelId'],
+ x: 80,
+ y: 80,
+ width: 220,
+ height: 220,
+ collapsed: false,
+ zIndex: 1,
+ };
+ expect(() => {
+ act(() => {
+ root!.render(
+ React.createElement(FloatingPanelWindow, {
+ panel: emptyFloating,
+ isDragging: false,
+ isDockTargetActive: false,
+ isMergeTabTarget: false,
+ renderPanelBody: () => null,
+ renderPanelIcon,
+ onStartHeaderDrag: vi.fn(),
+ onStartTabDrag: vi.fn(),
+ })
+ );
+ });
+ }).not.toThrow();
+
+ // 2. Corrupt primaryColor in tool store & mount DocumentLifecycleManager, then trigger handleCreateNewCanvas
+ useToolStore.setState({ primaryColor: 'not-a-hex' });
+ let lifecycleApi: ReturnType<typeof useDocumentLifecycle> | null = null;
+ const params: UseDocumentLifecycleParams = {
+ layers: [baseLayer],
+ activeLayer: baseLayer,
+ activeLayerId: 'layer-1',
+ getEffectiveOpacity: () => 1,
+ isLayerEffectivelyVisible: () => true,
+ setActiveLayerId: vi.fn(),
+ resetToNewCanvas: vi.fn(() => ({ layers: [baseLayer], activeLayerId: 'layer-1' })),
+ setDefaultToneFrequency: vi.fn(),
+ clearDocument: vi.fn(),
+ loadDocument: vi.fn(),
+ switchDocumentSession: vi.fn(),
+ resizeCanvas: vi.fn(),
+ copyLayer: vi.fn(() => null),
+ pasteLayer: vi.fn(async () => ({ success: false })),
+ deleteLayer: vi.fn(),
+ pasteLayerFromFile: vi.fn(async () => 'Pasted'),
+ resetZoomAndCenter: vi.fn(),
+ resetHistory: vi.fn(),
+ pushHistoryStep: vi.fn(),
+ showToast: vi.fn(),
+ };
+
+ function Harness() {
+ lifecycleApi = useDocumentLifecycle(params);
+ return null;
+ }
+
+ act(() => {
+ root!.render(React.createElement(Harness));
+ });
+
+ expect(() => {
+ act(() => {
+ lifecycleApi!.handleCreateNewCanvas({
+ name: 'Corrupt Test',
+ width: 1920,
+ height: 1080,
+ dpi: 300,
+ backgroundColor: '#zzzzzz',
+ colorMode: 'monochrome',
+ aspectRatioPreset: 'custom',
+ aspectRatioX: 16,
+ aspectRatioY: 9,
+ lockAspectRatio: false,
+ });
+ });
+ }).not.toThrow();
+
+ // Also test with undefined/missing primaryColor & partial malformed NewCanvasOptions
+ useToolStore.setState({ primaryColor: undefined as unknown as string });
+ expect(() => {
+ act(() => {
+ lifecycleApi!.handleCreateNewCanvas({
+ name: '',
+ width: Number.NaN,
+ height: -5,
+ dpi: 0,
+ backgroundColor: undefined as unknown as string,
+ colorMode: 'grayscale',
+ } as unknown as NewCanvasOptions);
+ });
+ }).not.toThrow();
+
+ expect(useUiStore.getState().appView).toBe('workspace');
+ expect(useDocumentStore.getState().documents).toHaveLength(2);
+ expect(useDocumentStore.getState().activeDocumentId).toBe(
+ useDocumentStore.getState().documents[1].id
+ );
+
+ // Restore clean primaryColor
+ toolStoreActions.setPrimaryColor('#000000', false, 'color');
+ });
+
+ it('guards curve LUTs, pressure curves, color utilities, native bridge, toolConfigs, stores, and NavigatorPanel against undefined/malformed [0] inputs', async () => {
+ // brushMath & pressureCurve
+ expect(getCompiledCurveLut([undefined as unknown as [number, number]])).toBeNull();
+ expect(getCompiledCurveLut('bad' as unknown as [number, number][])).toBeNull();
+ expect(evaluateFastSpline(0.5, [null as unknown as [number, number]])).toBe(0.5);
+ expect(
+ isLinearPressureCurve([
+ undefined as unknown as [number, number],
+ undefined as unknown as [number, number],
+ ])
+ ).toBe(true);
+ expect(sanitizePressureCurvePoints([undefined as unknown as [number, number]])).toEqual([
+ [0, 0],
+ [1, 1],
+ ]);
+ expect(normalizePressureCurve(undefined).points).toEqual([
+ [0, 0],
+ [1, 1],
+ ]);
+
+ // colorUtils & nativeEngineBridge
+ expect(parseRgba(undefined as unknown as string)).toEqual([0, 0, 0, 1]);
+ expect(enforceColorMode(undefined as unknown as string, 'monochrome')).toBe('#000000');
+ expect(hexToRgb(undefined as unknown as string)).toEqual({ r: 0, g: 0, b: 0 });
+ expect(isValidHex(undefined as unknown as string)).toBe(false);
+ expect(parseCssColorToRgba(undefined)).toEqual([0.086, 0.086, 0.086, 1.0]);
+ expect(parseCssColorToRgba(123 as unknown as string)).toEqual([0.086, 0.086, 0.086, 1.0]);
+
+ const payload = await buildNativeBrushConfigPayload(
+ 'brush',
+ {
+ size: Number.NaN,
+ pressureCurve: [undefined as unknown as [number, number]],
+ subTips: [undefined as unknown as NonNullable<BrushSettings['subTips']>[number]],
+ } as Partial<BrushSettings>,
+ '#zzzzzz',
+ undefined as unknown as string
+ );
+ expect(Array.isArray(payload.fgColor)).toBe(true);
+ expect(Array.isArray(payload.bgColor)).toBe(true);
+ expect(payload.pressureCurve).toBeNull();
+
+ await expect(
+ syncNativeFullBrushConfig('brush', undefined, '#000000', '#ffffff')
+ ).resolves.toBeUndefined();
+ await expect(
+ setNativePressureCurve({
+ enabled: true,
+ preset: 'custom',
+ points: [undefined as unknown as [number, number]],
+ })
+ ).resolves.toBeUndefined();
+ await expect(
+ createNativeDocument({
+ docId: 'doc-test',
+ name: 'Test',
+ dimensions: { width: 800, height: 600, dpi: 300 },
+ })
+ ).resolves.toBeNull();
+
+ // toolConfigs
+ expect(buildMonotonicCubicSplineLut([undefined as unknown as [number, number]]).length).toBe(256);
+ expect(buildGradientMapLut([null as unknown as { position: number; color: string }]).length).toBe(
+ 256 * 4
+ );
+ expect(
+ resolveGradientStops(
+ { stops: [] } as unknown as Parameters<typeof resolveGradientStops>[0],
+ '#000000',
+ '#ffffff'
+ ).length
+ ).toBeGreaterThanOrEqual(2);
+ expect(
+ createDefaultGradientMesh(
+ { x: 0, y: 0, width: 100, height: 100 },
+ 2,
+ 2,
+ '#000000',
+ '#ffffff',
+ [undefined as unknown as NonNullable<Parameters<typeof createDefaultGradientMesh>[5]>[number]]
+ ).nodes.length
+ ).toBe(4);
+
+ // AutoAction store when sets are empty
+ autoActionStoreActions.replaceSets([]);
+ expect(useAutoActionStore.getState().sets).toEqual([]);
+ const createdAction = autoActionStoreActions.createAction('Safe Action');
+ expect(createdAction.name).toBe('Safe Action');
+ expect(useAutoActionStore.getState().sets.length).toBe(1);
+
+ // NavigatorPanel quad helpers
+ const quad = computeViewportQuadInDoc(
+ 800,
+ 600,
+ { pan: { x: 0, y: 0 }, zoom: 1, rotation: 0, flipX: false, flipY: false },
+ { width: 1000, height: 1000, dpi: 300 }
+ );
+ expect(quad).toHaveLength(4);
+ expect(
+ isPointInConvexQuad(
+ { x: 10, y: 10 },
+ [] as unknown as Parameters<typeof isPointInConvexQuad>[1]
+ )
+ ).toBe(false);
+ });
+
+ it('renders ErrorBoundary with collapsible error stack, componentStack, and Copy Error Details button', () => {
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ function CrashingChild(): React.ReactElement {
+ throw new TypeError("Cannot read properties of undefined (reading '0')");
+ }
+
+ try {
+ act(() => {
+ root!.render(
+ React.createElement(ErrorBoundary, null, React.createElement(CrashingChild))
+ );
+ });
+
+ const renderedText = container!.textContent;
+ expect(renderedText).toContain('Graphics Editor Encountered an Error');
+ expect(renderedText).toContain("Cannot read properties of undefined (reading '0')");
+ expect(renderedText).toContain('Copy Error Details');
+ expect(container!.findAllByTag('details').length).toBe(1);
+ expect(renderedText).toContain('CrashingChild');
+ } finally {
+ errorSpy.mockRestore();
+ }
+ });
+});
diff --git a/src/utils/animationEngine.ts b/src/utils/animationEngine.ts
index d68d414..8808c4c 100644
--- a/src/utils/animationEngine.ts
+++ b/src/utils/animationEngine.ts
@@ -172,7 +172,7 @@ export function downloadBlob(blob: Blob, filename: string): void {
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
- URL.revokeObjectURL(url);
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
}
/**
@@ -219,7 +219,9 @@ export async function exportAnimationToVideo(
docId?: string | null
): Promise<Blob> {
const { fps, totalFrames } = timeline;
- const maxDim = Math.min(1920, Math.max(dimensions.width, dimensions.height));
+ const safeFps = Math.max(1, Number.isFinite(fps) ? fps : 12);
+ const safeTotalFrames = Math.max(0, Number.isFinite(totalFrames) ? Math.floor(totalFrames) : 0);
+ const maxDim = Math.min(1920, Math.max(1, dimensions.width, dimensions.height));
const scale = Math.min(1, maxDim / Math.max(1, dimensions.width, dimensions.height));
const targetW = Math.max(2, Math.round(dimensions.width * scale));
const targetH = Math.max(2, Math.round(dimensions.height * scale));
@@ -227,8 +229,11 @@ export async function exportAnimationToVideo(
const canvas = document.createElement('canvas');
canvas.width = targetW;
canvas.height = targetH;
- const ctx = canvas.getContext('2d')!;
- const stream = canvas.captureStream(fps);
+ const ctx = canvas.getContext('2d');
+ if (!ctx) {
+ throw new Error('Failed to create 2D context for animation video export.');
+ }
+ const stream = canvas.captureStream(safeFps);
const preferredTypes = [
'video/webm;codecs=vp9',
@@ -248,43 +253,77 @@ export async function exportAnimationToVideo(
if (e.data && e.data.size > 0) chunks.push(e.data);
};
- const delayMs = 1000 / fps;
+ const delayMs = 1000 / safeFps;
return new Promise<Blob>((resolve, reject) => {
- recorder.onstop = () => {
+ let settled = false;
+ const cleanupResources = () => {
+ stream.getTracks().forEach((t) => {
+ try {
+ t.stop();
+ } catch {
+ // Ignore track stop errors
+ }
+ });
canvas.width = 0;
canvas.height = 0;
- resolve(new Blob(chunks, { type: mimeType }));
+ };
+
+ recorder.onstop = () => {
+ cleanupResources();
+ if (!settled) {
+ settled = true;
+ resolve(new Blob(chunks, { type: mimeType }));
+ }
};
recorder.onerror = (e) => {
- canvas.width = 0;
- canvas.height = 0;
- reject(e);
+ cleanupResources();
+ if (!settled) {
+ settled = true;
+ reject(e);
+ }
};
recorder.start();
let frame = 0;
const renderNext = async () => {
- if (frame >= totalFrames) {
- recorder.stop();
- return;
- }
+ try {
+ if (frame >= safeTotalFrames) {
+ if (recorder.state !== 'inactive') {
+ recorder.stop();
+ }
+ return;
+ }
- onProgress?.(frame + 1, totalFrames);
- const flat = await flattenNativeDocument(docId ?? null, {
- maxDim,
- celVisibilityOverrides: buildCelVisibilityOverrides(timeline, frame),
- });
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- if (flat) {
- if (canvas.width !== flat.width) canvas.width = flat.width;
- if (canvas.height !== flat.height) canvas.height = flat.height;
- ctx.putImageData(new ImageData(flat.rgba, flat.width, flat.height), 0, 0);
- }
+ onProgress?.(frame + 1, safeTotalFrames);
+ const flat = await flattenNativeDocument(docId ?? null, {
+ maxDim,
+ celVisibilityOverrides: buildCelVisibilityOverrides(timeline, frame),
+ });
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ if (flat) {
+ if (canvas.width !== flat.width) canvas.width = flat.width;
+ if (canvas.height !== flat.height) canvas.height = flat.height;
+ ctx.putImageData(new ImageData(flat.rgba, flat.width, flat.height), 0, 0);
+ }
- frame++;
- setTimeout(() => void renderNext(), delayMs);
+ frame++;
+ setTimeout(() => void renderNext(), delayMs);
+ } catch (err) {
+ try {
+ if (recorder.state !== 'inactive') {
+ recorder.stop();
+ }
+ } catch {
+ // Ignore stop errors after failure
+ }
+ cleanupResources();
+ if (!settled) {
+ settled = true;
+ reject(err);
+ }
+ }
};
void renderNext();
@@ -412,7 +451,11 @@ export async function exportAnimationToApng(
docId?: string | null
): Promise<Blob> {
const { fps, totalFrames } = timeline;
- const numFrames = totalFrames;
+ const safeFps = Math.max(1, Number.isFinite(fps) ? fps : 12);
+ const numFrames = Math.max(0, Number.isFinite(totalFrames) ? Math.floor(totalFrames) : 0);
+ if (numFrames === 0) {
+ throw new Error('Cannot export an APNG with 0 frames.');
+ }
const framePngBuffers: Uint8Array[] = [];
for (let f = 0; f < numFrames; f++) {
@@ -489,7 +532,7 @@ export async function exportAnimationToApng(
fctl0Dv.setUint32(12, 0);
fctl0Dv.setUint32(16, 0);
fctl0Dv.setUint16(20, 1);
- fctl0Dv.setUint16(22, fps);
+ fctl0Dv.setUint16(22, safeFps);
fctl0Dv.setUint8(24, 0);
fctl0Dv.setUint8(25, 0);
outChunks.push(createChunk('fcTL', fctl0));
@@ -520,7 +563,7 @@ export async function exportAnimationToApng(
fctlDv.setUint32(12, 0);
fctlDv.setUint32(16, 0);
fctlDv.setUint16(20, 1);
- fctlDv.setUint16(22, fps);
+ fctlDv.setUint16(22, safeFps);
fctlDv.setUint8(24, 0);
fctlDv.setUint8(25, 0);
outChunks.push(createChunk('fcTL', fctl));
diff --git a/src/utils/autoActionEngine.ts b/src/utils/autoActionEngine.ts
index 8793580..cde42f3 100644
--- a/src/utils/autoActionEngine.ts
+++ b/src/utils/autoActionEngine.ts
@@ -354,7 +354,12 @@ export function exportAutoActionSetsJson(sets: AutoActionSet[]): string {
}
export function importAutoActionSetsJson(json: string): AutoActionSet[] {
- const parsed = JSON.parse(json);
+ let parsed: any;
+ try {
+ parsed = JSON.parse(json);
+ } catch {
+ throw new Error('Invalid Auto Actions JSON format');
+ }
const rawSets = Array.isArray(parsed) ? parsed : parsed?.sets;
if (!Array.isArray(rawSets)) {
throw new Error('Invalid Auto Actions JSON format');
diff --git a/src/utils/brushMath.ts b/src/utils/brushMath.ts
index af5002b..f891b34 100644
--- a/src/utils/brushMath.ts
+++ b/src/utils/brushMath.ts
@@ -139,14 +139,30 @@ const curveStringCache = new Map<string, Float32Array>();
const MAX_STRING_CURVE_CACHE = 128;
export function getCompiledCurveLut(curve?: readonly [number, number][]): Float32Array | null {
- if (!curve || curve.length === 0) return null;
+ if (!Array.isArray(curve) || curve.length === 0) return null;
const weakHit = curveWeakCache.get(curve);
if (weakHit) return weakHit;
- let key = '';
+ const validPts: [number, number][] = [];
for (let i = 0; i < curve.length; i++) {
- key += `${curve[i][0].toFixed(4)},${curve[i][1].toFixed(4)};`;
+ const p = curve[i];
+ if (
+ Array.isArray(p) &&
+ p.length >= 2 &&
+ typeof p[0] === 'number' &&
+ typeof p[1] === 'number' &&
+ Number.isFinite(p[0]) &&
+ Number.isFinite(p[1])
+ ) {
+ validPts.push([p[0], p[1]]);
+ }
+ }
+ if (validPts.length === 0) return null;
+
+ let key = '';
+ for (let i = 0; i < validPts.length; i++) {
+ key += `${validPts[i][0].toFixed(4)},${validPts[i][1].toFixed(4)};`;
}
const strHit = curveStringCache.get(key);
if (strHit) {
@@ -155,7 +171,7 @@ export function getCompiledCurveLut(curve?: readonly [number, number][]): Float3
}
const lut = new Float32Array(LUT_SIZE);
- const pts = curve.slice().sort((a, b) => a[0] - b[0]);
+ const pts = validPts.slice().sort((a, b) => a[0] - b[0]);
const dedup: [number, number][] = [pts[0]];
for (let i = 1; i < pts.length; i++) {
if (pts[i][0] - dedup[dedup.length - 1][0] > 1e-5) {
@@ -275,8 +291,8 @@ export function getCompiledCurveLut(curve?: readonly [number, number][]): Float3
}
export function evaluateFastSpline(x: number, curve?: readonly [number, number][]): number {
- const clamped = x <= 0 ? 0 : x >= 1 ? 1 : x;
- if (!curve || curve.length === 0) return clamped;
+ const clamped = !Number.isFinite(x) ? 0 : x <= 0 ? 0 : x >= 1 ? 1 : x;
+ if (!Array.isArray(curve) || curve.length === 0) return clamped;
const lut = getCompiledCurveLut(curve);
if (!lut) return clamped;
diff --git a/src/utils/brushPresetManager.ts b/src/utils/brushPresetManager.ts
index b5aac34..094a10e 100644
--- a/src/utils/brushPresetManager.ts
+++ b/src/utils/brushPresetManager.ts
@@ -390,11 +390,100 @@ export function resetBrushSettingsCache(): void {
_memorySettingsCache = null;
}
+const SENSOR_KEYS = [
+ 'sizeSensor',
+ 'opacitySensor',
+ 'densitySensor',
+ 'thicknessSensor',
+ 'angleSensor',
+ 'scatterSensor',
+ 'intervalSensor',
+ 'textureDensitySensor',
+ 'bristleSplaySensor',
+ 'paintLoadSensor',
+ 'grainPenetrationSensor',
+ 'amountOfPaintSensor',
+ 'densityOfPaintSensor',
+ 'colorStretchSensor',
+ 'dualAngleSensor',
+] as const;
+
+function sanitizeCurveTupleList(raw: unknown): [number, number][] | undefined {
+ if (!Array.isArray(raw)) return undefined;
+ const valid: [number, number][] = [];
+ for (const pt of raw) {
+ if (
+ Array.isArray(pt) &&
+ pt.length >= 2 &&
+ typeof pt[0] === 'number' &&
+ typeof pt[1] === 'number' &&
+ Number.isFinite(pt[0]) &&
+ Number.isFinite(pt[1])
+ ) {
+ valid.push([pt[0], pt[1]]);
+ }
+ }
+ return valid.length > 0 ? valid : undefined;
+}
+
+function sanitizePersistedBrushEntry(raw: unknown): BrushPersistentSettings | null {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const copy = { ...(raw as Record<string, unknown>) };
+
+ for (const curveKey of ['pressureCurve', 'velocityCurve'] as const) {
+ if (curveKey in copy) {
+ const cleaned = sanitizeCurveTupleList(copy[curveKey]);
+ if (cleaned) copy[curveKey] = cleaned;
+ else delete copy[curveKey];
+ }
+ }
+
+ for (const sensorKey of SENSOR_KEYS) {
+ if (!(sensorKey in copy)) continue;
+ const sensor = copy[sensorKey];
+ if (!sensor || typeof sensor !== 'object' || Array.isArray(sensor)) {
+ delete copy[sensorKey];
+ continue;
+ }
+ const cleanSensor = { ...(sensor as Record<string, unknown>) };
+ for (const cKey of ['pressureCurve', 'tiltCurve', 'velocityCurve'] as const) {
+ if (cKey in cleanSensor) {
+ const cleaned = sanitizeCurveTupleList(cleanSensor[cKey]);
+ if (cleaned) cleanSensor[cKey] = cleaned;
+ else delete cleanSensor[cKey];
+ }
+ }
+ copy[sensorKey] = cleanSensor;
+ }
+
+ for (const numKey of ['size', 'minSizeFactor', 'opacity', 'flow', 'spacing', 'hardness', 'stabilization'] as const) {
+ if (numKey in copy && (typeof copy[numKey] !== 'number' || !Number.isFinite(copy[numKey]))) {
+ delete copy[numKey];
+ }
+ }
+
+ if ('dualBrushConfig' in copy) {
+ const cfg = copy.dualBrushConfig;
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) {
+ delete copy.dualBrushConfig;
+ }
+ }
+
+ return copy as BrushPersistentSettings;
+}
+
export function loadAllSavedBrushSettings(): Record<string, BrushPersistentSettings> {
if (_memorySettingsCache) return _memorySettingsCache;
try {
const raw = typeof localStorage !== 'undefined' ? localStorage.getItem(STORAGE_KEY_SETTINGS) : null;
- const parsed: Record<string, BrushPersistentSettings> = raw ? JSON.parse(raw) : {};
+ const parsedRaw: unknown = raw ? JSON.parse(raw) : {};
+ const parsed: Record<string, BrushPersistentSettings> = {};
+ if (parsedRaw && typeof parsedRaw === 'object' && !Array.isArray(parsedRaw)) {
+ for (const [id, entry] of Object.entries(parsedRaw as Record<string, unknown>)) {
+ const clean = sanitizePersistedBrushEntry(entry);
+ if (clean) parsed[id] = clean;
+ }
+ }
if (typeof localStorage !== 'undefined') {
const storedVer = Number(localStorage.getItem(STORAGE_KEY_PRESET_SCHEMA) || '0');
if (storedVer < BUILTIN_PRESET_SCHEMA_VERSION) {
diff --git a/src/utils/brushPreview.ts b/src/utils/brushPreview.ts
index e5db4e2..14267e9 100644
--- a/src/utils/brushPreview.ts
+++ b/src/utils/brushPreview.ts
@@ -28,6 +28,7 @@ import { getBuiltinBrushConfig } from './presetBrushes';
import { evaluateFastSpline, getLegacyPencilPresetDefaults } from './brushMath';
import { resolveDualBrushConfig } from './dualBrushConfig';
import { isNativeCanvasActive, renderNativeBrushPreview } from './nativeEngineBridge';
+import { recoveryService } from '../services/recoveryService';
export interface BrushPreviewOptions {
preset?: BrushPresetId;
@@ -144,9 +145,206 @@ export interface BrushPreviewOptions {
height?: number;
}
+interface NativePreviewTask {
+ canvas: HTMLCanvasElement;
+ token: number;
+ cacheKey: string;
+ tool: 'brush' | 'eraser';
+ previewSettings: BrushSettings;
+ strokeColor: string;
+ secondaryColor: string;
+ bgColor: string;
+ targetWidth: number;
+ targetHeight: number;
+}
+
const previewCache = new Map<string, HTMLCanvasElement>();
-const pendingNativeRequests = new Set<string>();
+const gpuUpgradedCacheKeys = new Set<string>();
+const inFlightNativeKeys = new Set<string>();
+const nativePreviewQueue: NativePreviewTask[] = [];
+const canvasRequestTokens = new WeakMap<HTMLCanvasElement, number>();
+const liveCardDebounceTimers = new WeakMap<HTMLCanvasElement, ReturnType<typeof setTimeout>>();
+
const MAX_CACHE_ENTRIES = 220;
+const MAX_CONCURRENT_NATIVE_PREVIEWS = 2;
+const LIVE_CARD_NATIVE_DEBOUNCE_MS = 64;
+
+let inFlightNativeCount = 0;
+let drawingActiveUnsub: (() => void) | null = null;
+
+function ensureDrawingIdleResumeListener(): void {
+ if (drawingActiveUnsub !== null) return;
+ drawingActiveUnsub = recoveryService.subscribeDrawingActive((active) => {
+ if (!active && nativePreviewQueue.length > 0) {
+ drainNativePreviewQueue();
+ }
+ });
+}
+
+function setCachedPreview(cacheKey: string, canvas: HTMLCanvasElement, isGpuUpgraded: boolean): void {
+ if (previewCache.has(cacheKey)) {
+ previewCache.delete(cacheKey);
+ } else if (previewCache.size >= MAX_CACHE_ENTRIES) {
+ const firstKey = previewCache.keys().next().value;
+ if (firstKey) {
+ previewCache.delete(firstKey);
+ gpuUpgradedCacheKeys.delete(firstKey);
+ }
+ }
+ previewCache.set(cacheKey, canvas);
+ if (isGpuUpgraded) {
+ gpuUpgradedCacheKeys.add(cacheKey);
+ }
+}
+
+function removeQueuedTasksForCanvas(canvas: HTMLCanvasElement): void {
+ for (let i = nativePreviewQueue.length - 1; i >= 0; i--) {
+ if (nativePreviewQueue[i].canvas === canvas) {
+ nativePreviewQueue.splice(i, 1);
+ }
+ }
+}
+
+/**
+ * Cancels any pending or stale native GPU preview work associated with `canvas`
+ * (called when a `BrushPreview` unmounts or starts a fresh render during slider drag).
+ */
+export function cancelBrushPreviewForCanvas(canvas: HTMLCanvasElement | null | undefined): void {
+ if (!canvas) return;
+ const nextToken = (canvasRequestTokens.get(canvas) ?? 0) + 1;
+ canvasRequestTokens.set(canvas, nextToken);
+ const timer = liveCardDebounceTimers.get(canvas);
+ if (timer !== undefined) {
+ clearTimeout(timer);
+ liveCardDebounceTimers.delete(canvas);
+ }
+ removeQueuedTasksForCanvas(canvas);
+}
+
+function paintCanvasIfCurrent(
+ canvas: HTMLCanvasElement,
+ token: number,
+ source: HTMLCanvasElement,
+ targetWidth: number,
+ targetHeight: number
+): void {
+ if (canvasRequestTokens.get(canvas) !== token) return;
+ const liveCtx = canvas.getContext('2d');
+ if (liveCtx && canvas.width === targetWidth && canvas.height === targetHeight) {
+ liveCtx.clearRect(0, 0, targetWidth, targetHeight);
+ liveCtx.drawImage(source, 0, 0, targetWidth, targetHeight);
+ }
+}
+
+function drainNativePreviewQueue(): void {
+ if (!isNativeCanvasActive()) return;
+ if (recoveryService.getIsDrawingActive()) return;
+
+ while (inFlightNativeCount < MAX_CONCURRENT_NATIVE_PREVIEWS && nativePreviewQueue.length > 0) {
+ if (recoveryService.getIsDrawingActive()) return;
+
+ const idx = nativePreviewQueue.findIndex((t) => !inFlightNativeKeys.has(t.cacheKey));
+ if (idx < 0) return;
+
+ const [task] = nativePreviewQueue.splice(idx, 1);
+ if (!task) continue;
+
+ // Drop stale request if the canvas has already been re-rendered or unmounted
+ if (canvasRequestTokens.get(task.canvas) !== task.token) {
+ continue;
+ }
+
+ // If an identical config was already GPU-rendered while this task waited, paint from cache
+ if (gpuUpgradedCacheKeys.has(task.cacheKey)) {
+ const cached = previewCache.get(task.cacheKey);
+ if (cached) {
+ paintCanvasIfCurrent(task.canvas, task.token, cached, task.targetWidth, task.targetHeight);
+ }
+ continue;
+ }
+
+ inFlightNativeCount += 1;
+ inFlightNativeKeys.add(task.cacheKey);
+
+ void renderNativeBrushPreview(
+ task.tool,
+ task.previewSettings,
+ task.strokeColor,
+ task.secondaryColor,
+ task.targetWidth,
+ task.targetHeight
+ )
+ .then((img) => {
+ if (!img || typeof ImageData === 'undefined') return;
+ const gpuCanvas = document.createElement('canvas');
+ gpuCanvas.width = img.width;
+ gpuCanvas.height = img.height;
+ const gCtx = gpuCanvas.getContext('2d');
+ if (!gCtx) return;
+ if (task.bgColor && task.bgColor !== 'transparent') {
+ gCtx.fillStyle = task.bgColor;
+ gCtx.fillRect(0, 0, gpuCanvas.width, gpuCanvas.height);
+ const tmp = document.createElement('canvas');
+ tmp.width = img.width;
+ tmp.height = img.height;
+ const tCtx = tmp.getContext('2d');
+ tCtx?.putImageData(new ImageData(img.rgba, img.width, img.height), 0, 0);
+ gCtx.drawImage(tmp, 0, 0);
+ } else {
+ gCtx.putImageData(new ImageData(img.rgba, img.width, img.height), 0, 0);
+ }
+ setCachedPreview(task.cacheKey, gpuCanvas, true);
+ paintCanvasIfCurrent(task.canvas, task.token, gpuCanvas, task.targetWidth, task.targetHeight);
+
+ // Paint any other queued canvases waiting on the exact same config hash
+ for (let i = nativePreviewQueue.length - 1; i >= 0; i--) {
+ const waiter = nativePreviewQueue[i];
+ if (waiter.cacheKey === task.cacheKey) {
+ nativePreviewQueue.splice(i, 1);
+ paintCanvasIfCurrent(
+ waiter.canvas,
+ waiter.token,
+ gpuCanvas,
+ waiter.targetWidth,
+ waiter.targetHeight
+ );
+ }
+ }
+ })
+ .finally(() => {
+ inFlightNativeCount = Math.max(0, inFlightNativeCount - 1);
+ inFlightNativeKeys.delete(task.cacheKey);
+ drainNativePreviewQueue();
+ });
+ }
+}
+
+function enqueueNativePreviewTask(task: NativePreviewTask, debounceMs: number): void {
+ ensureDrawingIdleResumeListener();
+ removeQueuedTasksForCanvas(task.canvas);
+ const existingTimer = liveCardDebounceTimers.get(task.canvas);
+ if (existingTimer !== undefined) {
+ clearTimeout(existingTimer);
+ liveCardDebounceTimers.delete(task.canvas);
+ }
+
+ const pushAndDrain = () => {
+ if (canvasRequestTokens.get(task.canvas) !== task.token) return;
+ removeQueuedTasksForCanvas(task.canvas);
+ nativePreviewQueue.push(task);
+ drainNativePreviewQueue();
+ };
+
+ if (debounceMs > 0) {
+ const timer = setTimeout(() => {
+ liveCardDebounceTimers.delete(task.canvas);
+ pushAndDrain();
+ }, debounceMs);
+ liveCardDebounceTimers.set(task.canvas, timer);
+ } else {
+ pushAndDrain();
+ }
+}
function clamp(v: number, lo: number, hi: number): number {
return v < lo ? lo : v > hi ? hi : v;
@@ -345,18 +543,28 @@ export function renderBrushStrokePreview(
width: number,
height: number,
options: BrushPreviewOptions = {},
- _isLiveCard: boolean = false
+ isLiveCard: boolean = false
): void {
- renderBrushPreview(canvas, { ...options, width, height });
+ renderBrushPreview(canvas, { ...options, width, height }, isLiveCard);
}
export function renderBrushPreview(
canvas: HTMLCanvasElement,
- options: BrushPreviewOptions = {}
+ options: BrushPreviewOptions = {},
+ isLiveCard: boolean = false
): void {
const ctx = canvas.getContext('2d');
if (!ctx) return;
+ const token = (canvasRequestTokens.get(canvas) ?? 0) + 1;
+ canvasRequestTokens.set(canvas, token);
+ const existingTimer = liveCardDebounceTimers.get(canvas);
+ if (existingTimer !== undefined) {
+ clearTimeout(existingTimer);
+ liveCardDebounceTimers.delete(canvas);
+ }
+ removeQueuedTasksForCanvas(canvas);
+
const dpr = typeof window !== 'undefined' ? Math.min(2, window.devicePixelRatio || 1) : 1;
const targetWidth = Math.max(32, Math.round((options.width ?? canvas.width ?? 160) * (options.width ? dpr : 1)));
const targetHeight = Math.max(16, Math.round((options.height ?? canvas.height ?? 44) * (options.height ? dpr : 1)));
@@ -378,47 +586,47 @@ export function renderBrushPreview(
if (cached) {
ctx.clearRect(0, 0, targetWidth, targetHeight);
ctx.drawImage(cached, 0, 0);
- return;
+ if (!isNativeCanvasActive() || gpuUpgradedCacheKeys.has(cacheKey)) {
+ return;
+ }
}
const size = merged.size ?? 12;
const displayWidth = calculatePreviewWidth(size, targetHeight, dpr);
const minSizeFactor = clamp(merged.minSizeFactor ?? 0.15, 0.02, 1.0);
const usePressure = merged.usePressure !== false;
- const pts = buildScurvePoints(
- targetWidth,
- targetHeight,
- displayWidth,
- minSizeFactor,
- usePressure,
- merged.pressureCurve
- );
-
- const offscreen = document.createElement('canvas');
- offscreen.width = targetWidth;
- offscreen.height = targetHeight;
- const offCtx = offscreen.getContext('2d');
- if (!offCtx) return;
-
- if (bgColor && bgColor !== 'transparent') {
- offCtx.fillStyle = bgColor;
- offCtx.fillRect(0, 0, targetWidth, targetHeight);
- }
- renderLightweightScurvePreview(offCtx, pts, strokeColor, merged, displayWidth);
- ctx.clearRect(0, 0, targetWidth, targetHeight);
- ctx.drawImage(offscreen, 0, 0);
+ if (!cached) {
+ const pts = buildScurvePoints(
+ targetWidth,
+ targetHeight,
+ displayWidth,
+ minSizeFactor,
+ usePressure,
+ merged.pressureCurve
+ );
- if (previewCache.size >= MAX_CACHE_ENTRIES) {
- const firstKey = previewCache.keys().next().value;
- if (firstKey) previewCache.delete(firstKey);
+ const offscreen = document.createElement('canvas');
+ offscreen.width = targetWidth;
+ offscreen.height = targetHeight;
+ const offCtx = offscreen.getContext('2d');
+ if (!offCtx) return;
+
+ if (bgColor && bgColor !== 'transparent') {
+ offCtx.fillStyle = bgColor;
+ offCtx.fillRect(0, 0, targetWidth, targetHeight);
+ }
+ renderLightweightScurvePreview(offCtx, pts, strokeColor, merged, displayWidth);
+
+ ctx.clearRect(0, 0, targetWidth, targetHeight);
+ ctx.drawImage(offscreen, 0, 0);
+
+ setCachedPreview(cacheKey, offscreen, false);
}
- previewCache.set(cacheKey, offscreen);
- // On Windows Desktop with native DX12 engine active, asynchronously upgrade the preview
- // with the exact GPU-rendered S-curve directly from `ink-engine`!
- if (isNativeCanvasActive() && !pendingNativeRequests.has(cacheKey)) {
- pendingNativeRequests.add(cacheKey);
+ // On Windows Desktop with native DX12 engine active, queue a concurrency-limited GPU upgrade
+ // (max 2 in-flight, stale requests cancelled on slider drag, skipped while actively drawing).
+ if (isNativeCanvasActive() && !gpuUpgradedCacheKeys.has(cacheKey)) {
const dualCfg = resolveDualBrushConfig(merged as BrushSettings);
const previewSettings: BrushSettings = {
size: displayWidth,
@@ -497,47 +705,28 @@ export function renderBrushPreview(
preset: merged.preset,
};
- void renderNativeBrushPreview(
- isEraser ? 'eraser' : 'brush',
- previewSettings,
- strokeColor,
- merged.secondaryColor ?? '#ffffff',
- targetWidth,
- targetHeight
- )
- .then((img) => {
- if (!img || typeof ImageData === 'undefined') return;
- const gpuCanvas = document.createElement('canvas');
- gpuCanvas.width = img.width;
- gpuCanvas.height = img.height;
- const gCtx = gpuCanvas.getContext('2d');
- if (!gCtx) return;
- if (bgColor && bgColor !== 'transparent') {
- gCtx.fillStyle = bgColor;
- gCtx.fillRect(0, 0, gpuCanvas.width, gpuCanvas.height);
- const tmp = document.createElement('canvas');
- tmp.width = img.width;
- tmp.height = img.height;
- const tCtx = tmp.getContext('2d');
- tCtx?.putImageData(new ImageData(img.rgba, img.width, img.height), 0, 0);
- gCtx.drawImage(tmp, 0, 0);
- } else {
- gCtx.putImageData(new ImageData(img.rgba, img.width, img.height), 0, 0);
- }
- previewCache.set(cacheKey, gpuCanvas);
- const liveCtx = canvas.getContext('2d');
- if (liveCtx && canvas.width === targetWidth && canvas.height === targetHeight) {
- liveCtx.clearRect(0, 0, targetWidth, targetHeight);
- liveCtx.drawImage(gpuCanvas, 0, 0, targetWidth, targetHeight);
- }
- })
- .finally(() => {
- pendingNativeRequests.delete(cacheKey);
- });
+ enqueueNativePreviewTask(
+ {
+ canvas,
+ token,
+ cacheKey,
+ tool: isEraser ? 'eraser' : 'brush',
+ previewSettings,
+ strokeColor,
+ secondaryColor: merged.secondaryColor ?? '#ffffff',
+ bgColor,
+ targetWidth,
+ targetHeight,
+ },
+ isLiveCard ? LIVE_CARD_NATIVE_DEBOUNCE_MS : 0
+ );
}
}
export function clearBrushPreviewCache() {
previewCache.clear();
- pendingNativeRequests.clear();
+ gpuUpgradedCacheKeys.clear();
+ inFlightNativeKeys.clear();
+ nativePreviewQueue.length = 0;
+ inFlightNativeCount = 0;
}
diff --git a/src/utils/colorUtils.ts b/src/utils/colorUtils.ts
index 8a37e93..3be4cf9 100644
--- a/src/utils/colorUtils.ts
+++ b/src/utils/colorUtils.ts
@@ -4,13 +4,17 @@ import { CanvasColorMode } from '../types/editor';
* Parses any CSS color string (hex, rgb, rgba) into [r, g, b, a] in 0-255 range.
*/
export function parseRgba(color: string): [number, number, number, number] {
- if (color === 'transparent') {
+ if (typeof color !== 'string') {
+ return [0, 0, 0, 1];
+ }
+ const trimmed = color.trim();
+ if (trimmed === 'transparent') {
return [0, 0, 0, 0];
}
// Hex format (#RGB, #RGBA, #RRGGBB, #RRGGBBAA)
- if (color.startsWith('#')) {
- let hex = color.slice(1);
+ if (trimmed.startsWith('#')) {
+ let hex = trimmed.slice(1);
if (hex.length === 3 || hex.length === 4) {
hex = hex
.split('')
@@ -20,18 +24,19 @@ export function parseRgba(color: string): [number, number, number, number] {
const r = parseInt(hex.slice(0, 2), 16) || 0;
const g = parseInt(hex.slice(2, 4), 16) || 0;
const b = parseInt(hex.slice(4, 6), 16) || 0;
- const a = hex.length >= 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1;
+ const rawA = hex.length >= 8 ? parseInt(hex.slice(6, 8), 16) : 255;
+ const a = Number.isFinite(rawA) ? rawA / 255 : 1;
return [r, g, b, a];
}
// rgb/rgba format
- const rgbMatch = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
+ const rgbMatch = trimmed.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
if (rgbMatch) {
const r = parseInt(rgbMatch[1], 10);
const g = parseInt(rgbMatch[2], 10);
const b = parseInt(rgbMatch[3], 10);
const a = rgbMatch[4] !== undefined ? parseFloat(rgbMatch[4]) : 1;
- return [r, g, b, a];
+ return [r, g, b, Number.isFinite(a) ? a : 1];
}
return [0, 0, 0, 1];
@@ -48,11 +53,12 @@ export function getLuminance(r: number, g: number, b: number): number {
* Converts a color string to conform with the given CanvasColorMode.
*/
export function enforceColorMode(color: string, mode: CanvasColorMode): string {
- if (mode === 'color' || color === 'transparent') {
- return color;
+ const safeColor = typeof color === 'string' && color.trim().length > 0 ? color : '#000000';
+ if (mode === 'color' || safeColor === 'transparent') {
+ return safeColor;
}
- const [r, g, b, a] = parseRgba(color);
+ const [r, g, b, a] = parseRgba(safeColor);
const lum = getLuminance(r, g, b);
if (mode === 'grayscale') {
@@ -67,7 +73,7 @@ export function enforceColorMode(color: string, mode: CanvasColorMode): string {
return `#${hex}`;
}
- return color;
+ return safeColor;
}
/**
@@ -204,6 +210,9 @@ export interface RGB {
* Parses a hex string (#RGB, #RRGGBB) to RGB values (0-255).
*/
export function hexToRgb(hex: string): RGB {
+ if (typeof hex !== 'string') {
+ return { r: 0, g: 0, b: 0 };
+ }
let clean = hex.replace('#', '').trim();
if (clean.length === 3) {
clean = clean
@@ -333,6 +342,7 @@ export function hsvToHex(h: number, s: number, v: number): string {
* Validates whether a string is a valid 3- or 6-digit hex color.
*/
export function isValidHex(hex: string): boolean {
+ if (typeof hex !== 'string') return false;
return /^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/.test(hex.trim());
}
diff --git a/src/utils/interfaceScale.ts b/src/utils/interfaceScale.ts
index a491dde..757fc07 100644
--- a/src/utils/interfaceScale.ts
+++ b/src/utils/interfaceScale.ts
@@ -48,6 +48,19 @@ export function resetInterfaceScaleState(): void {
lastAppliedNativeScale = null;
}
+export const INTERFACE_SCALE_APPLIED_EVENT = 'ink-interface-scale-applied';
+
+function notifyInterfaceScaleApplied(scale: number, factor: number): void {
+ if (typeof window === 'undefined' || typeof CustomEvent !== 'function') return;
+ try {
+ window.dispatchEvent(
+ new CustomEvent(INTERFACE_SCALE_APPLIED_EVENT, { detail: { scale, factor } })
+ );
+ } catch {
+ // Ignore synthetic window dispatch failures in tests
+ }
+}
+
/**
* Applies the user's interface scale (60%–200%) across the application.
* - On Tauri desktop, uses the native WebView zoom API (`getCurrentWebview().setZoom`) so all
@@ -73,6 +86,7 @@ export async function applyInterfaceScale(percent: number): Promise<number> {
activeNativeWebviewZoom = 1;
lastAppliedNativeScale = null;
root.style.zoom = clamped === DEFAULT_INTERFACE_SCALE ? '' : String(factor);
+ notifyInterfaceScaleApplied(clamped, factor);
return clamped;
}
@@ -81,6 +95,7 @@ export async function applyInterfaceScale(percent: number): Promise<number> {
} else if (!isTauriEnvironment()) {
activeNativeWebviewZoom = 1;
lastAppliedNativeScale = null;
+ notifyInterfaceScaleApplied(clamped, factor);
return clamped;
}
}
@@ -95,6 +110,7 @@ export async function applyInterfaceScale(percent: number): Promise<number> {
} catch (err) {
console.warn('Failed to apply native WebView interface scale:', err);
}
+ notifyInterfaceScaleApplied(clamped, factor);
}
} else {
activeNativeWebviewZoom = 1;
diff --git a/src/utils/legacySoraMigrator.ts b/src/utils/legacySoraMigrator.ts
index 1b11995..a77753a 100644
--- a/src/utils/legacySoraMigrator.ts
+++ b/src/utils/legacySoraMigrator.ts
@@ -76,7 +76,12 @@ export function isLegacySoraV2Bytes(input: Uint8Array | ArrayBuffer): boolean {
*/
export function parseLegacySoraV1Json(jsonText: string): LegacySoraV1Project {
const cleanText = jsonText.charCodeAt(0) === 0xfeff ? jsonText.slice(1) : jsonText;
- const parsed = JSON.parse(cleanText);
+ let parsed: any;
+ try {
+ parsed = JSON.parse(cleanText);
+ } catch {
+ throw new Error('Invalid legacy .sora project payload: malformed JSON');
+ }
if (!parsed || typeof parsed !== 'object' || !Array.isArray(parsed.layers)) {
throw new Error('Invalid legacy .sora project payload: missing layers array');
}
diff --git a/src/utils/nativeEngineBridge.ts b/src/utils/nativeEngineBridge.ts
index d148ade..0255af1 100644
--- a/src/utils/nativeEngineBridge.ts
+++ b/src/utils/nativeEngineBridge.ts
@@ -111,6 +111,7 @@ export interface NativeEngineDiagnostics {
gpuTilesCapacity?: number;
stackCacheHits?: number;
stackCacheRebuilds?: number;
+ isIdle?: boolean;
}
export interface NativeSoftProofConfig {
@@ -247,12 +248,27 @@ export interface NativeLayerPropsPatch {
}
export interface NativeHistoryStateSnapshot {
- items: HistoryItemMeta[];
+ entries: HistoryItemMeta[];
+ /** Legacy alias kept optional for mocks/backward compatibility. */
+ items?: HistoryItemMeta[];
index: number;
canUndo: boolean;
canRedo: boolean;
}
+/**
+ * Safely extracts the ordered history entry list from a Rust `HistoryStateSnapshot`
+ * (which serializes `entries`, while older TS mocks may supply `items`).
+ */
+export function getHistorySnapshotEntries(
+ snap: NativeHistoryStateSnapshot | null | undefined
+): HistoryItemMeta[] {
+ if (!snap) return [];
+ if (Array.isArray(snap.entries)) return snap.entries;
+ if (Array.isArray(snap.items)) return snap.items;
+ return [];
+}
+
export interface NativeDocumentMetaSnapshot {
id: string;
name: string;
@@ -384,11 +400,52 @@ const EVENT_HISTORY = 'native-engine://history';
const EVENT_THUMBNAILS = 'native-engine://thumbnails';
const EVENT_STROKE_COMMITTED = 'native-engine://stroke-committed';
const EVENT_SELECTION_CHANGED = 'native-engine://selection-changed';
+const EVENT_VIEWPORT_INVALIDATED = 'native-engine://viewport-invalidated';
+
+type TauriInvokeFn = typeof import('@tauri-apps/api/core').invoke;
+type TauriListenFn = typeof import('@tauri-apps/api/event').listen;
let cachedNativeActive = false;
let initPromise: Promise<boolean> | null = null;
const activeListeners = new Set<(active: boolean) => void>();
+let cachedTauriInvoke: TauriInvokeFn | null = null;
+let tauriInvokePromise: Promise<TauriInvokeFn> | null = null;
+let cachedTauriListen: TauriListenFn | null = null;
+let tauriListenPromise: Promise<TauriListenFn> | null = null;
+
+async function getTauriInvoke(): Promise<TauriInvokeFn> {
+ if (cachedTauriInvoke) return cachedTauriInvoke;
+ if (!tauriInvokePromise) {
+ tauriInvokePromise = import('@tauri-apps/api/core')
+ .then((m) => {
+ cachedTauriInvoke = m.invoke;
+ return m.invoke;
+ })
+ .catch((err) => {
+ tauriInvokePromise = null;
+ throw err;
+ });
+ }
+ return tauriInvokePromise;
+}
+
+async function getTauriListen(): Promise<TauriListenFn> {
+ if (cachedTauriListen) return cachedTauriListen;
+ if (!tauriListenPromise) {
+ tauriListenPromise = import('@tauri-apps/api/event')
+ .then((m) => {
+ cachedTauriListen = m.listen;
+ return m.listen;
+ })
+ .catch((err) => {
+ tauriListenPromise = null;
+ throw err;
+ });
+ }
+ return tauriListenPromise;
+}
+
export function isTauriDesktopRuntime(): boolean {
if (typeof window === 'undefined') return false;
const w = window as unknown as Record<string, unknown>;
@@ -463,6 +520,7 @@ export function vramBudgetMbFromPreset(preset?: string): number {
switch (preset) {
case 'low':
return 128;
+ case 'balanced':
case 'medium':
return 256;
case 'high':
@@ -530,7 +588,7 @@ export async function initNativeEngineBridge(): Promise<boolean> {
initPromise = (async () => {
try {
- const { invoke } = await import('@tauri-apps/api/core');
+ const invoke = await getTauriInvoke();
const active = await invoke<boolean>('native_engine_is_active');
const resolved = Boolean(active);
setCachedNativeActive(resolved);
@@ -552,8 +610,18 @@ export function parseCssColorToRgba(
cssColor: string | null | undefined,
fallback: [number, number, number, number] = [0.086, 0.086, 0.086, 1.0]
): [number, number, number, number] {
- if (!cssColor) return fallback;
+ const safeFallback: [number, number, number, number] =
+ Array.isArray(fallback) && fallback.length >= 4
+ ? [
+ Number.isFinite(fallback[0]) ? fallback[0] : 0.086,
+ Number.isFinite(fallback[1]) ? fallback[1] : 0.086,
+ Number.isFinite(fallback[2]) ? fallback[2] : 0.086,
+ Number.isFinite(fallback[3]) ? fallback[3] : 1.0,
+ ]
+ : [0.086, 0.086, 0.086, 1.0];
+ if (typeof cssColor !== 'string') return safeFallback;
const raw = cssColor.trim();
+ if (!raw) return safeFallback;
if (raw.startsWith('#')) {
const hex = raw.slice(1);
if (hex.length === 3) {
@@ -572,7 +640,7 @@ export function parseCssColorToRgba(
return [r / 255, g / 255, b / 255, a / 255];
}
}
- return fallback;
+ return safeFallback;
}
const match = raw.match(
@@ -587,13 +655,13 @@ export function parseCssColorToRgba(
return [r, g, b, a];
}
}
- return fallback;
+ return safeFallback;
}
async function invokeFireAndForget(cmd: string, args?: Record<string, unknown>): Promise<void> {
if (!cachedNativeActive || !isTauriDesktopRuntime()) return;
try {
- const { invoke } = await import('@tauri-apps/api/core');
+ const invoke = await getTauriInvoke();
await invoke(cmd, args);
} catch {
// Ignore transient IPC errors during window teardown
@@ -601,7 +669,7 @@ async function invokeFireAndForget(cmd: string, args?: Record<string, unknown>):
}
async function invokeNative<T>(cmd: string, args?: Record<string, unknown>): Promise<T> {
- const { invoke } = await import('@tauri-apps/api/core');
+ const invoke = await getTauriInvoke();
return invoke<T>(cmd, args);
}
@@ -819,7 +887,7 @@ export async function ensureNativeTextureUploaded(
}
try {
- const { invoke } = await import('@tauri-apps/api/core');
+ const invoke = await getTauriInvoke();
const pngPrefix = 'data:image/png;base64,';
if (dataUrl.startsWith(pngPrefix)) {
const pngBytes = decodeBase64ToBytes(dataUrl.slice(pngPrefix.length));
@@ -878,6 +946,16 @@ export function setNativeMaskMode(enabled: boolean): Promise<void> {
return invokeFireAndForget('native_engine_set_mask_mode', { enabled: Boolean(enabled) });
}
+/**
+ * Enables or disables embedding the full `points` array on `native-engine://stroke-committed`
+ * events. Keep disabled during solo sketching to avoid per-stroke cloning & JSON serialization.
+ */
+export function setNativeCollabPointsEnabled(enabled: boolean): Promise<void> {
+ return invokeFireAndForget('native_engine_set_collab_points_enabled', {
+ enabled: Boolean(enabled),
+ });
+}
+
/**
* Renders a GPU-accelerated S-curve brush preview directly on DX12 via `ink-engine`.
*/
@@ -903,21 +981,41 @@ export async function renderNativeBrushPreview(
}
}
+function sanitizeOptionalCurveForNative(curve: unknown): [number, number][] | null {
+ if (!Array.isArray(curve) || curve.length === 0) return null;
+ const valid: [number, number][] = [];
+ for (const pt of curve) {
+ if (
+ Array.isArray(pt) &&
+ pt.length >= 2 &&
+ typeof pt[0] === 'number' &&
+ typeof pt[1] === 'number' &&
+ Number.isFinite(pt[0]) &&
+ Number.isFinite(pt[1])
+ ) {
+ valid.push([Math.max(0, Math.min(1, pt[0])), Math.max(0, Math.min(1, pt[1]))]);
+ }
+ }
+ return valid.length > 0 ? valid : null;
+}
+
export function setNativePressureCurve(curve: PressureCurveSettings | null | undefined): Promise<void> {
- const payload = curve
- ? {
- enabled: Boolean(curve.enabled),
- points: Array.isArray(curve.points) ? curve.points : [[0, 0], [1, 1]],
- gamma: 1.0,
- }
- : {
- enabled: false,
- points: [
- [0, 0],
- [1, 1],
- ],
- gamma: 1.0,
- };
+ const validPoints = sanitizeOptionalCurveForNative(curve?.points);
+ const payload =
+ curve && typeof curve === 'object'
+ ? {
+ enabled: Boolean(curve.enabled),
+ points: validPoints && validPoints.length >= 2 ? validPoints : [[0, 0], [1, 1]],
+ gamma: 1.0,
+ }
+ : {
+ enabled: false,
+ points: [
+ [0, 0],
+ [1, 1],
+ ],
+ gamma: 1.0,
+ };
return invokeFireAndForget('native_engine_set_pressure_curve', { curve: payload });
}
@@ -961,18 +1059,19 @@ export function setNativeRulers(
}
function mapSensorToNative(sensor: BrushSettings['sizeSensor']): Record<string, unknown> | null {
- if (!sensor) return null;
+ if (!sensor || typeof sensor !== 'object') return null;
return {
usePressure: Boolean(sensor.usePressure),
pressureMin: sensor.pressureMin ?? 0,
- pressureCurve: sensor.pressureCurve ?? null,
+ pressureCurve: sanitizeOptionalCurveForNative(sensor.pressureCurve),
useTilt: Boolean(sensor.useTilt),
tiltMin: sensor.tiltMin ?? 0,
- tiltCurve: sensor.tiltCurve ?? null,
+ tiltMax: sensor.tiltMax ?? 1.0,
+ tiltCurve: sanitizeOptionalCurveForNative(sensor.tiltCurve),
useVelocity: Boolean(sensor.useVelocity),
velocityMin: sensor.velocityMin ?? 0,
velocityInvert: Boolean(sensor.invertVelocity),
- velocityCurve: sensor.velocityCurve ?? null,
+ velocityCurve: sanitizeOptionalCurveForNative(sensor.velocityCurve),
useRandom: Boolean(sensor.useRandom),
randomMin: sensor.randomMin ?? 0,
useDistance: Boolean(sensor.useDistance),
@@ -1022,45 +1121,48 @@ function mapSprayToNative(spray: BrushSettings['spray']): Record<string, unknown
*/
export async function buildNativeBrushConfigPayload(
tool: ToolType,
- bs: BrushSettings,
+ bs: BrushSettings | Partial<BrushSettings> | null | undefined,
primaryColor: string,
secondaryColor: string,
isBgEraser = false
): Promise<Record<string, unknown>> {
+ const safeBs = (bs && typeof bs === 'object' ? bs : {}) as Partial<BrushSettings>;
const fg = parseCssColorToRgba(primaryColor, [0.05, 0.05, 0.05, 1.0]);
const bg = parseCssColorToRgba(secondaryColor, [1.0, 1.0, 1.0, 1.0]);
- const primaryTipDataUrl = bs.customTipDataUrl || bs.customTipImage?.src;
+ const primaryTipDataUrl = safeBs.customTipDataUrl || safeBs.customTipImage?.src;
const tipKey = await ensureNativeTextureUploaded(primaryTipDataUrl, 'tip');
const subTipKeys: string[] = [];
- if (bs.subTips && bs.subTips.length > 0) {
- for (const st of bs.subTips) {
+ if (Array.isArray(safeBs.subTips) && safeBs.subTips.length > 0) {
+ for (const st of safeBs.subTips) {
+ if (!st || typeof st !== 'object') continue;
const k = await ensureNativeTextureUploaded(st.dataUrl, 'tip');
if (k) subTipKeys.push(k);
}
- } else if (bs.subTipImages && bs.subTipImages.length > 0) {
- for (const img of bs.subTipImages) {
+ } else if (Array.isArray(safeBs.subTipImages) && safeBs.subTipImages.length > 0) {
+ for (const img of safeBs.subTipImages) {
const k = await ensureNativeTextureUploaded(img?.src, 'tip');
if (k) subTipKeys.push(k);
}
}
- const paperKey = await ensureNativeTextureUploaded(bs.paperTexture, 'paper');
+ const paperKey = await ensureNativeTextureUploaded(safeBs.paperTexture, 'paper');
// Dual brush secondary tip(s)
- const dualCfg = resolveDualBrushConfig(bs);
+ const dualCfg = resolveDualBrushConfig(safeBs as BrushSettings);
let dualPayload: Record<string, unknown> | null = null;
if (dualCfg && dualCfg.enabled) {
const dualTipDataUrl = dualCfg.tipDataUrl || dualCfg.tipImage?.src;
const dualTipKey = await ensureNativeTextureUploaded(dualTipDataUrl, 'tip');
const dualSubTipKeys: string[] = [];
- if (dualCfg.subTips && dualCfg.subTips.length > 0) {
+ if (Array.isArray(dualCfg.subTips) && dualCfg.subTips.length > 0) {
for (const st of dualCfg.subTips) {
+ if (!st || typeof st !== 'object') continue;
const k = await ensureNativeTextureUploaded(st.dataUrl, 'tip');
if (k) dualSubTipKeys.push(k);
}
- } else if (dualCfg.subTipImages && dualCfg.subTipImages.length > 0) {
+ } else if (Array.isArray(dualCfg.subTipImages) && dualCfg.subTipImages.length > 0) {
for (const img of dualCfg.subTipImages) {
const k = await ensureNativeTextureUploaded(img?.src, 'tip');
if (k) dualSubTipKeys.push(k);
@@ -1069,11 +1171,11 @@ export async function buildNativeBrushConfigPayload(
dualPayload = {
enabled: true,
combineMode: dualCfg.compositeMode ?? 'multiply',
- size: dualCfg.size ?? bs.size,
+ size: dualCfg.size ?? safeBs.size ?? 12,
linkSize: dualCfg.linkSizeWithMain !== false,
- sizeRatio: dualCfg.sizeRatio ?? bs.dualScale ?? 1.0,
- spacing: dualCfg.spacing ?? bs.spacing ?? 0.15,
- hardness: dualCfg.hardness ?? bs.hardness ?? 0.8,
+ sizeRatio: dualCfg.sizeRatio ?? safeBs.dualScale ?? 1.0,
+ spacing: dualCfg.spacing ?? safeBs.spacing ?? 0.15,
+ hardness: dualCfg.hardness ?? safeBs.hardness ?? 0.8,
thickness: dualCfg.thickness ?? 1.0,
thicknessVertical: Boolean(dualCfg.thicknessVertical),
angle: dualCfg.angle ?? 0,
@@ -1099,161 +1201,174 @@ export async function buildNativeBrushConfigPayload(
};
}
- const taperPayload = bs.taper
+ const taperPayload = safeBs.taper
? {
- useIn: Boolean(bs.taper.useIn),
- inLength: bs.taper.inLength ?? 0,
- inRatio: bs.taper.inRatio ?? 0,
- useOut: Boolean(bs.taper.useOut),
- outLength: bs.taper.outLength ?? 0,
- outRatio: bs.taper.outRatio ?? 0,
- inOutType: bs.taper.inOutType ?? 2,
- inOutBySpeed: Boolean(bs.taper.inOutBySpeed),
- startingSharpness: bs.taper.startingSharpness ?? 0.5,
- endingSharpness: bs.taper.endingSharpness ?? 0.5,
- affectSize: bs.taper.affectSize !== false,
- minSizeRatio: bs.taper.minSizeRatio ?? 0,
- affectOpacity: Boolean(bs.taper.affectOpacity),
- affectDensity: Boolean(bs.taper.affectDensity),
- minDensityRatio: bs.taper.minDensityRatio ?? 0,
- affectAmountOfPaint: Boolean(bs.taper.affectAmountOfPaint),
- minAmountRatio: bs.taper.minAmountRatio ?? 0,
- affectDensityOfPaint: Boolean(bs.taper.affectDensityOfPaint),
- minPaintDensityRatio: bs.taper.minPaintDensityRatio ?? 0,
- affectLoad: Boolean(bs.taper.affectLoad),
+ useIn: Boolean(safeBs.taper.useIn),
+ inLength: safeBs.taper.inLength ?? 0,
+ inRatio: safeBs.taper.inRatio ?? 0,
+ useOut: Boolean(safeBs.taper.useOut),
+ outLength: safeBs.taper.outLength ?? 0,
+ outRatio: safeBs.taper.outRatio ?? 0,
+ inOutType: safeBs.taper.inOutType ?? 2,
+ inOutBySpeed: Boolean(safeBs.taper.inOutBySpeed),
+ startingSharpness: safeBs.taper.startingSharpness ?? 0.5,
+ endingSharpness: safeBs.taper.endingSharpness ?? 0.5,
+ affectSize: safeBs.taper.affectSize !== false,
+ minSizeRatio: safeBs.taper.minSizeRatio ?? 0,
+ affectOpacity: Boolean(safeBs.taper.affectOpacity),
+ affectDensity: Boolean(safeBs.taper.affectDensity),
+ minDensityRatio: safeBs.taper.minDensityRatio ?? 0,
+ affectAmountOfPaint: Boolean(safeBs.taper.affectAmountOfPaint),
+ minAmountRatio: safeBs.taper.minAmountRatio ?? 0,
+ affectDensityOfPaint: Boolean(safeBs.taper.affectDensityOfPaint),
+ minPaintDensityRatio: safeBs.taper.minPaintDensityRatio ?? 0,
+ affectLoad: Boolean(safeBs.taper.affectLoad),
}
: null;
- const isEraser = tool === 'eraser' || Boolean(bs.isTransparentInk);
+ const isEraser = tool === 'eraser' || Boolean(safeBs.isTransparentInk);
return {
- fgColor: [fg[0], fg[1], fg[2]],
- bgColor: [bg[0], bg[1], bg[2]],
- size: Math.max(0.5, bs.size || 12),
- minSizeFactor: Math.max(0, Math.min(1, bs.minSizeFactor ?? 0.05)),
- opacity: Math.max(0.01, Math.min(1, bs.opacity ?? 1.0)),
- flow: Math.max(0.01, Math.min(1, bs.flow ?? 1.0)),
- brushDensity: Math.max(0.01, Math.min(1, bs.brushDensity ?? 1.0)),
- adjustDensityByGap: Boolean(bs.adjustDensityByGap),
- hardness: Math.max(0, Math.min(1, bs.hardness ?? 0.9)),
- antiAlias: Math.max(0, Math.min(3, Math.round(bs.antiAlias ?? 2))),
- spacing: Math.max(0.02, Math.min(4.0, bs.spacing || 0.1)),
- stabilization: Math.max(0, Math.min(50, bs.stabilization ?? 0)),
- sharpCorners: Boolean(bs.sharpCorners),
- postCorrection: Math.max(0, Math.min(5, Math.round(bs.postCorrection ?? 0))),
- smoothing: bs.smoothing !== false,
- usePressure: Boolean(bs.sizeSensor?.usePressure ?? bs.usePressure ?? true),
- useTilt: Boolean(bs.useTilt),
- tiltScale: bs.tiltScale ?? 1.0,
- pressureCurveGamma: bs.pressureCurveGamma ?? 1.0,
- pressureCurve: bs.pressureCurve ?? null,
+ fgColor: [fg?.[0] ?? 0.05, fg?.[1] ?? 0.05, fg?.[2] ?? 0.05],
+ bgColor: [bg?.[0] ?? 1.0, bg?.[1] ?? 1.0, bg?.[2] ?? 1.0],
+ size: Math.max(0.5, Number.isFinite(safeBs.size) ? (safeBs.size as number) : 12),
+ minSizeFactor: Math.max(0, Math.min(1, safeBs.minSizeFactor ?? 0.05)),
+ opacity: Math.max(0.01, Math.min(1, safeBs.opacity ?? 1.0)),
+ flow: Math.max(0.01, Math.min(1, safeBs.flow ?? 1.0)),
+ brushDensity: Math.max(0.01, Math.min(1, safeBs.brushDensity ?? 1.0)),
+ adjustDensityByGap: Boolean(safeBs.adjustDensityByGap),
+ hardness: Math.max(0, Math.min(1, safeBs.hardness ?? 0.9)),
+ antiAlias: Math.max(0, Math.min(3, Math.round(safeBs.antiAlias ?? 2))),
+ spacing: Math.max(0.02, Math.min(4.0, safeBs.spacing || 0.1)),
+ stabilization: Math.max(0, Math.min(50, safeBs.stabilization ?? 0)),
+ sharpCorners: Boolean(safeBs.sharpCorners),
+ postCorrection: Math.max(0, Math.min(5, Math.round(safeBs.postCorrection ?? 0))),
+ smoothing: safeBs.smoothing !== false,
+ usePressure: Boolean(safeBs.sizeSensor?.usePressure ?? safeBs.usePressure ?? true),
+ useTilt: Boolean(safeBs.useTilt),
+ tiltScale: safeBs.tiltScale ?? 1.0,
+ pressureCurveGamma: safeBs.pressureCurveGamma ?? 1.0,
+ pressureCurve: sanitizeOptionalCurveForNative(safeBs.pressureCurve),
isEraser,
- isTransparentInk: Boolean(bs.isTransparentInk),
+ isTransparentInk: Boolean(safeBs.isTransparentInk),
isBgEraser: Boolean(isBgEraser),
- enableFlickTaper: Boolean(bs.sharpCorners && (bs.taper?.useOut || bs.taper?.inOutBySpeed)),
+ enableFlickTaper: Boolean(safeBs.sharpCorners && (safeBs.taper?.useOut || safeBs.taper?.inOutBySpeed)),
tipKey,
subTipKeys,
- subTipOrder: bs.subTipOrder ?? 'sequential',
- isColorTip: Boolean(bs.isColorTip),
- isDualToneTip: Boolean(bs.isDualToneTip),
- thickness: Math.max(0.1, Math.min(1.0, bs.thickness ?? 1.0)),
- thicknessVertical: Boolean(bs.thicknessVertical),
- customTipAngle: bs.customTipAngle ?? 0,
- customTipAngleDynamics: bs.customTipAngleDynamics ?? 'none',
- customTipRotationRandomScale: bs.customTipRotationRandomScale ?? 0,
- flipH: bs.flipH ?? 'none',
- flipV: bs.flipV ?? 'none',
- blendTipsMode: bs.blendTipsMode ?? 'normal',
- brushCombineMode: bs.brushCombineMode ?? 'normal',
+ subTipOrder: safeBs.subTipOrder ?? 'sequential',
+ isColorTip: Boolean(safeBs.isColorTip),
+ isDualToneTip: Boolean(safeBs.isDualToneTip),
+ thickness: Math.max(0.1, Math.min(1.0, safeBs.thickness ?? 1.0)),
+ thicknessVertical: Boolean(safeBs.thicknessVertical),
+ customTipAngle: safeBs.customTipAngle ?? 0,
+ customTipAngleDynamics: safeBs.customTipAngleDynamics ?? 'none',
+ customTipRotationRandomScale: safeBs.customTipRotationRandomScale ?? 0,
+ flipH: safeBs.flipH ?? 'none',
+ flipV: safeBs.flipV ?? 'none',
+ blendTipsMode: safeBs.blendTipsMode ?? 'normal',
+ brushCombineMode: safeBs.brushCombineMode ?? 'normal',
paperTextureKey: paperKey,
- surfaceTextureId: bs.surfaceTextureId ?? null,
- grain: bs.grain ?? 0,
- textureDensity: bs.textureDensity ?? 0,
- paperTextureMode: bs.paperTextureMode ?? 'subtract',
- grainMappingMode: bs.grainMappingMode ?? 'canvas-locked',
- paperTextureScale: bs.paperTextureScale ?? 1.0,
- paperTextureRotate: bs.paperTextureRotate ?? 0,
- paperTextureOffsetX: bs.paperTextureOffsetX ?? 0,
- paperTextureOffsetY: bs.paperTextureOffsetY ?? 0,
- paperTextureBrightness: bs.paperTextureBrightness ?? 0,
- paperTextureContrast: bs.paperTextureContrast ?? 0,
- paperTextureInvert: Boolean(bs.paperTextureInverted),
- paperTextureApplyEachPlot: bs.paperTextureApplyEachPlot !== false,
- emphasizeDensity: Boolean(bs.paperTextureEmphasizeDensity),
- wetEdge: bs.wetEdge ?? 0,
- wetEdgeRadius: bs.wetEdgeRadius ?? 3.0,
- wetEdgeAlphaPower: bs.wetEdgeAlphaPower ?? 1.0,
- wetEdgeValuePower: bs.wetEdgeValuePower ?? 1.0,
- sizeSensor: mapSensorToNative(bs.sizeSensor),
- opacitySensor: mapSensorToNative(bs.opacitySensor),
- densitySensor: mapSensorToNative(bs.densitySensor),
- thicknessSensor: mapSensorToNative(bs.thicknessSensor),
- intervalSensor: mapSensorToNative(bs.intervalSensor),
- textureDensitySensor: mapSensorToNative(bs.textureDensitySensor),
- dynamics: mapDynamicsToNative(bs.dynamics),
- spray: mapSprayToNative(bs.spray),
+ surfaceTextureId: safeBs.surfaceTextureId ?? null,
+ grain: safeBs.grain ?? 0,
+ textureDensity: safeBs.textureDensity ?? 0,
+ paperTextureMode: safeBs.paperTextureMode ?? 'subtract',
+ grainMappingMode: safeBs.grainMappingMode ?? 'canvas-locked',
+ paperTextureScale: safeBs.paperTextureScale ?? 1.0,
+ paperTextureRotate: safeBs.paperTextureRotate ?? 0,
+ paperTextureOffsetX: safeBs.paperTextureOffsetX ?? 0,
+ paperTextureOffsetY: safeBs.paperTextureOffsetY ?? 0,
+ paperTextureBrightness: safeBs.paperTextureBrightness ?? 0,
+ paperTextureContrast: safeBs.paperTextureContrast ?? 0,
+ paperTextureInvert: Boolean(safeBs.paperTextureInverted),
+ paperTextureApplyEachPlot: safeBs.paperTextureApplyEachPlot !== false,
+ emphasizeDensity: Boolean(safeBs.paperTextureEmphasizeDensity),
+ wetEdge: safeBs.wetEdge ?? 0,
+ wetEdgeRadius: safeBs.wetEdgeRadius ?? 3.0,
+ wetEdgeAlphaPower: safeBs.wetEdgeAlphaPower ?? 1.0,
+ wetEdgeValuePower: safeBs.wetEdgeValuePower ?? 1.0,
+ sizeSensor: mapSensorToNative(safeBs.sizeSensor),
+ opacitySensor: mapSensorToNative(safeBs.opacitySensor),
+ densitySensor: mapSensorToNative(safeBs.densitySensor),
+ thicknessSensor: mapSensorToNative(safeBs.thicknessSensor),
+ intervalSensor: mapSensorToNative(safeBs.intervalSensor),
+ textureDensitySensor: mapSensorToNative(safeBs.textureDensitySensor),
+ dynamics: mapDynamicsToNative(safeBs.dynamics),
+ spray: mapSprayToNative(safeBs.spray),
taper: taperPayload,
dualBrush: Boolean(dualPayload),
dualBrushConfig: dualPayload,
// Phase 5: Natural Paint, Pigment Mixing, Bristle Ribbon, Continuous Ribbon & Impasto
- presetKey: bs.preset ?? bs.brushName ?? null,
- renderMode: bs.renderMode ?? 'stamp',
- isRibbon: Boolean(bs.isRibbon),
- ribbonRepeatMode: bs.ribbonRepeatMode ?? 'repeat',
- colorMixing: Boolean(bs.colorMixing),
- perceptualMixing: bs.perceptualMixing !== false,
- amountOfPaint: bs.amountOfPaint ?? 0.75,
- densityOfPaint: bs.densityOfPaint ?? 0.85,
- colorStretch: bs.colorStretch ?? 0.5,
- mixGroundColor: Boolean(bs.mixGroundColor),
- useBlur: Boolean(bs.useBlur),
- blurStrength: bs.blurStrength ?? 0.35,
- mixingMode: bs.mixingMode ?? 'blend',
- amountOfPaintSensor: mapSensorToNative(bs.amountOfPaintSensor),
- densityOfPaintSensor: mapSensorToNative(bs.densityOfPaintSensor),
- colorStretchSensor: mapSensorToNative(bs.colorStretchSensor),
- bristleSplaySensor: mapSensorToNative(bs.bristleSplaySensor),
- paintLoadSensor: mapSensorToNative(bs.paintLoadSensor),
- grainPenetrationSensor: mapSensorToNative(bs.grainPenetrationSensor),
- dualSurfaceTextureId: bs.dualSurfaceTextureId ?? null,
- dualGrainDepth: bs.dualGrainDepth ?? 0.0,
- bristle: bs.bristle
+ presetKey: safeBs.preset ?? safeBs.brushName ?? null,
+ renderMode: safeBs.renderMode ?? 'stamp',
+ isRibbon: Boolean(safeBs.isRibbon),
+ ribbonRepeatMode: safeBs.ribbonRepeatMode ?? 'repeat',
+ colorMixing: Boolean(safeBs.colorMixing),
+ perceptualMixing: safeBs.perceptualMixing !== false,
+ amountOfPaint: safeBs.amountOfPaint ?? 0.75,
+ densityOfPaint: safeBs.densityOfPaint ?? 0.85,
+ colorStretch: safeBs.colorStretch ?? 0.5,
+ mixGroundColor: Boolean(safeBs.mixGroundColor),
+ useBlur: Boolean(safeBs.useBlur),
+ blurStrength: safeBs.blurStrength ?? 0.35,
+ mixingMode: safeBs.mixingMode ?? 'blend',
+ amountOfPaintSensor: mapSensorToNative(safeBs.amountOfPaintSensor),
+ densityOfPaintSensor: mapSensorToNative(safeBs.densityOfPaintSensor),
+ colorStretchSensor: mapSensorToNative(safeBs.colorStretchSensor),
+ bristleSplaySensor: mapSensorToNative(safeBs.bristleSplaySensor),
+ paintLoadSensor: mapSensorToNative(safeBs.paintLoadSensor),
+ grainPenetrationSensor: mapSensorToNative(safeBs.grainPenetrationSensor),
+ dualSurfaceTextureId: safeBs.dualSurfaceTextureId ?? null,
+ dualGrainDepth: safeBs.dualGrainDepth ?? 0.0,
+ bristle: safeBs.bristle
? {
- profile: bs.bristle.profile ?? 'filbert',
- count: Math.max(4, Math.min(64, Math.round(bs.bristle.count ?? 24))),
- clumping: bs.bristle.clumping ?? 0.35,
- stiffness: bs.bristle.stiffness ?? 0.55,
- length: bs.bristle.length ?? 1.0,
- splay: bs.bristle.splay ?? 0.4,
- irregularity: bs.bristle.irregularity ?? 0.3,
- edgeRidge: bs.bristle.edgeRidge ?? 0.45,
+ profile: safeBs.bristle.profile ?? 'filbert',
+ count: Math.max(4, Math.min(64, Math.round(safeBs.bristle.count ?? 24))),
+ clumping: safeBs.bristle.clumping ?? 0.35,
+ stiffness: safeBs.bristle.stiffness ?? 0.55,
+ length: safeBs.bristle.length ?? 1.0,
+ splay: safeBs.bristle.splay ?? 0.4,
+ irregularity: safeBs.bristle.irregularity ?? 0.3,
+ edgeRidge: safeBs.bristle.edgeRidge ?? 0.45,
}
: null,
- naturalPaint: bs.naturalPaint
+ naturalPaint: safeBs.naturalPaint
? {
- enabled: Boolean(bs.naturalPaint.enabled),
- spatialMixing: bs.naturalPaint.spatialMixing !== false,
- pigmentMixingStrength: bs.naturalPaint.pigmentMixingStrength ?? 0.85,
- paintLoad: bs.naturalPaint.paintLoad ?? 0.85,
- depletionRate: bs.naturalPaint.depletionRate ?? 0.25,
- wetness: bs.naturalPaint.wetness ?? 0.45,
- viscosity: bs.naturalPaint.viscosity ?? 0.5,
- autoClean: bs.naturalPaint.autoClean !== false,
- chargePerPressure: bs.naturalPaint.chargePerPressure ?? 0.5,
- dryBrush: bs.naturalPaint.dryBrush ?? 0.0,
- granulation: bs.naturalPaint.granulation ?? 0.0,
- penetrationCurve: bs.naturalPaint.penetrationCurve ?? 1.0,
+ enabled: Boolean(safeBs.naturalPaint.enabled),
+ spatialMixing: safeBs.naturalPaint.spatialMixing !== false,
+ pigmentMixingStrength: safeBs.naturalPaint.pigmentMixingStrength ?? 0.85,
+ paintLoad: safeBs.naturalPaint.paintLoad ?? 0.85,
+ depletionRate: safeBs.naturalPaint.depletionRate ?? 0.25,
+ wetness: safeBs.naturalPaint.wetness ?? 0.45,
+ viscosity: safeBs.naturalPaint.viscosity ?? 0.5,
+ autoClean: safeBs.naturalPaint.autoClean !== false,
+ chargePerPressure: safeBs.naturalPaint.chargePerPressure ?? 0.5,
+ dryBrush: safeBs.naturalPaint.dryBrush ?? 0.0,
+ granulation: safeBs.naturalPaint.granulation ?? 0.0,
+ penetrationCurve:
+ typeof safeBs.naturalPaint.penetrationCurve === 'number' &&
+ Number.isFinite(safeBs.naturalPaint.penetrationCurve)
+ ? safeBs.naturalPaint.penetrationCurve
+ : Array.isArray(safeBs.naturalPaint.penetrationCurve) &&
+ safeBs.naturalPaint.penetrationCurve.length > 0
+ ? (() => {
+ const pts = safeBs.naturalPaint.penetrationCurve as [number, number][];
+ const mid = pts[Math.floor(pts.length / 2)];
+ const my = Array.isArray(mid) && typeof mid[1] === 'number' ? mid[1] : 0.5;
+ const clampedY = Math.max(0.05, Math.min(0.95, my));
+ return Math.max(0.25, Math.min(4.0, Math.log(clampedY) / Math.log(0.5)));
+ })()
+ : 1.0,
}
: null,
- impasto: bs.impasto
+ impasto: safeBs.impasto
? {
- enabled: Boolean(bs.impasto.enabled),
- depth: bs.impasto.depth ?? 0.72,
- bristleRelief: bs.impasto.bristleRelief ?? 0.78,
- gloss: bs.impasto.gloss ?? 0.42,
- reliefContrast: bs.impasto.reliefContrast ?? 1.15,
- lightAzimuth: bs.impasto.lightAzimuth ?? 315,
- lightElevation: bs.impasto.lightElevation ?? 50,
+ enabled: Boolean(safeBs.impasto.enabled),
+ depth: safeBs.impasto.depth ?? 0.72,
+ bristleRelief: safeBs.impasto.bristleRelief ?? 0.78,
+ gloss: safeBs.impasto.gloss ?? 0.42,
+ reliefContrast: safeBs.impasto.reliefContrast ?? 1.15,
+ lightAzimuth: safeBs.impasto.lightAzimuth ?? 315,
+ lightElevation: safeBs.impasto.lightElevation ?? 50,
}
: null,
};
@@ -1265,20 +1380,24 @@ export async function buildNativeBrushConfigPayload(
*/
export async function syncNativeFullBrushConfig(
tool: ToolType,
- bs: BrushSettings,
+ bs: BrushSettings | Partial<BrushSettings> | null | undefined,
primaryColor: string,
secondaryColor: string,
isBgEraser = false
): Promise<void> {
- if (!cachedNativeActive || !isTauriDesktopRuntime()) return;
- const payload = await buildNativeBrushConfigPayload(
- tool,
- bs,
- primaryColor,
- secondaryColor,
- isBgEraser
- );
- await setNativeFullBrush(payload);
+ if (!cachedNativeActive || !isTauriDesktopRuntime() || !bs) return;
+ try {
+ const payload = await buildNativeBrushConfigPayload(
+ tool,
+ bs,
+ primaryColor,
+ secondaryColor,
+ isBgEraser
+ );
+ await setNativeFullBrush(payload);
+ } catch {
+ // Ignore transient IPC / malformed brush config errors during sync
+ }
}
export function setNativePolicy(policy: NativeInteractionPolicy): Promise<void> {
@@ -1310,15 +1429,56 @@ export async function createNativeDocument(params: {
backgroundHex?: string;
defaultToneFrequency?: number;
}): Promise<NativeDocumentMetaSnapshot | null> {
- if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
- return invokeNative<NativeDocumentMetaSnapshot>('native_engine_create_document', {
- docId: params.docId,
- name: params.name,
- dimensions: params.dimensions,
- colorMode: params.colorMode ?? 'color',
- backgroundHex: params.backgroundHex ?? '#ffffff',
- defaultToneFrequency: params.defaultToneFrequency ?? 60,
- });
+ if (!cachedNativeActive || !isTauriDesktopRuntime() || !params || typeof params !== 'object') {
+ return null;
+ }
+ try {
+ const safeDims: CanvasDimensions = {
+ width:
+ typeof params.dimensions?.width === 'number' &&
+ Number.isFinite(params.dimensions.width) &&
+ params.dimensions.width >= 1
+ ? Math.round(params.dimensions.width)
+ : 1920,
+ height:
+ typeof params.dimensions?.height === 'number' &&
+ Number.isFinite(params.dimensions.height) &&
+ params.dimensions.height >= 1
+ ? Math.round(params.dimensions.height)
+ : 1080,
+ dpi:
+ typeof params.dimensions?.dpi === 'number' &&
+ Number.isFinite(params.dimensions.dpi) &&
+ params.dimensions.dpi >= 1
+ ? Math.round(params.dimensions.dpi)
+ : 300,
+ };
+ const snap = await invokeNative<NativeDocumentMetaSnapshot | null | undefined>(
+ 'native_engine_create_document',
+ {
+ docId: typeof params.docId === 'string' && params.docId ? params.docId : `doc-${Date.now()}`,
+ name: typeof params.name === 'string' && params.name ? params.name : 'Untitled*',
+ dimensions: safeDims,
+ colorMode: params.colorMode ?? 'color',
+ backgroundHex:
+ typeof params.backgroundHex === 'string' && params.backgroundHex.trim().length > 0
+ ? params.backgroundHex
+ : '#ffffff',
+ defaultToneFrequency:
+ typeof params.defaultToneFrequency === 'number' &&
+ Number.isFinite(params.defaultToneFrequency)
+ ? params.defaultToneFrequency
+ : 60,
+ }
+ );
+ if (!snap || typeof snap !== 'object') return null;
+ return {
+ ...snap,
+ layers: Array.isArray(snap.layers) ? snap.layers : [],
+ };
+ } catch {
+ return null;
+ }
}
export async function openNativeDocumentFromPath(
@@ -1336,7 +1496,7 @@ export async function openNativeDocumentBytes(
fileName: string,
bytes: Uint8Array
): Promise<NativeOpenDocumentResult> {
- const { invoke } = await import('@tauri-apps/api/core');
+ const invoke = await getTauriInvoke();
const payload =
bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength
? bytes
@@ -1485,13 +1645,52 @@ export async function updateNativeLayer(
export async function syncNativeLayers(
docId: string,
layers: LayerItem[],
- activeLayerId?: string | null
+ activeLayerId?: string | null,
+ options?: { recordHistory?: boolean; historyLabel?: string }
): Promise<NativeDocumentMetaSnapshot | null> {
if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
return invokeNative<NativeDocumentMetaSnapshot>('native_engine_sync_layers', {
docId,
layers: layers.map(toNativeLayerNodeMeta),
activeLayerId: activeLayerId ?? null,
+ recordHistory: options?.recordHistory ?? false,
+ historyLabel: options?.historyLabel ?? null,
+ });
+}
+
+export function setNativeActiveLayer(
+ docId: string,
+ layerId: string | null
+): Promise<void> {
+ if (!cachedNativeActive || !isTauriDesktopRuntime() || !docId) return Promise.resolve();
+ return invokeFireAndForget('native_engine_set_active_layer', {
+ docId,
+ layerId: layerId ?? null,
+ });
+}
+
+export async function syncNativeDocumentMeta(
+ docId: string,
+ meta: {
+ name?: string;
+ perspectiveRuler?: unknown;
+ straightRuler?: unknown;
+ animationTimeline?: unknown;
+ timelapse?: unknown;
+ workTimeMs?: number;
+ }
+): Promise<void> {
+ if (!cachedNativeActive || !isTauriDesktopRuntime() || !docId) return;
+ await invokeNative<void>('native_engine_sync_document_meta', {
+ docId,
+ name: meta.name ?? null,
+ perspectiveRuler: meta.perspectiveRuler === undefined ? null : meta.perspectiveRuler,
+ straightRuler: meta.straightRuler === undefined ? null : meta.straightRuler,
+ animationTimeline: meta.animationTimeline === undefined ? null : meta.animationTimeline,
+ timelapse: meta.timelapse === undefined ? null : meta.timelapse,
+ workTimeMs: typeof meta.workTimeMs === 'number' && Number.isFinite(meta.workTimeMs)
+ ? Math.max(0, Math.round(meta.workTimeMs))
+ : null,
});
}
@@ -1603,7 +1802,7 @@ export async function ingestNativeDirtyRect(params: {
strokeId?: string;
}): Promise<NativeDocumentMetaSnapshot | null> {
if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
- const { invoke } = await import('@tauri-apps/api/core');
+ const invoke = await getTauriInvoke();
const payload =
params.bytes.byteOffset === 0 && params.bytes.byteLength === params.bytes.buffer.byteLength
? params.bytes
@@ -1808,8 +2007,8 @@ function subscribeTauriEvent<T>(eventName: string, handler: (payload: T) => void
let unlistenFn: (() => void) | null = null;
let disposed = false;
- void import('@tauri-apps/api/event')
- .then(({ listen }) =>
+ void getTauriListen()
+ .then((listen) =>
listen<T>(eventName, (event) => {
if (!disposed) {
handler(event.payload);
@@ -1862,6 +2061,10 @@ export function subscribeNativeStrokeCommitted(
return subscribeTauriEvent<NativeStrokeCommittedEvent>(EVENT_STROKE_COMMITTED, cb);
}
+export function subscribeNativeViewportInvalidated(cb: () => void): () => void {
+ return subscribeTauriEvent<unknown>(EVENT_VIEWPORT_INVALIDATED, () => cb());
+}
+
// ---------------------------------------------------------------------------
// Phase 6: Native Selection, GPU Liquify, Fill/Eyedropper, 5-Mode Transform,
// Retouch, Gradients, Shapes, Live Filters/Tonal, Vector, Collab & Zero-Canvas IO
@@ -2144,17 +2347,22 @@ export type NativeLiquifyMode =
| 'twirl-ccw'
| 'reconstruct';
+export interface NativeLiquifySettings {
+ mode: NativeLiquifyMode;
+ size: number;
+ strength: number;
+ hardness: number;
+ usePressure: boolean;
+ multiLayer?: boolean;
+}
+
export interface NativeLiquifyStepParams {
fromX: number;
fromY: number;
toX: number;
toY: number;
- mode: NativeLiquifyMode;
- size: number;
- strength: number;
- hardness: number;
pressure: number;
- usePressure: boolean;
+ settings: NativeLiquifySettings;
}
export async function nativeLiquifyBegin(
@@ -2356,15 +2564,15 @@ export interface NativePoint2D {
}
export interface NativeAffineState {
- tx: number;
- ty: number;
- scaleX: number;
- scaleY: number;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
rotation: number;
skewX: number;
skewY: number;
- pivotX: number;
- pivotY: number;
+ flipX: boolean;
+ flipY: boolean;
}
export interface NativeMeshState {
@@ -2385,38 +2593,38 @@ export interface NativePuppetPin {
export interface NativePuppetState {
pins: NativePuppetPin[];
- triangleCount: number;
+ meshVertices: NativePoint2D[];
+ meshTriangles: [number, number, number][];
}
export interface NativeCageState {
- restVertices: NativePoint2D[];
- vertices: NativePoint2D[];
+ restPoints: NativePoint2D[];
+ points: NativePoint2D[];
closed: boolean;
}
export interface NativeTransformSessionSnapshot {
active: boolean;
+ docId: string;
mode: NativeTransformMode;
- bounds: NativeRectI32;
- layerIds: string[];
+ targetLayerIds: string[];
+ sourceBounds: NativeRectI32;
affine: NativeAffineState;
corners: [NativePoint2D, NativePoint2D, NativePoint2D, NativePoint2D];
mesh: NativeMeshState;
puppet: NativePuppetState;
cage: NativeCageState;
+ showMesh: boolean;
}
-export type NativeTransformUpdatePayload =
- | { kind: 'affine'; state: NativeAffineState }
- | { kind: 'perspective'; corners: [NativePoint2D, NativePoint2D, NativePoint2D, NativePoint2D] }
- | { kind: 'mesh'; mesh: NativeMeshState }
- | { kind: 'puppet'; pins: NativePuppetPin[] }
- | {
- kind: 'cage';
- restVertices: NativePoint2D[];
- vertices: NativePoint2D[];
- closed: boolean;
- };
+export interface NativeTransformUpdatePayload {
+ mode: NativeTransformMode;
+ affine?: NativeAffineState;
+ corners?: [NativePoint2D, NativePoint2D, NativePoint2D, NativePoint2D];
+ mesh?: NativeMeshState;
+ puppetPins?: NativePuppetPin[];
+ cage?: NativeCageState;
+}
export interface NativeTransformCommitResult {
modified: boolean;
@@ -2476,12 +2684,10 @@ export type NativeRetouchKind =
| 'heal';
export interface NativeRetouchStepParams {
- fromX: number;
- fromY: number;
- toX: number;
- toY: number;
+ x: number;
+ y: number;
pressure: number;
- sourceOrigin?: [number, number] | null;
+ cloneSource?: [number, number] | null;
settings: {
kind: NativeRetouchKind;
size: number;
@@ -2683,10 +2889,14 @@ export type NativeImageOpSpec =
| { category: 'tonal'; tonal: NativeTonalSpec };
export interface NativeLayerHistogram {
+ rgb: number[];
+ /** Compatibility alias populated from `rgb` so legacy callers reading `.luminance` still work. */
luminance: number[];
r: number[];
g: number[];
b: number[];
+ totalOpaquePixels: number;
+ /** Compatibility alias populated from `totalOpaquePixels`. */
pixelCount: number;
}
@@ -2724,10 +2934,31 @@ export async function nativeLayerHistogram(
docId?: string | null
): Promise<NativeLayerHistogram | null> {
if (!isTauriDesktopRuntime()) return null;
- return invokeNative<NativeLayerHistogram>('native_layer_histogram', {
+ const raw = await invokeNative<Partial<NativeLayerHistogram>>('native_layer_histogram', {
docId: docId ?? null,
layerId: layerId ?? null,
});
+ if (!raw) return null;
+ const rgb = Array.isArray(raw.rgb)
+ ? raw.rgb
+ : Array.isArray(raw.luminance)
+ ? raw.luminance
+ : new Array<number>(256).fill(0);
+ const totalOpaquePixels =
+ typeof raw.totalOpaquePixels === 'number'
+ ? raw.totalOpaquePixels
+ : typeof raw.pixelCount === 'number'
+ ? raw.pixelCount
+ : 0;
+ return {
+ rgb,
+ luminance: rgb,
+ r: Array.isArray(raw.r) ? raw.r : new Array<number>(256).fill(0),
+ g: Array.isArray(raw.g) ? raw.g : new Array<number>(256).fill(0),
+ b: Array.isArray(raw.b) ? raw.b : new Array<number>(256).fill(0),
+ totalOpaquePixels,
+ pixelCount: totalOpaquePixels,
+ };
}
// --- 8. Vector Layer & Bézier Pen Fast Rasterization ---
@@ -2836,7 +3067,7 @@ export async function nativeCollabEncodeTiles(
docId?: string | null
): Promise<Uint8Array[]> {
if (!isTauriDesktopRuntime()) return [];
- const { invoke } = await import('@tauri-apps/api/core');
+ const invoke = await getTauriInvoke();
const raw = await invoke<ArrayBuffer>('native_collab_encode_tiles', {
docId: docId ?? null,
layerId,
@@ -2865,7 +3096,7 @@ export async function nativeCollabApplyTileDelta(
docId?: string | null
): Promise<{ layerId: string; tx: number; ty: number; codec: number; cleared: boolean } | null> {
if (!isTauriDesktopRuntime()) return null;
- const { invoke } = await import('@tauri-apps/api/core');
+ const invoke = await getTauriInvoke();
const payload =
packet.byteOffset === 0 && packet.byteLength === packet.buffer.byteLength
? packet
@@ -2883,7 +3114,7 @@ export async function nativeCollabEncodeMask(
docId?: string | null
): Promise<Uint8Array | null> {
if (!isTauriDesktopRuntime()) return null;
- const { invoke } = await import('@tauri-apps/api/core');
+ const invoke = await getTauriInvoke();
const raw = await invoke<ArrayBuffer>('native_collab_encode_mask', {
docId: docId ?? null,
layerId,
@@ -2897,7 +3128,7 @@ export async function nativeCollabApplyMask(
docId?: string | null
): Promise<void> {
if (!isTauriDesktopRuntime()) return;
- const { invoke } = await import('@tauri-apps/api/core');
+ const invoke = await getTauriInvoke();
const payload =
packet.byteOffset === 0 && packet.byteLength === packet.buffer.byteLength
? packet
@@ -2923,7 +3154,7 @@ export async function exportNativeDocumentImage(params: {
options?: NativeFlattenOptions;
}): Promise<Uint8Array | null> {
if (!isTauriDesktopRuntime()) return null;
- const { invoke } = await import('@tauri-apps/api/core');
+ const invoke = await getTauriInvoke();
const raw = await invoke<ArrayBuffer>('native_engine_export_image', {
docId: params.docId ?? null,
format: params.format,
@@ -2943,7 +3174,7 @@ export async function importNativeImageLayer(params: {
recordHistory?: boolean;
}): Promise<NativeDocumentMetaSnapshot | null> {
if (!isTauriDesktopRuntime()) return null;
- const { invoke } = await import('@tauri-apps/api/core');
+ const invoke = await getTauriInvoke();
const payload =
params.bytes.byteOffset === 0 && params.bytes.byteLength === params.bytes.buffer.byteLength
? params.bytes
@@ -2966,7 +3197,7 @@ export async function readNativeLayerBoundsRgba(
docId?: string | null
): Promise<{ x: number; y: number; width: number; height: number; rgba: Uint8ClampedArray<ArrayBuffer> } | null> {
if (!isTauriDesktopRuntime()) return null;
- const { invoke } = await import('@tauri-apps/api/core');
+ const invoke = await getTauriInvoke();
const raw = await invoke<ArrayBuffer>('native_engine_read_layer_rgba', {
docId: docId ?? null,
layerId,
@@ -2988,7 +3219,7 @@ export async function readNativeLayerMaskRgba(
docId?: string | null
): Promise<{ width: number; height: number; defaultColor: number; rgba: Uint8ClampedArray<ArrayBuffer> } | null> {
if (!isTauriDesktopRuntime()) return null;
- const { invoke } = await import('@tauri-apps/api/core');
+ const invoke = await getTauriInvoke();
const raw = await invoke<ArrayBuffer>('native_engine_read_layer_mask_rgba', {
docId: docId ?? null,
layerId,
diff --git a/src/utils/nativeOsHotkeys.ts b/src/utils/nativeOsHotkeys.ts
index 42e5307..29113af 100644
--- a/src/utils/nativeOsHotkeys.ts
+++ b/src/utils/nativeOsHotkeys.ts
@@ -95,9 +95,14 @@ function buildSignature(bindings: readonly NativeOsHotkeyBinding[], recording: b
return `${recording ? 'R' : 'N'}|${sorted}`;
}
-async function flushNativeSync(): Promise<void> {
+let nativeSyncGeneration = 0;
+let nativeSyncChain: Promise<void> = Promise.resolve();
+
+async function runNativeSyncStep(gen: number): Promise<void> {
+ if (gen !== nativeSyncGeneration) return;
const recording = activeRecordingCount > 0;
- const sig = buildSignature(lastBindings, recording);
+ const bindingsSnapshot = lastBindings.slice();
+ const sig = buildSignature(bindingsSnapshot, recording);
if (sig === lastSentSignature && activeChannel !== null) return;
if (!isTauriEnvironment()) {
@@ -107,11 +112,15 @@ async function flushNativeSync(): Promise<void> {
try {
const { invoke, Channel } = await import('@tauri-apps/api/core');
- if (lastBindings.length === 0 && !recording) {
+ if (gen !== nativeSyncGeneration) return;
+
+ if (bindingsSnapshot.length === 0 && !recording) {
if (activeChannel !== null) {
await invoke('os_hotkeys_stop');
}
- lastSentSignature = sig;
+ if (gen === nativeSyncGeneration) {
+ lastSentSignature = sig;
+ }
return;
}
@@ -130,16 +139,24 @@ async function flushNativeSync(): Promise<void> {
}
await invoke('os_hotkeys_sync', {
- bindings: lastBindings,
+ bindings: bindingsSnapshot,
recording,
onEvent: activeChannel,
});
- lastSentSignature = sig;
+ if (gen === nativeSyncGeneration) {
+ lastSentSignature = sig;
+ }
} catch {
// Non-desktop or unavailable backend: keep silent fallback to DOM KeyboardEvents
}
}
+function flushNativeSync(): Promise<void> {
+ const gen = ++nativeSyncGeneration;
+ nativeSyncChain = nativeSyncChain.then(() => runNativeSyncStep(gen));
+ return nativeSyncChain;
+}
+
export function syncNativeOsHotkeys(
commands: readonly CommandDefinition[],
overrides?: ShortcutOverrides
diff --git a/src/utils/nativeTabletInput.ts b/src/utils/nativeTabletInput.ts
index 1bc8139..6d756e3 100644
--- a/src/utils/nativeTabletInput.ts
+++ b/src/utils/nativeTabletInput.ts
@@ -1,9 +1,11 @@
/**
- * Native low-latency Windows tablet input client (WinTab / Windows Ink API via Rust Channel).
- * Replaces throttled browser PointerEvents on Tauri desktop while falling back cleanly on Web.
+ * Native Windows tablet packet unpacking and WebView zoom coordinate helpers.
+ *
+ * Native raster/mask brush strokes are consumed directly in Rust `ink-engine` via its lock-free
+ * WinTab / Windows Ink SPSC ring (zero WebView IPC). Non-native tools and vector layers use
+ * standard DOM PointerEvents without a separate legacy JS tablet channel.
*/
-import { isTauriEnvironment } from './tauriEnv';
import { getActiveNativeWebviewZoom } from './interfaceScale';
export type TabletInputMode = 'auto' | 'wintab' | 'windows-ink' | 'off';
@@ -30,11 +32,9 @@ export interface NativeTabletSample {
backend: 1 | 2; // 1=wintab, 2=windows-ink
}
-export type TabletSampleBatchListener = (samples: NativeTabletSample[]) => void;
-
const SAMPLE_WIRE_BYTES = 36;
-const listeners = new Set<TabletSampleBatchListener>();
-let activeStatus: NativeTabletStatus = {
+
+const DEFAULT_TABLET_STATUS: NativeTabletStatus = {
active: false,
backend: 'none',
wintabAvailable: false,
@@ -42,17 +42,13 @@ let activeStatus: NativeTabletStatus = {
deviceName: null,
maxPressure: 1024,
};
-let lastPacketPerfMs = 0;
-let nativePenInProximity = false;
-let nativePenInContact = false;
-let lastNativeClientX = 0;
-let lastNativeClientY = 0;
-let startPromise: Promise<NativeTabletStatus> | null = null;
/**
* Unpacks a binary batch frame emitted by `src-tauri/src/tablet_input.rs`.
*/
-export function unpackTabletSampleBatch(raw: ArrayBuffer | Uint8Array | number[]): NativeTabletSample[] {
+export function unpackTabletSampleBatch(
+ raw: ArrayBuffer | Uint8Array | number[]
+): NativeTabletSample[] {
const bytes =
raw instanceof Uint8Array
? raw
@@ -86,139 +82,13 @@ export function unpackTabletSampleBatch(raw: ArrayBuffer | Uint8Array | number[]
return out;
}
-/**
- * Updates internal native pen proximity/contact tracking from a received native tablet batch.
- * Exported for deterministic unit testing of DOM pointer suppression logic.
- */
-export function recordNativeTabletBatchForSuppression(
- batch: ReadonlyArray<NativeTabletSample>,
- nowMs?: number
-): void {
- if (batch.length === 0) return;
- lastPacketPerfMs =
- nowMs !== undefined ? nowMs : typeof performance !== 'undefined' ? performance.now() : Date.now();
- for (let i = 0; i < batch.length; i++) {
- const s = batch[i];
- if (s.phase === 1 || s.phase === 2) {
- nativePenInProximity = true;
- nativePenInContact = true;
- lastNativeClientX = s.clientX;
- lastNativeClientY = s.clientY;
- } else if (s.phase === 0 || s.phase === 3) {
- nativePenInProximity = true;
- nativePenInContact = false;
- lastNativeClientX = s.clientX;
- lastNativeClientY = s.clientY;
- } else if (s.phase === 4) {
- const stillDown = (s.buttons & 1) !== 0 || s.pressure > 0.001;
- if (!stillDown) {
- nativePenInProximity = false;
- nativePenInContact = false;
- }
- }
- }
-}
-
-/**
- * Resets internal native tablet stream state (for unit tests and shutdown).
- */
-export function resetNativeTabletSuppressionState(activeOverride?: boolean): void {
- lastPacketPerfMs = 0;
- nativePenInProximity = false;
- nativePenInContact = false;
- lastNativeClientX = 0;
- lastNativeClientY = 0;
- if (activeOverride !== undefined) {
- activeStatus = { ...activeStatus, active: activeOverride };
- }
-}
-
-/**
- * Clears active native pen contact state (e.g. on window blur / tab hide) without disabling
- * the native tablet channel so stale contact cannot block subsequent DOM or pen strokes.
- */
-export function clearNativePenContact(): void {
- nativePenInContact = false;
-}
-
-/**
- * Returns true if native WinTab / Windows Ink packets are currently active and recently received
- * (used to suppress redundant DOM `pointerType === 'pen'` PointerEvents).
- */
-export function isNativePenStreamActive(nowMs?: number): boolean {
- if (!activeStatus.active) return false;
- const now =
- nowMs !== undefined ? nowMs : typeof performance !== 'undefined' ? performance.now() : Date.now();
- return lastPacketPerfMs > 0 && now - lastPacketPerfMs < 1500;
-}
-
-/**
- * Returns true ONLY if the native tablet stream is actively in tip-down contact right now
- * (recently received an in-contact packet without a subsequent pen-up/hover/leave).
- * Used to guard against stale native stroke lockout on DOM/mouse pointerdown.
- */
-export function isNativePenInActiveContact(nowMs?: number): boolean {
- if (!activeStatus.active || !nativePenInContact || lastPacketPerfMs <= 0) return false;
- const now =
- nowMs !== undefined ? nowMs : typeof performance !== 'undefined' ? performance.now() : Date.now();
- return now - lastPacketPerfMs < 500;
-}
-
-/**
- * Returns true if a DOM PointerEvent should be suppressed because the native WinTab / Windows Ink
- * channel already owns this pen interaction.
- *
- * Critically suppresses WinTab `CXO_SYSTEM`-synthesized DOM `pointerType === 'mouse'` events
- * (which carry constant `pressure = 0.5` and would otherwise abort/hijack active native pen strokes!),
- * while allowing a separate physical mouse to work immediately once the stylus leaves proximity.
- */
-export function shouldSuppressDomPointerEvent(
- pointerType: string,
- clientX: number,
- clientY: number,
- nowMs?: number
-): boolean {
- if (!activeStatus.active || lastPacketPerfMs <= 0) return false;
- const now =
- nowMs !== undefined ? nowMs : typeof performance !== 'undefined' ? performance.now() : Date.now();
- const elapsed = now - lastPacketPerfMs;
-
- if (pointerType === 'pen') {
- return elapsed < 1500;
- }
-
- if (pointerType === 'mouse') {
- // Active native pen stroke: NEVER allow a WinTab-synthesized mouse event to abort or duplicate it
- if (nativePenInContact && elapsed < 1500) {
- return true;
- }
- // Stylus actively hovering/tracking in proximity: WinTab CXO_SYSTEM drives the OS mouse cursor
- if (nativePenInProximity && elapsed < 400) {
- return true;
- }
- // Brief post-lift/pre-down coincidence window at the exact pen cursor location
- if (elapsed < 250 && Math.hypot(clientX - lastNativeClientX, clientY - lastNativeClientY) <= 24) {
- return true;
- }
- }
-
- return false;
-}
-
export function getCachedTabletStatus(): NativeTabletStatus {
- return activeStatus;
-}
-
-export function subscribeNativeTablet(listener: TabletSampleBatchListener): () => void {
- listeners.add(listener);
- return () => {
- listeners.delete(listener);
- };
+ return DEFAULT_TABLET_STATUS;
}
/**
- * Converts OS logical client coordinates emitted by `tablet_input.rs` into zoomed WebView CSS
- * pixel coordinates when native WebView interface scaling is active.
+ * Converts OS logical client coordinates into zoomed WebView CSS pixel coordinates when
+ * native WebView interface scaling is active.
*/
export function adjustTabletSamplesForWebviewZoom(
samples: NativeTabletSample[],
@@ -233,74 +103,3 @@ export function adjustTabletSamplesForWebviewZoom(
}
return samples;
}
-
-export async function startNativeTablet(mode: TabletInputMode = 'auto'): Promise<NativeTabletStatus> {
- if (!isTauriEnvironment()) {
- return activeStatus;
- }
- if (mode === 'off') {
- await stopNativeTablet();
- return activeStatus;
- }
- if (startPromise) return startPromise;
-
- startPromise = (async () => {
- try {
- const { invoke, Channel } = await import('@tauri-apps/api/core');
- const channel = new Channel<ArrayBuffer | Uint8Array | number[]>();
- channel.onmessage = (payload) => {
- const batch = adjustTabletSamplesForWebviewZoom(unpackTabletSampleBatch(payload));
- if (batch.length === 0) return;
- recordNativeTabletBatchForSuppression(batch);
- for (const fn of listeners) {
- fn(batch);
- }
- };
-
- const status = await invoke<NativeTabletStatus>('tablet_start_input', {
- mode,
- onSamples: channel,
- });
- activeStatus = status;
- return status;
- } catch {
- activeStatus = {
- ...activeStatus,
- active: false,
- backend: 'none',
- };
- return activeStatus;
- } finally {
- startPromise = null;
- }
- })();
-
- return startPromise;
-}
-
-export async function stopNativeTablet(): Promise<void> {
- if (!isTauriEnvironment()) return;
- try {
- const { invoke } = await import('@tauri-apps/api/core');
- await invoke('tablet_stop_input');
- } catch {
- // Ignore shutdown errors
- }
- resetNativeTabletSuppressionState(false);
- activeStatus = {
- ...activeStatus,
- active: false,
- backend: 'none',
- };
-}
-
-export async function queryNativeTabletStatus(): Promise<NativeTabletStatus> {
- if (!isTauriEnvironment()) return activeStatus;
- try {
- const { invoke } = await import('@tauri-apps/api/core');
- activeStatus = await invoke<NativeTabletStatus>('tablet_get_status');
- } catch {
- // Ignore
- }
- return activeStatus;
-}
diff --git a/src/utils/performanceManager.ts b/src/utils/performanceManager.ts
index 0e99db7..b7c2bce 100644
--- a/src/utils/performanceManager.ts
+++ b/src/utils/performanceManager.ts
@@ -77,28 +77,28 @@ export interface GpuTexturePoolSpec {
export const GPU_TEXTURE_POOL_CONFIGS: Record<GpuTexturePoolPreset, GpuTexturePoolSpec> = {
low: {
- arrayLayers: 128,
+ arrayLayers: 256,
maxTexture2D: 512,
- estimatedVramMb: 32,
- label: 'Low (32 MB)',
+ estimatedVramMb: 128,
+ label: 'Low (128 MB)',
},
balanced: {
- arrayLayers: 256,
+ arrayLayers: 512,
maxTexture2D: 1024,
- estimatedVramMb: 64,
- label: 'Balanced (64 MB)',
+ estimatedVramMb: 256,
+ label: 'Balanced (256 MB)',
},
high: {
- arrayLayers: 512,
+ arrayLayers: 1024,
maxTexture2D: 2048,
- estimatedVramMb: 128,
- label: 'High (128 MB)',
+ estimatedVramMb: 512,
+ label: 'High (512 MB)',
},
ultra: {
- arrayLayers: 1024,
+ arrayLayers: 2048,
maxTexture2D: 4096,
- estimatedVramMb: 256,
- label: 'Ultra (256 MB)',
+ estimatedVramMb: 1024,
+ label: 'Ultra (1024 MB)',
},
};
@@ -596,6 +596,13 @@ export interface RegisteredMemoryHooks {
purgeTiles: () => Promise<number>;
purgeUndo: () => Promise<number>;
flushBrushGpuCaches?: () => void;
+ refreshNativeMemoryStats?: () => Promise<{
+ ramTotalBytes: number;
+ ramBudgetBytes: number;
+ vramUsedBytes: number;
+ vramSlotsUsed: number;
+ vramSlotsCapacity: number;
+ } | null>;
}
type PerfListener = (config: RuntimePerformanceConfig) => void;
@@ -822,9 +829,26 @@ class PerformanceManager {
}
public async getMemoryTelemetry(): Promise<LiveMemoryTelemetry> {
- const activeTileBytes = this.memoryHooks?.getActiveTileBytes() ?? 0;
+ let nativeStats: {
+ ramTotalBytes: number;
+ ramBudgetBytes: number;
+ vramUsedBytes: number;
+ vramSlotsUsed: number;
+ vramSlotsCapacity: number;
+ } | null = null;
+ if (this.memoryHooks?.refreshNativeMemoryStats) {
+ try {
+ nativeStats = await this.memoryHooks.refreshNativeMemoryStats();
+ } catch {
+ // Ignore transient native stats errors
+ }
+ }
+
+ const activeTileBytes = nativeStats?.ramTotalBytes ?? this.memoryHooks?.getActiveTileBytes() ?? 0;
const tileBudgetBytes =
- this.memoryHooks?.getTileBudgetBytes() ?? this.config.tileMemoryBudgetMb * 1024 * 1024;
+ (nativeStats && nativeStats.ramBudgetBytes > 0 ? nativeStats.ramBudgetBytes : null) ??
+ this.memoryHooks?.getTileBudgetBytes() ??
+ this.config.tileMemoryBudgetMb * 1024 * 1024;
const undoStats = this.memoryHooks?.getUndoStats() ?? {
ramSteps: 0,
diskSteps: 0,
@@ -873,15 +897,22 @@ class PerformanceManager {
(poolPreset && GPU_TEXTURE_POOL_CONFIGS[poolPreset]) || GPU_TEXTURE_POOL_CONFIGS.high;
const compositor: CompositorTelemetry = this.compositorHooks?.getTelemetry() ?? {
- backend: this.config.renderBackend === 'canvas2d' ? 'canvas2d' : 'webgl2',
- rendererName:
- this.config.renderBackend === 'canvas2d'
+ backend: nativeStats
+ ? 'dx12'
+ : this.config.renderBackend === 'canvas2d'
+ ? 'canvas2d'
+ : 'webgl2',
+ rendererName: nativeStats
+ ? 'Native DX12 Engine'
+ : this.config.renderBackend === 'canvas2d'
? 'Canvas 2D (CPU)'
: this.cachedHardwareInfo?.activeWebGl?.renderer || 'WebGL2',
- arrayPoolUsed: 0,
- arrayPoolCapacity: poolSpec.arrayLayers,
+ arrayPoolUsed: nativeStats?.vramSlotsUsed ?? 0,
+ arrayPoolCapacity: nativeStats?.vramSlotsCapacity || poolSpec.arrayLayers,
texture2DPoolUsed: 0,
- estimatedVramMb: 0,
+ estimatedVramMb: nativeStats
+ ? Math.round((nativeStats.vramUsedBytes / (1024 * 1024)) * 10) / 10
+ : 0,
stackCacheHits: 0,
stackCacheRebuilds: 0,
};
diff --git a/src/utils/pressureCurve.ts b/src/utils/pressureCurve.ts
index fcea047..23d06b6 100644
--- a/src/utils/pressureCurve.ts
+++ b/src/utils/pressureCurve.ts
@@ -14,9 +14,9 @@ const MIN_POINT_SPACING_X = 0.02;
* Clamps, sorts, and deduplicates pressure curve control points while pinning endpoints at x=0 and x=1.
*/
export function sanitizePressureCurvePoints(
- points: readonly PressureCurvePoint[]
+ points?: readonly PressureCurvePoint[] | null
): PressureCurvePoint[] {
- if (!points || points.length < 2) {
+ if (!Array.isArray(points) || points.length < 2) {
return [
[0, 0],
[1, 1],
@@ -28,6 +28,8 @@ export function sanitizePressureCurvePoints(
(p) =>
Array.isArray(p) &&
p.length >= 2 &&
+ typeof p[0] === 'number' &&
+ typeof p[1] === 'number' &&
Number.isFinite(p[0]) &&
Number.isFinite(p[1])
)
@@ -78,17 +80,47 @@ export function sanitizePressureCurvePoints(
return dedup;
}
+/**
+ * Normalizes a potentially missing, legacy, or malformed PressureCurveSettings object.
+ */
+export function normalizePressureCurve(
+ settings?: Partial<PressureCurveSettings> | null
+): PressureCurveSettings {
+ const validPresets: readonly PressureCurvePreset[] = ['linear', 'soft', 'hard', 'custom'];
+ const preset: PressureCurvePreset =
+ settings && typeof settings.preset === 'string' && validPresets.includes(settings.preset)
+ ? settings.preset
+ : 'linear';
+ const enabled = typeof settings?.enabled === 'boolean' ? settings.enabled : true;
+ const points = sanitizePressureCurvePoints(settings?.points);
+ return { enabled, preset, points };
+}
+
/**
* Fast identity check to avoid unnecessary LUT lookups on default linear curve.
*/
export function isLinearPressureCurve(points?: readonly PressureCurvePoint[] | null): boolean {
- if (!points || points.length < 2) return true;
+ if (!Array.isArray(points) || points.length < 2) return true;
if (points.length !== 2) return false;
+ const p0 = points[0];
+ const p1 = points[1];
+ if (
+ !Array.isArray(p0) ||
+ !Array.isArray(p1) ||
+ p0.length < 2 ||
+ p1.length < 2 ||
+ !Number.isFinite(p0[0]) ||
+ !Number.isFinite(p0[1]) ||
+ !Number.isFinite(p1[0]) ||
+ !Number.isFinite(p1[1])
+ ) {
+ return true;
+ }
return (
- Math.abs(points[0][0]) < 1e-4 &&
- Math.abs(points[0][1]) < 1e-4 &&
- Math.abs(points[1][0] - 1) < 1e-4 &&
- Math.abs(points[1][1] - 1) < 1e-4
+ Math.abs(p0[0]) < 1e-4 &&
+ Math.abs(p0[1]) < 1e-4 &&
+ Math.abs(p1[0] - 1) < 1e-4 &&
+ Math.abs(p1[1] - 1) < 1e-4
);
}
@@ -131,10 +163,10 @@ export function createPressureCurvePreset(
preset: Exclude<PressureCurvePreset, 'custom'>,
enabled: boolean = true
): PressureCurveSettings {
- const pts = PRESSURE_CURVE_PRESETS[preset];
+ const pts = PRESSURE_CURVE_PRESETS[preset] ?? PRESSURE_CURVE_PRESETS.linear;
return {
enabled,
- preset,
+ preset: PRESSURE_CURVE_PRESETS[preset] ? preset : 'linear',
points: pts.map(([x, y]) => [x, y] as PressureCurvePoint),
};
}
diff --git a/src/utils/recentDocumentsManager.ts b/src/utils/recentDocumentsManager.ts
index d0d7aba..0c76332 100644
--- a/src/utils/recentDocumentsManager.ts
+++ b/src/utils/recentDocumentsManager.ts
@@ -70,18 +70,26 @@ function stripForLocalStorage(doc: RecentDocument): RecentDocument {
return lightweight;
}
+let cachedRecentDbPromise: Promise<IDBDatabase> | null = null;
+let cachedRecentIdbFactory: IDBFactory | null = null;
+
function openDB(): Promise<IDBDatabase> {
- return new Promise((resolve, reject) => {
- const idb =
- typeof indexedDB !== 'undefined'
- ? indexedDB
- : typeof window !== 'undefined'
- ? window.indexedDB
- : undefined;
- if (!idb) {
- reject(new Error('IndexedDB not available'));
- return;
- }
+ const idb =
+ typeof indexedDB !== 'undefined'
+ ? indexedDB
+ : typeof window !== 'undefined'
+ ? window.indexedDB
+ : undefined;
+ if (!idb) {
+ cachedRecentDbPromise = null;
+ cachedRecentIdbFactory = null;
+ return Promise.reject(new Error('IndexedDB not available'));
+ }
+ if (cachedRecentDbPromise && cachedRecentIdbFactory === idb) {
+ return cachedRecentDbPromise;
+ }
+ cachedRecentIdbFactory = idb;
+ cachedRecentDbPromise = new Promise<IDBDatabase>((resolve, reject) => {
const req = idb.open(DB_NAME, DB_VERSION);
req.onupgradeneeded = (e) => {
const db = (e.target as IDBOpenDBRequest).result;
@@ -91,9 +99,26 @@ function openDB(): Promise<IDBDatabase> {
store.createIndex('isStarred', 'isStarred', { unique: false });
}
};
- req.onsuccess = () => resolve(req.result);
- req.onerror = () => reject(req.error);
+ req.onsuccess = () => {
+ const db = req.result;
+ db.onclose = () => {
+ cachedRecentDbPromise = null;
+ cachedRecentIdbFactory = null;
+ };
+ db.onversionchange = () => {
+ db.close();
+ cachedRecentDbPromise = null;
+ cachedRecentIdbFactory = null;
+ };
+ resolve(db);
+ };
+ req.onerror = () => {
+ cachedRecentDbPromise = null;
+ cachedRecentIdbFactory = null;
+ reject(req.error);
+ };
});
+ return cachedRecentDbPromise;
}
function writeFallbackDocs(docs: RecentDocument[]): void {
@@ -284,6 +309,8 @@ export async function toggleStarDocument(id: string): Promise<boolean> {
}
};
req.onerror = () => resolve(false);
+ tx.onerror = () => resolve(false);
+ tx.onabort = () => resolve(false);
});
} catch {
const current = getFallbackDocs();
@@ -305,6 +332,7 @@ export async function removeRecentDocument(id: string): Promise<void> {
tx.objectStore(STORE_NAME).delete(id);
tx.oncomplete = () => resolve();
tx.onerror = () => resolve();
+ tx.onabort = () => resolve();
});
} catch {
// ignore
diff --git a/src/utils/saveManager/fileActions.ts b/src/utils/saveManager/fileActions.ts
index ead934c..0401d34 100644
--- a/src/utils/saveManager/fileActions.ts
+++ b/src/utils/saveManager/fileActions.ts
@@ -4,6 +4,7 @@ import { buildInkStudioXmpMetadata, sanitizeWorkTimeMs } from '../artworkTimeTra
import {
exportNativeDocumentImage,
saveNativeInkDocument,
+ syncNativeDocumentMeta,
} from '../nativeEngineBridge';
import {
ExportImageOptions,
@@ -289,6 +290,14 @@ export async function promptSaveAs(
let previewDataUrl: string | undefined;
if (normalized.extension === PRIMARY_PROJECT_EXTENSION && data.tabId) {
+ await syncNativeDocumentMeta(data.tabId, {
+ name: normalized.stem,
+ perspectiveRuler: data.perspectiveRuler ?? null,
+ straightRuler: data.straightRuler ?? null,
+ animationTimeline: data.animationTimeline ?? null,
+ timelapse: data.timelapse ?? null,
+ workTimeMs: data.workTimeMs,
+ }).catch((err) => console.warn('[SaveManager] Failed to sync doc meta before save:', err));
const nativeSave = await saveNativeInkDocument(data.tabId, chosenPath);
bytesWritten = nativeSave.bytesWritten;
previewDataUrl = nativeSave.previewDataUrl ?? undefined;
@@ -372,6 +381,14 @@ export async function saveToExistingHandle(
const targetExt = normalizeExtension(fileInfo.extension, PRIMARY_PROJECT_EXTENSION);
if (targetExt === PRIMARY_PROJECT_EXTENSION && data.tabId) {
+ await syncNativeDocumentMeta(data.tabId, {
+ name: cleanStem,
+ perspectiveRuler: data.perspectiveRuler ?? null,
+ straightRuler: data.straightRuler ?? null,
+ animationTimeline: data.animationTimeline ?? null,
+ timelapse: data.timelapse ?? null,
+ workTimeMs: data.workTimeMs,
+ }).catch((err) => console.warn('[SaveManager] Failed to sync doc meta before save:', err));
const nativeSave = await saveNativeInkDocument(data.tabId, fileInfo.path!);
recoveryService.markCleanSaved(data.tabId).catch(console.warn);
return {
diff --git a/src/utils/saveManager/types.ts b/src/utils/saveManager/types.ts
index 5a3e317..70dc568 100644
--- a/src/utils/saveManager/types.ts
+++ b/src/utils/saveManager/types.ts
@@ -72,6 +72,7 @@ export interface SaveDocumentData {
isLayerEffectivelyVisible: (layer: LayerItem) => boolean;
tabId?: string;
perspectiveRuler?: PerspectiveRuler | null;
+ straightRuler?: unknown;
animationTimeline?: AnimationTimeline | null;
timelapse?: InkTimelapseMetadata | null;
/** Legacy embedded frames (only written if `embedTimelapseFrames` is explicitly true). */
diff --git a/src/utils/timelapseEngine.ts b/src/utils/timelapseEngine.ts
index 9770bc6..c560f69 100644
--- a/src/utils/timelapseEngine.ts
+++ b/src/utils/timelapseEngine.ts
@@ -170,10 +170,10 @@ function packFrameIndices(indices: number[]): Uint8Array {
/**
* Packs a batch of timelapse frames into the binary format expected by Rust `timelapse_write_frames_batch`:
- * `[count: u32 LE] ([frameIndex: u32 LE][extCode: u8 (0=webp, 1=jpg)][dataLen: u32 LE][data])*`
+ * `[count: u32 LE] ([frameIndex: u32 LE][extCode: u8 (0=webp, 1=jpg, 2=png)][dataLen: u32 LE][data])*`
*/
export function packTimelapseFrameBatch(
- entries: Array<{ index: number; ext: 'webp' | 'jpg'; bytes: Uint8Array }>
+ entries: Array<{ index: number; ext: 'webp' | 'jpg' | 'png'; bytes: Uint8Array }>
): Uint8Array {
let total = 4;
for (const e of entries) {
@@ -185,7 +185,7 @@ export function packTimelapseFrameBatch(
let offset = 4;
for (const e of entries) {
view.setUint32(offset, e.index >>> 0, true);
- out[offset + 4] = e.ext === 'jpg' ? 1 : 0;
+ out[offset + 4] = e.ext === 'png' ? 2 : e.ext === 'jpg' ? 1 : 0;
view.setUint32(offset + 5, e.bytes.byteLength >>> 0, true);
offset += 9;
out.set(e.bytes, offset);
@@ -904,7 +904,12 @@ export class TimelapseRecorderManager {
timestamp: pf.timestamp || fallbackFm?.timestamp || 0,
width: pf.width || fallbackFm?.width || fallbackW,
height: pf.height || fallbackFm?.height || fallbackH,
- mimeType: pf.mimeType === 'image/jpeg' ? 'image/jpeg' : 'image/webp',
+ mimeType:
+ pf.mimeType === 'image/png'
+ ? 'image/png'
+ : pf.mimeType === 'image/jpeg'
+ ? 'image/jpeg'
+ : 'image/webp',
bytes,
offloadedToDisk: true,
captureArea: pf.captureArea,
@@ -958,9 +963,14 @@ export class TimelapseRecorderManager {
): Promise<void> {
const total = validFrames.length;
const normalized = validFrames.map((f, seqIdx) => {
- const mimeType: 'image/webp' | 'image/jpeg' =
- f.mimeType === 'image/jpeg' ? 'image/jpeg' : 'image/webp';
- const ext: 'webp' | 'jpg' = mimeType === 'image/jpeg' ? 'jpg' : 'webp';
+ const mimeType: 'image/webp' | 'image/jpeg' | 'image/png' =
+ f.mimeType === 'image/png'
+ ? 'image/png'
+ : f.mimeType === 'image/jpeg'
+ ? 'image/jpeg'
+ : 'image/webp';
+ const ext: 'webp' | 'jpg' | 'png' =
+ mimeType === 'image/png' ? 'png' : mimeType === 'image/jpeg' ? 'jpg' : 'webp';
return {
index: seqIdx,
timestamp: Number.isFinite(f.timestamp) ? f.timestamp : 0,
@@ -1602,7 +1612,12 @@ export class TimelapseRecorderManager {
let body: Uint8Array;
const headers: Record<string, string> = {
'x-session-id': encodeURIComponent(sess.recordingId),
- 'x-ext': refFrame.mimeType === 'image/webp' ? 'webp' : 'jpg',
+ 'x-ext':
+ refFrame.mimeType === 'image/png'
+ ? 'png'
+ : refFrame.mimeType === 'image/webp'
+ ? 'webp'
+ : 'jpg',
'x-fps': String(fps),
'x-width': String(targetDims.width),
'x-height': String(targetDims.height),
@@ -1739,6 +1754,7 @@ export class TimelapseRecorderManager {
recorder.start();
const frameIntervalMs = Math.max(16, Math.round(1000 / fps));
let lastDrawnSrcIdx = -1;
+ let blob: Blob;
try {
for (let i = 0; i < sampledIndices.length; i++) {
@@ -1757,6 +1773,20 @@ export class TimelapseRecorderManager {
onProgress?.((i + 1) / sampledIndices.length);
await new Promise((r) => setTimeout(r, frameIntervalMs));
}
+ if (recorder.state !== 'inactive') {
+ recorder.stop();
+ }
+ blob = await stoppedPromise;
+ } catch (err) {
+ try {
+ if (recorder.state !== 'inactive') {
+ recorder.stop();
+ }
+ } catch {
+ // Ignore stop errors during failure unwind
+ }
+ void stoppedPromise.catch(() => {});
+ throw err;
} finally {
for (const item of decodedCache.values()) {
if ('close' in item && typeof item.close === 'function') {
@@ -1764,12 +1794,15 @@ export class TimelapseRecorderManager {
}
}
decodedCache.clear();
+ stream.getTracks().forEach((t) => {
+ try {
+ t.stop();
+ } catch {
+ // Ignore track stop errors
+ }
+ });
}
- recorder.stop();
- const blob = await stoppedPromise;
- stream.getTracks().forEach((t) => t.stop());
-
return {
blob,
mimeType,
diff --git a/src/utils/timelapseStorage.ts b/src/utils/timelapseStorage.ts
index 77dd214..e43d679 100644
--- a/src/utils/timelapseStorage.ts
+++ b/src/utils/timelapseStorage.ts
@@ -303,6 +303,7 @@ async function idbSaveMeta(meta: PersistentTimelapseMeta): Promise<boolean> {
};
tx.oncomplete = () => resolve(true);
tx.onerror = () => resolve(false);
+ tx.onabort = () => resolve(false);
} catch {
resolve(false);
}
@@ -347,6 +348,9 @@ async function idbWriteFrame(
frames: [],
totalBytes: 0,
};
+ if (!Array.isArray(base.frames)) {
+ base.frames = [];
+ }
const existingIdx = base.frames.findIndex((f) => f.index === record.index);
if (existingIdx >= 0) {
base.totalBytes = Math.max(0, base.totalBytes - base.frames[existingIdx].bytes) + record.bytes;
@@ -363,6 +367,7 @@ async function idbWriteFrame(
tx.oncomplete = () => resolve(true);
tx.onerror = () => resolve(false);
+ tx.onabort = () => resolve(false);
} catch {
resolve(false);
}
@@ -428,14 +433,18 @@ async function idbListSessions(): Promise<StoredRecordingSummary[]> {
req.onsuccess = () => {
const rows = (req.result as IdbStoredSessionRecord[] | undefined) ?? [];
const summaries: StoredRecordingSummary[] = rows
- .filter((r) => r && (r.frames.length > 0 || r.enabled))
+ .filter((r) => {
+ if (!r) return false;
+ const framesLen = Array.isArray(r.frames) ? r.frames.length : 0;
+ return framesLen > 0 || Boolean(r.enabled);
+ })
.map((r) => ({
recordingId: r.recordingId,
documentName: r.documentName || 'Untitled',
enabled: Boolean(r.enabled),
captureArea: r.captureArea || 'artwork',
captureResolution: r.captureResolution || '1080p',
- frameCount: r.frames.length,
+ frameCount: Array.isArray(r.frames) ? r.frames.length : 0,
totalBytes: r.totalBytes || 0,
createdAt: r.createdAt || 0,
updatedAt: r.updatedAt || 0,
@@ -444,6 +453,8 @@ async function idbListSessions(): Promise<StoredRecordingSummary[]> {
resolve(summaries);
};
req.onerror = () => resolve([]);
+ tx.onerror = () => resolve([]);
+ tx.onabort = () => resolve([]);
} catch {
resolve([]);
}
@@ -469,6 +480,7 @@ async function idbClearSession(recordingId: string): Promise<void> {
};
tx.oncomplete = () => resolve();
tx.onerror = () => resolve();
+ tx.onabort = () => resolve();
} catch {
resolve();
}
diff --git a/src/utils/toolConfigs.ts b/src/utils/toolConfigs.ts
index 1404ca5..3c20e91 100644
--- a/src/utils/toolConfigs.ts
+++ b/src/utils/toolConfigs.ts
@@ -174,16 +174,19 @@ export function resolveGradientStops(
primaryColor: string,
secondaryColor: string
): ParsedRgbaStop[] {
- const raw = settings.stops.length >= 2 ? settings.stops : DEFAULT_GRADIENT_SETTINGS.stops;
+ const candidateStops = Array.isArray(settings?.stops)
+ ? settings.stops.filter((s) => Boolean(s) && typeof s === 'object')
+ : [];
+ const raw = candidateStops.length >= 2 ? candidateStops : DEFAULT_GRADIENT_SETTINGS.stops;
const sorted = [...raw]
.map((s) => ({
offset: Math.max(0, Math.min(1, Number.isFinite(s.offset) ? s.offset : 0)),
- color: s.color,
+ color: typeof s.color === 'string' && s.color ? s.color : '#000000',
opacity: Math.max(0, Math.min(1, Number.isFinite(s.opacity) ? s.opacity : 1)),
}))
.sort((a, b) => a.offset - b.offset);
- if (settings.useForegroundBackground && sorted.length >= 2) {
+ if (settings?.useForegroundBackground && sorted.length >= 2) {
sorted[0] = { ...sorted[0], color: primaryColor || '#000000' };
sorted[sorted.length - 1] = {
...sorted[sorted.length - 1],
@@ -223,11 +226,14 @@ export function createDefaultGradientMesh(
const w = Math.max(1, bounds.width);
const h = Math.max(1, bounds.height);
+ const safeStops = Array.isArray(stops) ? stops : [];
+ const midStopColor = safeStops.length > 2 ? safeStops[Math.floor(safeStops.length / 2)]?.color : undefined;
+ const endStopColor = safeStops.length > 0 ? safeStops[safeStops.length - 1]?.color : undefined;
const cornerColors = [
primaryColor || '#3b82f6',
secondaryColor || '#f43f5e',
- stops && stops.length > 2 ? stops[Math.floor(stops.length / 2)].color : '#10b981',
- stops && stops.length > 0 ? stops[stops.length - 1].color : '#f59e0b',
+ typeof midStopColor === 'string' && midStopColor ? midStopColor : '#10b981',
+ typeof endStopColor === 'string' && endStopColor ? endStopColor : '#f59e0b',
];
const parsedCorners = cornerColors.map((c) => parseHexRgb(c));
@@ -540,20 +546,31 @@ export function toNativeGradientParams(params: {
const b = getGradientMeshBounds(mesh);
const w = Math.max(1, b.width);
const h = Math.max(1, b.height);
+ const cx = b.minX + w * 0.5;
+ const cy = b.minY + h * 0.5;
+ const rotRad = ((mesh.rotationDeg ?? 0) * Math.PI) / 180;
+ const cRot = Math.cos(-rotRad);
+ const sRot = Math.sin(-rotRad);
+ // Rust GradientMeshParams uses cell counts (stride = cols + 1, expecting (cols+1)*(rows+1) nodes),
+ // whereas TS GradientMeshState stores vertex counts (mesh.cols * mesh.rows === mesh.nodes.length).
+ const cellCols = Math.max(1, mesh.cols - 1);
+ const cellRows = Math.max(1, mesh.rows - 1);
nativeMesh = {
- cols: mesh.cols,
- rows: mesh.rows,
+ cols: cellCols,
+ rows: cellRows,
x: b.minX,
y: b.minY,
width: w,
height: h,
- rotation: ((mesh.rotationDeg ?? 0) * Math.PI) / 180,
- nodes: mesh.nodes.map((n, idx) => {
- const c = idx % mesh.cols;
- const r = Math.floor(idx / mesh.cols);
+ rotation: rotRad,
+ nodes: mesh.nodes.map((n) => {
+ const dx = n.x - cx;
+ const dy = n.y - cy;
+ const lx = dx * cRot - dy * sRot;
+ const ly = dx * sRot + dy * cRot;
return {
- u: mesh.cols > 1 ? c / (mesh.cols - 1) : 0,
- v: mesh.rows > 1 ? r / (mesh.rows - 1) : 0,
+ u: Math.max(0, Math.min(1, lx / w + 0.5)),
+ v: Math.max(0, Math.min(1, ly / h + 0.5)),
color: n.color,
opacity: n.opacity,
};
@@ -724,11 +741,24 @@ export interface TileHistogramMap {
*/
export function buildMonotonicCubicSplineLut(points: [number, number][]): Uint8Array {
const lut = new Uint8Array(256);
- if (!points || points.length === 0) {
+ const validPoints: [number, number][] = Array.isArray(points)
+ ? points
+ .filter(
+ (pt): pt is [number, number] =>
+ Array.isArray(pt) &&
+ pt.length >= 2 &&
+ typeof pt[0] === 'number' &&
+ typeof pt[1] === 'number' &&
+ Number.isFinite(pt[0]) &&
+ Number.isFinite(pt[1])
+ )
+ .map(([x, y]) => [x, y])
+ : [];
+ if (validPoints.length === 0) {
for (let i = 0; i < 256; i++) lut[i] = i;
return lut;
}
- const sorted = [...points].sort((a, b) => a[0] - b[0]);
+ const sorted = validPoints.sort((a, b) => a[0] - b[0]);
const unique: [number, number][] = [];
for (const pt of sorted) {
if (unique.length > 0 && Math.abs(unique[unique.length - 1][0] - pt[0]) < 1e-4) {
@@ -824,7 +854,16 @@ export function buildGradientMapLut(
interpolation: 'linear' | 'smooth' = 'linear'
): Uint8ClampedArray {
const lut = new Uint8ClampedArray(256 * 4);
- if (!stops || stops.length === 0) {
+ const validStops = Array.isArray(stops)
+ ? stops.filter(
+ (s) =>
+ Boolean(s) &&
+ typeof s === 'object' &&
+ typeof s.position === 'number' &&
+ Number.isFinite(s.position)
+ )
+ : [];
+ if (validStops.length === 0) {
for (let i = 0; i < 256; i++) {
lut[i * 4] = i;
lut[i * 4 + 1] = i;
@@ -833,7 +872,7 @@ export function buildGradientMapLut(
}
return lut;
}
- const sorted = [...stops]
+ const sorted = [...validStops]
.sort((a, b) => a.position - b.position)
.map((s) => ({
pos: Math.max(0, Math.min(1, s.position)),
@@ -889,7 +928,7 @@ export function toNativeFilterSpec(type: FilterType, params: Record<string, unkn
kind: 'unsharp-mask',
amount: Number(params.amount ?? 1.0),
radius: Number(params.radius ?? 2.0),
- threshold: Math.round(Number(params.threshold ?? 0)),
+ threshold: Math.max(0, Math.min(255, Math.round(Number(params.threshold ?? 0)))),
};
case 'film-grain':
default:
@@ -898,7 +937,7 @@ export function toNativeFilterSpec(type: FilterType, params: Record<string, unkn
intensity: Number(params.intensity ?? 25),
size: Number(params.size ?? 1),
monochrome: params.monochromatic !== false,
- seed: Math.round(Number(params.seed ?? 1337)),
+ seed: Math.max(0, Math.round(Number(params.seed ?? 1337))) >>> 0,
};
}
}
diff --git a/src/utils/vectorLayerRenderer.ts b/src/utils/vectorLayerRenderer.ts
index 544930f..785a2cd 100644
--- a/src/utils/vectorLayerRenderer.ts
+++ b/src/utils/vectorLayerRenderer.ts
@@ -129,11 +129,12 @@ export function hitTestEditableVectorLayer(
export function syncVectorObjectLayerToGrid(
layer: LayerItem,
dimensions: CanvasDimensions,
- explicitDocId?: string | null
-): void {
- if (typeof document === 'undefined') return;
- if (layer.type !== 'text' && layer.type !== 'balloon') return;
- if (dimensions.width <= 0 || dimensions.height <= 0) return;
+ explicitDocId?: string | null,
+ recordHistory: boolean = true
+): Promise<void> {
+ if (typeof document === 'undefined') return Promise.resolve();
+ if (layer.type !== 'text' && layer.type !== 'balloon') return Promise.resolve();
+ if (dimensions.width <= 0 || dimensions.height <= 0) return Promise.resolve();
let minX = 0;
let minY = 0;
@@ -177,11 +178,10 @@ export function syncVectorObjectLayerToGrid(
const rw = maxX - minX;
const rh = maxY - minY;
const nativeDocId = explicitDocId ?? useDocumentStore.getState().activeDocumentId;
- if (!nativeDocId) return;
+ if (!nativeDocId) return Promise.resolve();
if (rw <= 0 || rh <= 0) {
- void clearNativeLayer(nativeDocId, layer.id, false);
- return;
+ return clearNativeLayer(nativeDocId, layer.id, false).then(() => undefined);
}
// Render in <= 1024x1024 bounded chunks so WebView2 never allocates a full-document canvas
@@ -193,7 +193,7 @@ export function syncVectorObjectLayerToGrid(
const ctx = scratch.getContext('2d', { willReadFrequently: true });
if (!ctx) {
releaseTemporaryCanvas(scratch);
- return;
+ return Promise.resolve();
}
for (let cy = minY; cy < maxY; cy += CHUNK) {
@@ -219,7 +219,7 @@ export function syncVectorObjectLayerToGrid(
}
releaseTemporaryCanvas(scratch);
- void (async () => {
+ return (async () => {
await clearNativeLayer(nativeDocId, layer.id, false);
for (let i = 0; i < chunks.length; i++) {
const c = chunks[i];
@@ -231,7 +231,7 @@ export function syncVectorObjectLayerToGrid(
width: c.w,
height: c.h,
bytes: c.bytes,
- recordHistory: i === chunks.length - 1,
+ recordHistory: recordHistory && i === chunks.length - 1,
actionType: layer.type,
label: layer.type === 'balloon' ? 'Edit Speech Balloon' : 'Edit Text Layer',
});
diff --git a/src/utils/webtoonExporter.ts b/src/utils/webtoonExporter.ts
index 7d46e7d..a4f3dbc 100644
--- a/src/utils/webtoonExporter.ts
+++ b/src/utils/webtoonExporter.ts
@@ -30,19 +30,20 @@ export async function exportNativeWebtoonChapterZip(
totalHeight: number,
options: WebtoonSliceOptions = {}
): Promise<Uint8Array> {
- const sliceHeight = options.sliceHeight || 1280;
+ const safeTotalWidth = Math.max(1, Math.round(totalWidth) || 1);
+ const safeTotalHeight = Math.max(1, Math.round(totalHeight) || 1);
+ const sliceHeight = Math.max(1, Math.round(options.sliceHeight || 1280));
const format = options.format || 'jpg';
const quality = options.quality ?? 0.92;
const filePrefix = options.filePrefix || 'slice_';
const ext = format === 'jpg' ? 'jpg' : 'png';
- const sliceWidth = options.sliceWidth || totalWidth;
- const totalSlices = Math.max(1, Math.ceil(totalHeight / sliceHeight));
+ const totalSlices = Math.max(1, Math.ceil(safeTotalHeight / sliceHeight));
const zipFiles: Record<string, Uint8Array> = {};
for (let i = 0; i < totalSlices; i++) {
const srcY = i * sliceHeight;
- const currentSliceH = Math.min(sliceHeight, totalHeight - srcY);
+ const currentSliceH = Math.max(1, Math.min(sliceHeight, safeTotalHeight - srcY));
const bytes = await exportNativeDocumentImage({
docId: docId ?? null,
@@ -52,7 +53,7 @@ export async function exportNativeWebtoonChapterZip(
region: {
x: 0,
y: srcY,
- width: sliceWidth,
+ width: safeTotalWidth,
height: currentSliceH,
},
fillWhiteBackground: format === 'jpg',
diff --git a/src/utils/workspacePresets.ts b/src/utils/workspacePresets.ts
index 8f4ee23..83f6b28 100644
--- a/src/utils/workspacePresets.ts
+++ b/src/utils/workspacePresets.ts
@@ -648,27 +648,28 @@ function normalizeFloatingZIndices(panels: FloatingPanelState[]): FloatingPanelS
}
export function getGroupCells(group: DockGroup): DockSplitCell[] {
- if (group.splitCells && group.splitCells.length > 1) {
+ if (Array.isArray(group?.splitCells) && group.splitCells.length > 1) {
return group.splitCells;
}
return [
{
- id: group.id,
- panelIds: group.panelIds,
- activePanelId: group.activePanelId,
+ id: group?.id ?? 'group',
+ panelIds: Array.isArray(group?.panelIds) ? group.panelIds : [],
+ activePanelId: group?.activePanelId,
widthRatio: 1,
- collapsed: group.collapsed,
+ collapsed: group?.collapsed,
},
];
}
export function isGroupSplit(group: DockGroup): boolean {
- return Boolean(group.splitCells && group.splitCells.length > 1);
+ return Boolean(Array.isArray(group?.splitCells) && group.splitCells.length > 1);
}
function normalizeSplitCells(cells: DockSplitCell[]): DockSplitCell[] {
+ if (!Array.isArray(cells)) return [];
const nonEmpty = cells
- .filter((c) => c.panelIds.length > 0)
+ .filter((c) => c && Array.isArray(c.panelIds) && c.panelIds.length > 0)
.map((c) => ({
...c,
panelIds: [...c.panelIds],
@@ -1235,18 +1236,21 @@ export function movePanelInLayout(
const grpIdx = col ? col.groups.findIndex((g) => g.id === target.targetGroupId) : -1;
if (col && grpIdx >= 0) {
const grp = col.groups[grpIdx];
- if (grp.splitCells && grp.splitCells.length > 1) {
+ if (Array.isArray(grp.splitCells) && grp.splitCells.length > 1) {
const targetCell =
(target.targetCellId
? grp.splitCells.find((c) => c.id === target.targetCellId)
: undefined) ?? grp.splitCells[0];
- if (!targetCell.panelIds.includes(panelId)) {
- targetCell.panelIds.push(panelId);
+ if (targetCell) {
+ if (!Array.isArray(targetCell.panelIds)) targetCell.panelIds = [];
+ if (!targetCell.panelIds.includes(panelId)) {
+ targetCell.panelIds.push(panelId);
+ }
+ targetCell.activePanelId = panelId;
+ targetCell.collapsed = false;
}
- targetCell.activePanelId = panelId;
- targetCell.collapsed = false;
grp.collapsed = false;
- grp.panelIds = grp.splitCells.flatMap((c) => c.panelIds);
+ grp.panelIds = grp.splitCells.flatMap((c) => (Array.isArray(c.panelIds) ? c.panelIds : []));
} else {
if (!grp.panelIds.includes(panelId)) {
grp.panelIds.push(panelId);
@@ -1360,7 +1364,7 @@ export function setGroupActivePanelInLayout(
return {
...g,
collapsed: false,
- activePanelId: nextCells[0].activePanelId,
+ activePanelId: nextCells[0]?.activePanelId ?? g.activePanelId,
splitCells: nextCells,
};
}
@@ -1785,7 +1789,9 @@ export function dockFloatingPanelInLayout(
const preferredCol = sideCols.find(
(c) =>
!(
+ Array.isArray(c.groups) &&
c.groups.length === 1 &&
+ Array.isArray(c.groups[0]?.panelIds) &&
c.groups[0].panelIds.length === 1 &&
c.groups[0].panelIds[0] === 'tools'
)
@@ -2005,7 +2011,14 @@ export function togglePanelInLayout(
}
const targetCols = targetSide === 'left' ? layout.leftDocks : layout.rightDocks;
const preferredCol = targetCols.find(
- (c) => !(c.groups.length === 1 && c.groups[0].panelIds.length === 1 && c.groups[0].panelIds[0] === 'tools')
+ (c) =>
+ !(
+ Array.isArray(c.groups) &&
+ c.groups.length === 1 &&
+ Array.isArray(c.groups[0]?.panelIds) &&
+ c.groups[0].panelIds.length === 1 &&
+ c.groups[0].panelIds[0] === 'tools'
+ )
);
if (preferredCol && panelId !== 'tools') {
return movePanelInLayout(layout, panelId, {