Skip to content

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

45.4 KB
Raw Blame
//! GPU `R8Unorm` Sparse Selection Mask Atlas + Animated Display-Resolution GPU Marching Ants
//! Overlay Shader (`gpu_ants.rs`).
//!
//! 1. Uploads sparse `256×256` `R8Unorm` selection mask tiles directly to VRAM so all
//!    Phase 4/5 brush commit shaders, natural paint compute shaders, and live-stroke
//!    compositor merges clip pixel-accurately to the active selection.
//! 2. Projects visible selection tiles into a lightweight viewport-resolution `R8Unorm`
//!    target (`vp_w × vp_h`, 1 byte/px) and renders crisp animated black-and-white
//!    marching ants via display-resolution 4-neighbor edge detection — completely replacing
//!    heavy DOM SVG marching ants!

use super::mask::SparseSelectionMask;
use crate::tiles::{TileCoord, TILE_SIZE};
use crate::types::CameraState;
use bytemuck::{Pod, Zeroable};
use std::borrow::Cow;
use std::collections::HashMap;

/// Projects sparse `256×256` `R8Unorm` selection tiles into viewport space.
pub const SELECTION_PROJECT_WGSL: &str = r#"
struct SelProjectUniforms {
    viewport_size_phys: vec2<f32>,
    doc_size: vec2<f32>,
    pan_css: vec2<f32>,
    zoom: f32,
    rotation_rad: f32,
    flip: vec2<f32>,
    dpr: f32,
    default_val: f32,
};

@group(0) @binding(0) var<uniform> u: SelProjectUniforms;
@group(0) @binding(1) var sel_atlas: texture_2d_array<f32>;

struct SelTileInst {
    @location(0) tile_origin_doc: vec2<f32>,
    @location(1) slot_f: f32,
    @location(2) _pad: f32,
};

struct VsOut {
    @builtin(position) pos: vec4<f32>,
    @location(0) uv: vec2<f32>,
    @location(1) doc_coord: vec2<f32>,
    @location(2) @interpolate(flat) slot_i: i32,
};

@vertex
fn vs_main(@builtin(vertex_index) vid: u32, inst: SelTileInst) -> VsOut {
    var uv: vec2<f32>;
    switch (vid) {
        case 0u: { uv = vec2<f32>(0.0, 0.0); }
        case 1u: { uv = vec2<f32>(1.0, 0.0); }
        case 2u: { uv = vec2<f32>(0.0, 1.0); }
        case 3u: { uv = vec2<f32>(0.0, 1.0); }
        case 4u: { uv = vec2<f32>(1.0, 0.0); }
        default: { uv = vec2<f32>(1.0, 1.0); }
    }
    let doc_pos = inst.tile_origin_doc + uv * 256.0;
    let centered = (doc_pos - u.doc_size * 0.5) * u.flip;
    let c = cos(u.rotation_rad);
    let s = sin(u.rotation_rad);
    let rotated = vec2<f32>(
        centered.x * c - centered.y * s,
        centered.x * s + centered.y * c,
    );
    let screen_phys = (u.pan_css + rotated * u.zoom) * u.dpr;
    let ndc = vec2<f32>(
        (2.0 * screen_phys.x / max(1.0, u.viewport_size_phys.x)) - 1.0,
        1.0 - (2.0 * screen_phys.y / max(1.0, u.viewport_size_phys.y)),
    );
    var out: VsOut;
    out.pos = vec4<f32>(ndc, 0.0, 1.0);
    out.uv = uv;
    out.doc_coord = doc_pos;
    out.slot_i = i32(round(inst.slot_f));
    return out;
}

@fragment
fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
    if (
        in.doc_coord.x < 0.0 ||
        in.doc_coord.y < 0.0 ||
        in.doc_coord.x >= u.doc_size.x ||
        in.doc_coord.y >= u.doc_size.y
    ) {
        discard;
    }
    var a = u.default_val;
    if (in.slot_i >= 0) {
        let px = clamp(vec2<i32>(floor(in.uv * 256.0)), vec2<i32>(0), vec2<i32>(255));
        a = textureLoad(sel_atlas, px, in.slot_i, 0).r;
    }
    return vec4<f32>(a, 0.0, 0.0, 1.0);
}
"#;

/// Animated display-resolution GPU Marching Ants shader.
/// Performs crisp 4-neighbor edge detection on the viewport `R8Unorm` selection mask and
/// draws animated alternating black/white diagonal stripes at 60 FPS with zero DOM SVG overhead!
pub const MARCHING_ANTS_WGSL: &str = r#"
struct MarchingAntsUniforms {
    viewport_size_phys: vec2<f32>,
    dpr: f32,
    time_sec: f32,
    active_flag: u32,
    _pad0: u32,
    _pad1: u32,
    _pad2: u32,
};

