Skip to content

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

139 KB
Raw Blame
//! Sparse GPU Stroke Tile Pool & Instanced DX12 Brush Renderer (`sparse_stroke.rs`).
//!
//! Never allocates a full-canvas (e.g. 8K) FBO: allocates only `256×256` `Rgba16Float`
//! tile slices touched by the active stroke, batches dab instances into a single GPU upload,
//! runs Dual Brush / Per-Stroke Paper Grain / 2-Pass Seamless Watercolor Wet Edge strictly
//! over dirty tiles, and commits finished tiles directly into `GpuTilePool` in <1 ms!

use super::config::{
    CspBlendTipsMode, CspBrushCombineMode, DualBrushCompositeMode, NativeBrushConfig,
};
use super::dynamics::GpuBrushDab;
use super::shaders::{
    build_brush_dab_wgsl, build_stroke_post_tile_wgsl, build_tile_commit_compute_wgsl,
    STROKE_DARKEN_MERGE_WGSL, WET_EDGE_TILE_WGSL,
};
use super::tip_cache::{BrushTextureKind, TipTextureCache};
use crate::document::{Document, ImpastoLayerLight, LayerNode};
use crate::memory::{GpuTileKey, GpuTilePool, ScratchBackend};
use crate::natural_paint::{
    collect_ribbon_touched_tiles, CommittedNaturalPaintBatch, GpuBristleCapsule,
    GpuNaturalPaintEngine, GpuRibbonPipeline, RibbonVertex,
};
use crate::tiles::{RectI32, SparseLayerGrid, TileCoord, TILE_SIZE};
use bytemuck::{Pod, Zeroable};
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};

const UNIFORM_STRIDE: u64 = 256;

#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
pub struct DabPassUniforms {
    pub tile_origin_doc: [f32; 2],
    pub doc_size: [f32; 2],
    pub viewport_size_phys: [f32; 2],
    pub pan_css: [f32; 2],
    pub zoom: f32,
    pub rotation_rad: f32,
    pub flip: [f32; 2],
    pub dpr: f32,
    pub paper_scale: f32,
    pub paper_rot_rad: f32,
    pub paper_brightness: f32,
    pub paper_contrast: f32,
    pub _pad0: f32,
    pub paper_size: [f32; 2],
    pub paper_offset_norm: [f32; 2],
    pub stroke_rand_offset: [f32; 2],
    pub flags0: [u32; 4],
    pub flags1: [u32; 4],
    pub flags2: [u32; 4],
}

#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct DarkenParamsUniform {
    dst_slot: i32,
    _pad: [i32; 3],
}

#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct StrokePostUniforms {
    tile_origin_doc: [f32; 2],
    paper_size: [f32; 2],
    paper_offset_norm: [f32; 2],
    stroke_rand_offset: [f32; 2],
    paper_scale: f32,
    paper_rot_rad: f32,
    paper_brightness: f32,
    paper_contrast: f32,
    grain_strength: f32,
    avg_pressure: f32,
    stroke_angle_rad: f32,
    _pad0: f32,
    slots: [i32; 4],
    paper_flags: [u32; 4],
    extra_flags: [u32; 4],
}

#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct WetEdgeUniforms {
    n0: [i32; 4],
    n1: [i32; 4],
    n2: [i32; 4],
    params: [f32; 4],
}

#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct TileCommitUniforms {
    slots: [i32; 4],
    flags: [u32; 4],
    extra: [u32; 4],
    params: [f32; 4],
}

/// Sparse `256×256` `Rgba16Float` `Texture2DArray` pool for active stroke tiles.
/// Dynamically grows only if a single stroke exceeds current capacity (starts lean at 32 slots).
struct SparseStrokePool {
    label: &'static str,
    texture: wgpu::Texture,
    array_view: wgpu::TextureView,
    slice_views: Vec<wgpu::TextureView>,
    capacity: u32,
    gen: u64,
    coord_to_slot: HashMap<TileCoord, u32>,
    next_slot: u32,
}

impl SparseStrokePool {
    fn new(device: &wgpu::Device, label: &'static str, initial_capacity: u32) -> Self {
        let cap = initial_capacity.clamp(4, device.limits().max_texture_array_layers.max(4));
        let (texture, array_view, slice_views) = Self::alloc_texture(device, label, cap);
        Self {
            label,
            texture,
            array_view,
            slice_views,
            capacity: cap,
            gen: 1,
            coord_to_slot: HashMap::with_capacity(cap as usize),
            next_slot: 0,
        }
    }

