Skip to content

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

57.5 KB
Raw Blame
//! Per-layer sparse virtual tile grid storing BOTH raster tiles and non-destructive
//! 8-bit mask tiles with O(1) Copy-on-Write (`Arc<TileData>`) cloning and diffing.

use super::format::{
    convert_tile_bytes, get_pixel_1bit, is_raw_empty, pack_rgba8_to_1bit, pack_rgba8_to_8bit,
    rgba16f_to_rgba8_dithered, rgba8_to_rgba16f, set_pixel_1bit,
};
use super::tile_data::{TileData, TileStorage};
use super::{
    allocate_tile_version, pixel_to_tile_coord, TileCoord, TileFormat, TileKind, BYTES_16F,
    BYTES_1BIT, BYTES_32BIT, BYTES_8BIT, TILE_SIZE, TILE_SIZE_I32,
};
use crate::memory::ScratchBackend;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

/// Integer axis-aligned rectangle in document pixel space.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RectI32 {
    pub x: i32,
    pub y: i32,
    pub width: u32,
    pub height: u32,
}

impl RectI32 {
    #[inline]
    pub const fn new(x: i32, y: i32, width: u32, height: u32) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }

    #[inline]
    pub const fn empty() -> Self {
        Self {
            x: 0,
            y: 0,
            width: 0,
            height: 0,
        }
    }

    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.width == 0 || self.height == 0
    }

    #[inline]
    pub const fn right(&self) -> i32 {
        let sum = (self.x as i64) + (self.width as i64);
        if sum > i32::MAX as i64 {
            i32::MAX
        } else if sum < i32::MIN as i64 {
            i32::MIN
        } else {
            sum as i32
        }
    }

    #[inline]
    pub const fn bottom(&self) -> i32 {
        let sum = (self.y as i64) + (self.height as i64);
        if sum > i32::MAX as i64 {
            i32::MAX
        } else if sum < i32::MIN as i64 {
            i32::MIN
        } else {
            sum as i32
        }
    }

    #[inline]
    pub fn union(self, other: Self) -> Self {
        if self.is_empty() {
            return other;
        }
        if other.is_empty() {
            return self;
        }
        let x0 = self.x.min(other.x);
        let y0 = self.y.min(other.y);
        let x1 = self.right().max(other.right());
        let y1 = self.bottom().max(other.bottom());
        let w = (x1 as i64 - x0 as i64).clamp(0, u32::MAX as i64) as u32;
        let h = (y1 as i64 - y0 as i64).clamp(0, u32::MAX as i64) as u32;
        Self::new(x0, y0, w, h)
    }

    #[inline]
    pub fn intersect(self, other: Self) -> Self {
        if self.is_empty() || other.is_empty() {
            return Self::empty();
        }
        let x0 = self.x.max(other.x);
        let y0 = self.y.max(other.y);
        let x1 = self.right().min(other.right());
        let y1 = self.bottom().min(other.bottom());
        if x1 <= x0 || y1 <= y0 {
            Self::empty()
        } else {
            let w = (x1 as i64 - x0 as i64).clamp(0, u32::MAX as i64) as u32;
            let h = (y1 as i64 - y0 as i64).clamp(0, u32::MAX as i64) as u32;
            Self::new(x0, y0, w, h)
        }
    }
}

/// Copy-on-Write tile delta stored in the Rust Undo/Redo history stack.
///
/// Both `before` and `after` hold shared `Arc<TileData>` references, so untouched tiles
/// cost zero extra memory and undo/redo swaps pointers in O(1).
#[derive(Debug, Clone)]
pub struct CowTileDelta {
    pub layer_id: String,
    pub kind: TileKind,
    pub coord: TileCoord,
    pub before: Option<Arc<TileData>>,
    pub after: Option<Arc<TileData>>,
    pub remote_epoch: u64,
}

/// Sparse virtual tile store for a single layer (raster tiles + non-destructive 8-bit mask tiles
/// + lazily-allocated R16Float impasto 3D paint heightfield tiles).
#[derive(Debug, Clone)]
pub struct SparseLayerGrid {
    pub format: TileFormat,
    /// LOD 0 raster tiles keyed by `(tx, ty)`. Empty/transparent tiles are omitted.
    pub tiles: HashMap<TileCoord, Arc<TileData>>,
    /// Whether this layer has a non-destructive 8-bit mask attached.
    pub has_mask: bool,
    /// Default mask alpha (`255` = reveal all, `0` = hide all) for unallocated mask tiles.
    pub mask_default_value: u8,
    /// LOD 0 sparse 8-bit mask tiles (`TileFormat::Grayscale8Bit`, `TileKind::Mask`).
    /// Tiles uniform at `mask_default_value` are omitted for 0-byte memory footprint.
    pub mask_tiles: HashMap<TileCoord, Arc<TileData>>,
    /// Lazily-allocated LOD 0 sparse `R16Float` impasto 3D heightfield tiles
    /// (`TileFormat::Height16Float`, `TileKind::ImpastoHeight`). Zero memory on non-impasto layers!
    pub impasto_tiles: HashMap<TileCoord, Arc<TileData>>,
    /// Dirty mipmap tiles awaiting GPU compute downsample regeneration for LOD 1, 2, 3.
    pub dirty_lods: [HashSet<TileCoord>; 3],
    /// Monotonic version counter bumped on any raster, mask, or impasto mutation.
    pub layer_version: u64,
    /// Monotonic version counter bumped ONLY when mask tiles, `has_mask`, or `mask_default_value` mutate
    /// (NEVER bumped by raster or impasto strokes!).
    pub mask_version: u64,
    /// Per-tile remote peer mutation epoch for collaborative conflict-aware selective undo.
    pub remote_epochs: HashMap<TileCoord, u64>,
}

impl Default for SparseLayerGrid {
    fn default() -> Self {
        Self::new(TileFormat::Color32Bit)
    }
}

impl SparseLayerGrid {
    pub fn new(format: TileFormat) -> Self {
        Self {
            format,
            tiles: HashMap::new(),
            has_mask: false,
            mask_default_value: 255,
            mask_tiles: HashMap::new(),
            impasto_tiles: HashMap::new(),
            dirty_lods: [HashSet::new(), HashSet::new(), HashSet::new()],
            layer_version: allocate_tile_version(),
            mask_version: allocate_tile_version(),
            remote_epochs: HashMap::new(),
        }
    }

    /// O(1) Copy-on-Write clone: shares every `Arc<TileData>` without duplicating pixel buffers.
    pub fn clone_cow(&self) -> Self {
        Self {
            format: self.format,
            tiles: self.tiles.clone(),
            has_mask: self.has_mask,
            mask_default_value: self.mask_default_value,
            mask_tiles: self.mask_tiles.clone(),
            impasto_tiles: self.impasto_tiles.clone(),
            dirty_lods: self.dirty_lods.clone(),
            layer_version: allocate_tile_version(),
            mask_version: self.mask_version,
            remote_epochs: self.remote_epochs.clone(),
        }
    }

    #[inline]
    pub fn bump_version(&mut self) {
        self.layer_version = allocate_tile_version();
    }

    #[inline]
    pub fn bump_mask_version(&mut self) {
        self.mask_version = allocate_tile_version();
    }

    #[inline]
    pub fn mark_lod_ancestors_dirty(&mut self, coord: TileCoord) {
        let mut c = coord;
        for lod_idx in 0..3 {
            c = c.parent();
            self.dirty_lods[lod_idx].insert(c);
        }
    }