@group(0) @binding(0) var<uniform> u: MarchingAntsUniforms;
@group(0) @binding(1) var sel_vp_tex: texture_2d<f32>;

@vertex
fn vs_main(@builtin(vertex_index) vid: u32) -> @builtin(position) vec4<f32> {
    let x = f32((vid << 1u) & 2u);
    let y = f32(vid & 2u);
    return vec4<f32>(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0);
}

fn load_sel(p: vec2<i32>, dims: vec2<i32>) -> f32 {
    if (p.x < 0 || p.y < 0 || p.x >= dims.x || p.y >= dims.y) {
        return 0.0;
    }
    return textureLoad(sel_vp_tex, p, 0).r;
}

@fragment
fn fs_main(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
    if (u.active_flag == 0u) {
        discard;
    }
    let dims = vec2<i32>(max(vec2<f32>(1.0), u.viewport_size_phys));
    let p = vec2<i32>(pos.xy);
    let center = load_sel(p, dims) >= 0.5;

    let step_px = max(1, i32(round(u.dpr * 1.15)));
    let l = load_sel(p + vec2<i32>(-step_px, 0), dims) >= 0.5;
    let r = load_sel(p + vec2<i32>( step_px, 0), dims) >= 0.5;
    let t = load_sel(p + vec2<i32>(0, -step_px), dims) >= 0.5;
    let b = load_sel(p + vec2<i32>(0,  step_px), dims) >= 0.5;

    let is_edge = center && (!l || !r || !t || !b);
    if (!is_edge) {
        discard;
    }

    let safe_dpr = max(0.5, u.dpr);
    let stripe_coord = (pos.x + pos.y) / safe_dpr + u.time_sec * 18.0;
    let phase = fract(stripe_coord / 8.0);
    if (phase < 0.5) {
        return vec4<f32>(1.0, 1.0, 1.0, 0.96);
    }
    return vec4<f32>(0.05, 0.05, 0.07, 0.96);
}
"#;

/// Full-document floating selection RGBA quad projector (zero DOM `<canvas>`!).
const FLOATING_SEL_QUAD_WGSL: &str = r#"
struct FloatingQuadUniforms {
    viewport_size_phys: vec2<f32>,
    doc_size: vec2<f32>,
    pan_css: vec2<f32>,
    zoom: f32,
    rotation_rad: f32,
    flip: vec2<f32>,
    dpr: f32,
    opacity: f32,
    rect_doc: vec4<f32>, // [x, y, width, height]
};

@group(0) @binding(0) var<uniform> u: FloatingQuadUniforms;
@group(0) @binding(1) var src_tex: texture_2d<f32>;
@group(0) @binding(2) var src_sampler: sampler;

struct VsOut {
    @builtin(position) pos: vec4<f32>,
    @location(0) uv: vec2<f32>,
};

@vertex
fn vs_main(@builtin(vertex_index) vid: u32) -> VsOut {
    var uv: vec2<f32>;
    switch (vid) {
        case 0u: { uv = vec2<f32>(0.0, 0.0); }
        case 1u: { uv = vec2<f32>(1.0, 0.0); }
        case 2u: { uv = vec2<f32>(0.0, 1.0); }
        case 3u: { uv = vec2<f32>(0.0, 1.0); }
        case 4u: { uv = vec2<f32>(1.0, 0.0); }
        default: { uv = vec2<f32>(1.0, 1.0); }
    }
    let doc_pos = u.rect_doc.xy + uv * u.rect_doc.zw;
    let centered = (doc_pos - u.doc_size * 0.5) * u.flip;
    let c = cos(u.rotation_rad);
    let s = sin(u.rotation_rad);
    let rotated = vec2<f32>(
        centered.x * c - centered.y * s,
        centered.x * s + centered.y * c,
    );
    let screen_phys = (u.pan_css + rotated * u.zoom) * u.dpr;
    let ndc = vec2<f32>(
        (2.0 * screen_phys.x / max(1.0, u.viewport_size_phys.x)) - 1.0,
        1.0 - (2.0 * screen_phys.y / max(1.0, u.viewport_size_phys.y)),
    );
    var out: VsOut;
    out.pos = vec4<f32>(ndc, 0.0, 1.0);
    out.uv = uv;
    return out;
}

@fragment
fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
    let px = textureSampleLevel(src_tex, src_sampler, in.uv, 0.0);
    let a = clamp(px.a * u.opacity, 0.0, 1.0);
    if (a <= 0.001) {
        discard;
    }
    return vec4<f32>(px.rgb * a, a);
}
"#;

