Skip to content

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

64.1 KB
Raw Blame
//! Interactive DX12 GPU Liquify Engine (`liquify.rs`).
//!
//! Uses a sparse `256×256` `Rg16Float` displacement field `Texture2DArray` (`dx, dy` in doc px)
//! and two WGSL compute shaders:
//! 1. `LIQUIFY_DISPLACE_WGSL`: Updates displacement vectors for all 8 `LiquifyMode`s
//!    (`push`, `push-left`, `push-right`, `expand`, `pinch`, `twirl-cw`, `twirl-ccw`,
//!    `reconstruct`), honoring `size`, `strength`, `hardness`, `usePressure`, and the active
//!    sparse `R8Unorm` selection mask!
//! 2. `LIQUIFY_WARP_TILE_WGSL`: Resamples each target layer's original `Rgba16Float` tiles
//!    through the displacement field with premultiplied 4×4 Catmull-Rom bicubic filtering
//!    into sparse live preview `Rgba16Float` tiles composited in-stack at 120+ FPS, plus
//!    single-submit GPU-to-GPU CoW tile commit across single or multiple layers!

use crate::document::{Document, LayerId};
use crate::memory::{GpuTileKey, GpuTilePool, ScratchBackend};
use crate::selection::GpuSelectionOverlay;
use crate::tiles::{allocate_tile_version, CowTileDelta, RectI32, TileCoord, TileData, TILE_SIZE};
use bytemuck::{Pod, Zeroable};
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::num::NonZeroU64;
use std::sync::Arc;

const MAX_LIQUIFY_LOOKUP: usize = 512;
const LIQUIFY_UNIFORM_STRIDE: u64 = 256;

/// All 8 InkStudio Liquify brush modes matching `src/types/editor.ts`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum LiquifyMode {
    #[default]
    Push,
    PushLeft,
    PushRight,
    Expand,
    Pinch,
    TwirlCw,
    TwirlCcw,
    Reconstruct,
}

impl LiquifyMode {
    #[inline]
    pub fn as_u32(self) -> u32 {
        match self {
            Self::Push => 0,
            Self::PushLeft => 1,
            Self::PushRight => 2,
            Self::Expand => 3,
            Self::Pinch => 4,
            Self::TwirlCw => 5,
            Self::TwirlCcw => 6,
            Self::Reconstruct => 7,
        }
    }
}

/// Interactive Liquify tool parameters.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LiquifySettings {
    #[serde(default)]
    pub mode: LiquifyMode,
    #[serde(default = "default_liquify_size")]
    pub size: f32,
    #[serde(default = "default_liquify_strength")]
    pub strength: f32,
    #[serde(default = "default_liquify_hardness")]
    pub hardness: f32,
    #[serde(default = "default_true")]
    pub use_pressure: bool,
    #[serde(default)]
    pub multi_layer: bool,
}

fn default_liquify_size() -> f32 {
    120.0
}
fn default_liquify_strength() -> f32 {
    0.5
}
fn default_liquify_hardness() -> f32 {
    0.5
}
fn default_true() -> bool {
    true
}

impl Default for LiquifySettings {
    fn default() -> Self {
        Self {
            mode: LiquifyMode::Push,
            size: default_liquify_size(),
            strength: default_liquify_strength(),
            hardness: default_liquify_hardness(),
            use_pressure: true,
            multi_layer: false,
        }
    }
}

/// A single Liquify stroke step in document pixel coordinates.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LiquifyStepParams {
    pub from_x: f32,
    pub from_y: f32,
    pub to_x: f32,
    pub to_y: f32,
    #[serde(default = "default_one")]
    pub pressure: f32,
    pub settings: LiquifySettings,
}

fn default_one() -> f32 {
    1.0
}

#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct DisplaceUniforms {
    /// `[tile_origin_x, tile_origin_y, disp_slot_f, mode_f]`
    tile_info: [f32; 4],
    /// `[from_x, from_y, to_x, to_y]`
    seg: [f32; 4],
    /// `[radius, strength, hardness, pressure]`
    brush: [f32; 4],
    /// `[sel_slot_f (-2=none, -1=default, >=0=tile slot), sel_default_f, doc_w, doc_h]`
    sel_doc: [f32; 4],
}

#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct TileLookupEntry {
    tx: i32,
    ty: i32,
    slot: i32,
    _pad: i32,
}

#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct WarpUniforms {
    /// `[tile_origin_x, tile_origin_y, disp_slot_f, lookup_count_f]`
    tile_info: [f32; 4],
    /// `[doc_w, doc_h, out_tile_idx_f, write_rgba8_f]`
    doc_out: [f32; 4],
}

/// WGSL fullscreen render shader updating sparse `256×256` `Rg16Float` displacement tiles (`dx, dy`)
/// for all 8 Liquify modes with smooth cubic/hardness falloff and selection mask clipping.
/// Uses `RENDER_ATTACHMENT` on `Rg16Float` (core WebGPU/DX12 spec — zero adapter-specific storage flags!).
pub const LIQUIFY_DISPLACE_WGSL: &str = r#"
struct DisplaceUniforms {
    tile_info: vec4<f32>,
    seg: vec4<f32>,
    brush: vec4<f32>,
    sel_doc: vec4<f32>,
};

@group(0) @binding(0) var<uniform> u: DisplaceUniforms;
@group(0) @binding(1) var disp_in_atlas: texture_2d_array<f32>;
@group(0) @binding(2) var sel_mask_atlas: texture_2d_array<f32>;

@vertex
fn vs_liquify_displace(@builtin(vertex_index) vid: u32) -> @builtin(position) vec4<f32> {
    var pos = vec2<f32>(-1.0, -1.0);
    if (vid == 1u) {
        pos = vec2<f32>(3.0, -1.0);
    } else if (vid == 2u) {
        pos = vec2<f32>(-1.0, 3.0);
    }
    return vec4<f32>(pos, 0.0, 1.0);
}