    /// Marks all populated tiles' LOD 1..3 ancestors dirty (e.g. after bulk hydration).
    pub fn mark_all_lods_dirty(&mut self) {
        let coords: Vec<TileCoord> = self.tiles.keys().copied().collect();
        for c in coords {
            self.mark_lod_ancestors_dirty(c);
        }
    }

    /// Returns the union document-space bounding box covering all populated raster tiles.
    pub fn tile_bounds(&self) -> Option<RectI32> {
        let mut iter = self.tiles.keys();
        let first = *iter.next()?;
        let mut min_tx = first.tx;
        let mut min_ty = first.ty;
        let mut max_tx = first.tx;
        let mut max_ty = first.ty;
        for c in iter {
            min_tx = min_tx.min(c.tx);
            min_ty = min_ty.min(c.ty);
            max_tx = max_tx.max(c.tx);
            max_ty = max_ty.max(c.ty);
        }
        Some(RectI32::new(
            min_tx * TILE_SIZE_I32,
            min_ty * TILE_SIZE_I32,
            ((max_tx - min_tx + 1) * TILE_SIZE_I32) as u32,
            ((max_ty - min_ty + 1) * TILE_SIZE_I32) as u32,
        ))
    }

    /// Returns all `TileCoord`s overlapped by a document-space rectangle.
    pub fn tile_coords_for_rect(&self, rect: RectI32) -> Vec<TileCoord> {
        if rect.is_empty() {
            return Vec::new();
        }
        let tx0 = rect.x.div_euclid(TILE_SIZE_I32);
        let ty0 = rect.y.div_euclid(TILE_SIZE_I32);
        let tx1 = (rect.x + rect.width as i32 - 1).div_euclid(TILE_SIZE_I32);
        let ty1 = (rect.y + rect.height as i32 - 1).div_euclid(TILE_SIZE_I32);
        let mut out = Vec::with_capacity(((tx1 - tx0 + 1) * (ty1 - ty0 + 1)).max(0) as usize);
        for ty in ty0..=ty1 {
            for tx in tx0..=tx1 {
                out.push(TileCoord::new(tx, ty));
            }
        }
        out
    }

    /// Clears all raster tiles on this grid and marks all prior LOD ancestors dirty.
    pub fn clear_all(&mut self) {
        let prev: Vec<TileCoord> = self.tiles.keys().copied().collect();
        self.tiles.clear();
        for c in prev {
            self.mark_lod_ancestors_dirty(c);
        }
        self.bump_version();
    }

    #[inline]
    pub fn tile_map(&self, kind: TileKind) -> &HashMap<TileCoord, Arc<TileData>> {
        match kind {
            TileKind::Raster => &self.tiles,
            TileKind::Mask => &self.mask_tiles,
            TileKind::ImpastoHeight => &self.impasto_tiles,
        }
    }

    #[inline]
    pub fn tile_map_mut(&mut self, kind: TileKind) -> &mut HashMap<TileCoord, Arc<TileData>> {
        match kind {
            TileKind::Raster => &mut self.tiles,
            TileKind::Mask => &mut self.mask_tiles,
            TileKind::ImpastoHeight => &mut self.impasto_tiles,
        }
    }

    #[inline]
    pub fn get_tile(&self, coord: TileCoord) -> Option<&Arc<TileData>> {
        self.tiles.get(&coord)
    }

    #[inline]
    pub fn get_mask_tile(&self, coord: TileCoord) -> Option<&Arc<TileData>> {
        self.mask_tiles.get(&coord)
    }

    #[inline]
    pub fn get_impasto_tile(&self, coord: TileCoord) -> Option<&Arc<TileData>> {
        self.impasto_tiles.get(&coord)
    }

    #[inline]
    pub fn has_impasto(&self) -> bool {
        !self.impasto_tiles.is_empty()
    }

    pub fn set_impasto_tile(&mut self, coord: TileCoord, tile: Arc<TileData>) {
        self.impasto_tiles.insert(coord, tile);
        self.bump_version();
    }

    pub fn remove_impasto_tile(&mut self, coord: TileCoord) -> Option<Arc<TileData>> {
        let prev = self.impasto_tiles.remove(&coord);
        if prev.is_some() {
            self.bump_version();
        }
        prev
    }

    pub fn set_tile(&mut self, coord: TileCoord, tile: Arc<TileData>) {
        self.tiles.insert(coord, tile);
        self.mark_lod_ancestors_dirty(coord);
        self.bump_version();
    }

    /// Commits a batch of GPU-composited `256×256` RGBA8 tiles directly into this sparse grid
    /// with their exact matching GPU slot versions, building Copy-on-Write [`CowTileDelta`]s
    /// against `before_snapshots` (captured lazily before the first dab touched each tile!).
    ///
    /// Returns `(deltas, cleared_coords)` where `cleared_coords` are tiles that became
    /// completely transparent and were removed from the sparse grid.
    pub fn apply_gpu_committed_tiles(
        &mut self,
        layer_id: &str,
        committed: Vec<(TileCoord, Vec<u8>, u64)>,
        before_snapshots: &HashMap<TileCoord, Option<Arc<TileData>>>,
        mono_threshold: u8,
    ) -> (Vec<CowTileDelta>, Vec<TileCoord>) {
        let mut deltas = Vec::with_capacity(committed.len());
        let mut cleared_coords = Vec::new();

        for (coord, rgba8, gpu_ver) in committed {
            let before = before_snapshots
                .get(&coord)
                .cloned()
                .unwrap_or_else(|| self.tiles.get(&coord).cloned());
            let raw = if self.format == TileFormat::Color32Bit {
                rgba8
            } else {
                convert_tile_bytes(
                    &rgba8,
                    TileFormat::Color32Bit,
                    self.format,
                    mono_threshold,
                    false,
                )
            };

            let after = if is_raw_empty(self.format, &raw) {
                self.tiles.remove(&coord);
                cleared_coords.push(coord);
                None
            } else {
                let mut td = TileData::from_raw_auto_compact(self.format, TileKind::Raster, raw);
                // Only preserve GPU atlas slot version for full-precision color tiles;
                // quantized Monochrome1Bit / Grayscale8Bit tiles must re-upload their quantized pixels!
                if matches!(
                    self.format,
                    TileFormat::Color32Bit | TileFormat::Rgba16Float
                ) {
                    td.version = gpu_ver;
                }
                let arc = Arc::new(td);
                self.tiles.insert(coord, Arc::clone(&arc));
                Some(arc)
            };

            self.mark_lod_ancestors_dirty(coord);
            let remote_epoch = self.remote_epochs.get(&coord).copied().unwrap_or(0);
            if before.is_some() || after.is_some() {
                deltas.push(CowTileDelta {
                    layer_id: layer_id.to_string(),
                    kind: TileKind::Raster,
                    coord,
                    before,
                    after,
                    remote_epoch,
                });
            }
        }

        if !deltas.is_empty() {
            self.bump_version();
        }
        (deltas, cleared_coords)
    }

    pub fn remove_tile(&mut self, coord: TileCoord) -> Option<Arc<TileData>> {
        let prev = self.tiles.remove(&coord);
        if prev.is_some() {
            self.mark_lod_ancestors_dirty(coord);
            self.bump_version();
        }
        prev
    }

    pub fn set_mask_tile(&mut self, coord: TileCoord, tile: Arc<TileData>) {
        self.has_mask = true;
        self.mask_tiles.insert(coord, tile);
        self.bump_mask_version();
        self.bump_version();
    }

    pub fn remove_mask_tile(&mut self, coord: TileCoord) -> Option<Arc<TileData>> {
        let prev = self.mask_tiles.remove(&coord);
        if prev.is_some() {
            self.bump_mask_version();
            self.bump_version();
        }
        prev
    }