#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct SelProjectUniforms {
    viewport_size_phys: [f32; 2],
    doc_size: [f32; 2],
    pan_css: [f32; 2],
    zoom: f32,
    rotation_rad: f32,
    flip: [f32; 2],
    dpr: f32,
    default_val: f32,
}

#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct SelTileInst {
    tile_origin_doc: [f32; 2],
    slot_f: f32,
    _pad: f32,
}

#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct MarchingAntsUniforms {
    viewport_size_phys: [f32; 2],
    dpr: f32,
    time_sec: f32,
    active_flag: u32,
    _pad0: u32,
    _pad1: u32,
    _pad2: u32,
}

#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct FloatingQuadUniforms {
    viewport_size_phys: [f32; 2],
    doc_size: [f32; 2],
    pan_css: [f32; 2],
    zoom: f32,
    rotation_rad: f32,
    flip: [f32; 2],
    dpr: f32,
    opacity: f32,
    rect_doc: [f32; 4],
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct VpMaskCacheKey {
    synced_version: u64,
    atlas_gen: u64,
    doc_width: u32,
    doc_height: u32,
    default_value: u8,
    vp_w: u32,
    vp_h: u32,
    camera_sig: u64,
    shift_x_bits: u32,
    shift_y_bits: u32,
}

#[inline]
fn hash_sel_camera(camera: &CameraState, dpr: f32) -> u64 {
    let mut h: u64 = 0xcbf29ce484222325;
    let mix = |h: &mut u64, v: u32| {
        *h ^= u64::from(v);
        *h = h.wrapping_mul(0x100000001b3);
    };
    let fbits = |f: f32| if f == 0.0 { 0u32 } else { f.to_bits() };
    mix(&mut h, fbits(camera.pan_x));
    mix(&mut h, fbits(camera.pan_y));
    mix(&mut h, fbits(camera.zoom));
    mix(&mut h, fbits(camera.rotation));
    mix(&mut h, u32::from(camera.flip_x) | (u32::from(camera.flip_y) << 1));
    mix(&mut h, fbits(dpr));
    h
}

/// Manages sparse `R8Unorm` GPU selection tiles, viewport selection mask projection,
/// floating selection RGBA preview, and animated GPU marching ants rendering.
pub struct GpuSelectionOverlay {
    atlas_tex: wgpu::Texture,
    atlas_view: wgpu::TextureView,
    atlas_capacity: u32,
    atlas_gen: u64,
    coord_to_slot: HashMap<TileCoord, u32>,
    synced_version: u64,
    active: bool,
    default_value: u8,
    doc_width: u32,
    doc_height: u32,

    vp_tex: wgpu::Texture,
    vp_view: wgpu::TextureView,
    vp_width: u32,
    vp_height: u32,
    vp_mask_cache_key: Option<VpMaskCacheKey>,
    vp_mask_rebuilds: u64,

    project_bgl: wgpu::BindGroupLayout,
    project_pipeline: wgpu::RenderPipeline,
    project_uniform_buf: wgpu::Buffer,
    project_bg: Option<wgpu::BindGroup>,
    inst_buf: wgpu::Buffer,
    inst_cap: usize,

    ants_bgl: wgpu::BindGroupLayout,
    ants_pipeline: wgpu::RenderPipeline,
    ants_uniform_buf: wgpu::Buffer,
    ants_bg: Option<wgpu::BindGroup>,

    // Floating selection GPU texture (allocated strictly while floating move is active)
    floating_tex: Option<(wgpu::Texture, wgpu::TextureView, u32, u32, u64)>,
    floating_bg: Option<wgpu::BindGroup>,
    floating_bgl: wgpu::BindGroupLayout,
    floating_pipeline: wgpu::RenderPipeline,
    floating_uniform_buf: wgpu::Buffer,
    linear_sampler: wgpu::Sampler,
}