@fragment
fn fs_liquify_displace(@builtin(position) frag_pos: vec4<f32>) -> @location(0) vec4<f32> {
    let lp = clamp(vec2<i32>(i32(frag_pos.x), i32(frag_pos.y)), vec2<i32>(0), vec2<i32>(255));
    let slot = i32(round(u.tile_info.z));
    let cur = select(vec2<f32>(0.0), textureLoad(disp_in_atlas, lp, slot, 0).xy, slot >= 0);

    let px = vec2<f32>(u.tile_info.x + f32(lp.x) + 0.5, u.tile_info.y + f32(lp.y) + 0.5);
    let p0 = u.seg.xy;
    let p1 = u.seg.zw;
    let delta = p1 - p0;
    let radius = max(u.brush.x, 1.0);
    let strength = clamp(u.brush.y, 0.01, 1.0);
    let hardness = clamp(u.brush.z, 0.0, 1.0);
    let pressure = clamp(u.brush.w, 0.05, 1.0);

    // Distance to segment [p0, p1] (smooth capsule stroke for fast drags)
    let ab_len2 = dot(delta, delta);
    var t_seg = 1.0;
    if (ab_len2 > 1e-4) {
        t_seg = clamp(dot(px - p0, delta) / ab_len2, 0.0, 1.0);
    }
    let center = p0 + delta * t_seg;
    let rel = px - center;
    let dist = length(rel);
    if (dist >= radius) {
        return vec4<f32>(cur, 0.0, 0.0);
    }

    var sel_a = 1.0;
    let sel_slot = i32(round(u.sel_doc.x));
    if (sel_slot >= 0) {
        sel_a = textureLoad(sel_mask_atlas, lp, sel_slot, 0).r;
    } else if (sel_slot == -1) {
        sel_a = u.sel_doc.y;
    }
    if (sel_a <= 0.001) {
        return vec4<f32>(cur, 0.0, 0.0);
    }

    // Smooth falloff controlled by hardness (0 = soft Gaussian-like dome, 1 = crisp plateau)
    let r_norm = dist / radius;
    let inner = hardness * 0.72;
    let falloff_t = clamp((r_norm - inner) / max(1e-4, 1.0 - inner), 0.0, 1.0);
    let smooth_f = 1.0 - falloff_t * falloff_t * (3.0 - 2.0 * falloff_t);
    let weight = smooth_f * smooth_f * strength * pressure * sel_a;

    let mode = u32(round(u.tile_info.w));
    var next_disp = cur;

    if (mode == 7u) {
        // Reconstruct: smoothly relax displacement field back toward original (0, 0)
        let decay = clamp(weight * 0.55, 0.0, 0.95);
        next_disp = cur * (1.0 - decay);
    } else if (mode == 0u) {
        // Push: shift pixels along cursor motion vector
        next_disp = cur + delta * (weight * 0.85);
    } else if (mode == 1u) {
        // Push Left: shift perpendicular left to stroke direction
        let perp = vec2<f32>(-delta.y, delta.x);
        next_disp = cur + perp * (weight * 0.75);
    } else if (mode == 2u) {
        // Push Right: shift perpendicular right to stroke direction
        let perp = vec2<f32>(delta.y, -delta.x);
        next_disp = cur + perp * (weight * 0.75);
    } else if (mode == 3u) {
        // Expand / Bloat: push pixels radially outward from brush center
        let dir = select(vec2<f32>(0.0), rel / max(dist, 1e-4), dist > 0.25);
        let mag = radius * 0.14 * weight * (1.0 - r_norm * 0.35);
        next_disp = cur + dir * mag;
    } else if (mode == 4u) {
        // Pinch / Pucker: pull pixels radially inward toward brush center
        let dir = select(vec2<f32>(0.0), rel / max(dist, 1e-4), dist > 0.25);
        let mag = radius * 0.14 * weight * (1.0 - r_norm * 0.35);
        next_disp = cur - dir * mag;
    } else if (mode == 5u || mode == 6u) {
        // Twirl CW (5) / Twirl CCW (6): rotate local vector around brush center
        let sign = select(-1.0, 1.0, mode == 5u);
        let ang = sign * weight * 0.32;
        let c = cos(ang);
        let s = sin(ang);
        let rot = vec2<f32>(rel.x * c - rel.y * s, rel.x * s + rel.y * c);
        next_disp = cur + (rot - rel);
    }

    // Clamp displacement within safe float16 precision bounds
    let max_d = max(u.sel_doc.z, u.sel_doc.w);
    next_disp = clamp(next_disp, vec2<f32>(-max_d), vec2<f32>(max_d));
    return vec4<f32>(next_disp, 0.0, 0.0);
}
"#;

/// WGSL compute shader resampling original `GpuTilePool` `Rgba16Float` tiles through the
/// `RG16Float` displacement field using premultiplied 4×4 Catmull-Rom bicubic interpolation.
pub const LIQUIFY_WARP_TILE_WGSL: &str = r#"
struct TileLookupEntry {
    tx: i32,
    ty: i32,
    slot: i32,
    _pad: i32,
};

struct WarpUniforms {
    tile_info: vec4<f32>,
    doc_out: vec4<f32>,
};

@group(0) @binding(0) var<uniform> u: WarpUniforms;
@group(0) @binding(1) var base_pool: texture_2d_array<f32>;
@group(0) @binding(2) var disp_atlas: texture_2d_array<f32>;
@group(0) @binding(3) var<storage, read> tile_lookup: array<TileLookupEntry>;
@group(0) @binding(4) var dst_tile_16f: texture_storage_2d<rgba16float, write>;
@group(0) @binding(5) var<storage, read_write> out_rgba8_buf: array<u32>;

fn find_base_slot(tx: i32, ty: i32) -> i32 {
    let n = u32(round(u.tile_info.w));
    for (var i: u32 = 0u; i < n; i = i + 1u) {
        let e = tile_lookup[i];
        if (e.tx == tx && e.ty == ty) {
            return e.slot;
        }
    }
    return -1;
}

fn div_floor_256(v: i32) -> i32 {
    if (v >= 0) { return v / 256; }
    return -(((-v) + 255) / 256);
}

fn fetch_base_premul(ix: i32, iy: i32) -> vec4<f32> {
    let dw = i32(round(u.doc_out.x));
    let dh = i32(round(u.doc_out.y));
    if (ix < 0 || iy < 0 || ix >= dw || iy >= dh) {
        return vec4<f32>(0.0);
    }
    let tx = div_floor_256(ix);
    let ty = div_floor_256(iy);
    let slot = find_base_slot(tx, ty);
    if (slot < 0) {
        return vec4<f32>(0.0);
    }
    let lx = clamp(ix - tx * 256, 0, 255);
    let ly = clamp(iy - ty * 256, 0, 255);
    let c = textureLoad(base_pool, vec2<i32>(lx, ly), slot, 0);
    let a = clamp(c.a, 0.0, 1.0);
    return vec4<f32>(clamp(c.rgb, vec3<f32>(0.0), vec3<f32>(1.0)) * a, a);
}

fn catmull_rom(x: f32) -> f32 {
    let ax = abs(x);
    if (ax < 1.0) {
        return 1.5 * ax * ax * ax - 2.5 * ax * ax + 1.0;
    } else if (ax < 2.0) {
        return -0.5 * ax * ax * ax + 2.5 * ax * ax - 4.0 * ax + 2.0;
    }
    return 0.0;
}