    pub fn clear_raster(&mut self) {
        let coords: Vec<TileCoord> = self.tiles.keys().copied().collect();
        self.tiles.clear();
        self.impasto_tiles.clear();
        for c in coords {
            self.mark_lod_ancestors_dirty(c);
        }
        self.bump_version();
    }

    /// Commits a batch of GPU-updated sparse `R16Float` impasto heightfield tiles (`131,072` bytes each)
    /// into `self.impasto_tiles`, producing CoW [`CowTileDelta`]s for Undo/Redo.
    pub fn apply_gpu_committed_impasto_tiles(
        &mut self,
        layer_id: &str,
        committed: Vec<(TileCoord, Vec<u8>, u64)>,
        before_snapshots: &HashMap<TileCoord, Option<Arc<TileData>>>,
    ) -> (Vec<CowTileDelta>, Vec<TileCoord>) {
        let mut deltas = Vec::with_capacity(committed.len());
        let mut cleared_coords = Vec::new();

        for (coord, r16f_bytes, gpu_ver) in committed {
            let before = before_snapshots
                .get(&coord)
                .cloned()
                .unwrap_or_else(|| self.impasto_tiles.get(&coord).cloned());

            let after = if is_raw_empty(TileFormat::Height16Float, &r16f_bytes) {
                self.impasto_tiles.remove(&coord);
                cleared_coords.push(coord);
                None
            } else {
                let mut td = TileData::from_raw_auto_compact(
                    TileFormat::Height16Float,
                    TileKind::ImpastoHeight,
                    r16f_bytes,
                );
                td.version = gpu_ver;
                let arc = Arc::new(td);
                self.impasto_tiles.insert(coord, Arc::clone(&arc));
                Some(arc)
            };

            let remote_epoch = self.remote_epochs.get(&coord).copied().unwrap_or(0);
            if before.is_some() || after.is_some() {
                deltas.push(CowTileDelta {
                    layer_id: layer_id.to_string(),
                    kind: TileKind::ImpastoHeight,
                    coord,
                    before,
                    after,
                    remote_epoch,
                });
            }
        }

        if !deltas.is_empty() {
            self.bump_version();
        }
        (deltas, cleared_coords)
    }

    /// Commits a batch of GPU-composited `256×256` RGBA8 mask-mode stroke tiles directly into
    /// `self.mask_tiles` (`Grayscale8Bit`, `TileKind::Mask`), producing CoW [`CowTileDelta`]s.
    pub fn apply_gpu_committed_mask_tiles(
        &mut self,
        layer_id: &str,
        committed: Vec<(TileCoord, Vec<u8>, u64)>,
        before_snapshots: &HashMap<TileCoord, Option<Arc<TileData>>>,
    ) -> (Vec<CowTileDelta>, Vec<TileCoord>) {
        let mut deltas = Vec::with_capacity(committed.len());
        let mut cleared_coords = Vec::new();
        self.has_mask = true;

        for (coord, rgba8, gpu_ver) in committed {
            let before = before_snapshots
                .get(&coord)
                .cloned()
                .unwrap_or_else(|| self.mask_tiles.get(&coord).cloned());
            let mut mask8 = vec![0u8; BYTES_8BIT];
            // Mask tiles carry luminance in R/G/B and alpha in A (`lum * alpha / 255` or R channel).
            super::format::pack_rgba8_to_mask8(&rgba8, &mut mask8);

            let is_default = mask8.iter().all(|&b| b == self.mask_default_value);
            let after = if is_default {
                self.mask_tiles.remove(&coord);
                cleared_coords.push(coord);
                None
            } else {
                let mut td = TileData::from_raw_auto_compact(
                    TileFormat::Grayscale8Bit,
                    TileKind::Mask,
                    mask8,
                );
                td.version = gpu_ver;
                let arc = Arc::new(td);
                self.mask_tiles.insert(coord, Arc::clone(&arc));
                Some(arc)
            };

            let remote_epoch = self.remote_epochs.get(&coord).copied().unwrap_or(0);
            if before.is_some() || after.is_some() {
                deltas.push(CowTileDelta {
                    layer_id: layer_id.to_string(),
                    kind: TileKind::Mask,
                    coord,
                    before,
                    after,
                    remote_epoch,
                });
            }
        }

        if !deltas.is_empty() {
            self.bump_mask_version();
            self.bump_version();
        }
        (deltas, cleared_coords)
    }

    /// Reads a single `R16Float` impasto height sample (`0.0` if unallocated) at document `(x, y)`.
    pub fn get_impasto_height_f32(
        &self,
        x: i32,
        y: i32,
        scratch: Option<&dyn ScratchBackend>,
    ) -> f32 {
        let tx = pixel_to_tile_coord(x, 0);
        let ty = pixel_to_tile_coord(y, 0);
        let Some(tile) = self.impasto_tiles.get(&TileCoord::new(tx, ty)) else {
            return 0.0;
        };
        if let TileStorage::SolidColor { rgba16f, .. } = tile.storage {
            return half::f16::from_bits(rgba16f[0]).to_f32();
        }
        let lx = (x - tx * TILE_SIZE_I32) as usize;
        let ly = (y - ty * TILE_SIZE_I32) as usize;
        let Ok(raw) = tile.materialize_raw(scratch) else {
            return 0.0;
        };
        let off = (ly * TILE_SIZE + lx) * 2;
        if off + 1 >= raw.len() {
            return 0.0;
        }
        half::f16::from_bits(u16::from_le_bytes([raw[off], raw[off + 1]])).to_f32()
    }

    /// Initializes a non-destructive 8-bit layer mask (`default_value = 255` for reveal-all
    /// allocates ZERO mask tiles!).
    pub fn init_mask(&mut self, default_value: u8) {
        self.has_mask = true;
        self.mask_default_value = default_value;
        self.mask_tiles.clear();
        self.bump_mask_version();
        self.bump_version();
    }

    pub fn remove_mask(&mut self) {
        self.has_mask = false;
        self.mask_tiles.clear();
        self.bump_mask_version();
        self.bump_version();
    }

    /// Fills `[0..width, 0..height]` with a uniform RGBA8 color using zero-allocation
    /// [`TileStorage::SolidColor`] tiles shared via `Arc` across the entire canvas
    /// (both GPU shaders and CPU readers clip strictly to `[0..doc_w, 0..doc_h]`).
    pub fn fill_solid_layer(&mut self, width: u32, height: u32, rgba8: [u8; 4]) {
        self.clear_raster();
        if width == 0 || height == 0 || rgba8[3] == 0 {
            return;
        }
        let max_tx = pixel_to_tile_coord(width as i32 - 1, 0);
        let max_ty = pixel_to_tile_coord(height as i32 - 1, 0);
        // Share a single Arc<TileData> across EVERY tile (0 bytes pixel RAM & 1 VRAM slot!)
        let shared_solid = Arc::new(TileData::new_solid(self.format, TileKind::Raster, rgba8));

        for ty in 0..=max_ty {
            for tx in 0..=max_tx {
                let coord = TileCoord::new(tx, ty);
                self.tiles.insert(coord, Arc::clone(&shared_solid));
                self.mark_lod_ancestors_dirty(coord);
            }
        }
        self.bump_version();
    }