impl GpuSelectionOverlay {
    pub fn new(device: &wgpu::Device, surface_format: wgpu::TextureFormat) -> Self {
        let atlas_capacity = 32u32;
        let (atlas_tex, atlas_view) = Self::alloc_atlas(device, atlas_capacity);
        let (vp_tex, vp_view) = Self::alloc_vp_mask(device, 1, 1);

        let project_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("ink-sel-project-bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    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,
                },
            ],
        });
        let project_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("ink-sel-project-shader"),
            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(SELECTION_PROJECT_WGSL)),
        });
        let project_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("ink-sel-project-pl"),
            bind_group_layouts: &[Some(&project_bgl)],
            immediate_size: 0,
        });
        let inst_layout = wgpu::VertexBufferLayout {
            array_stride: std::mem::size_of::<SelTileInst>() as u64,
            step_mode: wgpu::VertexStepMode::Instance,
            attributes: &[
                wgpu::VertexAttribute {
                    offset: 0,
                    shader_location: 0,
                    format: wgpu::VertexFormat::Float32x2,
                },
                wgpu::VertexAttribute {
                    offset: 8,
                    shader_location: 1,
                    format: wgpu::VertexFormat::Float32,
                },
                wgpu::VertexAttribute {
                    offset: 12,
                    shader_location: 2,
                    format: wgpu::VertexFormat::Float32,
                },
            ],
        };
        let project_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("ink-sel-project-pipeline"),
            layout: Some(&project_pl),
            vertex: wgpu::VertexState {
                module: &project_shader,
                entry_point: Some("vs_main"),
                buffers: &[Some(inst_layout)],
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &project_shader,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: wgpu::TextureFormat::R8Unorm,
                    blend: Some(wgpu::BlendState::REPLACE),
                    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 project_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-sel-project-uniforms"),
            size: std::mem::size_of::<SelProjectUniforms>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let inst_cap = 256usize;
        let inst_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-sel-tile-insts"),
            size: (inst_cap * std::mem::size_of::<SelTileInst>()) as u64,
            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let ants_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("ink-marching-ants-bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    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::D2,
                        multisampled: false,
                    },
                    count: None,
                },
            ],
        });
        let ants_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("ink-marching-ants-shader"),
            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(MARCHING_ANTS_WGSL)),
        });
        let ants_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("ink-marching-ants-pl"),
            bind_group_layouts: &[Some(&ants_bgl)],
            immediate_size: 0,
        });
        let ants_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("ink-marching-ants-pipeline"),
            layout: Some(&ants_pl),
            vertex: wgpu::VertexState {
                module: &ants_shader,
                entry_point: Some("vs_main"),
                buffers: &[],
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &ants_shader,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: surface_format,
                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                    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 ants_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-marching-ants-uniforms"),
            size: std::mem::size_of::<MarchingAntsUniforms>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let floating_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("ink-sel-floating-bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        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::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
            ],
        });
        let floating_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("ink-sel-floating-shader"),
            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(FLOATING_SEL_QUAD_WGSL)),
        });
        let floating_pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("ink-sel-floating-pl"),
            bind_group_layouts: &[Some(&floating_bgl)],
            immediate_size: 0,
        });
        let floating_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("ink-sel-floating-pipeline"),
            layout: Some(&floating_pl),
            vertex: wgpu::VertexState {
                module: &floating_shader,
                entry_point: Some("vs_main"),
                buffers: &[],
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &floating_shader,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: surface_format,
                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
                    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 floating_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-sel-floating-uniforms"),
            size: std::mem::size_of::<FloatingQuadUniforms>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let linear_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("ink-sel-linear-sampler"),
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            ..Default::default()
        });

        Self {
            atlas_tex,
            atlas_view,
            atlas_capacity,
            atlas_gen: 1,
            coord_to_slot: HashMap::new(),
            synced_version: 0,
            active: false,
            default_value: 0,
            doc_width: 1,
            doc_height: 1,
            vp_tex,
            vp_view,
            vp_width: 1,
            vp_height: 1,
            vp_mask_cache_key: None,
            vp_mask_rebuilds: 0,
            project_bgl,
            project_pipeline,
            project_uniform_buf,
            project_bg: None,
            inst_buf,
            inst_cap,
            ants_bgl,
            ants_pipeline,
            ants_uniform_buf,
            ants_bg: None,
            floating_tex: None,
            floating_bg: None,
            floating_bgl,
            floating_pipeline,
            floating_uniform_buf,
            linear_sampler,
        }
    }

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

    fn alloc_vp_mask(device: &wgpu::Device, w: u32, h: u32) -> (wgpu::Texture, wgpu::TextureView) {
        let tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("ink-sel-vp-mask-r8"),
            size: wgpu::Extent3d {
                width: w.max(1),
                height: h.max(1),
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::R8Unorm,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
            view_formats: &[],
        });
        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
        (tex, view)
    }

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

    #[inline]
    pub fn atlas_view(&self) -> &wgpu::TextureView {
        &self.atlas_view
    }

    #[inline]
    pub fn atlas_gen(&self) -> u64 {
        self.atlas_gen
    }

    #[inline]
    pub fn default_alpha_f32(&self) -> f32 {
        self.default_value as f32 / 255.0
    }

    /// Returns the sparse GPU `R8Unorm` slot index for `coord` (or `None` if unallocated -> use `default_alpha_f32()`).
    #[inline]
    pub fn tile_slot(&self, coord: &TileCoord) -> Option<u32> {
        self.coord_to_slot.get(coord).copied()
    }

    #[inline]
    pub fn viewport_mask_view(&self) -> &wgpu::TextureView {
        &self.vp_view
    }

    #[inline]
    pub fn vp_mask_rebuilds(&self) -> u64 {
        self.vp_mask_rebuilds
    }

    /// Synchronizes a `Document`'s [`SparseSelectionMask`] into GPU `R8Unorm` sparse tiles (O(1) no-op if unchanged).
    pub fn sync_from_mask(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        mask_opt: Option<&SparseSelectionMask>,
    ) {
        let Some(mask) = mask_opt.filter(|m| !m.is_empty()) else {
            self.active = false;
            self.coord_to_slot.clear();
            self.synced_version = 0;
            self.vp_mask_cache_key = None;
            self.floating_tex = None;
            self.floating_bg = None;
            return;
        };

        self.active = true;
        self.doc_width = mask.doc_width;
        self.doc_height = mask.doc_height;
        self.default_value = mask.default_value;

        // Sync floating pixels texture if floating selection is active
        if let Some(ref fl) = mask.floating {
            let needs_upload = self
                .floating_tex
                .as_ref()
                .map(|(_, _, w, h, v)| *w != fl.width || *h != fl.height || *v != fl.version)
                .unwrap_or(true);
            if needs_upload && fl.width > 0 && fl.height > 0 {
                let tex = device.create_texture(&wgpu::TextureDescriptor {
                    label: Some("ink-sel-floating-rgba8"),
                    size: wgpu::Extent3d {
                        width: fl.width,
                        height: fl.height,
                        depth_or_array_layers: 1,
                    },
                    mip_level_count: 1,
                    sample_count: 1,
                    dimension: wgpu::TextureDimension::D2,
                    format: wgpu::TextureFormat::Rgba8Unorm,
                    usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
                    view_formats: &[],
                });
                let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
                queue.write_texture(
                    wgpu::TexelCopyTextureInfo {
                        texture: &tex,
                        mip_level: 0,
                        origin: wgpu::Origin3d::ZERO,
                        aspect: wgpu::TextureAspect::All,
                    },
                    &fl.rgba,
                    wgpu::TexelCopyBufferLayout {
                        offset: 0,
                        bytes_per_row: Some(fl.width * 4),
                        rows_per_image: Some(fl.height),
                    },
                    wgpu::Extent3d {
                        width: fl.width,
                        height: fl.height,
                        depth_or_array_layers: 1,
                    },
                );
                self.floating_tex = Some((tex, view, fl.width, fl.height, fl.version));
                self.floating_bg = None;
            }
        } else {
            self.floating_tex = None;
            self.floating_bg = None;
        }

        if self.synced_version == mask.version {
            return;
        }

        let needed = (mask.tiles.len() as u32).max(1);
        if needed > self.atlas_capacity {
            let new_cap = needed.next_power_of_two().min(device.limits().max_texture_array_layers);
            let (tex, view) = Self::alloc_atlas(device, new_cap);
            self.atlas_tex = tex;
            self.atlas_view = view;
            self.atlas_capacity = new_cap;
            self.atlas_gen = self.atlas_gen.saturating_add(1);
            self.project_bg = None;
        }

        self.coord_to_slot.clear();
        for (slot_idx, &coord) in mask.tiles.keys().enumerate() {
            if (slot_idx as u32) >= self.atlas_capacity {
                break;
            }
            let raw = mask.materialize_tile(coord);
            queue.write_texture(
                wgpu::TexelCopyTextureInfo {
                    texture: &self.atlas_tex,
                    mip_level: 0,
                    origin: wgpu::Origin3d {
                        x: 0,
                        y: 0,
                        z: slot_idx as u32,
                    },
                    aspect: wgpu::TextureAspect::All,
                },
                &raw,
                wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(TILE_SIZE as u32), // 256 bytes exact alignment
                    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.coord_to_slot.insert(coord, slot_idx as u32);
        }
        self.synced_version = mask.version;
        self.vp_mask_cache_key = None;
    }

    /// Projects sparse `R8Unorm` selection tiles into viewport-resolution `self.vp_view`
    /// by recording the pass directly into a caller-supplied `CommandEncoder` (zero extra submit).
    ///
    /// Cached by `(synced_version, atlas_gen, doc_size, default_value, vp_size, camera_sig, floating_shift)`
    /// so 240 Hz hover cursor moves and 30 Hz marching-ants ticks do ZERO selection re-projection!
    #[allow(clippy::too_many_arguments)]
    pub fn encode_viewport_mask(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        encoder: &mut wgpu::CommandEncoder,
        mask_opt: Option<&SparseSelectionMask>,
        camera: &CameraState,
        vp_w: u32,
        vp_h: u32,
        dpr: f32,
    ) {
        self.sync_from_mask(device, queue, mask_opt);
        if !self.active || vp_w == 0 || vp_h == 0 {
            return;
        }
        let Some(mask) = mask_opt else {
            return;
        };

        let safe_dpr = dpr.max(0.05);
        let (shift_x, shift_y) = mask
            .floating
            .as_ref()
            .map(|fl| ((fl.x - fl.orig_x) as f32, (fl.y - fl.orig_y) as f32))
            .unwrap_or((0.0, 0.0));

        let cache_key = VpMaskCacheKey {
            synced_version: self.synced_version,
            atlas_gen: self.atlas_gen,
            doc_width: self.doc_width,
            doc_height: self.doc_height,
            default_value: self.default_value,
            vp_w,
            vp_h,
            camera_sig: hash_sel_camera(camera, safe_dpr),
            shift_x_bits: if shift_x == 0.0 { 0 } else { shift_x.to_bits() },
            shift_y_bits: if shift_y == 0.0 { 0 } else { shift_y.to_bits() },
        };

        if self.vp_width == vp_w
            && self.vp_height == vp_h
            && self.vp_mask_cache_key == Some(cache_key)
        {
            return;
        }

        if self.vp_width != vp_w || self.vp_height != vp_h {
            let (t, v) = Self::alloc_vp_mask(device, vp_w, vp_h);
            self.vp_tex = t;
            self.vp_view = v;
            self.vp_width = vp_w;
            self.vp_height = vp_h;
            self.ants_bg = None;
        }

        // Frustum-cull emitted selection tile quads against the visible document bounds
        // (critical for inverted selections on 4K–8K canvases!).
        let frustum = crate::compositor::calculate_visible_doc_bounds(
            vp_w as f32 / safe_dpr,
            vp_h as f32 / safe_dpr,
            camera,
            self.doc_width,
            self.doc_height,
        );
        let vis_min_tx =
            ((frustum.min_x as f32 - shift_x).floor() as i32).div_euclid(TILE_SIZE as i32) - 1;
        let vis_max_tx =
            ((frustum.max_x as f32 - shift_x).ceil() as i32).div_euclid(TILE_SIZE as i32) + 1;
        let vis_min_ty =
            ((frustum.min_y as f32 - shift_y).floor() as i32).div_euclid(TILE_SIZE as i32) - 1;
        let vis_max_ty =
            ((frustum.max_y as f32 - shift_y).ceil() as i32).div_euclid(TILE_SIZE as i32) + 1;

        let mut insts = Vec::with_capacity(self.coord_to_slot.len().min(64).max(16));
        if self.default_value > 0 {
            let max_tx = (self.doc_width.saturating_sub(1) / TILE_SIZE as u32) as i32;
            let max_ty = (self.doc_height.saturating_sub(1) / TILE_SIZE as u32) as i32;
            let tx0 = vis_min_tx.clamp(0, max_tx);
            let tx1 = vis_max_tx.clamp(0, max_tx);
            let ty0 = vis_min_ty.clamp(0, max_ty);
            let ty1 = vis_max_ty.clamp(0, max_ty);
            if !frustum.is_empty() && tx0 <= tx1 && ty0 <= ty1 {
                for ty in ty0..=ty1 {
                    for tx in tx0..=tx1 {
                        let coord = TileCoord::new(tx, ty);
                        let slot = self
                            .coord_to_slot
                            .get(&coord)
                            .map(|&s| s as f32)
                            .unwrap_or(-1.0);
                        insts.push(SelTileInst {
                            tile_origin_doc: [
                                (tx * TILE_SIZE as i32) as f32 + shift_x,
                                (ty * TILE_SIZE as i32) as f32 + shift_y,
                            ],
                            slot_f: slot,
                            _pad: 0.0,
                        });
                    }
                }
            }
        } else if !frustum.is_empty() {
            for (&coord, &slot) in &self.coord_to_slot {
                if coord.tx < vis_min_tx
                    || coord.tx > vis_max_tx
                    || coord.ty < vis_min_ty
                    || coord.ty > vis_max_ty
                {
                    continue;
                }
                insts.push(SelTileInst {
                    tile_origin_doc: [
                        (coord.tx * TILE_SIZE as i32) as f32 + shift_x,
                        (coord.ty * TILE_SIZE as i32) as f32 + shift_y,
                    ],
                    slot_f: slot as f32,
                    _pad: 0.0,
                });
            }
        }

        if insts.len() > self.inst_cap {
            self.inst_cap = insts.len().next_power_of_two();
            self.inst_buf = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("ink-sel-tile-insts"),
                size: (self.inst_cap * std::mem::size_of::<SelTileInst>()) as u64,
                usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
        }
        if !insts.is_empty() {
            queue.write_buffer(&self.inst_buf, 0, bytemuck::cast_slice(&insts));
        }

        let proj_u = SelProjectUniforms {
            viewport_size_phys: [vp_w as f32, vp_h as f32],
            doc_size: [self.doc_width as f32, self.doc_height as f32],
            pan_css: [camera.pan_x, camera.pan_y],
            zoom: camera.zoom.max(0.01),
            rotation_rad: camera.rotation.to_radians(),
            flip: [
                if camera.flip_x { -1.0 } else { 1.0 },
                if camera.flip_y { -1.0 } else { 1.0 },
            ],
            dpr: safe_dpr,
            default_val: self.default_value as f32 / 255.0,
        };
        queue.write_buffer(&self.project_uniform_buf, 0, bytemuck::bytes_of(&proj_u));

        let proj_bgl = &self.project_bgl;
        let project_uniform_buf = &self.project_uniform_buf;
        let atlas_view = &self.atlas_view;
        let proj_bg = self.project_bg.get_or_insert_with(|| {
            device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("ink-sel-project-bg"),
                layout: proj_bgl,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: project_uniform_buf.as_entire_binding(),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: wgpu::BindingResource::TextureView(atlas_view),
                    },
                ],
            })
        });

        {
            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("ink-sel-project-pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &self.vp_view,
                    depth_slice: None,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
                        store: wgpu::StoreOp::Store,
                    },
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
                multiview_mask: None,
            });
            if !insts.is_empty() {
                pass.set_pipeline(&self.project_pipeline);
                pass.set_bind_group(0, &*proj_bg, &[]);
                pass.set_vertex_buffer(0, self.inst_buf.slice(..));
                pass.draw(0..6, 0..insts.len() as u32);
            }
        }
        self.vp_mask_cache_key = Some(cache_key);
        self.vp_mask_rebuilds = self.vp_mask_rebuilds.saturating_add(1);
    }

    /// Projects sparse `R8Unorm` selection tiles into viewport-resolution `self.vp_view`
    /// so both `WgpuCompositor` (live stroke clipping) and `render_floating_and_ants` can read it.
    #[allow(clippy::too_many_arguments)]
    pub fn project_viewport_mask(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        mask_opt: Option<&SparseSelectionMask>,
        camera: &CameraState,
        vp_w: u32,
        vp_h: u32,
        dpr: f32,
    ) {
        self.sync_from_mask(device, queue, mask_opt);
        if !self.active || vp_w == 0 || vp_h == 0 {
            return;
        }
        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("ink-sel-project-encoder"),
        });
        self.encode_viewport_mask(device, queue, &mut encoder, mask_opt, camera, vp_w, vp_h, dpr);
        queue.submit(Some(encoder.finish()));
    }

    /// Encodes optional floating selection pixels + animated display-resolution GPU Marching Ants
    /// onto `target_view` inside a caller-supplied `CommandEncoder` (zero extra submit).
    #[allow(clippy::too_many_arguments)]
    pub fn encode_floating_and_ants(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        encoder: &mut wgpu::CommandEncoder,
        mask_opt: Option<&SparseSelectionMask>,
        camera: &CameraState,
        vp_w: u32,
        vp_h: u32,
        dpr: f32,
        time_sec: f32,
        target_view: &wgpu::TextureView,
    ) {
        if !self.active || vp_w == 0 || vp_h == 0 {
            return;
        }
        let Some(mask) = mask_opt else {
            return;
        };

        let ants_u = MarchingAntsUniforms {
            viewport_size_phys: [vp_w as f32, vp_h as f32],
            dpr: dpr.max(0.05),
            time_sec,
            active_flag: 1,
            _pad0: 0,
            _pad1: 0,
            _pad2: 0,
        };
        queue.write_buffer(&self.ants_uniform_buf, 0, bytemuck::bytes_of(&ants_u));

        let ants_bgl = &self.ants_bgl;
        let ants_uniform_buf = &self.ants_uniform_buf;
        let vp_view = &self.vp_view;
        let ants_bg = self.ants_bg.get_or_insert_with(|| {
            device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("ink-marching-ants-bg"),
                layout: ants_bgl,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: ants_uniform_buf.as_entire_binding(),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: wgpu::BindingResource::TextureView(vp_view),
                    },
                ],
            })
        });

        // Pass 1: Draw optional floating selection pixels directly onto swapchain target
        if let (Some(ref fl), Some((_, ref fl_view, _, _, _))) = (&mask.floating, &self.floating_tex)
        {
            let fl_u = FloatingQuadUniforms {
                viewport_size_phys: [vp_w as f32, vp_h as f32],
                doc_size: [self.doc_width as f32, self.doc_height as f32],
                pan_css: [camera.pan_x, camera.pan_y],
                zoom: camera.zoom.max(0.01),
                rotation_rad: camera.rotation.to_radians(),
                flip: [
                    if camera.flip_x { -1.0 } else { 1.0 },
                    if camera.flip_y { -1.0 } else { 1.0 },
                ],
                dpr: dpr.max(0.05),
                opacity: 1.0,
                rect_doc: [fl.x as f32, fl.y as f32, fl.width as f32, fl.height as f32],
            };
            queue.write_buffer(&self.floating_uniform_buf, 0, bytemuck::bytes_of(&fl_u));
            let floating_bgl = &self.floating_bgl;
            let floating_uniform_buf = &self.floating_uniform_buf;
            let linear_sampler = &self.linear_sampler;
            let fl_bg = self.floating_bg.get_or_insert_with(|| {
                device.create_bind_group(&wgpu::BindGroupDescriptor {
                    label: Some("ink-sel-floating-bg"),
                    layout: floating_bgl,
                    entries: &[
                        wgpu::BindGroupEntry {
                            binding: 0,
                            resource: floating_uniform_buf.as_entire_binding(),
                        },
                        wgpu::BindGroupEntry {
                            binding: 1,
                            resource: wgpu::BindingResource::TextureView(fl_view),
                        },
                        wgpu::BindGroupEntry {
                            binding: 2,
                            resource: wgpu::BindingResource::Sampler(linear_sampler),
                        },
                    ],
                })
            });
            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("ink-sel-floating-pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: target_view,
                    depth_slice: None,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Load,
                        store: wgpu::StoreOp::Store,
                    },
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
                multiview_mask: None,
            });
            pass.set_pipeline(&self.floating_pipeline);
            pass.set_bind_group(0, &*fl_bg, &[]);
            pass.draw(0..6, 0..1);
        }

        // Pass 2: Animated Display-Resolution GPU Marching Ants
        {
            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("ink-marching-ants-pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: target_view,
                    depth_slice: None,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Load,
                        store: wgpu::StoreOp::Store,
                    },
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
                multiview_mask: None,
            });
            pass.set_pipeline(&self.ants_pipeline);
            pass.set_bind_group(0, &*ants_bg, &[]);
            pass.draw(0..3, 0..1);
        }
    }

    /// Renders optional floating selection pixels + animated display-resolution GPU Marching Ants
    /// onto `target_view` using the already-projected `self.vp_view`.
    #[allow(clippy::too_many_arguments)]
    pub fn render_floating_and_ants(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        mask_opt: Option<&SparseSelectionMask>,
        camera: &CameraState,
        vp_w: u32,
        vp_h: u32,
        dpr: f32,
        time_sec: f32,
        target_view: &wgpu::TextureView,
    ) {
        if !self.active || vp_w == 0 || vp_h == 0 || mask_opt.is_none() {
            return;
        }
        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("ink-sel-ants-encoder"),
        });
        self.encode_floating_and_ants(
            device,
            queue,
            &mut encoder,
            mask_opt,
            camera,
            vp_w,
            vp_h,
            dpr,
            time_sec,
            target_view,
        );
        queue.submit(Some(encoder.finish()));
    }

    /// Projects the sparse `R8Unorm` selection tiles into viewport space and renders
    /// floating pixels + animated display-resolution GPU Marching Ants onto `target_view`.
    #[allow(clippy::too_many_arguments)]
    pub fn render_overlay(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        mask_opt: Option<&SparseSelectionMask>,
        camera: &CameraState,
        vp_w: u32,
        vp_h: u32,
        dpr: f32,
        time_sec: f32,
        target_view: &wgpu::TextureView,
    ) {
        self.project_viewport_mask(device, queue, mask_opt, camera, vp_w, vp_h, dpr);
        self.render_floating_and_ants(device, queue, mask_opt, camera, vp_w, vp_h, dpr, time_sec, target_view);
    }
}