fn pack_rgba8(c: vec4<f32>) -> u32 {
    let r = u32(clamp(round(c.r * 255.0), 0.0, 255.0));
    let g = u32(clamp(round(c.g * 255.0), 0.0, 255.0));
    let b = u32(clamp(round(c.b * 255.0), 0.0, 255.0));
    let a = u32(clamp(round(c.a * 255.0), 0.0, 255.0));
    return r | (g << 8u) | (b << 16u) | (a << 24u);
}

@compute @workgroup_size(16, 16, 1)
fn cs_liquify_warp(@builtin(global_invocation_id) gid: vec3<u32>) {
    if (gid.x >= 256u || gid.y >= 256u) {
        return;
    }
    let lp = vec2<i32>(i32(gid.x), i32(gid.y));
    let d_slot = i32(round(u.tile_info.z));
    let disp = select(vec2<f32>(0.0), textureLoad(disp_atlas, lp, d_slot, 0).xy, d_slot >= 0);

    // Inverse lookup: pixel `p` samples source at `p - disp`
    let src_x = u.tile_info.x + f32(gid.x) - disp.x;
    let src_y = u.tile_info.y + f32(gid.y) - disp.y;

    var out_straight = vec4<f32>(0.0);
    if (abs(disp.x) < 1e-4 && abs(disp.y) < 1e-4) {
        let p = fetch_base_premul(i32(round(src_x)), i32(round(src_y)));
        if (p.a > 1e-4) {
            out_straight = vec4<f32>(clamp(p.rgb / p.a, vec3<f32>(0.0), vec3<f32>(1.0)), clamp(p.a, 0.0, 1.0));
        }
    } else {
        let ix = i32(floor(src_x));
        let iy = i32(floor(src_y));
        let fx = src_x - f32(ix);
        let fy = src_y - f32(iy);

        var wx: array<f32, 4>;
        var wy: array<f32, 4>;
        wx[0] = catmull_rom(fx + 1.0);
        wx[1] = catmull_rom(fx);
        wx[2] = catmull_rom(1.0 - fx);
        wx[3] = catmull_rom(2.0 - fx);
        wy[0] = catmull_rom(fy + 1.0);
        wy[1] = catmull_rom(fy);
        wy[2] = catmull_rom(1.0 - fy);
        wy[3] = catmull_rom(2.0 - fy);

        var acc = vec4<f32>(0.0);
        var wsum = 0.0;
        var min_c = vec4<f32>(10.0);
        var max_c = vec4<f32>(-10.0);

        for (var j: i32 = -1; j <= 2; j = j + 1) {
            let wj = wy[j + 1];
            for (var i: i32 = -1; i <= 2; i = i + 1) {
                let w = wx[i + 1] * wj;
                let s = fetch_base_premul(ix + i, iy + j);
                acc = acc + s * w;
                wsum = wsum + w;
                if (i >= 0 && i <= 1 && j >= 0 && j <= 1) {
                    min_c = min(min_c, s);
                    max_c = max(max_c, s);
                }
            }
        }
        if (abs(wsum) > 1e-5) {
            acc = acc / wsum;
        }
        // Anti-ringing clamp prevents dark/bright Catmull-Rom halos on crisp lineart!
        let clamped = clamp(acc, min_c, max_c);
        let a = clamp(clamped.a, 0.0, 1.0);
        if (a > 0.0005) {
            out_straight = vec4<f32>(clamp(clamped.rgb / a, vec3<f32>(0.0), vec3<f32>(1.0)), a);
        }
    }

    textureStore(dst_tile_16f, lp, out_straight);

    if (u.doc_out.w > 0.5) {
        let tile_idx = u32(max(0.0, round(u.doc_out.z)));
        let flat = tile_idx * 65536u + gid.y * 256u + gid.x;
        out_rgba8_buf[flat] = pack_rgba8(out_straight);
    }
}
"#;

struct LayerWarpState {
    layer_id: LayerId,
    /// Original immutable `Arc<TileData>` snapshots captured before Liquify began (for CoW Undo).
    before_tiles: HashMap<TileCoord, Option<Arc<TileData>>>,
    /// Sparse `256×256` `Rgba16Float` warped preview tile array.
    warped_tex: wgpu::Texture,
    warped_view: wgpu::TextureView,
    warped_cap: u32,
    coord_to_slot: HashMap<TileCoord, u32>,
    next_slot: u32,
}

impl LayerWarpState {
    fn new(device: &wgpu::Device, layer_id: LayerId) -> Self {
        let cap = 32u32;
        let (warped_tex, warped_view) = Self::alloc_rgba16f_array(device, cap);
        Self {
            layer_id,
            before_tiles: HashMap::new(),
            warped_tex,
            warped_view,
            warped_cap: cap,
            coord_to_slot: HashMap::new(),
            next_slot: 0,
        }
    }

    fn alloc_rgba16f_array(device: &wgpu::Device, cap: u32) -> (wgpu::Texture, wgpu::TextureView) {
        let layers = cap.clamp(4, device.limits().max_texture_array_layers.max(4));
        let tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("ink-liquify-warped-rgba16f"),
            size: wgpu::Extent3d {
                width: TILE_SIZE as u32,
                height: TILE_SIZE as u32,
                depth_or_array_layers: layers,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba16Float,
            usage: wgpu::TextureUsages::TEXTURE_BINDING
                | wgpu::TextureUsages::COPY_DST
                | wgpu::TextureUsages::COPY_SRC,
            view_formats: &[],
        });
        let view = tex.create_view(&wgpu::TextureViewDescriptor {
            dimension: Some(wgpu::TextureViewDimension::D2Array),
            base_array_layer: 0,
            array_layer_count: Some(layers),
            ..Default::default()
        });
        (tex, view)
    }

    fn get_or_alloc(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, coord: TileCoord) -> u32 {
        if let Some(&slot) = self.coord_to_slot.get(&coord) {
            return slot;
        }
        if self.next_slot >= self.warped_cap {
            let new_cap = (self.warped_cap * 2)
                .min(device.limits().max_texture_array_layers.max(self.warped_cap));
            if new_cap > self.warped_cap {
                let (new_tex, new_view) = Self::alloc_rgba16f_array(device, new_cap);
                if self.next_slot > 0 {
                    let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
                        label: Some("ink-liquify-warped-grow"),
                    });
                    enc.copy_texture_to_texture(
                        wgpu::TexelCopyTextureInfo {
                            texture: &self.warped_tex,
                            mip_level: 0,
                            origin: wgpu::Origin3d::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.warped_tex = new_tex;
                self.warped_view = new_view;
                self.warped_cap = new_cap;
            }
        }
        let slot = self.next_slot.min(self.warped_cap.saturating_sub(1));
        if self.next_slot < self.warped_cap {
            self.next_slot += 1;
        }
        self.coord_to_slot.insert(coord, slot);
        slot
    }
}