    fn alloc_texture(
        device: &wgpu::Device,
        label: &'static str,
        capacity: u32,
    ) -> (wgpu::Texture, wgpu::TextureView, Vec<wgpu::TextureView>) {
        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some(label),
            size: wgpu::Extent3d {
                width: TILE_SIZE as u32,
                height: TILE_SIZE as u32,
                depth_or_array_layers: capacity,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba16Float,
            usage: wgpu::TextureUsages::TEXTURE_BINDING
                | wgpu::TextureUsages::RENDER_ATTACHMENT
                | wgpu::TextureUsages::COPY_DST
                | wgpu::TextureUsages::COPY_SRC,
            view_formats: &[],
        });
        let array_view = texture.create_view(&wgpu::TextureViewDescriptor {
            label: Some(label),
            dimension: Some(wgpu::TextureViewDimension::D2Array),
            base_array_layer: 0,
            array_layer_count: Some(capacity),
            ..Default::default()
        });
        let slice_views = (0..capacity)
            .map(|i| {
                texture.create_view(&wgpu::TextureViewDescriptor {
                    label: None,
                    dimension: Some(wgpu::TextureViewDimension::D2),
                    base_array_layer: i,
                    array_layer_count: Some(1),
                    ..Default::default()
                })
            })
            .collect();
        (texture, array_view, slice_views)
    }

    fn reset(&mut self) {
        self.coord_to_slot.clear();
        self.next_slot = 0;
    }

    fn grow_if_needed(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        needed_total: u32,
    ) {
        if needed_total <= self.capacity {
            return;
        }
        let max_layers = device.limits().max_texture_array_layers.max(16);
        let new_cap = (needed_total.next_power_of_two()).min(max_layers);
        if new_cap <= self.capacity {
            return;
        }
        let (new_tex, new_array_view, new_slices) =
            Self::alloc_texture(device, self.label, new_cap);

        // Preserve already-allocated active stroke slices via VRAM copy
        if self.next_slot > 0 {
            let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("ink-sparse-pool-grow-copy"),
            });
            enc.copy_texture_to_texture(
                wgpu::TexelCopyTextureInfo {
                    texture: &self.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: self.next_slot,
                },
            );
            queue.submit(Some(enc.finish()));
        }

        self.texture = new_tex;
        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)`.
    fn get_or_alloc(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        coord: TileCoord,
    ) -> Option<(u32, bool)> {
        if let Some(&slot) = self.coord_to_slot.get(&coord) {
            return Some((slot, false));
        }
        let target = self.next_slot + 1;
        self.grow_if_needed(device, queue, target);
        if self.next_slot >= self.capacity {
            return None;
        }
        let slot = self.next_slot;
        self.next_slot += 1;
        self.coord_to_slot.insert(coord, slot);
        Some((slot, true))
    }

    #[inline]
    fn get_slot(&self, coord: &TileCoord) -> Option<u32> {
        self.coord_to_slot.get(coord).copied()
    }
}

/// Result returned by [`GpuBrushEngine::commit_to_layer_pool`].
pub struct CommittedTileBatch {
    /// Updated RGBA8 tile buffers `(coord, rgba8_bytes, new_version)` ready to store into `SparseLayerGrid`.
    pub tiles: Vec<(TileCoord, Vec<u8>, u64)>,
    /// Union document-space dirty rectangle of committed tiles.
    pub dirty_rect: RectI32,
}

/// Complete DX12 GPU Instanced Brush Engine managing sparse stroke tiles,
/// tips & paper texture cache, dual brush, wet edge, prediction, and sub-ms tile commit.
pub struct GpuBrushEngine {
    pub tip_cache: TipTextureCache,
    tip_sampler: wgpu::Sampler,
    paper_sampler: wgpu::Sampler,

    // Instanced dab rendering pipelines (tile-space & viewport-prediction-space)
    dab_bgl: wgpu::BindGroupLayout,
    dab_tile_normal_pipeline: wgpu::RenderPipeline,
    dab_tile_compare_pipeline: wgpu::RenderPipeline,
    dab_viewport_normal_pipeline: wgpu::RenderPipeline,
    dab_viewport_compare_pipeline: wgpu::RenderPipeline,
    dab_instance_buf: wgpu::Buffer,
    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,

    // Dual brush combine + per-stroke paper grain compute pipeline
    post_bgl: wgpu::BindGroupLayout,
    post_pipeline: wgpu::ComputePipeline,
    post_uniform_buf: wgpu::Buffer,
    post_uniform_cap: usize,
    post_scratch_tex: wgpu::Texture,
    post_scratch_view: wgpu::TextureView,

    // 2-pass seamless watercolor wet-edge compute pipelines
    wet_bgl: wgpu::BindGroupLayout,
    wet_horiz_pipeline: wgpu::ComputePipeline,
    wet_vert_pipeline: wgpu::ComputePipeline,
    wet_uniform_buf: wgpu::Buffer,
    wet_uniform_cap: usize,
    _wet_padded_tex: wgpu::Texture,
    wet_padded_view: wgpu::TextureView,

    // Sub-millisecond GPU-to-GPU tile commit compute pipeline
    commit_bgl: wgpu::BindGroupLayout,
    commit_pipeline: wgpu::ComputePipeline,
    commit_uniform_buf: wgpu::Buffer,
    commit_uniform_cap: usize,
    commit_scratch_16f: wgpu::Texture,
    commit_scratch_16f_view: wgpu::TextureView,
    _commit_dummy_sel_tex: wgpu::Texture,
    commit_dummy_sel_view: wgpu::TextureView,
    commit_rgba8_storage_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!)
    primary_pool: SparseStrokePool,
    secondary_pool: SparseStrokePool,
    mid_pool: SparseStrokePool,
    resolved_pool: SparseStrokePool,

    // Phase 5: Continuous UV-mapped Ribbon Mesh Pipeline + Full Physical Media Compute Engine
    pub ribbon_pipeline: GpuRibbonPipeline,
    pub natural_paint: GpuNaturalPaintEngine,

    // Active stroke state
    active: bool,
    doc_width: u32,
    doc_height: u32,
    mono_1bit: bool,
    active_brush: NativeBrushConfig,
    stroke_rand_offset: [f32; 2],
    last_stroke_angle_rad: f32,
    avg_pressure: f32,
    dirty_post_tiles: HashSet<TileCoord>,
    use_resolved_output: bool,
    /// True while a Select Pen / Select Eraser stroke is active (disables clipping the live stroke preview to the old selection mask).
    is_selection_brush_stroke: bool,
}

impl GpuBrushEngine {
    pub fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self {
        let tip_cache = TipTextureCache::new(device, queue);
        let tip_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("ink-brush-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 paper_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("ink-brush-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()
        });

        // 1. Instanced Dab Pipelines
        let dab_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("ink-brush-dab-bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: true,
                        min_binding_size: None,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2Array,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 3,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 4,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
            ],
        });

        let dab_shader_src = build_brush_dab_wgsl();
        let dab_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("ink-brush-dab-shader"),
            source: wgpu::ShaderSource::Wgsl(Cow::Owned(dab_shader_src)),
        });
        let dab_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("ink-brush-dab-pl"),
            bind_group_layouts: &[Some(&dab_bgl)],
            immediate_size: 0,
        });

        let compare_blend = wgpu::BlendState {
            color: wgpu::BlendComponent {
                src_factor: wgpu::BlendFactor::One,
                dst_factor: wgpu::BlendFactor::One,
                operation: wgpu::BlendOperation::Max,
            },
            alpha: wgpu::BlendComponent {
                src_factor: wgpu::BlendFactor::One,
                dst_factor: wgpu::BlendFactor::One,
                operation: wgpu::BlendOperation::Max,
            },
        };

        let make_dab_pipeline = |label: &str, vs: &str, blend: wgpu::BlendState| {
            let instance_attrs = [
                wgpu::VertexAttribute {
                    offset: 0,
                    shader_location: 0,
                    format: wgpu::VertexFormat::Float32x4,
                },
                wgpu::VertexAttribute {
                    offset: 16,
                    shader_location: 1,
                    format: wgpu::VertexFormat::Float32x4,
                },
                wgpu::VertexAttribute {
                    offset: 32,
                    shader_location: 2,
                    format: wgpu::VertexFormat::Float32x4,
                },
                wgpu::VertexAttribute {
                    offset: 48,
                    shader_location: 3,
                    format: wgpu::VertexFormat::Float32x4,
                },
                wgpu::VertexAttribute {
                    offset: 64,
                    shader_location: 4,
                    format: wgpu::VertexFormat::Float32x4,
                },
            ];
            let instance_layout = wgpu::VertexBufferLayout {
                array_stride: std::mem::size_of::<GpuBrushDab>() as u64,
                step_mode: wgpu::VertexStepMode::Instance,
                attributes: &instance_attrs,
            };
            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some(label),
                layout: Some(&dab_pl),
                vertex: wgpu::VertexState {
                    module: &dab_shader,
                    entry_point: Some(vs),
                    buffers: &[Some(instance_layout)],
                    compilation_options: Default::default(),
                },
                fragment: Some(wgpu::FragmentState {
                    module: &dab_shader,
                    entry_point: Some("fs_main"),
                    targets: &[Some(wgpu::ColorTargetState {
                        format: wgpu::TextureFormat::Rgba16Float,
                        blend: Some(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,
            })
        };

        let dab_tile_normal_pipeline = make_dab_pipeline(
            "ink-brush-dab-tile-normal",
            "vs_tile",
            wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING,
        );
        let dab_tile_compare_pipeline =
            make_dab_pipeline("ink-brush-dab-tile-compare", "vs_tile", compare_blend);
        let dab_viewport_normal_pipeline = make_dab_pipeline(
            "ink-brush-dab-viewport-normal",
            "vs_viewport",
            wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING,
        );
        let dab_viewport_compare_pipeline = make_dab_pipeline(
            "ink-brush-dab-viewport-compare",
            "vs_viewport",
            compare_blend,
        );

        let dab_instance_cap = 4096usize;
        let dab_instance_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-brush-dab-instances"),
            size: (dab_instance_cap * std::mem::size_of::<GpuBrushDab>()) as u64,
            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let dab_uniform_cap = 256usize;
        let dab_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-brush-dab-uniforms"),
            size: dab_uniform_cap as u64 * UNIFORM_STRIDE,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        // 2. Darken Merge Compute Pipeline
        let darken_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("ink-brush-darken-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: None,
                    },
                    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::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 3,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::StorageTexture {
                        access: wgpu::StorageTextureAccess::WriteOnly,
                        format: wgpu::TextureFormat::Rgba16Float,
                        view_dimension: wgpu::TextureViewDimension::D2,
                    },
                    count: None,
                },
            ],
        });
        let darken_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("ink-brush-darken-shader"),
            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(STROKE_DARKEN_MERGE_WGSL)),
        });
        let darken_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("ink-brush-darken-pl"),
            bind_group_layouts: &[Some(&darken_bgl)],
            immediate_size: 0,
        });
        let darken_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: Some("ink-brush-darken-pipeline"),
            layout: Some(&darken_pl),
            module: &darken_shader,
            entry_point: Some("cs_main"),
            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: darken_uniform_cap as u64 * UNIFORM_STRIDE,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let darken_batch_tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("ink-brush-darken-batch-256"),
            size: wgpu::Extent3d {
                width: TILE_SIZE as u32,
                height: TILE_SIZE as u32,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba16Float,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
            view_formats: &[],
        });
        let darken_batch_view =
            darken_batch_tex.create_view(&wgpu::TextureViewDescriptor::default());

        // 3. Dual Brush + Per-Stroke Paper Post-Pass Compute Pipeline
        let post_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("ink-brush-post-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: None,
                    },
                    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::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
                        view_dimension: wgpu::TextureViewDimension::D2Array,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 3,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 4,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 5,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::StorageTexture {
                        access: wgpu::StorageTextureAccess::WriteOnly,
                        format: wgpu::TextureFormat::Rgba16Float,
                        view_dimension: wgpu::TextureViewDimension::D2,
                    },
                    count: None,
                },
            ],
        });
        let post_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("ink-brush-post-shader"),
            source: wgpu::ShaderSource::Wgsl(Cow::Owned(build_stroke_post_tile_wgsl())),
        });
        let post_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("ink-brush-post-pl"),
            bind_group_layouts: &[Some(&post_bgl)],
            immediate_size: 0,
        });
        let post_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: Some("ink-brush-post-pipeline"),
            layout: Some(&post_pl),
            module: &post_shader,
            entry_point: Some("cs_main"),
            compilation_options: Default::default(),
            cache: None,
        });
        let post_uniform_cap = 256usize;
        let post_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-brush-post-uniforms"),
            size: post_uniform_cap as u64 * UNIFORM_STRIDE,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let post_scratch_tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("ink-brush-post-scratch-256"),
            size: wgpu::Extent3d {
                width: TILE_SIZE as u32,
                height: TILE_SIZE as u32,
                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::COPY_SRC,
            view_formats: &[],
        });
        let post_scratch_view =
            post_scratch_tex.create_view(&wgpu::TextureViewDescriptor::default());

        // 4. Seamless 2-Pass Watercolor Wet Edge Compute Pipelines
        let wet_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("ink-brush-wet-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: None,
                    },
                    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::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 3,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::StorageTexture {
                        access: wgpu::StorageTextureAccess::WriteOnly,
                        format: wgpu::TextureFormat::Rgba16Float,
                        view_dimension: wgpu::TextureViewDimension::D2,
                    },
                    count: None,
                },
            ],
        });
        let wet_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("ink-brush-wet-shader"),
            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(WET_EDGE_TILE_WGSL)),
        });
        let wet_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("ink-brush-wet-pl"),
            bind_group_layouts: &[Some(&wet_bgl)],
            immediate_size: 0,
        });
        let wet_horiz_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: Some("ink-brush-wet-horiz"),
            layout: Some(&wet_pl),
            module: &wet_shader,
            entry_point: Some("cs_wet_horiz"),
            compilation_options: Default::default(),
            cache: None,
        });
        let wet_vert_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: Some("ink-brush-wet-vert"),
            layout: Some(&wet_pl),
            module: &wet_shader,
            entry_point: Some("cs_wet_vert"),
            compilation_options: Default::default(),
            cache: None,
        });
        let wet_uniform_cap = 256usize;
        let wet_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-brush-wet-uniforms"),
            size: wet_uniform_cap as u64 * UNIFORM_STRIDE,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let wet_padded_tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("ink-brush-wet-padded-288"),
            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 wet_padded_view = wet_padded_tex.create_view(&wgpu::TextureViewDescriptor::default());

        // 5. Sub-millisecond GPU-to-GPU Tile Commit Compute Pipeline
        let commit_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("ink-tile-commit-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: None,
                    },
                    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::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
                        view_dimension: wgpu::TextureViewDimension::D2Array,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 3,
                    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: 4,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::StorageTexture {
                        access: wgpu::StorageTextureAccess::WriteOnly,
                        format: wgpu::TextureFormat::Rgba16Float,
                        view_dimension: wgpu::TextureViewDimension::D2,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 5,
                    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 commit_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("ink-tile-commit-shader"),
            source: wgpu::ShaderSource::Wgsl(Cow::Owned(build_tile_commit_compute_wgsl())),
        });
        let commit_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("ink-tile-commit-pl"),
            bind_group_layouts: &[Some(&commit_bgl)],
            immediate_size: 0,
        });
        let commit_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: Some("ink-tile-commit-pipeline"),
            layout: Some(&commit_pl),
            module: &commit_shader,
            entry_point: Some("cs_commit"),
            compilation_options: Default::default(),
            cache: None,
        });
        let commit_uniform_cap = 256usize;
        let commit_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-tile-commit-uniforms"),
            size: commit_uniform_cap as u64 * UNIFORM_STRIDE,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let commit_scratch_16f = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("ink-tile-commit-scratch-16f"),
            size: wgpu::Extent3d {
                width: TILE_SIZE as u32,
                height: TILE_SIZE as u32,
                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::COPY_SRC,
            view_formats: &[],
        });
        let commit_scratch_16f_view =
            commit_scratch_16f.create_view(&wgpu::TextureViewDescriptor::default());

        let commit_dummy_sel_tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("ink-tile-commit-dummy-sel"),
            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::R8Unorm,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });
        queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &commit_dummy_sel_tex,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            &[255u8],
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(1),
                rows_per_image: Some(1),
            },
            wgpu::Extent3d {
                width: 1,
                height: 1,
                depth_or_array_layers: 1,
            },
        );
        let commit_dummy_sel_view = commit_dummy_sel_tex.create_view(&wgpu::TextureViewDescriptor {
            dimension: Some(wgpu::TextureViewDimension::D2Array),
            base_array_layer: 0,
            array_layer_count: Some(1),
            ..Default::default()
        });

        let commit_buf_tile_cap = 32usize;
        let commit_buf_bytes = (commit_buf_tile_cap * TILE_SIZE * TILE_SIZE * 4) as u64;
        let commit_rgba8_storage_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-tile-commit-rgba8-storage"),
            size: commit_buf_bytes,
            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
            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);
        let secondary_pool = SparseStrokePool::new(device, "ink-stroke-secondary-pool", 16);
        let mid_pool = SparseStrokePool::new(device, "ink-stroke-mid-pool", 16);
        let resolved_pool = SparseStrokePool::new(device, "ink-stroke-resolved-pool", 16);

        let ribbon_pipeline = GpuRibbonPipeline::new(device);
        let natural_paint = GpuNaturalPaintEngine::new(device);

        Self {
            tip_cache,
            tip_sampler,
            paper_sampler,
            dab_bgl,
            dab_tile_normal_pipeline,
            dab_tile_compare_pipeline,
            dab_viewport_normal_pipeline,
            dab_viewport_compare_pipeline,
            dab_instance_buf,
            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,
            post_pipeline,
            post_uniform_buf,
            post_uniform_cap,
            post_scratch_tex,
            post_scratch_view,
            wet_bgl,
            wet_horiz_pipeline,
            wet_vert_pipeline,
            wet_uniform_buf,
            wet_uniform_cap,
            _wet_padded_tex: wet_padded_tex,
            wet_padded_view,
            commit_bgl,
            commit_pipeline,
            commit_uniform_buf,
            commit_uniform_cap,
            commit_scratch_16f,
            commit_scratch_16f_view,
            _commit_dummy_sel_tex: commit_dummy_sel_tex,
            commit_dummy_sel_view,
            commit_rgba8_storage_buf,
            commit_rgba8_readback_bufs,
            commit_rb_idx: 0,
            commit_buf_tile_cap,
            primary_pool,
            secondary_pool,
            mid_pool,
            resolved_pool,
            ribbon_pipeline,
            natural_paint,
            active: false,
            doc_width: 1,
            doc_height: 1,
            mono_1bit: false,
            active_brush: NativeBrushConfig::default(),
            stroke_rand_offset: [0.0, 0.0],
            last_stroke_angle_rad: 0.0,
            avg_pressure: 0.5,
            dirty_post_tiles: HashSet::new(),
            use_resolved_output: false,
            is_selection_brush_stroke: false,
        }
    }

    #[inline]
    pub fn set_selection_brush_stroke(&mut self, active: bool) {
        self.is_selection_brush_stroke = active;
    }

    #[inline]
    pub fn is_selection_brush_stroke(&self) -> bool {
        self.is_selection_brush_stroke
    }

    #[allow(clippy::too_many_arguments)]
    pub fn upload_texture_rgba8(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        hash: String,
        kind: BrushTextureKind,
        width: u32,
        height: u32,
        rgba8: Vec<u8>,
    ) -> Result<(), String> {
        self.tip_cache
            .upload_rgba8(device, queue, hash, kind, width, height, rgba8)
    }

    pub fn upload_texture_png(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        hash: String,
        kind: BrushTextureKind,
        png_bytes: &[u8],
    ) -> Result<(u32, u32), String> {
        self.tip_cache
            .upload_png(device, queue, hash, kind, png_bytes)
    }

    #[inline]
    pub fn is_active(&self) -> bool {
        self.active || self.natural_paint.is_active()
    }

    /// True when the active stroke is executing in Phase 5 direct-layer-replacement mode
    /// (Natural Paint / Color Mixing compute shaders whose tiles already hold Base + Mixed Stroke).
    #[inline]
    pub fn is_direct_replace_mode(&self) -> bool {
        self.natural_paint.is_active()
    }

    #[inline]
    pub fn active_brush(&self) -> &NativeBrushConfig {
        &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() {
            self.natural_paint.pools.coord_to_slot.len()
        } else if self.use_resolved_output {
            self.resolved_pool.coord_to_slot.len()
        } else {
            self.primary_pool.coord_to_slot.len()
        }
    }

    /// 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() {
            let (v, m) = self.natural_paint.active_color_atlas();
            ((3, self.natural_paint.pools.atlas_gen), v, m)
        } else if self.use_resolved_output {
            (
                (2, self.resolved_pool.gen),
                &self.resolved_pool.array_view,
                &self.resolved_pool.coord_to_slot,
            )
        } else {
            (
                (1, self.primary_pool.gen),
                &self.primary_pool.array_view,
                &self.primary_pool.coord_to_slot,
            )
        }
    }

    /// Exposes the active live `R16Float` impasto heightfield overlay during an active impasto stroke.
    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((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.
    pub fn resolve_tip_dims(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        brush: &NativeBrushConfig,
    ) -> (u32, u32, usize) {
        let (is_tex, tip_arr) = self.tip_cache.resolve_tip_set(
            device,
            queue,
            brush.tip_key.as_deref(),
            &brush.sub_tip_keys,
        );
        if is_tex {
            (tip_arr.width.max(1), tip_arr.height.max(1), (tip_arr.layer_count as usize).max(1))
        } else {
            (64, 64, 1)
        }
    }

    /// Begins a Phase 5 GPU Natural Paint / Multi-Bristle / Color-Mixing stroke session.
    #[allow(clippy::too_many_arguments)]
    pub fn begin_natural_paint_stroke(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        doc_id: &str,
        layer_id: &str,
        doc_width: u32,
        doc_height: u32,
        brush: NativeBrushConfig,
    ) {
        self.clear_stroke();
        self.doc_width = doc_width.max(1);
        self.doc_height = doc_height.max(1);
        self.active_brush = brush.clone();
        self.active = true;
        self.natural_paint
            .begin_stroke(device, queue, doc_id, layer_id, &brush);
    }

    /// Dispatches multi-bristle capsules on GPU (zero-readback pickup + raster + impasto R16F).
    #[allow(clippy::too_many_arguments, clippy::type_complexity)]
    pub fn dispatch_natural_paint_capsules(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        tile_pool: &mut GpuTilePool,
        doc: &Document,
        active_layer: &LayerNode,
        capsules: &[GpuBristleCapsule],
        scratch: Option<&dyn ScratchBackend>,
    ) -> (Vec<TileCoord>, Option<(f32, f32, f32, f32)>) {
        if !self.natural_paint.is_active() || capsules.is_empty() {
            return (Vec::new(), None);
        }
        let prev_coords: HashSet<TileCoord> = self
            .natural_paint
            .pools
            .coord_to_slot
            .keys()
            .copied()
            .collect();
        let brush = self.active_brush.clone();
        let (is_tex, tip_arr, surf_tex, dual_surf_tex, fallback_tip, default_paper) =
            self.tip_cache.resolve_natural_paint_assets(
                device,
                queue,
                brush.tip_key.as_deref(),
                &brush.sub_tip_keys,
                brush.paper_texture_key.as_deref(),
                brush.surface_texture_id.as_deref(),
                brush.dual_surface_texture_id.as_deref(),
            );
        let bounds = self.natural_paint.dispatch_bristle_capsules(
            device,
            queue,
            tile_pool,
            doc,
            active_layer,
            &brush,
            capsules,
            Some(surf_tex),
            dual_surf_tex,
            if is_tex { Some(tip_arr) } else { None },
            default_paper,
            fallback_tip,
            scratch,
            None,
        );
        let newly_touched: Vec<TileCoord> = self
            .natural_paint
            .pools
            .coord_to_slot
            .keys()
            .copied()
            .filter(|c| !prev_coords.contains(c))
            .collect();
        (newly_touched, bounds)
    }

    /// Dispatches multi-bristle Natural Paint capsules honoring an active [`GpuSelectionOverlay`].
    #[allow(clippy::too_many_arguments, clippy::type_complexity)]
    pub fn dispatch_natural_paint_capsules_with_selection(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        tile_pool: &mut GpuTilePool,
        doc: &Document,
        active_layer: &LayerNode,
        capsules: &[GpuBristleCapsule],
        scratch: Option<&dyn ScratchBackend>,
        selection: Option<&crate::selection::GpuSelectionOverlay>,
    ) -> (Vec<TileCoord>, Option<(f32, f32, f32, f32)>) {
        if !self.natural_paint.is_active() || capsules.is_empty() {
            return (Vec::new(), None);
        }
        let prev_coords: HashSet<TileCoord> = self
            .natural_paint
            .pools
            .coord_to_slot
            .keys()
            .copied()
            .collect();
        let brush = self.active_brush.clone();
        let (is_tex, tip_arr, surf_tex, dual_surf_tex, fallback_tip, default_paper) =
            self.tip_cache.resolve_natural_paint_assets(
                device,
                queue,
                brush.tip_key.as_deref(),
                &brush.sub_tip_keys,
                brush.paper_texture_key.as_deref(),
                brush.surface_texture_id.as_deref(),
                brush.dual_surface_texture_id.as_deref(),
            );
        let bounds = self.natural_paint.dispatch_bristle_capsules(
            device,
            queue,
            tile_pool,
            doc,
            active_layer,
            &brush,
            capsules,
            Some(surf_tex),
            dual_surf_tex,
            if is_tex { Some(tip_arr) } else { None },
            default_paper,
            fallback_tip,
            scratch,
            selection,
        );
        let newly_touched: Vec<TileCoord> = self
            .natural_paint
            .pools
            .coord_to_slot
            .keys()
            .copied()
            .filter(|c| !prev_coords.contains(c))
            .collect();
        (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(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        tile_pool: &mut GpuTilePool,
        doc: &Document,
        active_layer: &LayerNode,
        dabs: &[GpuBrushDab],
        scratch: Option<&dyn ScratchBackend>,
    ) -> (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,
            None,
        )
    }

    /// Dispatches standard CSP `colorMixing` dabs honoring an active [`GpuSelectionOverlay`].
    #[allow(clippy::too_many_arguments, clippy::type_complexity)]
    pub fn dispatch_color_mixing_dabs_with_selection(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        tile_pool: &mut GpuTilePool,
        doc: &Document,
        active_layer: &LayerNode,
        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
            .coord_to_slot
            .keys()
            .copied()
            .collect();
        let (is_tex, tip_arr, paper_tex, fallback_tip, default_paper) =
            self.tip_cache.resolve_tip_and_paper_with_fallbacks(
                device,
                queue,
                brush.tip_key.as_deref(),
                &brush.sub_tip_keys,
                brush.paper_texture_key.as_deref(),
                brush.surface_texture_id.as_deref(),
            );
        let bounds = self.natural_paint.dispatch_color_mixing_dabs(
            device,
            queue,
            tile_pool,
            doc,
            active_layer,
            &brush,
            dabs,
            if is_tex { Some(tip_arr) } else { None },
            Some(paper_tex),
            fallback_tip,
            default_paper,
            scratch,
            selection,
            dual_secondary,
        );
        let newly_touched: Vec<TileCoord> = self
            .natural_paint
            .pools
            .coord_to_slot
            .keys()
            .copied()
            .filter(|c| !prev_coords.contains(c))
            .collect();
        (newly_touched, bounds)
    }

    /// Commits an active GPU Natural Paint / Color Mixing stroke to `GpuTilePool` and returns
    /// CoW-ready color & `R16Float` impasto heightfield tiles!
    pub fn commit_natural_paint_to_layer(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        tile_pool: &mut GpuTilePool,
    ) -> Result<CommittedNaturalPaintBatch, String> {
        let batch = self
            .natural_paint
            .commit_stroke(device, queue, tile_pool)?;
        self.active = false;
        Ok(batch)
    }

    /// Cleans one preset's or all presets' persistent dirty GPU brush reservoirs (`autoClean: false`).
    pub fn clean_dirty_brush(&mut self, preset_key: Option<&str>) {
        self.natural_paint.clean_dirty_brush(preset_key);
    }

    /// Renders continuous UV-mapped [`RibbonVertex`] triangles directly into sparse `primary_pool`
    /// (and optional `secondary_pool` for Dual Brush ribbons!) and refreshes resolved post-passes.
    pub fn stamp_ribbon_vertices(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        primary_verts: &[RibbonVertex],
        secondary_verts: &[RibbonVertex],
        clear_existing: bool,
    ) -> Vec<TileCoord> {
        if !self.active || (primary_verts.is_empty() && secondary_verts.is_empty()) {
            return Vec::new();
        }
        if clear_existing {
            self.primary_pool.reset();
            self.secondary_pool.reset();
            self.mid_pool.reset();
            self.resolved_pool.reset();
            self.dirty_post_tiles.clear();
        }
        let mut newly_touched = Vec::new();
        let use_max = self.active_brush.blend_tips_mode == CspBlendTipsMode::Compare;

        if !primary_verts.is_empty() {
            let brush = self.active_brush.clone();
            let touched = collect_ribbon_touched_tiles(primary_verts);
            let (is_tex, tip_arr, paper_tex, fallback_tip, default_paper) =
                self.tip_cache.resolve_tip_and_paper_with_fallbacks(
                    device,
                    queue,
                    brush.tip_key.as_deref(),
                    &brush.sub_tip_keys,
                    brush.paper_texture_key.as_deref(),
                    brush.surface_texture_id.as_deref(),
                );
            let tip_opt = if is_tex { Some(tip_arr) } else { None };
            let paper_opt = if brush.paper_texture_apply_each_plot
                && brush.effective_grain_strength() > 0.001
            {
                Some(paper_tex)
            } 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.primary_pool.get_or_alloc(device, queue, coord) {
                    if is_new {
                        newly_touched.push(coord);
                    }
                    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() {
            if let Some(sec_brush) = self.active_brush.build_secondary_brush_config() {
                let touched = collect_ribbon_touched_tiles(secondary_verts);
                let (is_tex, tip_arr, _, fallback_tip, default_paper) =
                    self.tip_cache.resolve_tip_and_paper_with_fallbacks(
                        device,
                        queue,
                        sec_brush.tip_key.as_deref(),
                        &sec_brush.sub_tip_keys,
                        None,
                        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)
                    {
                        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,
                    );
                }
            }
        }

        if self.use_resolved_output && !self.dirty_post_tiles.is_empty() {
            self.refresh_resolved_tiles(device, queue);
        }
        newly_touched
    }

    /// Begins a new sparse GPU stroke session (O(1) pool reset, zero FBO allocation).
    pub fn begin_stroke(
        &mut self,
        doc_width: u32,
        doc_height: u32,
        mono_1bit: bool,
        brush: NativeBrushConfig,
        stroke_rand_offset: [f32; 2],
    ) {
        self.primary_pool.reset();
        self.secondary_pool.reset();
        self.mid_pool.reset();
        self.resolved_pool.reset();
        self.dirty_post_tiles.clear();
        self.doc_width = doc_width.max(1);
        self.doc_height = doc_height.max(1);
        self.mono_1bit = mono_1bit || brush.anti_alias == 0;
        self.active_brush = brush;
        self.stroke_rand_offset = stroke_rand_offset;
        self.last_stroke_angle_rad = 0.0;
        self.avg_pressure = 0.5;
        self.use_resolved_output = self.needs_post_pass();
        self.active = true;
    }

    /// Resets stroke buffers after commit or cancel.
    pub fn clear_stroke(&mut self) {
        self.primary_pool.reset();
        self.secondary_pool.reset();
        self.mid_pool.reset();
        self.resolved_pool.reset();
        self.dirty_post_tiles.clear();
        self.natural_paint.cancel_stroke();
        self.active = false;
        self.use_resolved_output = false;
    }

    #[inline]
    fn needs_post_pass(&self) -> bool {
        let dual = self.active_brush.is_dual_brush_active();
        let stroke_paper = self.active_brush.effective_grain_strength() > 0.001
            && !self.active_brush.paper_texture_apply_each_plot;
        let wet_edge = self.active_brush.wet_edge > 0.01;
        dual || stroke_paper || wet_edge
    }

    /// Stamps batches of primary (and optional dual-brush secondary) [`GpuBrushDab`]s into
    /// 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,
        queue: &wgpu::Queue,
        primary_dabs: &[GpuBrushDab],
        secondary_dabs: &[GpuBrushDab],
    ) -> Vec<TileCoord> {
        if !self.active || (primary_dabs.is_empty() && secondary_dabs.is_empty()) {
            return Vec::new();
        }

        if let Some(last) = primary_dabs.last() {
            self.avg_pressure = self.avg_pressure * 0.7 + last.extra[2] * 0.3;
            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. 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,
                primary_dabs,
                &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. 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,
                    &mut self.darken_uniform_buf,
                    &mut self.darken_uniform_cap,
                    primary_jobs.len(),
                    "ink-brush-darken-uniforms",
                );
                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. 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));
                }
            }
        }

        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));
            }
        }

        // 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);
        }

        queue.submit(Some(encoder.finish()));
        newly_touched
    }

    fn bin_and_alloc_stream(
        &mut self,
        device: &wgpu::Device,
        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),
            size: new_cap as u64 * UNIFORM_STRIDE,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            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(
        &self,
        brush: &NativeBrushConfig,
        tile_origin_doc: [f32; 2],
        is_textured: bool,
        tip_layers: u32,
        paper_size: [f32; 2],
        allow_per_dab_paper: bool,
    ) -> DabPassUniforms {
        let apply_per_dab = allow_per_dab_paper
            && brush.paper_texture_apply_each_plot
            && brush.effective_grain_strength() > 0.001;
        DabPassUniforms {
            tile_origin_doc,
            doc_size: [self.doc_width as f32, self.doc_height as f32],
            viewport_size_phys: [1.0, 1.0],
            pan_css: [0.0, 0.0],
            zoom: 1.0,
            rotation_rad: 0.0,
            flip: [1.0, 1.0],
            dpr: 1.0,
            paper_scale: brush.paper_texture_scale.clamp(0.05, 10.0),
            paper_rot_rad: brush.paper_texture_rotate.to_radians(),
            paper_brightness: brush.paper_texture_brightness,
            paper_contrast: brush.paper_texture_contrast,
            _pad0: 0.0,
            paper_size,
            paper_offset_norm: [
                brush.paper_texture_offset_x / paper_size[0].max(1.0),
                brush.paper_texture_offset_y / paper_size[1].max(1.0),
            ],
            stroke_rand_offset: self.stroke_rand_offset,
            flags0: [
                u32::from(is_textured),
                u32::from(brush.is_color_tip),
                u32::from(brush.is_dual_tone_tip),
                brush.anti_alias.min(3) as u32,
            ],
            flags1: [
                u32::from(apply_per_dab),
                brush.paper_texture_mode.as_u32(),
                brush.grain_mapping_mode.as_u32(),
                u32::from(brush.paper_texture_invert),
            ],
            flags2: [
                u32::from(brush.emphasize_density),
                tip_layers.max(1),
                u32::from(self.mono_1bit),
                0,
            ],
        }
    }

    fn stamp_stream_into_pool(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        is_primary: bool,
        brush: &NativeBrushConfig,
        dabs: &[GpuBrushDab],
        allow_per_dab_paper: bool,
    ) -> 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;

        // 1. Bin dabs strictly into overlapping 256×256 tiles
        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();
        }

        // 2. Flatten binned instances & allocate sparse tile slots
        let mut flat_instances: Vec<GpuBrushDab> = Vec::with_capacity(dabs.len() * 2);
        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));
        }

        if tile_jobs.is_empty() {
            return newly_touched;
        }

        // 3. Upload flattened instance buffer + dynamic uniform table in 2 single writes
        self.ensure_instance_buf(device, flat_instances.len());
        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 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() {
            let u = self.build_dab_uniforms(
                brush,
                [
                    (coord.tx * TILE_SIZE as i32) as f32,
                    (coord.ty * TILE_SIZE as i32) as f32,
                ],
                is_textured,
                tip_layers,
                paper_size,
                allow_per_dab_paper,
            );
            let off = i * 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);

        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"),
        });

        for (i, &(_, slot, is_new, start, count)) in tile_jobs.iter().enumerate() {
            let dyn_off = (i as u32) * (UNIFORM_STRIDE as u32);
            if use_darken && !is_new {
                // Render batch into scratch 256×256 then compute-merge Darken into primary_pool[slot]
                {
                    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(pipeline);
                    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));
                }
                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 target_view = if is_primary {
                    &self.primary_pool.slice_views[slot as usize]
                } else {
                    &self.secondary_pool.slice_views[slot as usize]
                };
                let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                    label: Some("ink-brush-tile-stamp"),
                    color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                        view: target_view,
                        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(pipeline);
                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));
            }
        }

        queue.submit(Some(encoder.finish()));
        newly_touched
    }

    /// 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;
        }

        let dual_enabled = self.active_brush.is_dual_brush_active();
        let dual_mode = self
            .active_brush
            .dual_brush_config
            .as_ref()
            .map(|d| d.combine_mode.as_u32() as i32)
            .unwrap_or(0);
        let apply_stroke_paper = self.active_brush.effective_grain_strength() > 0.001
            && !self.active_brush.paper_texture_apply_each_plot;
        let wet_active = self.active_brush.wet_edge > 0.01;
        let need_mid = dual_enabled || apply_stroke_paper;

        // 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(
                device,
                &mut self.post_uniform_buf,
                &mut self.post_uniform_cap,
                dirty.len(),
                "ink-brush-post-uniforms",
            );

            // Allocate destination slots first so Texture2DArray capacity is finalized before bind group
            let mut post_jobs: Vec<(TileCoord, i32, i32, u32)> = Vec::with_capacity(dirty.len());
            for &coord in &dirty {
                let p_slot = self.primary_pool.get_slot(&coord).map(|s| s as i32).unwrap_or(-1);
                let s_slot = self.secondary_pool.get_slot(&coord).map(|s| s as i32).unwrap_or(-1);
                let dst = if wet_active {
                    self.mid_pool.get_or_alloc(device, queue, coord)
                } else {
                    self.resolved_pool.get_or_alloc(device, queue, coord)
                };
                if let Some((dst_slot, _)) = dst {
                    post_jobs.push((coord, p_slot, s_slot, dst_slot));
                }
            }

            let paper_size = {
                let p = self.tip_cache.resolve_paper_texture(
                    device,
                    queue,
                    self.active_brush.paper_texture_key.as_deref(),
                    self.active_brush.surface_texture_id.as_deref(),
                );
                [p.width as f32, p.height as f32]
            };

            let mut ubytes = vec![0u8; post_jobs.len() * UNIFORM_STRIDE as usize];
            for (i, &(coord, p_slot, s_slot, _)) in post_jobs.iter().enumerate() {
                let u = StrokePostUniforms {
                    tile_origin_doc: [
                        (coord.tx * TILE_SIZE as i32) as f32,
                        (coord.ty * TILE_SIZE as i32) as f32,
                    ],
                    paper_size,
                    paper_offset_norm: [
                        self.active_brush.paper_texture_offset_x / paper_size[0].max(1.0),
                        self.active_brush.paper_texture_offset_y / paper_size[1].max(1.0),
                    ],
                    stroke_rand_offset: self.stroke_rand_offset,
                    paper_scale: self.active_brush.paper_texture_scale.clamp(0.05, 10.0),
                    paper_rot_rad: self.active_brush.paper_texture_rotate.to_radians(),
                    paper_brightness: self.active_brush.paper_texture_brightness,
                    paper_contrast: self.active_brush.paper_texture_contrast,
                    grain_strength: self.active_brush.effective_grain_strength(),
                    avg_pressure: self.avg_pressure,
                    stroke_angle_rad: self.last_stroke_angle_rad,
                    _pad0: 0.0,
                    slots: [p_slot, s_slot, i32::from(dual_enabled), dual_mode],
                    paper_flags: [
                        u32::from(apply_stroke_paper),
                        self.active_brush.paper_texture_mode.as_u32(),
                        self.active_brush.grain_mapping_mode.as_u32(),
                        u32::from(self.active_brush.paper_texture_invert),
                    ],
                    extra_flags: [
                        u32::from(self.active_brush.emphasize_density),
                        u32::from(self.mono_1bit),
                        0,
                        0,
                    ],
                };
                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.post_uniform_buf, 0, &ubytes);

            let paper = self.tip_cache.resolve_paper_texture(
                device,
                queue,
                self.active_brush.paper_texture_key.as_deref(),
                self.active_brush.surface_texture_id.as_deref(),
            );
            let post_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("ink-brush-post-bg"),
                layout: &self.post_bgl,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
                            buffer: &self.post_uniform_buf,
                            offset: 0,
                            size: wgpu::BufferSize::new(
                                std::mem::size_of::<StrokePostUniforms>() as u64,
                            ),
                        }),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: wgpu::BindingResource::TextureView(&self.primary_pool.array_view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 2,
                        resource: wgpu::BindingResource::TextureView(
                            &self.secondary_pool.array_view,
                        ),
                    },
                    wgpu::BindGroupEntry {
                        binding: 3,
                        resource: wgpu::BindingResource::TextureView(&paper.view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 4,
                        resource: wgpu::BindingResource::Sampler(&self.paper_sampler),
                    },
                    wgpu::BindGroupEntry {
                        binding: 5,
                        resource: wgpu::BindingResource::TextureView(&self.post_scratch_view),
                    },
                ],
            });

            let dst_tex = if wet_active {
                &self.mid_pool.texture
            } else {
                &self.resolved_pool.texture
            };
            for (i, &(_, _, _, dst_slot)) in post_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-brush-post-pass"),
                        timestamp_writes: None,
                    });
                    cp.set_pipeline(&self.post_pipeline);
                    cp.set_bind_group(0, &post_bg, &[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: dst_tex,
                        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,
                    },
                );
            }
        }

        // Step B: 2-Pass Seamless Watercolor Wet Edge over dirty tiles + existing 8-neighbors
        if wet_active {
            let mut wet_set: HashSet<TileCoord> = HashSet::with_capacity(dirty.len() * 2);
            for &c in &dirty {
                for dy in -1..=1 {
                    for dx in -1..=1 {
                        let nb = TileCoord::new(c.tx + dx, c.ty + dy);
                        let exists = if need_mid {
                            self.mid_pool.get_slot(&nb).is_some()
                        } else {
                            self.primary_pool.get_slot(&nb).is_some()
                        };
                        if exists {
                            wet_set.insert(nb);
                        }
                    }
                }
            }

            let wet_coords: Vec<TileCoord> = wet_set.into_iter().collect();
            if !wet_coords.is_empty() {
                Self::ensure_uniform_buf(
                    device,
                    &mut self.wet_uniform_buf,
                    &mut self.wet_uniform_cap,
                    wet_coords.len(),
                    "ink-brush-wet-uniforms",
                );

                let mut wet_jobs: Vec<(TileCoord, u32)> = Vec::with_capacity(wet_coords.len());
                for &coord in &wet_coords {
                    if let Some((dst_slot, _)) =
                        self.resolved_pool.get_or_alloc(device, queue, coord)
                    {
                        wet_jobs.push((coord, dst_slot));
                    }
                }

                let radius_px = (self.active_brush.wet_edge_radius.round() as i32).clamp(1, 14);
                let mut ubytes = vec![0u8; wet_jobs.len() * UNIFORM_STRIDE as usize];
                for (i, &(coord, _)) in wet_jobs.iter().enumerate() {
                    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);
                            let s = if need_mid {
                                self.mid_pool.get_slot(&nc)
                            } else {
                                self.primary_pool.get_slot(&nc)
                            };
                            nb[((oy + 1) * 3 + (ox + 1)) as usize] =
                                s.map(|v| v as i32).unwrap_or(-1);
                        }
                    }
                    let u = WetEdgeUniforms {
                        n0: [nb[0], nb[1], nb[2], nb[3]],
                        n1: [nb[4], nb[5], nb[6], nb[7]],
                        n2: [nb[8], radius_px, 0, 0],
                        params: [
                            self.active_brush.wet_edge.clamp(0.0, 1.0),
                            radius_px as f32,
                            self.active_brush.wet_edge_alpha_power.clamp(0.0, 4.0),
                            self.active_brush.wet_edge_value_power.clamp(0.0, 4.0),
                        ],
                    };
                    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.wet_uniform_buf, 0, &ubytes);

                let src_pool_view = if need_mid {
                    &self.mid_pool.array_view
                } else {
                    &self.primary_pool.array_view
                };

                // Bind group for Pass 1 (horiz -> wet_padded_view)
                let wet_h_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
                    label: Some("ink-brush-wet-h-bg"),
                    layout: &self.wet_bgl,
                    entries: &[
                        wgpu::BindGroupEntry {
                            binding: 0,
                            resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
                                buffer: &self.wet_uniform_buf,
                                offset: 0,
                                size: wgpu::BufferSize::new(
                                    std::mem::size_of::<WetEdgeUniforms>() as u64,
                                ),
                            }),
                        },
                        wgpu::BindGroupEntry {
                            binding: 1,
                            resource: wgpu::BindingResource::TextureView(src_pool_view),
                        },
                        wgpu::BindGroupEntry {
                            binding: 2,
                            resource: wgpu::BindingResource::TextureView(&self.darken_batch_view),
                        },
                        wgpu::BindGroupEntry {
                            binding: 3,
                            resource: wgpu::BindingResource::TextureView(&self.wet_padded_view),
                        },
                    ],
                });

                // Bind group for Pass 2 (vert reading wet_padded_view -> post_scratch_view)
                let wet_v_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
                    label: Some("ink-brush-wet-v-bg"),
                    layout: &self.wet_bgl,
                    entries: &[
                        wgpu::BindGroupEntry {
                            binding: 0,
                            resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
                                buffer: &self.wet_uniform_buf,
                                offset: 0,
                                size: wgpu::BufferSize::new(
                                    std::mem::size_of::<WetEdgeUniforms>() as u64,
                                ),
                            }),
                        },
                        wgpu::BindGroupEntry {
                            binding: 1,
                            resource: wgpu::BindingResource::TextureView(src_pool_view),
                        },
                        wgpu::BindGroupEntry {
                            binding: 2,
                            resource: wgpu::BindingResource::TextureView(&self.wet_padded_view),
                        },
                        wgpu::BindGroupEntry {
                            binding: 3,
                            resource: wgpu::BindingResource::TextureView(&self.post_scratch_view),
                        },
                    ],
                });

                for (i, &(_, dst_slot)) in wet_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-brush-wet-horiz-pass"),
                            timestamp_writes: None,
                        });
                        cp.set_pipeline(&self.wet_horiz_pipeline);
                        cp.set_bind_group(0, &wet_h_bg, &[dyn_off]);
                        cp.dispatch_workgroups(18, 18, 1);
                    }
                    {
                        let mut cp = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                            label: Some("ink-brush-wet-vert-pass"),
                            timestamp_writes: None,
                        });
                        cp.set_pipeline(&self.wet_vert_pipeline);
                        cp.set_bind_group(0, &wet_v_bg, &[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.resolved_pool.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,
                        },
                    );
                }
            }
        }
    }

    /// Renders transient predicted-head [`GpuBrushDab`]s directly into `WgpuCompositor`'s
    /// 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,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        encoder: &mut wgpu::CommandEncoder,
        target_view: &wgpu::TextureView,
        predicted_dabs: &[GpuBrushDab],
        viewport_size_phys: [f32; 2],
        pan_css: [f32; 2],
        zoom: f32,
        rotation_rad: f32,
        flip: [f32; 2],
        dpr: f32,
        scissor: [u32; 4],
    ) {
        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_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,
            [0.0, 0.0],
            is_textured,
            tip_layers,
            paper_size,
            !is_direct_replace,
        );
        u.viewport_size_phys = viewport_size_phys;
        u.pan_css = pan_css;
        u.zoom = zoom;
        u.rotation_rad = rotation_rad;
        u.flip = flip;
        u.dpr = dpr;
        queue.write_buffer(&self.dab_uniform_buf, 0, bytemuck::bytes_of(&u));

        let dab_bg = &self.cached_dab_bgs[dab_bg_slot]
            .as_ref()
            .expect("cached dab_bg")
            .1;

        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 {
            label: Some("ink-brush-predicted-head-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,
        });
        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_vertex_buffer(0, self.dab_instance_buf.slice(..));
        rp.draw(0..6, 0..predicted_dabs.len() as u32);
    }

    /// Sub-millisecond GPU-to-GPU commit of all touched sparse stroke tiles directly into
    /// `GpuTilePool` LOD 0 tiles (plus single-submit packed RGBA8 readback for `SparseLayerGrid`
    /// & CoW Undo!).
    #[allow(clippy::too_many_arguments)]
    pub fn commit_to_layer_pool(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        gpu_pool: &mut GpuTilePool,
        doc_id: &str,
        layer_id: &str,
        layer_grid: &SparseLayerGrid,
        scratch: Option<&dyn ScratchBackend>,
        alpha_locked: bool,
        mono_layer: bool,
    ) -> Result<CommittedTileBatch, String> {
        self.commit_to_layer_pool_with_selection(
            device,
            queue,
            gpu_pool,
            doc_id,
            layer_id,
            layer_grid,
            scratch,
            alpha_locked,
            mono_layer,
            None,
        )
    }

    /// Sub-millisecond GPU-to-GPU commit honoring an active [`GpuSelectionOverlay`] `R8Unorm`
    /// sparse selection mask directly inside the commit compute shader!
    #[allow(clippy::too_many_arguments)]
    pub fn commit_to_layer_pool_with_selection(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        gpu_pool: &mut GpuTilePool,
        doc_id: &str,
        layer_id: &str,
        layer_grid: &SparseLayerGrid,
        scratch: Option<&dyn ScratchBackend>,
        alpha_locked: bool,
        mono_layer: bool,
        selection: Option<&crate::selection::GpuSelectionOverlay>,
    ) -> Result<CommittedTileBatch, String> {
        if !self.active {
            return Ok(CommittedTileBatch {
                tiles: Vec::new(),
                dirty_rect: RectI32::empty(),
            });
        }

        // Flush any pending post-pass tiles before committing
        if self.use_resolved_output && !self.dirty_post_tiles.is_empty() {
            self.refresh_resolved_tiles(device, queue);
        }

        let mut jobs: Vec<(TileCoord, u32)> = if self.use_resolved_output {
            self.resolved_pool
                .coord_to_slot
                .iter()
                .map(|(&c, &s)| (c, s))
                .collect()
        } else {
            self.primary_pool
                .coord_to_slot
                .iter()
                .map(|(&c, &s)| (c, s))
                .collect()
        };
        jobs.sort_by_key(|(c, _)| (c.ty, c.tx));

        if jobs.is_empty() {
            return Ok(CommittedTileBatch {
                tiles: Vec::new(),
                dirty_rect: RectI32::empty(),
            });
        }

        // 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,
            buf_tile_req,
            "ink-tile-commit-uniforms",
        );
        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"),
                size: bytes,
                usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
                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;
        }

        let combine_code = self.active_brush.brush_combine_mode.as_u32();
        let is_eraser = u32::from(
            self.active_brush.is_eraser
                || self.active_brush.is_transparent_ink
                || self.active_brush.brush_combine_mode == CspBrushCombineMode::Clear,
        );
        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
            .map(|s| (s.default_alpha_f32() * 255.0).round().clamp(0.0, 255.0) as u32)
            .unwrap_or(255u32);
        let sel_atlas_view = active_sel
            .map(|s| s.atlas_view())
            .unwrap_or(&self.commit_dummy_sel_view);

        let stroke_view = if self.use_resolved_output {
            &self.resolved_pool.array_view
        } else {
            &self.primary_pool.array_view
        };

        let tile_bytes = TILE_SIZE * TILE_SIZE * 4;
        let mut tiles = Vec::with_capacity(jobs.len());
        let mut dirty_rect = RectI32::empty();

        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>,
        }

        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);
            }
            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,
                            ),
                        }),
                    },
                    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 sub_idx = 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);
        }

        if let Some(last) = prev_in_flight {
            drain_in_flight(&self.commit_rgba8_readback_bufs, gpu_pool, last, &mut tiles)?;
        }

        // Clamp dirty rect to document bounds
        let doc_rect = RectI32::new(0, 0, self.doc_width, self.doc_height);
        let clamped_dirty = dirty_rect.intersect(doc_rect);

        Ok(CommittedTileBatch {
            tiles,
            dirty_rect: clamped_dirty,
        })
    }

    /// Reads back touched sparse GPU stroke tiles' alpha channel (`Vec<u8>` per `256×256` tile)
    /// directly for **Select Pen** / **Select Eraser** strokes onto [`SparseSelectionMask`]!
    pub fn readback_stroke_alpha_tiles(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        gpu_pool: &mut GpuTilePool,
    ) -> Result<Vec<(TileCoord, Vec<u8>)>, String> {
        let empty_grid = SparseLayerGrid::new(crate::tiles::TileFormat::Color32Bit);
        let batch = self.commit_to_layer_pool_with_selection(
            device,
            queue,
            gpu_pool,
            "__selection_stroke__",
            "__selection_stroke__",
            &empty_grid,
            None,
            false,
            false,
            None,
        )?;
        gpu_pool.invalidate_document("__selection_stroke__");
        let mut out = Vec::with_capacity(batch.tiles.len());
        for (coord, rgba, _) in batch.tiles {
            let mut alpha = vec![0u8; TILE_SIZE * TILE_SIZE];
            for (dst, px) in alpha.iter_mut().zip(rgba.chunks_exact(4)) {
                *dst = px[3];
            }
            out.push((coord, alpha));
        }
        Ok(out)
    }
}