    /// Reads a single RGBA8 pixel in O(1) without allocating a tile buffer.
    pub fn get_pixel_rgba8(&self, x: i32, y: i32, scratch: Option<&dyn ScratchBackend>) -> [u8; 4] {
        let tx = pixel_to_tile_coord(x, 0);
        let ty = pixel_to_tile_coord(y, 0);
        let Some(tile) = self.tiles.get(&TileCoord::new(tx, ty)) else {
            return [0, 0, 0, 0];
        };
        if let TileStorage::SolidColor { rgba8, .. } = tile.storage {
            return rgba8;
        }
        let lx = (x - tx * TILE_SIZE_I32) as usize;
        let ly = (y - ty * TILE_SIZE_I32) as usize;
        let Ok(raw) = tile.materialize_raw(scratch) else {
            return [0, 0, 0, 0];
        };
        match tile.format {
            TileFormat::Color32Bit => {
                let off = (ly * TILE_SIZE + lx) * 4;
                [raw[off], raw[off + 1], raw[off + 2], raw[off + 3]]
            }
            TileFormat::Monochrome1Bit => {
                if get_pixel_1bit(&raw, lx, ly) != 0 {
                    [0, 0, 0, 255]
                } else {
                    [0, 0, 0, 0]
                }
            }
            TileFormat::Grayscale8Bit => {
                let v = raw[ly * TILE_SIZE + lx];
                if v == 0 {
                    [0, 0, 0, 0]
                } else {
                    [v, v, v, 255]
                }
            }
            TileFormat::Rgba16Float => {
                let off = (ly * TILE_SIZE + lx) * 8;
                let px = [
                    u16::from_le_bytes([raw[off], raw[off + 1]]),
                    u16::from_le_bytes([raw[off + 2], raw[off + 3]]),
                    u16::from_le_bytes([raw[off + 4], raw[off + 5]]),
                    u16::from_le_bytes([raw[off + 6], raw[off + 7]]),
                ];
                super::format::f16_pixel_to_rgba8(px)
            }
            TileFormat::Height16Float => {
                let off = (ly * TILE_SIZE + lx) * 2;
                let h = half::f16::from_bits(u16::from_le_bytes([raw[off], raw[off + 1]])).to_f32();
                let g = (h.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
                [g, g, g, if h.abs() > 1e-5 { 255 } else { 0 }]
            }
        }
    }

    /// Reads a single 8-bit mask alpha value (`0..=255`) at `(x, y)`.
    pub fn get_mask_alpha(&self, x: i32, y: i32, scratch: Option<&dyn ScratchBackend>) -> u8 {
        if !self.has_mask {
            return 255;
        }
        let tx = pixel_to_tile_coord(x, 0);
        let ty = pixel_to_tile_coord(y, 0);
        let Some(tile) = self.mask_tiles.get(&TileCoord::new(tx, ty)) else {
            return self.mask_default_value;
        };
        if let TileStorage::SolidColor { rgba8, .. } = tile.storage {
            return rgba8[0];
        }
        let lx = (x - tx * TILE_SIZE_I32) as usize;
        let ly = (y - ty * TILE_SIZE_I32) as usize;
        match tile.materialize_raw(scratch) {
            Ok(raw) => raw[ly * TILE_SIZE + lx],
            Err(_) => self.mask_default_value,
        }
    }

    /// Writes an arbitrary RGBA8 rectangle into LOD 0 raster tiles (Copy-on-Write).
    /// Auto-converts into `self.format`, prunes completely transparent tiles, compacts uniform
    /// tiles to `SolidColor`, and returns the list of touched tile coordinates.
    pub fn write_rgba8_rect(
        &mut self,
        rgba8: &[u8],
        rect: RectI32,
        mono_threshold: u8,
        scratch: Option<&dyn ScratchBackend>,
    ) -> Result<Vec<TileCoord>, String> {
        if rect.is_empty() {
            return Ok(Vec::new());
        }
        let expected_len = (rect.width as usize)
            .checked_mul(rect.height as usize)
            .and_then(|n| n.checked_mul(4))
            .ok_or_else(|| "write_rgba8_rect dimensions overflow".to_string())?;
        if rgba8.len() != expected_len {
            return Err(format!(
                "write_rgba8_rect buffer length mismatch: expected {}, got {}",
                expected_len,
                rgba8.len()
            ));
        }

        let x0 = rect.x;
        let y0 = rect.y;
        let x1 = rect.right();
        let y1 = rect.bottom();
        let min_tx = pixel_to_tile_coord(x0, 0);
        let min_ty = pixel_to_tile_coord(y0, 0);
        let max_tx = pixel_to_tile_coord(x1 - 1, 0);
        let max_ty = pixel_to_tile_coord(y1 - 1, 0);

        let src_w = rect.width as usize;
        let mut touched = Vec::new();

        for ty in min_ty..=max_ty {
            let tile_y0 = ty * TILE_SIZE_I32;
            let iy0 = y0.max(tile_y0);
            let iy1 = y1.min(tile_y0 + TILE_SIZE_I32);
            if iy0 >= iy1 {
                continue;
            }
            for tx in min_tx..=max_tx {
                let tile_x0 = tx * TILE_SIZE_I32;
                let ix0 = x0.max(tile_x0);
                let ix1 = x1.min(tile_x0 + TILE_SIZE_I32);
                if ix0 >= ix1 {
                    continue;
                }
                let coord = TileCoord::new(tx, ty);
                let copy_w = (ix1 - ix0) as usize;
                let full_tile = ix0 == tile_x0
                    && iy0 == tile_y0
                    && ix1 == tile_x0 + TILE_SIZE_I32
                    && iy1 == tile_y0 + TILE_SIZE_I32;

                let mut work_rgba = if full_tile {
                    vec![0u8; BYTES_32BIT]
                } else if let Some(existing) = self.tiles.get(&coord) {
                    existing.to_rgba8(scratch, false)?
                } else {
                    vec![0u8; BYTES_32BIT]
                };

                for y in iy0..iy1 {
                    let sy = (y - y0) as usize;
                    let sx = (ix0 - x0) as usize;
                    let dy = (y - tile_y0) as usize;
                    let dx = (ix0 - tile_x0) as usize;
                    let src_off = (sy * src_w + sx) * 4;
                    let dst_off = (dy * TILE_SIZE + dx) * 4;
                    work_rgba[dst_off..dst_off + copy_w * 4]
                        .copy_from_slice(&rgba8[src_off..src_off + copy_w * 4]);
                }

                if is_raw_empty(TileFormat::Color32Bit, &work_rgba) {
                    self.tiles.remove(&coord);
                } else {
                    let tile_bytes = match self.format {
                        TileFormat::Color32Bit => work_rgba,
                        TileFormat::Monochrome1Bit => {
                            let mut out = vec![0u8; BYTES_1BIT];
                            pack_rgba8_to_1bit(&work_rgba, &mut out, mono_threshold);
                            if is_raw_empty(TileFormat::Monochrome1Bit, &out) {
                                self.tiles.remove(&coord);
                                self.mark_lod_ancestors_dirty(coord);
                                touched.push(coord);
                                continue;
                            }
                            out
                        }
                        TileFormat::Grayscale8Bit => {
                            let mut out = vec![0u8; BYTES_8BIT];
                            pack_rgba8_to_8bit(&work_rgba, &mut out);
                            if is_raw_empty(TileFormat::Grayscale8Bit, &out) {
                                self.tiles.remove(&coord);
                                self.mark_lod_ancestors_dirty(coord);
                                touched.push(coord);
                                continue;
                            }
                            out
                        }
                        TileFormat::Rgba16Float => {
                            let mut out = vec![0u8; BYTES_16F];
                            rgba8_to_rgba16f(&work_rgba, &mut out);
                            out
                        }
                        TileFormat::Height16Float => convert_tile_bytes(
                            &work_rgba,
                            TileFormat::Color32Bit,
                            TileFormat::Height16Float,
                            mono_threshold,
                            false,
                        ),
                    };
                    self.tiles.insert(
                        coord,
                        Arc::new(TileData::from_raw_auto_compact(
                            self.format,
                            TileKind::Raster,
                            tile_bytes,
                        )),
                    );
                }
                self.mark_lod_ancestors_dirty(coord);
                touched.push(coord);
            }
        }

        if !touched.is_empty() {
            self.bump_version();
        }
        Ok(touched)
    }

    /// Reads an arbitrary RGBA8 rectangle out of LOD 0 raster tiles.
    pub fn read_rgba8_rect(
        &self,
        rect: RectI32,
        dither: bool,
        scratch: Option<&dyn ScratchBackend>,
    ) -> Result<Vec<u8>, String> {
        let total = (rect.width as usize)
            .checked_mul(rect.height as usize)
            .and_then(|n| n.checked_mul(4))
            .ok_or_else(|| "read_rgba8_rect dimensions overflow".to_string())?;
        let mut out = vec![0u8; total];
        if rect.is_empty() || self.tiles.is_empty() {
            return Ok(out);
        }

        let x0 = rect.x;
        let y0 = rect.y;
        let x1 = rect.right();
        let y1 = rect.bottom();
        let min_tx = pixel_to_tile_coord(x0, 0);
        let min_ty = pixel_to_tile_coord(y0, 0);
        let max_tx = pixel_to_tile_coord(x1 - 1, 0);
        let max_ty = pixel_to_tile_coord(y1 - 1, 0);
        let dst_w = rect.width as usize;

        for ty in min_ty..=max_ty {
            let tile_y0 = ty * TILE_SIZE_I32;
            let iy0 = y0.max(tile_y0);
            let iy1 = y1.min(tile_y0 + TILE_SIZE_I32);
            if iy0 >= iy1 {
                continue;
            }
            for tx in min_tx..=max_tx {
                let Some(tile) = self.tiles.get(&TileCoord::new(tx, ty)) else {
                    continue;
                };
                let tile_x0 = tx * TILE_SIZE_I32;
                let ix0 = x0.max(tile_x0);
                let ix1 = x1.min(tile_x0 + TILE_SIZE_I32);
                if ix0 >= ix1 {
                    continue;
                }
                let copy_w = (ix1 - ix0) as usize;

                if let TileStorage::SolidColor { rgba8, .. } = tile.storage {
                    if rgba8[3] == 0 {
                        continue;
                    }
                    for y in iy0..iy1 {
                        let dy = (y - y0) as usize;
                        let dx = (ix0 - x0) as usize;
                        let row_base = (dy * dst_w + dx) * 4;
                        for px in 0..copy_w {
                            out[row_base + px * 4..row_base + px * 4 + 4].copy_from_slice(&rgba8);
                        }
                    }
                    continue;
                }

                let tile_rgba = tile.to_rgba8(scratch, dither)?;
                for y in iy0..iy1 {
                    let sy = (y - tile_y0) as usize;
                    let sx = (ix0 - tile_x0) as usize;
                    let dy = (y - y0) as usize;
                    let dx = (ix0 - x0) as usize;
                    let src_off = (sy * TILE_SIZE + sx) * 4;
                    let dst_off = (dy * dst_w + dx) * 4;
                    out[dst_off..dst_off + copy_w * 4]
                        .copy_from_slice(&tile_rgba[src_off..src_off + copy_w * 4]);
                }
            }
        }
        Ok(out)
    }

    /// Writes an 8-bit grayscale mask rectangle (`1 byte/pixel`) directly into sparse `mask_tiles`.
    /// Tiles that uniformly match `self.mask_default_value` are automatically deleted for zero memory.
    pub fn write_mask8_rect(
        &mut self,
        mask8: &[u8],
        rect: RectI32,
        scratch: Option<&dyn ScratchBackend>,
    ) -> Result<Vec<TileCoord>, String> {
        if rect.is_empty() {
            return Ok(Vec::new());
        }
        let expected_len = (rect.width as usize)
            .checked_mul(rect.height as usize)
            .ok_or_else(|| "write_mask8_rect dimensions overflow".to_string())?;
        if mask8.len() != expected_len {
            return Err(format!(
                "write_mask8_rect length mismatch: expected {}, got {}",
                expected_len,
                mask8.len()
            ));
        }

        self.has_mask = true;
        let x0 = rect.x;
        let y0 = rect.y;
        let x1 = rect.right();
        let y1 = rect.bottom();
        let min_tx = pixel_to_tile_coord(x0, 0);
        let min_ty = pixel_to_tile_coord(y0, 0);
        let max_tx = pixel_to_tile_coord(x1 - 1, 0);
        let max_ty = pixel_to_tile_coord(y1 - 1, 0);
        let src_w = rect.width as usize;
        let default_v = self.mask_default_value;
        let mut touched = Vec::new();

        for ty in min_ty..=max_ty {
            let tile_y0 = ty * TILE_SIZE_I32;
            let iy0 = y0.max(tile_y0);
            let iy1 = y1.min(tile_y0 + TILE_SIZE_I32);
            if iy0 >= iy1 {
                continue;
            }
            for tx in min_tx..=max_tx {
                let tile_x0 = tx * TILE_SIZE_I32;
                let ix0 = x0.max(tile_x0);
                let ix1 = x1.min(tile_x0 + TILE_SIZE_I32);
                if ix0 >= ix1 {
                    continue;
                }
                let coord = TileCoord::new(tx, ty);
                let copy_w = (ix1 - ix0) as usize;
                let full_tile = ix0 == tile_x0
                    && iy0 == tile_y0
                    && ix1 == tile_x0 + TILE_SIZE_I32
                    && iy1 == tile_y0 + TILE_SIZE_I32;

                let mut buf = if full_tile {
                    vec![default_v; BYTES_8BIT]
                } else if let Some(existing) = self.mask_tiles.get(&coord) {
                    existing.materialize_raw(scratch)?
                } else {
                    vec![default_v; BYTES_8BIT]
                };

                for y in iy0..iy1 {
                    let sy = (y - y0) as usize;
                    let sx = (ix0 - x0) as usize;
                    let dy = (y - tile_y0) as usize;
                    let dx = (ix0 - tile_x0) as usize;
                    let src_off = sy * src_w + sx;
                    let dst_off = dy * TILE_SIZE + dx;
                    buf[dst_off..dst_off + copy_w]
                        .copy_from_slice(&mask8[src_off..src_off + copy_w]);
                }

                if buf.iter().all(|&b| b == default_v) {
                    self.mask_tiles.remove(&coord);
                } else {
                    self.mask_tiles.insert(
                        coord,
                        Arc::new(TileData::from_raw_auto_compact(
                            TileFormat::Grayscale8Bit,
                            TileKind::Mask,
                            buf,
                        )),
                    );
                }
                touched.push(coord);
            }
        }

        if !touched.is_empty() {
            self.bump_mask_version();
            self.bump_version();
        }
        Ok(touched)
    }

    /// Reads an 8-bit grayscale mask rectangle out of sparse `mask_tiles`.
    pub fn read_mask8_rect(
        &self,
        rect: RectI32,
        scratch: Option<&dyn ScratchBackend>,
    ) -> Result<Vec<u8>, String> {
        let total = (rect.width as usize)
            .checked_mul(rect.height as usize)
            .ok_or_else(|| "read_mask8_rect dimensions overflow".to_string())?;
        let fill = if self.has_mask {
            self.mask_default_value
        } else {
            255
        };
        let mut out = vec![fill; total];
        if !self.has_mask || rect.is_empty() || self.mask_tiles.is_empty() {
            return Ok(out);
        }

        let x0 = rect.x;
        let y0 = rect.y;
        let x1 = rect.right();
        let y1 = rect.bottom();
        let min_tx = pixel_to_tile_coord(x0, 0);
        let min_ty = pixel_to_tile_coord(y0, 0);
        let max_tx = pixel_to_tile_coord(x1 - 1, 0);
        let max_ty = pixel_to_tile_coord(y1 - 1, 0);
        let dst_w = rect.width as usize;

        for ty in min_ty..=max_ty {
            let tile_y0 = ty * TILE_SIZE_I32;
            let iy0 = y0.max(tile_y0);
            let iy1 = y1.min(tile_y0 + TILE_SIZE_I32);
            if iy0 >= iy1 {
                continue;
            }
            for tx in min_tx..=max_tx {
                let Some(tile) = self.mask_tiles.get(&TileCoord::new(tx, ty)) else {
                    continue;
                };
                let tile_x0 = tx * TILE_SIZE_I32;
                let ix0 = x0.max(tile_x0);
                let ix1 = x1.min(tile_x0 + TILE_SIZE_I32);
                if ix0 >= ix1 {
                    continue;
                }
                let copy_w = (ix1 - ix0) as usize;
                let raw = tile.materialize_raw(scratch)?;
                for y in iy0..iy1 {
                    let sy = (y - tile_y0) as usize;
                    let sx = (ix0 - tile_x0) as usize;
                    let dy = (y - y0) as usize;
                    let dx = (ix0 - x0) as usize;
                    out[dy * dst_w + dx..dy * dst_w + dx + copy_w]
                        .copy_from_slice(&raw[sy * TILE_SIZE + sx..sy * TILE_SIZE + sx + copy_w]);
                }
            }
        }
        Ok(out)
    }

    /// Captures an O(1) Copy-on-Write snapshot of all tiles in `kind` (just clones `Arc` pointers).
    pub fn snapshot_all_cow(&self, kind: TileKind) -> HashMap<TileCoord, Arc<TileData>> {
        self.tile_map(kind).clone()
    }

    /// Captures an O(1) Copy-on-Write snapshot of tiles intersecting `rect`.
    pub fn snapshot_rect_cow(
        &self,
        kind: TileKind,
        rect: RectI32,
    ) -> HashMap<TileCoord, Option<Arc<TileData>>> {
        let mut snap = HashMap::new();
        if rect.is_empty() {
            return snap;
        }
        let map = self.tile_map(kind);
        let min_tx = pixel_to_tile_coord(rect.x, 0);
        let min_ty = pixel_to_tile_coord(rect.y, 0);
        let max_tx = pixel_to_tile_coord(rect.right() - 1, 0);
        let max_ty = pixel_to_tile_coord(rect.bottom() - 1, 0);
        for ty in min_ty..=max_ty {
            for tx in min_tx..=max_tx {
                let c = TileCoord::new(tx, ty);
                snap.insert(c, map.get(&c).cloned());
            }
        }
        snap
    }

    /// Computes minimal Copy-on-Write deltas from a full `snapshot_all_cow`.
    /// Untouched tiles are skipped in O(1) via `Arc::ptr_eq`!
    pub fn diff_from_full_snapshot(
        &self,
        layer_id: &str,
        kind: TileKind,
        before_snap: &HashMap<TileCoord, Arc<TileData>>,
    ) -> Vec<CowTileDelta> {
        let current = self.tile_map(kind);
        let mut all_coords: HashSet<TileCoord> = before_snap.keys().copied().collect();
        all_coords.extend(current.keys().copied());

        let mut deltas = Vec::new();
        for coord in all_coords {
            let before = before_snap.get(&coord);
            let after = current.get(&coord);
            let unchanged = match (before, after) {
                (None, None) => true,
                (Some(a), Some(b)) => Arc::ptr_eq(a, b),
                _ => false,
            };
            if !unchanged {
                deltas.push(CowTileDelta {
                    layer_id: layer_id.to_string(),
                    kind,
                    coord,
                    before: before.cloned(),
                    after: after.cloned(),
                    remote_epoch: self.remote_epochs.get(&coord).copied().unwrap_or(0),
                });
            }
        }
        deltas
    }

    /// Applies a single CoW tile delta (`undo = true` restores `before`, `undo = false` restores `after`).
    pub fn apply_delta(&mut self, delta: &CowTileDelta, undo: bool) {
        let target = if undo { &delta.before } else { &delta.after };
        match delta.kind {
            TileKind::Raster => {
                if let Some(tile) = target {
                    self.tiles.insert(delta.coord, Arc::clone(tile));
                } else {
                    self.tiles.remove(&delta.coord);
                }
                self.mark_lod_ancestors_dirty(delta.coord);
            }
            TileKind::Mask => {
                if let Some(tile) = target {
                    self.has_mask = true;
                    self.mask_tiles.insert(delta.coord, Arc::clone(tile));
                } else {
                    self.mask_tiles.remove(&delta.coord);
                }
                self.bump_mask_version();
            }
            TileKind::ImpastoHeight => {
                if let Some(tile) = target {
                    self.impasto_tiles.insert(delta.coord, Arc::clone(tile));
                } else {
                    self.impasto_tiles.remove(&delta.coord);
                }
            }
        }
        self.bump_version();
    }

    /// Converts all populated raster tiles in this layer to `target_format`.
    pub fn convert_format(
        &mut self,
        target_format: TileFormat,
        mono_threshold: u8,
        dither: bool,
        scratch: Option<&dyn ScratchBackend>,
    ) -> Result<(), String> {
        if self.format == target_format {
            return Ok(());
        }
        let coords: Vec<TileCoord> = self.tiles.keys().copied().collect();
        for coord in coords {
            let Some(tile) = self.tiles.get(&coord) else {
                continue;
            };
            let converted = tile.to_format_raw(target_format, mono_threshold, dither, scratch)?;
            if is_raw_empty(target_format, &converted) {
                self.tiles.remove(&coord);
            } else {
                self.tiles.insert(
                    coord,
                    Arc::new(TileData::from_raw_auto_compact(
                        target_format,
                        TileKind::Raster,
                        converted,
                    )),
                );
            }
            self.mark_lod_ancestors_dirty(coord);
        }
        self.format = target_format;
        self.bump_version();
        Ok(())
    }

    /// Resizes or crops this layer's raster (and optional mask) tiles directly without
    /// duplicating unaffected storage, supporting both anchor offset shift/crop and bilinear scaling.
    #[allow(clippy::too_many_arguments)]
    pub fn resize_and_crop(
        &mut self,
        old_w: u32,
        old_h: u32,
        new_w: u32,
        new_h: u32,
        offset_x: i32,
        offset_y: i32,
        scale_content: bool,
        bg_fill: Option<[u8; 4]>,
        scratch: Option<&dyn ScratchBackend>,
    ) -> Result<(), String> {
        let old_raster = self.read_rgba8_rect(RectI32::new(0, 0, old_w, old_h), false, scratch)?;
        let old_mask = if self.has_mask {
            Some(self.read_mask8_rect(RectI32::new(0, 0, old_w, old_h), scratch)?)
        } else {
            None
        };

        self.clear_raster();
        if let Some(bg) = bg_fill {
            if bg[3] > 0 {
                self.fill_solid_layer(new_w, new_h, bg);
            }
        }

        if new_w > 0 && new_h > 0 && old_w > 0 && old_h > 0 {
            let new_rgba = if scale_content {
                bilinear_scale_rgba8(&old_raster, old_w, old_h, new_w, new_h)
            } else {
                shift_and_crop_rgba8(&old_raster, old_w, old_h, new_w, new_h, offset_x, offset_y, bg_fill)
            };
            self.write_rgba8_rect(&new_rgba, RectI32::new(0, 0, new_w, new_h), 128, scratch)?;

            if let Some(mask_bytes) = old_mask {
                self.mask_tiles.clear();
                let new_mask = if scale_content {
                    bilinear_scale_u8(&mask_bytes, old_w, old_h, new_w, new_h)
                } else {
                    shift_and_crop_u8(
                        &mask_bytes,
                        old_w,
                        old_h,
                        new_w,
                        new_h,
                        offset_x,
                        offset_y,
                        self.mask_default_value,
                    )
                };
                self.write_mask8_rect(&new_mask, RectI32::new(0, 0, new_w, new_h), scratch)?;
            }
        }
        self.bump_version();
        Ok(())
    }

    /// Computes a tight bounding box of non-transparent (or non-white for background) pixels.
    pub fn content_bounds(
        &self,
        doc_w: u32,
        doc_h: u32,
        is_background: bool,
        scratch: Option<&dyn ScratchBackend>,
    ) -> Option<RectI32> {
        if self.tiles.is_empty() || doc_w == 0 || doc_h == 0 {
            return None;
        }
        let mut min_x = doc_w as i32;
        let mut min_y = doc_h as i32;
        let mut max_x = -1i32;
        let mut max_y = -1i32;

        for (&coord, tile) in &self.tiles {
            if is_background && tile.solid_rgba8() == Some([255, 255, 255, 255]) {
                continue;
            }
            let tile_x0 = coord.tx * TILE_SIZE_I32;
            let tile_y0 = coord.ty * TILE_SIZE_I32;
            if tile_x0 >= doc_w as i32
                || tile_y0 >= doc_h as i32
                || tile_x0 + TILE_SIZE_I32 <= 0
                || tile_y0 + TILE_SIZE_I32 <= 0
            {
                continue;
            }
            let start_lx = (-tile_x0).max(0) as usize;
            let start_ly = (-tile_y0).max(0) as usize;
            let end_lx = (doc_w as i32 - tile_x0).min(TILE_SIZE_I32) as usize;
            let end_ly = (doc_h as i32 - tile_y0).min(TILE_SIZE_I32) as usize;

            if let TileStorage::SolidColor { rgba8, .. } = tile.storage {
                if rgba8[3] == 0 {
                    continue;
                }
                min_x = min_x.min(tile_x0 + start_lx as i32);
                min_y = min_y.min(tile_y0 + start_ly as i32);
                max_x = max_x.max(tile_x0 + end_lx as i32 - 1);
                max_y = max_y.max(tile_y0 + end_ly as i32 - 1);
                continue;
            }

            let Ok(rgba) = tile.to_rgba8(scratch, false) else {
                continue;
            };
            for ly in start_ly..end_ly {
                let doc_y = tile_y0 + ly as i32;
                for lx in start_lx..end_lx {
                    let off = (ly * TILE_SIZE + lx) * 4;
                    let a = rgba[off + 3];
                    if a == 0 {
                        continue;
                    }
                    if is_background
                        && rgba[off] == 255
                        && rgba[off + 1] == 255
                        && rgba[off + 2] == 255
                    {
                        continue;
                    }
                    let doc_x = tile_x0 + lx as i32;
                    min_x = min_x.min(doc_x);
                    min_y = min_y.min(doc_y);
                    max_x = max_x.max(doc_x);
                    max_y = max_y.max(doc_y);
                }
            }
        }

        if max_x < 0 || max_y < 0 {
            return None;
        }
        Some(RectI32::new(
            min_x,
            min_y,
            (max_x - min_x + 1) as u32,
            (max_y - min_y + 1) as u32,
        ))
    }

    /// Stamps a single pixel on a 1-bit tile (primarily for direct testing and binary ink ops).
    pub fn set_pixel_1bit_cow(
        &mut self,
        x: i32,
        y: i32,
        ink: bool,
        scratch: Option<&dyn ScratchBackend>,
    ) -> Result<(), String> {
        let tx = pixel_to_tile_coord(x, 0);
        let ty = pixel_to_tile_coord(y, 0);
        let coord = TileCoord::new(tx, ty);
        let lx = (x - tx * TILE_SIZE_I32) as usize;
        let ly = (y - ty * TILE_SIZE_I32) as usize;
        let entry = self
            .tiles
            .entry(coord)
            .or_insert_with(|| {
                Arc::new(TileData::from_raw(
                    TileFormat::Monochrome1Bit,
                    TileKind::Raster,
                    vec![0u8; BYTES_1BIT],
                ))
            });
        let td = Arc::make_mut(entry);
        let raw = td.make_raw_mut(scratch)?;
        set_pixel_1bit(raw, lx, ly, ink);
        self.mark_lod_ancestors_dirty(coord);
        self.bump_version();
        Ok(())
    }

    /// Removes tiles that have become completely empty/transparent.
    pub fn prune_empty_tiles(&mut self, scratch: Option<&dyn ScratchBackend>) -> usize {
        let to_remove: Vec<TileCoord> = self
            .tiles
            .iter()
            .filter_map(|(&c, t)| if t.is_empty(scratch) { Some(c) } else { None })
            .collect();
        let count = to_remove.len();
        for c in to_remove {
            self.tiles.remove(&c);
            self.mark_lod_ancestors_dirty(c);
        }
        if count > 0 {
            self.bump_version();
        }
        count
    }

    /// Converts a single tile's RGBA16F GPU readback buffer into `self.format` and stores it
    /// (with dithering if `self.format == Color32Bit` and `dither == true`).
    pub fn commit_gpu_tile_rgba16f(
        &mut self,
        coord: TileCoord,
        rgba16f_bytes: &[u8],
        mono_threshold: u8,
        dither: bool,
    ) {
        debug_assert_eq!(rgba16f_bytes.len(), BYTES_16F);
        if is_raw_empty(TileFormat::Rgba16Float, rgba16f_bytes) {
            self.tiles.remove(&coord);
        } else {
            let stored = match self.format {
                TileFormat::Rgba16Float => rgba16f_bytes.to_vec(),
                TileFormat::Color32Bit => {
                    let mut out = vec![0u8; BYTES_32BIT];
                    if dither {
                        rgba16f_to_rgba8_dithered(rgba16f_bytes, &mut out);
                    } else {
                        super::format::rgba16f_to_rgba8_lossless(rgba16f_bytes, &mut out);
                    }
                    out
                }
                other => convert_tile_bytes(
                    rgba16f_bytes,
                    TileFormat::Rgba16Float,
                    other,
                    mono_threshold,
                    dither,
                ),
            };
            if is_raw_empty(self.format, &stored) {
                self.tiles.remove(&coord);
            } else {
                self.tiles.insert(
                    coord,
                    Arc::new(TileData::from_raw_auto_compact(
                        self.format,
                        TileKind::Raster,
                        stored,
                    )),
                );
            }
        }
        self.mark_lod_ancestors_dirty(coord);
        self.bump_version();
    }
}

#[allow(clippy::too_many_arguments)]
fn shift_and_crop_rgba8(
    src: &[u8],
    old_w: u32,
    old_h: u32,
    new_w: u32,
    new_h: u32,
    offset_x: i32,
    offset_y: i32,
    bg_fill: Option<[u8; 4]>,
) -> Vec<u8> {
    let mut dst = vec![0u8; (new_w as usize) * (new_h as usize) * 4];
    if let Some(bg) = bg_fill {
        if bg[3] > 0 {
            for px in dst.chunks_exact_mut(4) {
                px.copy_from_slice(&bg);
            }
        }
    }
    let sx0 = (-offset_x).max(0) as usize;
    let sy0 = (-offset_y).max(0) as usize;
    let sx1 = (new_w as i32 - offset_x).min(old_w as i32).max(0) as usize;
    let sy1 = (new_h as i32 - offset_y).min(old_h as i32).max(0) as usize;
    if sx0 >= sx1 || sy0 >= sy1 {
        return dst;
    }
    let copy_w = sx1 - sx0;
    for sy in sy0..sy1 {
        let dy = (sy as i32 + offset_y) as usize;
        let dx = (sx0 as i32 + offset_x) as usize;
        let src_off = (sy * old_w as usize + sx0) * 4;
        let dst_off = (dy * new_w as usize + dx) * 4;
        dst[dst_off..dst_off + copy_w * 4]
            .copy_from_slice(&src[src_off..src_off + copy_w * 4]);
    }
    dst
}

#[allow(clippy::too_many_arguments)]
fn shift_and_crop_u8(
    src: &[u8],
    old_w: u32,
    old_h: u32,
    new_w: u32,
    new_h: u32,
    offset_x: i32,
    offset_y: i32,
    default_v: u8,
) -> Vec<u8> {
    let mut dst = vec![default_v; (new_w as usize) * (new_h as usize)];
    let sx0 = (-offset_x).max(0) as usize;
    let sy0 = (-offset_y).max(0) as usize;
    let sx1 = (new_w as i32 - offset_x).min(old_w as i32).max(0) as usize;
    let sy1 = (new_h as i32 - offset_y).min(old_h as i32).max(0) as usize;
    if sx0 >= sx1 || sy0 >= sy1 {
        return dst;
    }
    let copy_w = sx1 - sx0;
    for sy in sy0..sy1 {
        let dy = (sy as i32 + offset_y) as usize;
        let dx = (sx0 as i32 + offset_x) as usize;
        let src_off = sy * old_w as usize + sx0;
        let dst_off = dy * new_w as usize + dx;
        dst[dst_off..dst_off + copy_w].copy_from_slice(&src[src_off..src_off + copy_w]);
    }
    dst
}

fn bilinear_scale_rgba8(src: &[u8], old_w: u32, old_h: u32, new_w: u32, new_h: u32) -> Vec<u8> {
    let mut dst = vec![0u8; (new_w as usize) * (new_h as usize) * 4];
    let ow = old_w as f32;
    let oh = old_h as f32;
    let nw = new_w as f32;
    let nh = new_h as f32;
    let max_x = (old_w - 1) as usize;
    let max_y = (old_h - 1) as usize;

    for dy in 0..new_h as usize {
        let sy = ((dy as f32 + 0.5) * (oh / nh) - 0.5).clamp(0.0, max_y as f32);
        let y0 = sy.floor() as usize;
        let y1 = (y0 + 1).min(max_y);
        let fy = sy - y0 as f32;
        for dx in 0..new_w as usize {
            let sx = ((dx as f32 + 0.5) * (ow / nw) - 0.5).clamp(0.0, max_x as f32);
            let x0 = sx.floor() as usize;
            let x1 = (x0 + 1).min(max_x);
            let fx = sx - x0 as f32;

            let i00 = (y0 * old_w as usize + x0) * 4;
            let i10 = (y0 * old_w as usize + x1) * 4;
            let i01 = (y1 * old_w as usize + x0) * 4;
            let i11 = (y1 * old_w as usize + x1) * 4;

            let w00 = (1.0 - fx) * (1.0 - fy);
            let w10 = fx * (1.0 - fy);
            let w01 = (1.0 - fx) * fy;
            let w11 = fx * fy;

            // Premultiplied alpha bilinear interpolation (prevents dark fringing)
            let a00 = src[i00 + 3] as f32 * w00;
            let a10 = src[i10 + 3] as f32 * w10;
            let a01 = src[i01 + 3] as f32 * w01;
            let a11 = src[i11 + 3] as f32 * w11;
            let sum_a = a00 + a10 + a01 + a11;

            let dst_off = (dy * new_w as usize + dx) * 4;
            if sum_a <= 0.5 {
                dst[dst_off..dst_off + 4].fill(0);
            } else {
                for c in 0..3 {
                    let premul = src[i00 + c] as f32 * a00
                        + src[i10 + c] as f32 * a10
                        + src[i01 + c] as f32 * a01
                        + src[i11 + c] as f32 * a11;
                    dst[dst_off + c] = (premul / sum_a + 0.5).clamp(0.0, 255.0) as u8;
                }
                dst[dst_off + 3] = (sum_a + 0.5).clamp(0.0, 255.0) as u8;
            }
        }
    }
    dst
}

fn bilinear_scale_u8(src: &[u8], old_w: u32, old_h: u32, new_w: u32, new_h: u32) -> Vec<u8> {
    let mut dst = vec![0u8; (new_w as usize) * (new_h as usize)];
    let ow = old_w as f32;
    let oh = old_h as f32;
    let nw = new_w as f32;
    let nh = new_h as f32;
    let max_x = (old_w - 1) as usize;
    let max_y = (old_h - 1) as usize;

    for dy in 0..new_h as usize {
        let sy = ((dy as f32 + 0.5) * (oh / nh) - 0.5).clamp(0.0, max_y as f32);
        let y0 = sy.floor() as usize;
        let y1 = (y0 + 1).min(max_y);
        let fy = sy - y0 as f32;
        for dx in 0..new_w as usize {
            let sx = ((dx as f32 + 0.5) * (ow / nw) - 0.5).clamp(0.0, max_x as f32);
            let x0 = sx.floor() as usize;
            let x1 = (x0 + 1).min(max_x);
            let fx = sx - x0 as f32;

            let v00 = src[y0 * old_w as usize + x0] as f32;
            let v10 = src[y0 * old_w as usize + x1] as f32;
            let v01 = src[y1 * old_w as usize + x0] as f32;
            let v11 = src[y1 * old_w as usize + x1] as f32;

            let v = (v00 * (1.0 - fx) + v10 * fx) * (1.0 - fy)
                + (v01 * (1.0 - fx) + v11 * fx) * fy;
            dst[dy * new_w as usize + dx] = (v + 0.5).clamp(0.0, 255.0) as u8;
        }
    }
    dst
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rect_i32_right_and_bottom_saturate_without_overflow() {
        let near_max = RectI32::new(i32::MAX - 5, i32::MAX - 10, 100, 200);
        assert_eq!(near_max.right(), i32::MAX);
        assert_eq!(near_max.bottom(), i32::MAX);

        let huge_dims = RectI32::new(0, 0, u32::MAX, u32::MAX);
        assert_eq!(huge_dims.right(), i32::MAX);
        assert_eq!(huge_dims.bottom(), i32::MAX);

        let neg_origin_huge = RectI32::new(-100, -50, u32::MAX, u32::MAX);
        assert_eq!(neg_origin_huge.right(), i32::MAX);
        assert_eq!(neg_origin_huge.bottom(), i32::MAX);

        let normal = RectI32::new(-10, 20, 30, 40);
        assert_eq!(normal.right(), 20);
        assert_eq!(normal.bottom(), 60);

        let u = normal.union(near_max);
        assert_eq!(u.x, -10);
        assert_eq!(u.y, 20);
        assert_eq!(u.right(), i32::MAX);
        assert_eq!(u.bottom(), i32::MAX);
    }
}