/// Complete DX12 GPU Interactive Liquify Engine supporting all 8 modes + multi-layer sessions.
pub struct GpuLiquifyEngine {
    disp_bgl: wgpu::BindGroupLayout,
    disp_pipe: wgpu::RenderPipeline,
    disp_uniform_buf: wgpu::Buffer,
    disp_uniform_cap: usize,
    disp_scratch_tex: wgpu::Texture,
    disp_scratch_view: wgpu::TextureView,
    _dummy_sel_tex: wgpu::Texture,
    dummy_sel_view: wgpu::TextureView,

    warp_bgl: wgpu::BindGroupLayout,
    warp_pipe: wgpu::ComputePipeline,
    warp_uniform_buf: wgpu::Buffer,
    warp_uniform_cap: usize,
    lookup_buf: wgpu::Buffer,
    warp_scratch_tex: wgpu::Texture,
    warp_scratch_view: wgpu::TextureView,
    readback_storage_buf: wgpu::Buffer,
    readback_map_buf: wgpu::Buffer,
    readback_tile_cap: usize,

    // Sparse RG16Float displacement field pool (shared across multi-layer session!)
    disp_atlas_tex: wgpu::Texture,
    disp_atlas_view: wgpu::TextureView,
    disp_atlas_cap: u32,
    disp_coord_to_slot: HashMap<TileCoord, u32>,
    disp_next_slot: u32,
    zero_disp_tile: Vec<u8>,

    // Active session state
    active: bool,
    doc_id: String,
    doc_width: u32,
    doc_height: u32,
    layers: Vec<LayerWarpState>,
    pub total_steps_dispatched: u64,
}

impl GpuLiquifyEngine {
    pub fn new(device: &wgpu::Device) -> Self {
        let disp_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("ink-liquify-disp-bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: true,
                        min_binding_size: NonZeroU64::new(
                            std::mem::size_of::<DisplaceUniforms>() as u64,
                        ),
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    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::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
                        view_dimension: wgpu::TextureViewDimension::D2Array,
                        multisampled: false,
                    },
                    count: None,
                },
            ],
        });
        let disp_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("ink-liquify-disp-shader"),
            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(LIQUIFY_DISPLACE_WGSL)),
        });
        let disp_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("ink-liquify-disp-pl"),
            bind_group_layouts: &[Some(&disp_bgl)],
            immediate_size: 0,
        });
        let disp_pipe = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("ink-liquify-disp-pipe"),
            layout: Some(&disp_pl),
            vertex: wgpu::VertexState {
                module: &disp_shader,
                entry_point: Some("vs_liquify_displace"),
                buffers: &[],
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &disp_shader,
                entry_point: Some("fs_liquify_displace"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: wgpu::TextureFormat::Rg16Float,
                    blend: None,
                    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 disp_uniform_cap = 64usize;
        let disp_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-liquify-disp-uniforms-dyn"),
            size: disp_uniform_cap as u64 * LIQUIFY_UNIFORM_STRIDE,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let disp_scratch_tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("ink-liquify-disp-scratch"),
            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::Rg16Float,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
            view_formats: &[],
        });
        let disp_scratch_view =
            disp_scratch_tex.create_view(&wgpu::TextureViewDescriptor::default());

        let dummy_sel_tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("ink-liquify-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: &[],
        });
        let dummy_sel_view = dummy_sel_tex.create_view(&wgpu::TextureViewDescriptor {
            dimension: Some(wgpu::TextureViewDimension::D2Array),
            base_array_layer: 0,
            array_layer_count: Some(1),
            ..Default::default()
        });

        let warp_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("ink-liquify-warp-bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: true,
                        min_binding_size: NonZeroU64::new(
                            std::mem::size_of::<WarpUniforms>() as u64,
                        ),
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
                        view_dimension: wgpu::TextureViewDimension::D2Array,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::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::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: true },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    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 warp_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("ink-liquify-warp-shader"),
            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(LIQUIFY_WARP_TILE_WGSL)),
        });
        let warp_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("ink-liquify-warp-pl"),
            bind_group_layouts: &[Some(&warp_bgl)],
            immediate_size: 0,
        });
        let warp_pipe = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: Some("ink-liquify-warp-pipe"),
            layout: Some(&warp_pl),
            module: &warp_shader,
            entry_point: Some("cs_liquify_warp"),
            compilation_options: Default::default(),
            cache: None,
        });
        let warp_uniform_cap = 64usize;
        let warp_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-liquify-warp-uniforms-dyn"),
            size: warp_uniform_cap as u64 * LIQUIFY_UNIFORM_STRIDE,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let lookup_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-liquify-tile-lookup"),
            size: (MAX_LIQUIFY_LOOKUP * std::mem::size_of::<TileLookupEntry>()) as u64,
            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let warp_scratch_tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("ink-liquify-warp-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 warp_scratch_view =
            warp_scratch_tex.create_view(&wgpu::TextureViewDescriptor::default());

        let readback_tile_cap = 32usize;
        let rb_bytes = (readback_tile_cap * TILE_SIZE * TILE_SIZE * 4) as u64;
        let readback_storage_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-liquify-rb-storage"),
            size: rb_bytes,
            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
            mapped_at_creation: false,
        });
        let readback_map_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-liquify-rb-map"),
            size: rb_bytes,
            usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let disp_atlas_cap = 32u32;
        let (disp_atlas_tex, disp_atlas_view) = Self::alloc_disp_atlas(device, disp_atlas_cap);

        Self {
            disp_bgl,
            disp_pipe,
            disp_uniform_buf,
            disp_uniform_cap,
            disp_scratch_tex,
            disp_scratch_view,
            _dummy_sel_tex: dummy_sel_tex,
            dummy_sel_view,
            warp_bgl,
            warp_pipe,
            warp_uniform_buf,
            warp_uniform_cap,
            lookup_buf,
            warp_scratch_tex,
            warp_scratch_view,
            readback_storage_buf,
            readback_map_buf,
            readback_tile_cap,
            disp_atlas_tex,
            disp_atlas_view,
            disp_atlas_cap,
            disp_coord_to_slot: HashMap::new(),
            disp_next_slot: 0,
            zero_disp_tile: vec![0u8; TILE_SIZE * TILE_SIZE * 4], // RG16F = 4 bytes/px
            active: false,
            doc_id: String::new(),
            doc_width: 1,
            doc_height: 1,
            layers: Vec::new(),
            total_steps_dispatched: 0,
        }
    }

    fn alloc_disp_atlas(device: &wgpu::Device, cap: u32) -> (wgpu::Texture, wgpu::TextureView) {
        let layers = cap.clamp(4, device.limits().max_texture_array_layers.max(4));
        let tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("ink-liquify-disp-atlas-rg16f"),
            size: wgpu::Extent3d {
                width: TILE_SIZE as u32,
                height: TILE_SIZE as u32,
                depth_or_array_layers: layers,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rg16Float,
            usage: wgpu::TextureUsages::TEXTURE_BINDING
                | wgpu::TextureUsages::COPY_DST
                | wgpu::TextureUsages::COPY_SRC,
            view_formats: &[],
        });
        let view = tex.create_view(&wgpu::TextureViewDescriptor {
            dimension: Some(wgpu::TextureViewDimension::D2Array),
            base_array_layer: 0,
            array_layer_count: Some(layers),
            ..Default::default()
        });
        (tex, view)
    }

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

    /// Returns live warped `Rgba16Float` tile overrides for `layer_id` so `WgpuCompositor`
    /// renders the interactive Liquify preview in-stack at 120+ FPS!
    pub fn layer_override(
        &self,
        layer_id: &str,
    ) -> Option<(&wgpu::TextureView, &HashMap<TileCoord, u32>)> {
        if !self.active {
            return None;
        }
        let l = self.layers.iter().find(|ls| ls.layer_id == layer_id)?;
        if l.coord_to_slot.is_empty() {
            return None;
        }
        Some((&l.warped_view, &l.coord_to_slot))
    }

    pub fn active_layer_ids(&self) -> Vec<&str> {
        self.layers.iter().map(|l| l.layer_id.as_str()).collect()
    }

    fn get_or_alloc_disp_slot(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        coord: TileCoord,
    ) -> u32 {
        if let Some(&slot) = self.disp_coord_to_slot.get(&coord) {
            return slot;
        }
        if self.disp_next_slot >= self.disp_atlas_cap {
            let new_cap = (self.disp_atlas_cap * 2)
                .min(device.limits().max_texture_array_layers.max(self.disp_atlas_cap));
            if new_cap > self.disp_atlas_cap {
                let (new_tex, new_view) = Self::alloc_disp_atlas(device, new_cap);
                if self.disp_next_slot > 0 {
                    let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
                        label: Some("ink-liquify-disp-grow"),
                    });
                    enc.copy_texture_to_texture(
                        wgpu::TexelCopyTextureInfo {
                            texture: &self.disp_atlas_tex,
                            mip_level: 0,
                            origin: wgpu::Origin3d::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.disp_next_slot,
                        },
                    );
                    queue.submit(Some(enc.finish()));
                }
                self.disp_atlas_tex = new_tex;
                self.disp_atlas_view = new_view;
                self.disp_atlas_cap = new_cap;
            }
        }
        let slot = self.disp_next_slot.min(self.disp_atlas_cap.saturating_sub(1));
        if self.disp_next_slot < self.disp_atlas_cap {
            self.disp_next_slot += 1;
        }
        // Zero-initialize displacement tile `(0.0, 0.0)`
        queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &self.disp_atlas_tex,
                mip_level: 0,
                origin: wgpu::Origin3d { x: 0, y: 0, z: slot },
                aspect: wgpu::TextureAspect::All,
            },
            &self.zero_disp_tile,
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(TILE_SIZE as u32 * 4),
                rows_per_image: Some(TILE_SIZE as u32),
            },
            wgpu::Extent3d {
                width: TILE_SIZE as u32,
                height: TILE_SIZE as u32,
                depth_or_array_layers: 1,
            },
        );
        self.disp_coord_to_slot.insert(coord, slot);
        slot
    }

    /// Starts a new GPU Liquify session targeting either the active raster layer or all
    /// visible editable raster layers (`multi_layer = true` or explicit `target_layer_ids`).
    pub fn begin_session(
        &mut self,
        device: &wgpu::Device,
        doc: &Document,
        multi_layer: bool,
        explicit_layer_ids: Option<&[String]>,
    ) -> Result<Vec<LayerId>, String> {
        let mut target_ids: Vec<LayerId> = Vec::new();
        if let Some(ids) = explicit_layer_ids {
            for id in ids {
                if let Some(l) = doc.layer(id) {
                    if l.meta.layer_type.has_tiles() && !l.meta.locked {
                        target_ids.push(l.meta.id.clone());
                    }
                }
            }
        } else if multi_layer {
            for l in &doc.layers {
                if l.meta.layer_type.has_tiles()
                    && !l.meta.locked
                    && doc.is_layer_effectively_visible(&l.meta.id)
                    && !Document::is_background_layer_id(&l.meta.id)
                {
                    target_ids.push(l.meta.id.clone());
                }
            }
        } else if let Some(active_id) = doc.active_layer_id.as_deref() {
            if let Some(l) = doc.layer(active_id) {
                if l.meta.layer_type.has_tiles() && !l.meta.locked {
                    target_ids.push(l.meta.id.clone());
                }
            }
        }

        if target_ids.is_empty() {
            return Err("No editable raster layer available for Liquify".to_string());
        }

        self.disp_coord_to_slot.clear();
        self.disp_next_slot = 0;
        self.doc_id = doc.id.clone();
        self.doc_width = doc.dimensions.width.max(1);
        self.doc_height = doc.dimensions.height.max(1);
        self.layers = target_ids
            .iter()
            .map(|id| LayerWarpState::new(device, id.clone()))
            .collect();
        self.active = true;
        Ok(target_ids)
    }

    /// Applies one interactive GPU Liquify step in real time (zero CPU pixel readback!).
    #[allow(clippy::too_many_arguments)]
    pub fn apply_step(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        tile_pool: &mut GpuTilePool,
        doc: &Document,
        scratch: Option<&dyn ScratchBackend>,
        selection: Option<&GpuSelectionOverlay>,
        step: LiquifyStepParams,
    ) -> Result<RectI32, String> {
        if !self.active || self.doc_id != doc.id {
            self.begin_session(device, doc, step.settings.multi_layer, None)?;
        }

        let radius = (step.settings.size * 0.5).max(2.0);
        let eff_pressure = if step.settings.use_pressure {
            step.pressure.clamp(0.05, 1.0)
        } else {
            1.0
        };
        let min_x = step.from_x.min(step.to_x) - radius - 4.0;
        let min_y = step.from_y.min(step.to_y) - radius - 4.0;
        let max_x = step.from_x.max(step.to_x) + radius + 4.0;
        let max_y = step.from_y.max(step.to_y) + radius + 4.0;

        let max_tx = (self.doc_width.saturating_sub(1) / TILE_SIZE as u32) as i32;
        let max_ty = (self.doc_height.saturating_sub(1) / TILE_SIZE as u32) as i32;
        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 {
            return Ok(RectI32::empty());
        }

        let active_sel = selection.filter(|s| s.is_active());
        let sel_default = active_sel.map(|s| s.default_alpha_f32()).unwrap_or(1.0);

        let mut touched_coords = Vec::new();
        for ty in ty0..=ty1 {
            for tx in tx0..=tx1 {
                touched_coords.push(TileCoord::new(tx, ty));
            }
        }

        // 1. Pre-allocate all displacement slots & pack ALL DisplaceUniforms into dynamic buffer
        let mut disp_jobs: Vec<(TileCoord, u32)> = Vec::with_capacity(touched_coords.len());
        for &coord in &touched_coords {
            let slot = self.get_or_alloc_disp_slot(device, queue, coord);
            disp_jobs.push((coord, slot));
        }

        if disp_jobs.len() > self.disp_uniform_cap {
            self.disp_uniform_cap = disp_jobs.len().next_power_of_two().max(64);
            self.disp_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("ink-liquify-disp-uniforms-dyn"),
                size: self.disp_uniform_cap as u64 * LIQUIFY_UNIFORM_STRIDE,
                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
        }
        let stride = LIQUIFY_UNIFORM_STRIDE as usize;
        let mut disp_bytes = vec![0u8; disp_jobs.len() * stride];
        for (i, &(coord, slot)) in disp_jobs.iter().enumerate() {
            let sel_slot_f = match active_sel {
                Some(s) => s.tile_slot(&coord).map(|v| v as f32).unwrap_or(-1.0),
                None => -2.0,
            };
            let u = DisplaceUniforms {
                tile_info: [
                    (coord.tx * TILE_SIZE as i32) as f32,
                    (coord.ty * TILE_SIZE as i32) as f32,
                    slot as f32,
                    step.settings.mode.as_u32() as f32,
                ],
                seg: [step.from_x, step.from_y, step.to_x, step.to_y],
                brush: [
                    radius,
                    step.settings.strength.clamp(0.01, 1.0),
                    step.settings.hardness.clamp(0.0, 1.0),
                    eff_pressure,
                ],
                sel_doc: [
                    sel_slot_f,
                    sel_default,
                    self.doc_width as f32,
                    self.doc_height as f32,
                ],
            };
            let src = bytemuck::bytes_of(&u);
            disp_bytes[i * stride..i * stride + src.len()].copy_from_slice(src);
        }
        queue.write_buffer(&self.disp_uniform_buf, 0, &disp_bytes);

        let sel_view = active_sel
            .map(|s| s.atlas_view())
            .unwrap_or(&self.dummy_sel_view);
        let disp_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("ink-liquify-disp-bg"),
            layout: &self.disp_bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
                        buffer: &self.disp_uniform_buf,
                        offset: 0,
                        size: NonZeroU64::new(std::mem::size_of::<DisplaceUniforms>() as u64),
                    }),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::TextureView(&self.disp_atlas_view),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::TextureView(sel_view),
                },
            ],
        });

        // 2. Encode ALL displacement updates + Layer 0 warp passes into ONE CommandEncoder + ONE queue.submit!
        //    (Additional layers in multi-layer sessions each batch ALL their tiles into 1 submit.)
        if touched_coords.len() > self.warp_uniform_cap {
            self.warp_uniform_cap = touched_coords.len().next_power_of_two().max(64);
            self.warp_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("ink-liquify-warp-uniforms-dyn"),
                size: self.warp_uniform_cap as u64 * LIQUIFY_UNIFORM_STRIDE,
                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
        }

        let doc_id = self.doc_id.clone();
        let doc_w = self.doc_width;
        let doc_h = self.doc_height;
        let mut disp_encoded = false;

        let encode_disp_passes = |enc: &mut wgpu::CommandEncoder| {
            for (i, &(_, slot)) in disp_jobs.iter().enumerate() {
                let dyn_off = (i as u32) * (LIQUIFY_UNIFORM_STRIDE as u32);
                {
                    let mut rp = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
                        label: Some("ink-liquify-disp-pass"),
                        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                            view: &self.disp_scratch_view,
                            depth_slice: None,
                            resolve_target: None,
                            ops: wgpu::Operations {
                                load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
                                store: wgpu::StoreOp::Store,
                            },
                        })],
                        depth_stencil_attachment: None,
                        timestamp_writes: None,
                        occlusion_query_set: None,
                        multiview_mask: None,
                    });
                    rp.set_pipeline(&self.disp_pipe);
                    rp.set_bind_group(0, &disp_bg, &[dyn_off]);
                    rp.draw(0..3, 0..1);
                }
                enc.copy_texture_to_texture(
                    wgpu::TexelCopyTextureInfo {
                        texture: &self.disp_scratch_tex,
                        mip_level: 0,
                        origin: wgpu::Origin3d::ZERO,
                        aspect: wgpu::TextureAspect::All,
                    },
                    wgpu::TexelCopyTextureInfo {
                        texture: &self.disp_atlas_tex,
                        mip_level: 0,
                        origin: wgpu::Origin3d {
                            x: 0,
                            y: 0,
                            z: slot,
                        },
                        aspect: wgpu::TextureAspect::All,
                    },
                    wgpu::Extent3d {
                        width: TILE_SIZE as u32,
                        height: TILE_SIZE as u32,
                        depth_or_array_layers: 1,
                    },
                );
            }
        };

        for ls in &mut self.layers {
            let Some(layer_node) = doc.layer(&ls.layer_id) else {
                continue;
            };
            let mut lookup: Vec<TileLookupEntry> =
                Vec::with_capacity(layer_node.grid.tiles.len().min(MAX_LIQUIFY_LOOKUP));
            let mut pinned_base_slots: Vec<u32> = Vec::with_capacity(lookup.capacity());
            let doc_key = tile_pool.intern_doc(&doc_id);
            let layer_key = tile_pool.intern_layer(&ls.layer_id);
            for (&c, tile_arc) in layer_node.grid.tiles.iter().take(MAX_LIQUIFY_LOOKUP) {
                let key = GpuTileKey {
                    doc_id: doc_key,
                    layer_id: layer_key,
                    lod: 0,
                    coord: c,
                };
                if let Ok(base_slot) = tile_pool.ensure_tile_uploaded(queue, key, tile_arc, scratch)
                {
                    tile_pool.pin_slot(base_slot);
                    pinned_base_slots.push(base_slot);
                    lookup.push(TileLookupEntry {
                        tx: c.tx,
                        ty: c.ty,
                        slot: base_slot as i32,
                        _pad: 0,
                    });
                }
            }
            if !lookup.is_empty() {
                queue.write_buffer(&self.lookup_buf, 0, bytemuck::cast_slice(&lookup));
            }

            let mut warp_dst_slots: Vec<u32> = Vec::with_capacity(touched_coords.len());
            let mut warp_bytes = vec![0u8; touched_coords.len() * stride];
            for (i, &coord) in touched_coords.iter().enumerate() {
                ls.before_tiles
                    .entry(coord)
                    .or_insert_with(|| layer_node.grid.tiles.get(&coord).cloned());
                let dst_slot = ls.get_or_alloc(device, queue, coord);
                warp_dst_slots.push(dst_slot);
                let disp_slot = self
                    .disp_coord_to_slot
                    .get(&coord)
                    .map(|&s| s as f32)
                    .unwrap_or(-1.0);
                let wu = WarpUniforms {
                    tile_info: [
                        (coord.tx * TILE_SIZE as i32) as f32,
                        (coord.ty * TILE_SIZE as i32) as f32,
                        disp_slot,
                        lookup.len() as f32,
                    ],
                    doc_out: [doc_w as f32, doc_h as f32, 0.0, 0.0],
                };
                let src = bytemuck::bytes_of(&wu);
                warp_bytes[i * stride..i * stride + src.len()].copy_from_slice(src);
            }
            queue.write_buffer(&self.warp_uniform_buf, 0, &warp_bytes);

            let warp_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("ink-liquify-warp-bg"),
                layout: &self.warp_bgl,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
                            buffer: &self.warp_uniform_buf,
                            offset: 0,
                            size: NonZeroU64::new(std::mem::size_of::<WarpUniforms>() as u64),
                        }),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: wgpu::BindingResource::TextureView(tile_pool.atlas_view()),
                    },
                    wgpu::BindGroupEntry {
                        binding: 2,
                        resource: wgpu::BindingResource::TextureView(&self.disp_atlas_view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 3,
                        resource: self.lookup_buf.as_entire_binding(),
                    },
                    wgpu::BindGroupEntry {
                        binding: 4,
                        resource: wgpu::BindingResource::TextureView(&self.warp_scratch_view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 5,
                        resource: self.readback_storage_buf.as_entire_binding(),
                    },
                ],
            });

            let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("ink-liquify-step-batch-enc"),
            });
            if !disp_encoded {
                encode_disp_passes(&mut enc);
                disp_encoded = true;
            }
            for (i, &dst_slot) in warp_dst_slots.iter().enumerate() {
                let dyn_off = (i as u32) * (LIQUIFY_UNIFORM_STRIDE as u32);
                {
                    let mut cp = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
                        label: Some("ink-liquify-warp-pass"),
                        timestamp_writes: None,
                    });
                    cp.set_pipeline(&self.warp_pipe);
                    cp.set_bind_group(0, &warp_bg, &[dyn_off]);
                    cp.dispatch_workgroups(16, 16, 1);
                }
                enc.copy_texture_to_texture(
                    wgpu::TexelCopyTextureInfo {
                        texture: &self.warp_scratch_tex,
                        mip_level: 0,
                        origin: wgpu::Origin3d::ZERO,
                        aspect: wgpu::TextureAspect::All,
                    },
                    wgpu::TexelCopyTextureInfo {
                        texture: &ls.warped_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,
                    },
                );
            }
            queue.submit(Some(enc.finish()));
            for s in pinned_base_slots {
                tile_pool.unpin_slot(s);
            }
        }

        if !disp_encoded {
            let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("ink-liquify-disp-batch-enc"),
            });
            encode_disp_passes(&mut enc);
            queue.submit(Some(enc.finish()));
        }

        self.total_steps_dispatched += 1;
        let dirty = RectI32::new(
            (min_x.floor() as i32).max(0),
            (min_y.floor() as i32).max(0),
            ((max_x.ceil() as i32 - min_x.floor() as i32).max(1)) as u32,
            ((max_y.ceil() as i32 - min_y.floor() as i32).max(1)) as u32,
        )
        .intersect(RectI32::new(0, 0, self.doc_width, self.doc_height));
        Ok(dirty)
    }

    /// Commits all warped Liquify tiles atomically into `Document`'s sparse grids, `GpuTilePool`,
    /// and a single CoW Undo entry across all touched layers!
    pub fn commit_session(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        tile_pool: &mut GpuTilePool,
        doc: &mut Document,
        scratch: Option<&dyn ScratchBackend>,
    ) -> Result<(Vec<LayerId>, RectI32), String> {
        if !self.active || self.doc_id != doc.id {
            self.cancel_session();
            return Ok((Vec::new(), RectI32::empty()));
        }

        let mut all_deltas: Vec<CowTileDelta> = Vec::new();
        let mut modified_layers: Vec<LayerId> = Vec::new();
        let mut dirty_union = RectI32::empty();
        let doc_rect = RectI32::new(0, 0, doc.dimensions.width, doc.dimensions.height);

        self.active = false;
        let layers_taken = std::mem::take(&mut self.layers);
        for ls in layers_taken {
            let mut coords: Vec<TileCoord> = ls.coord_to_slot.keys().copied().collect();
            if coords.is_empty() {
                continue;
            }
            coords.sort_by_key(|c| (c.ty, c.tx));

            if coords.len() > self.readback_tile_cap {
                let new_cap = coords.len().next_power_of_two().max(32);
                let bytes = (new_cap * TILE_SIZE * TILE_SIZE * 4) as u64;
                self.readback_storage_buf = device.create_buffer(&wgpu::BufferDescriptor {
                    label: Some("ink-liquify-rb-storage"),
                    size: bytes,
                    usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
                    mapped_at_creation: false,
                });
                self.readback_map_buf = device.create_buffer(&wgpu::BufferDescriptor {
                    label: Some("ink-liquify-rb-map"),
                    size: bytes,
                    usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
                    mapped_at_creation: false,
                });
                self.readback_tile_cap = new_cap;
            }

            let Some(layer_node) = doc.layer(&ls.layer_id) else {
                continue;
            };
            let mono_thresh = layer_node.meta.mono_threshold.unwrap_or(128);
            let mut lookup: Vec<TileLookupEntry> =
                Vec::with_capacity(layer_node.grid.tiles.len().min(MAX_LIQUIFY_LOOKUP));
            let mut pinned_base_slots: Vec<u32> = Vec::with_capacity(lookup.capacity());
            let doc_key = tile_pool.intern_doc(&doc.id);
            let layer_key = tile_pool.intern_layer(&ls.layer_id);
            for (&c, tile_arc) in layer_node.grid.tiles.iter().take(MAX_LIQUIFY_LOOKUP) {
                let key = GpuTileKey {
                    doc_id: doc_key,
                    layer_id: layer_key,
                    lod: 0,
                    coord: c,
                };
                if let Ok(base_slot) = tile_pool.ensure_tile_uploaded(queue, key, tile_arc, scratch)
                {
                    tile_pool.pin_slot(base_slot);
                    pinned_base_slots.push(base_slot);
                    lookup.push(TileLookupEntry {
                        tx: c.tx,
                        ty: c.ty,
                        slot: base_slot as i32,
                        _pad: 0,
                    });
                }
            }
            if !lookup.is_empty() {
                queue.write_buffer(&self.lookup_buf, 0, bytemuck::cast_slice(&lookup));
            }

            if coords.len() > self.warp_uniform_cap {
                self.warp_uniform_cap = coords.len().next_power_of_two().max(64);
                self.warp_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
                    label: Some("ink-liquify-warp-uniforms-dyn"),
                    size: self.warp_uniform_cap as u64 * LIQUIFY_UNIFORM_STRIDE,
                    usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                    mapped_at_creation: false,
                });
            }

            // Re-run warp with `write_rgba8 = 1.0` across ALL tiles + readback copy in ONE submit!
            let stride = LIQUIFY_UNIFORM_STRIDE as usize;
            let mut warp_bytes = vec![0u8; coords.len() * stride];
            for (idx, &coord) in coords.iter().enumerate() {
                let disp_slot = self
                    .disp_coord_to_slot
                    .get(&coord)
                    .map(|&s| s as f32)
                    .unwrap_or(-1.0);
                let wu = WarpUniforms {
                    tile_info: [
                        (coord.tx * TILE_SIZE as i32) as f32,
                        (coord.ty * TILE_SIZE as i32) as f32,
                        disp_slot,
                        lookup.len() as f32,
                    ],
                    doc_out: [
                        self.doc_width as f32,
                        self.doc_height as f32,
                        idx as f32,
                        1.0,
                    ],
                };
                let src = bytemuck::bytes_of(&wu);
                warp_bytes[idx * stride..idx * stride + src.len()].copy_from_slice(src);
            }
            queue.write_buffer(&self.warp_uniform_buf, 0, &warp_bytes);

            let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("ink-liquify-commit-bg"),
                layout: &self.warp_bgl,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
                            buffer: &self.warp_uniform_buf,
                            offset: 0,
                            size: NonZeroU64::new(std::mem::size_of::<WarpUniforms>() as u64),
                        }),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: wgpu::BindingResource::TextureView(tile_pool.atlas_view()),
                    },
                    wgpu::BindGroupEntry {
                        binding: 2,
                        resource: wgpu::BindingResource::TextureView(&self.disp_atlas_view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 3,
                        resource: self.lookup_buf.as_entire_binding(),
                    },
                    wgpu::BindGroupEntry {
                        binding: 4,
                        resource: wgpu::BindingResource::TextureView(&self.warp_scratch_view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 5,
                        resource: self.readback_storage_buf.as_entire_binding(),
                    },
                ],
            });

            let total_bytes = (coords.len() * TILE_SIZE * TILE_SIZE * 4) as u64;
            let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("ink-liquify-commit-batch-enc"),
            });
            for idx in 0..coords.len() {
                let dyn_off = (idx as u32) * (LIQUIFY_UNIFORM_STRIDE as u32);
                let mut cp = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
                    label: Some("ink-liquify-commit-pass"),
                    timestamp_writes: None,
                });
                cp.set_pipeline(&self.warp_pipe);
                cp.set_bind_group(0, &bg, &[dyn_off]);
                cp.dispatch_workgroups(16, 16, 1);
            }
            enc.copy_buffer_to_buffer(
                &self.readback_storage_buf,
                0,
                &self.readback_map_buf,
                0,
                total_bytes,
            );
            queue.submit(Some(enc.finish()));
            for s in pinned_base_slots {
                tile_pool.unpin_slot(s);
            }

            let mut committed_tiles = Vec::with_capacity(coords.len());

            let slice = self.readback_map_buf.slice(0..total_bytes);
            let (tx, rx) = std::sync::mpsc::channel();
            slice.map_async(wgpu::MapMode::Read, move |res| {
                let _ = tx.send(res);
            });
            let _ = device.poll(wgpu::PollType::wait_indefinitely());
            rx.recv()
                .map_err(|_| "Liquify readback channel closed".to_string())?
                .map_err(|e| format!("Liquify readback failed: {e:?}"))?;

            let mapped = slice
                .get_mapped_range()
                .map_err(|e| format!("Liquify get_mapped_range failed: {e}"))?;
            let tile_bytes = TILE_SIZE * TILE_SIZE * 4;
            for (i, &coord) in coords.iter().enumerate() {
                let bytes = mapped[i * tile_bytes..(i + 1) * tile_bytes].to_vec();
                let ver = allocate_tile_version();
                committed_tiles.push((coord, bytes, ver));
                dirty_union = dirty_union.union(RectI32::new(
                    coord.tx * TILE_SIZE as i32,
                    coord.ty * TILE_SIZE as i32,
                    TILE_SIZE as u32,
                    TILE_SIZE as u32,
                ));
            }
            drop(mapped);
            self.readback_map_buf.unmap();

            if let Some(layer_mut) = doc.layer_mut(&ls.layer_id) {
                let (deltas, cleared_coords) = layer_mut.grid.apply_gpu_committed_tiles(
                    &ls.layer_id,
                    committed_tiles,
                    &ls.before_tiles,
                    mono_thresh,
                );
                if !deltas.is_empty() {
                    all_deltas.extend(deltas);
                    modified_layers.push(ls.layer_id.clone());
                }
                let doc_key = tile_pool.intern_doc(&doc.id);
                let layer_key = tile_pool.intern_layer(&ls.layer_id);
                for cc in cleared_coords {
                    tile_pool.evict_key(&GpuTileKey {
                        doc_id: doc_key,
                        layer_id: layer_key,
                        lod: 0,
                        coord: cc,
                    });
                }
            }
        }

        if !all_deltas.is_empty() {
            let primary_id = modified_layers
                .first()
                .cloned()
                .or_else(|| doc.active_layer_id.clone())
                .unwrap_or_default();
            let label = if modified_layers.len() > 1 {
                format!("Liquify ({} layers)", modified_layers.len())
            } else {
                "Liquify".to_string()
            };
            doc.record_stroke_deltas(&primary_id, "liquify", &label, all_deltas, None, None);
            doc.dirty_for_render = true;
        }

        self.cancel_session();
        Ok((modified_layers, dirty_union.intersect(doc_rect)))
    }

    pub fn cancel_session(&mut self) {
        self.active = false;
        self.doc_id.clear();
        self.layers.clear();
        self.disp_coord_to_slot.clear();
        self.disp_next_slot = 0;
    }

    /// Utility to inspect touched displacement tile count (for diagnostics & tests).
    pub fn active_displacement_tile_count(&self) -> usize {
        self.disp_coord_to_slot.len()
    }

    /// Returns set of all layers currently having live warped tiles.
    pub fn warped_layer_set(&self) -> HashSet<&str> {
        self.layers
            .iter()
            .filter(|l| !l.coord_to_slot.is_empty())
            .map(|l| l.layer_id.as_str())
            .collect()
    }
}