Skip to content

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

32.3 KB
Raw Blame
//! Sparse `256×256` `R8Unorm` selection mask grid (`SparseSelectionMask`),
//! floating selection buffer, and in-process selection clipboard.
//!
//! Never allocates a full-document `Uint8Array` in WebView2: uniform regions (e.g.
//! `Select All` or `Invert` on an 8K canvas) use zero-allocation `TileStorage::SolidColor`
//! or `default_value` so memory scales strictly with mutated boundary tiles.

use crate::memory::ScratchBackend;
use crate::tiles::{
    allocate_tile_version, pixel_to_tile_coord, RectI32, TileCoord, TileData, TileFormat,
    TileKind, TileStorage, BYTES_8BIT, TILE_SIZE, TILE_SIZE_I32,
};
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;

/// Boolean combine mode when creating/updating a selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum SelectionCombineMode {
    #[default]
    Replace,
    Add,
    Subtract,
    Intersect,
}

/// Layer reference mode for Magic Wand selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum WandReferMode {
    #[default]
    Active,
    All,
    Reference,
}

/// Compact JSON metadata snapshot sent to React (ZERO full-resolution mask buffers!).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SelectionMetaSnapshot {
    pub active: bool,
    pub bounds: RectI32,
    pub version: u64,
    pub has_floating: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub floating_x: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub floating_y: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub floating_width: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub floating_height: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub floating_layer_id: Option<String>,
}

impl SelectionMetaSnapshot {
    pub fn empty() -> Self {
        Self {
            active: false,
            bounds: RectI32::empty(),
            version: 0,
            has_floating: false,
            floating_x: None,
            floating_y: None,
            floating_width: None,
            floating_height: None,
            floating_layer_id: None,
        }
    }
}

/// Lifted pixels currently floating over a layer during selection move (rendered live on GPU).
#[derive(Debug, Clone)]
pub struct FloatingSelection {
    pub layer_id: String,
    pub orig_x: i32,
    pub orig_y: i32,
    pub x: i32,
    pub y: i32,
    pub width: u32,
    pub height: u32,
    /// Straight RGBA8 pixels (`width * height * 4`), already masked by the selection alpha.
    pub rgba: Vec<u8>,
    /// CoW snapshot of the source layer's tiles captured BEFORE lifting pixels.
    pub before_tiles: HashMap<TileCoord, Option<Arc<TileData>>>,
    pub version: u64,
}

/// In-process native selection clipboard shared across open tabs in `DocumentManager`.
#[derive(Debug, Clone)]
pub struct SelectionClipboard {
    pub x: i32,
    pub y: i32,
    pub width: u32,
    pub height: u32,
    pub rgba: Vec<u8>,
    pub source_layer_name: String,
}

/// Sparse `256×256` `R8Unorm` selection mask stored directly on a Rust [`Document`].
#[derive(Debug, Clone)]
pub struct SparseSelectionMask {
    pub doc_width: u32,
    pub doc_height: u32,
    /// Default selection value (`0` or `255`) for unallocated tiles inside `[0..doc_width, 0..doc_height]`.
    pub default_value: u8,
    /// Sparse 8-bit tiles (`TileFormat::Grayscale8Bit`, `TileKind::Mask`).
    /// Tiles uniform at `default_value` are pruned automatically.
    pub tiles: HashMap<TileCoord, Arc<TileData>>,
    /// Tight document-space bounding box of pixels with alpha > 0.
    pub bounds: RectI32,
    /// Monotonic version counter bumped on every selection mutation.
    pub version: u64,
    /// Optional lifted floating selection pixels (rendered on GPU, zero DOM canvas).
    pub floating: Option<FloatingSelection>,
}

impl SparseSelectionMask {
    pub fn new_empty(doc_width: u32, doc_height: u32) -> Self {
        Self {
            doc_width: doc_width.max(1),
            doc_height: doc_height.max(1),
            default_value: 0,
            tiles: HashMap::new(),
            bounds: RectI32::empty(),
            version: allocate_tile_version(),
            floating: None,
        }
    }

    pub fn new_all(doc_width: u32, doc_height: u32) -> Self {
        let w = doc_width.max(1);
        let h = doc_height.max(1);
        Self {
            doc_width: w,
            doc_height: h,
            default_value: 255,
            tiles: HashMap::new(),
            bounds: RectI32::new(0, 0, w, h),
            version: allocate_tile_version(),
            floating: None,
        }
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.bounds.is_empty() && self.floating.is_none()
    }

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

    pub fn snapshot_meta(&self) -> SelectionMetaSnapshot {
        if self.is_empty() {
            return SelectionMetaSnapshot::empty();
        }
        if let Some(ref fl) = self.floating {
            SelectionMetaSnapshot {
                active: true,
                bounds: RectI32::new(fl.x, fl.y, fl.width, fl.height),
                version: self.version,
                has_floating: true,
                floating_x: Some(fl.x),
                floating_y: Some(fl.y),
                floating_width: Some(fl.width),
                floating_height: Some(fl.height),
                floating_layer_id: Some(fl.layer_id.clone()),
            }
        } else {
            SelectionMetaSnapshot {
                active: true,
                bounds: self.bounds,
                version: self.version,
                has_floating: false,
                floating_x: None,
                floating_y: None,
                floating_width: None,
                floating_height: None,
                floating_layer_id: None,
            }
        }
    }

    /// Samples a single pixel's selection coverage (`0..=255`) in O(1).
    #[inline]
    pub fn get_alpha(&self, x: i32, y: i32) -> u8 {
        if x < 0 || y < 0 || x >= self.doc_width as i32 || y >= self.doc_height as i32 {
            return 0;
        }
        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 self.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.storage {
            TileStorage::Raw(raw) => raw[ly * TILE_SIZE + lx],
            _ => tile
                .materialize_raw(None)
                .map(|r| r[ly * TILE_SIZE + lx])
                .unwrap_or(self.default_value),
        }
    }

    /// Materializes a single tile `(tx, ty)` as a 65,536-byte `Vec<u8>`, clamping pixels
    /// outside `[0..doc_width, 0..doc_height]` to 0.
    pub fn materialize_tile(&self, coord: TileCoord) -> Vec<u8> {
        let mut out = if let Some(tile) = self.tiles.get(&coord) {
            tile.materialize_raw(None)
                .unwrap_or_else(|_| vec![self.default_value; BYTES_8BIT])
        } else {
            vec![self.default_value; BYTES_8BIT]
        };

        // Zero out any padding beyond document boundaries on edge tiles
        let tx0 = coord.tx * TILE_SIZE_I32;
        let ty0 = coord.ty * TILE_SIZE_I32;
        let dw = self.doc_width as i32;
        let dh = self.doc_height as i32;
        if tx0 < 0 || ty0 < 0 || tx0 + TILE_SIZE_I32 > dw || ty0 + TILE_SIZE_I32 > dh {
            for ly in 0..TILE_SIZE {
                let gy = ty0 + ly as i32;
                let row = ly * TILE_SIZE;
                if gy < 0 || gy >= dh {
                    out[row..row + TILE_SIZE].fill(0);
                } else {
                    for lx in 0..TILE_SIZE {
                        let gx = tx0 + lx as i32;
                        if gx < 0 || gx >= dw {
                            out[row + lx] = 0;
                        }
                    }
                }
            }
        }
        out
    }

    /// Stores a raw `256×256` 8-bit tile, automatically pruning uniform `default_value` tiles
    /// or compacting uniform solid tiles to zero-allocation `TileStorage::SolidColor`.
    pub fn set_tile_raw(&mut self, coord: TileCoord, mut raw: Vec<u8>) {
        debug_assert_eq!(raw.len(), BYTES_8BIT);
        // Clamp out-of-document pixels to 0
        let tx0 = coord.tx * TILE_SIZE_I32;
        let ty0 = coord.ty * TILE_SIZE_I32;
        let dw = self.doc_width as i32;
        let dh = self.doc_height as i32;
        if tx0 < 0 || ty0 < 0 || tx0 + TILE_SIZE_I32 > dw || ty0 + TILE_SIZE_I32 > dh {
            for ly in 0..TILE_SIZE {
                let gy = ty0 + ly as i32;
                let row = ly * TILE_SIZE;
                if gy < 0 || gy >= dh {
                    raw[row..row + TILE_SIZE].fill(0);
                } else {
                    for lx in 0..TILE_SIZE {
                        let gx = tx0 + lx as i32;
                        if gx < 0 || gx >= dw {
                            raw[row + lx] = 0;
                        }
                    }
                }
            }
        }
        let first = raw[0];
        let uniform = raw.iter().all(|&b| b == first);
        if uniform && first == self.default_value {
            self.tiles.remove(&coord);
        } else if uniform {
            self.tiles.insert(
                coord,
                Arc::new(TileData::new_solid(
                    TileFormat::Grayscale8Bit,
                    TileKind::Mask,
                    [first, first, first, first],
                )),
            );
        } else {
            self.tiles.insert(
                coord,
                Arc::new(TileData::from_raw_auto_compact(
                    TileFormat::Grayscale8Bit,
                    TileKind::Mask,
                    raw,
                )),
            );
        }
    }

    /// Reads an arbitrary document-space rectangle of the selection mask as 1 byte/pixel.
    pub fn read_rect(&self, rect: RectI32) -> Vec<u8> {
        let w = rect.width as usize;
        let h = rect.height as usize;
        let mut out = vec![0u8; w * h];
        if rect.is_empty() {
            return out;
        }
        let doc_rect = RectI32::new(0, 0, self.doc_width, self.doc_height);
        let clipped = rect.intersect(doc_rect);
        if clipped.is_empty() {
            return out;
        }

        let min_tx = pixel_to_tile_coord(clipped.x, 0);
        let min_ty = pixel_to_tile_coord(clipped.y, 0);
        let max_tx = pixel_to_tile_coord(clipped.right() - 1, 0);
        let max_ty = pixel_to_tile_coord(clipped.bottom() - 1, 0);

        for ty in min_ty..=max_ty {
            let tile_y0 = ty * TILE_SIZE_I32;
            let iy0 = clipped.y.max(tile_y0);
            let iy1 = clipped.bottom().min(tile_y0 + TILE_SIZE_I32);
            for tx in min_tx..=max_tx {
                let tile_x0 = tx * TILE_SIZE_I32;
                let ix0 = clipped.x.max(tile_x0);
                let ix1 = clipped.right().min(tile_x0 + TILE_SIZE_I32);
                let copy_w = (ix1 - ix0) as usize;
                let coord = TileCoord::new(tx, ty);
                if let Some(tile) = self.tiles.get(&coord) {
                    if let TileStorage::SolidColor { rgba8, .. } = tile.storage {
                        let v = rgba8[0];
                        if v != 0 {
                            for y in iy0..iy1 {
                                let dst_off = ((y - rect.y) as usize) * w + ((ix0 - rect.x) as usize);
                                out[dst_off..dst_off + copy_w].fill(v);
                            }
                        }
                    } else if let Ok(raw) = tile.materialize_raw(None) {
                        for y in iy0..iy1 {
                            let sy = (y - tile_y0) as usize;
                            let sx = (ix0 - tile_x0) as usize;
                            let dst_off = ((y - rect.y) as usize) * w + ((ix0 - rect.x) as usize);
                            let src_off = sy * TILE_SIZE + sx;
                            out[dst_off..dst_off + copy_w]
                                .copy_from_slice(&raw[src_off..src_off + copy_w]);
                        }
                    }
                } else if self.default_value != 0 {
                    for y in iy0..iy1 {
                        let dst_off = ((y - rect.y) as usize) * w + ((ix0 - rect.x) as usize);
                        out[dst_off..dst_off + copy_w].fill(self.default_value);
                    }
                }
            }
        }
        out
    }

    /// Writes a rectangular 8-bit mask buffer into the sparse selection grid using `mode`.
    pub fn combine_rect(&mut self, rect: RectI32, incoming: &[u8], mode: SelectionCombineMode) {
        let doc_rect = RectI32::new(0, 0, self.doc_width, self.doc_height);
        if mode == SelectionCombineMode::Replace {
            self.default_value = 0;
            self.tiles.clear();
        }
        if mode == SelectionCombineMode::Intersect {
            // Zero out any existing tiles outside `rect`
            let clipped = rect.intersect(doc_rect);
            if clipped.is_empty() {
                self.default_value = 0;
                self.tiles.clear();
                self.bounds = RectI32::empty();
                self.bump_version();
                return;
            }
            let min_tx = pixel_to_tile_coord(clipped.x, 0);
            let min_ty = pixel_to_tile_coord(clipped.y, 0);
            let max_tx = pixel_to_tile_coord(clipped.right() - 1, 0);
            let max_ty = pixel_to_tile_coord(clipped.bottom() - 1, 0);
            let old_default = self.default_value;
            self.default_value = 0;
            // Remove tiles completely outside rect
            self.tiles.retain(|c, _| {
                c.tx >= min_tx && c.tx <= max_tx && c.ty >= min_ty && c.ty <= max_ty
            });
            // Materialize & intersect each tile inside rect
            let rw = rect.width as usize;
            for ty in min_ty..=max_ty {
                let tile_y0 = ty * TILE_SIZE_I32;
                for tx in min_tx..=max_tx {
                    let tile_x0 = tx * TILE_SIZE_I32;
                    let coord = TileCoord::new(tx, ty);
                    let mut existing = if let Some(t) = self.tiles.get(&coord) {
                        t.materialize_raw(None)
                            .unwrap_or_else(|_| vec![old_default; BYTES_8BIT])
                    } else {
                        vec![old_default; BYTES_8BIT]
                    };
                    for ly in 0..TILE_SIZE {
                        let gy = tile_y0 + ly as i32;
                        let row = ly * TILE_SIZE;
                        if gy < clipped.y || gy >= clipped.bottom() {
                            existing[row..row + TILE_SIZE].fill(0);
                            continue;
                        }
                        let sy = (gy - rect.y) as usize;
                        for lx in 0..TILE_SIZE {
                            let gx = tile_x0 + lx as i32;
                            if gx < clipped.x || gx >= clipped.right() {
                                existing[row + lx] = 0;
                            } else {
                                let sx = (gx - rect.x) as usize;
                                let inc = incoming[sy * rw + sx];
                                existing[row + lx] = existing[row + lx].min(inc);
                            }
                        }
                    }
                    self.set_tile_raw(coord, existing);
                }
            }
            self.recompute_bounds();
            self.bump_version();
            return;
        }

        let clipped = rect.intersect(doc_rect);
        if clipped.is_empty() {
            self.recompute_bounds();
            self.bump_version();
            return;
        }
        let min_tx = pixel_to_tile_coord(clipped.x, 0);
        let min_ty = pixel_to_tile_coord(clipped.y, 0);
        let max_tx = pixel_to_tile_coord(clipped.right() - 1, 0);
        let max_ty = pixel_to_tile_coord(clipped.bottom() - 1, 0);
        let rw = rect.width as usize;

        for ty in min_ty..=max_ty {
            let tile_y0 = ty * TILE_SIZE_I32;
            let iy0 = clipped.y.max(tile_y0);
            let iy1 = clipped.bottom().min(tile_y0 + TILE_SIZE_I32);
            for tx in min_tx..=max_tx {
                let tile_x0 = tx * TILE_SIZE_I32;
                let ix0 = clipped.x.max(tile_x0);
                let ix1 = clipped.right().min(tile_x0 + TILE_SIZE_I32);
                let coord = TileCoord::new(tx, ty);
                let mut cur = self.materialize_tile(coord);
                for gy in iy0..iy1 {
                    let sy = (gy - rect.y) as usize;
                    let ly = (gy - tile_y0) as usize;
                    let row = ly * TILE_SIZE;
                    for gx in ix0..ix1 {
                        let sx = (gx - rect.x) as usize;
                        let lx = (gx - tile_x0) as usize;
                        let inc = incoming[sy * rw + sx];
                        let dst = &mut cur[row + lx];
                        match mode {
                            SelectionCombineMode::Replace => *dst = inc,
                            SelectionCombineMode::Add => *dst = (*dst).max(inc),
                            SelectionCombineMode::Subtract => *dst = dst.saturating_sub(inc),
                            SelectionCombineMode::Intersect => *dst = (*dst).min(inc),
                        }
                    }
                }
                self.set_tile_raw(coord, cur);
            }
        }
        self.recompute_bounds();
        self.bump_version();
    }

    /// Recomputes the exact tight bounding box of selected pixels (`alpha > 0`).
    pub fn recompute_bounds(&mut self) {
        let dw = self.doc_width as i32;
        let dh = self.doc_height as i32;
        if self.default_value > 0 && self.tiles.is_empty() {
            self.bounds = RectI32::new(0, 0, self.doc_width, self.doc_height);
            return;
        }

        let max_tx = pixel_to_tile_coord(dw - 1, 0);
        let max_ty = pixel_to_tile_coord(dh - 1, 0);

        let mut min_x = dw;
        let mut min_y = dh;
        let mut max_x = -1i32;
        let mut max_y = -1i32;

        if self.default_value > 0 {
            // Check every tile coordinate in document bounds (unallocated tiles are solid 255!)
            for ty in 0..=max_ty {
                let y0 = ty * TILE_SIZE_I32;
                let y1 = (y0 + TILE_SIZE_I32).min(dh);
                for tx in 0..=max_tx {
                    let x0 = tx * TILE_SIZE_I32;
                    let x1 = (x0 + TILE_SIZE_I32).min(dw);
                    let coord = TileCoord::new(tx, ty);
                    match self.tiles.get(&coord) {
                        None => {
                            min_x = min_x.min(x0);
                            min_y = min_y.min(y0);
                            max_x = max_x.max(x1 - 1);
                            max_y = max_y.max(y1 - 1);
                        }
                        Some(tile) => {
                            Self::scan_tile_bounds(
                                tile, coord, dw, dh, &mut min_x, &mut min_y, &mut max_x, &mut max_y,
                            );
                        }
                    }
                }
            }
        } else {
            for (&coord, tile) in &self.tiles {
                Self::scan_tile_bounds(
                    tile, coord, dw, dh, &mut min_x, &mut min_y, &mut max_x, &mut max_y,
                );
            }
        }

        if max_x < min_x || max_y < min_y {
            self.bounds = RectI32::empty();
        } else {
            self.bounds = RectI32::new(
                min_x,
                min_y,
                (max_x - min_x + 1) as u32,
                (max_y - min_y + 1) as u32,
            );
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn scan_tile_bounds(
        tile: &TileData,
        coord: TileCoord,
        dw: i32,
        dh: i32,
        min_x: &mut i32,
        min_y: &mut i32,
        max_x: &mut i32,
        max_y: &mut i32,
    ) {
        let x0 = coord.tx * TILE_SIZE_I32;
        let y0 = coord.ty * TILE_SIZE_I32;
        let x1 = (x0 + TILE_SIZE_I32).min(dw);
        let y1 = (y0 + TILE_SIZE_I32).min(dh);
        if x1 <= x0 || y1 <= y0 {
            return;
        }
        if let TileStorage::SolidColor { rgba8, .. } = tile.storage {
            if rgba8[0] > 0 {
                *min_x = (*min_x).min(x0.max(0));
                *min_y = (*min_y).min(y0.max(0));
                *max_x = (*max_x).max(x1 - 1);
                *max_y = (*max_y).max(y1 - 1);
            }
            return;
        }
        let Ok(raw) = tile.materialize_raw(None) else {
            return;
        };
        let lx_start = (0 - x0).max(0) as usize;
        let ly_start = (0 - y0).max(0) as usize;
        let lx_end = (x1 - x0) as usize;
        let ly_end = (y1 - y0) as usize;
        for ly in ly_start..ly_end {
            let row = ly * TILE_SIZE;
            let gy = y0 + ly as i32;
            for lx in lx_start..lx_end {
                if raw[row + lx] > 0 {
                    let gx = x0 + lx as i32;
                    if gx < *min_x {
                        *min_x = gx;
                    }
                    if gx > *max_x {
                        *max_x = gx;
                    }
                    if gy < *min_y {
                        *min_y = gy;
                    }
                    if gy > *max_y {
                        *max_y = gy;
                    }
                }
            }
        }
    }

    /// Inverts the selection mask in O(allocated tiles) — zero full-canvas allocation!
    pub fn invert(&mut self) {
        self.default_value = 255u8.saturating_sub(self.default_value);
        let coords: Vec<TileCoord> = self.tiles.keys().copied().collect();
        for coord in coords {
            let Some(tile) = self.tiles.remove(&coord) else {
                continue;
            };
            if let TileStorage::SolidColor { rgba8, .. } = tile.storage {
                let inv = 255u8.saturating_sub(rgba8[0]);
                if inv != self.default_value {
                    self.tiles.insert(
                        coord,
                        Arc::new(TileData::new_solid(
                            TileFormat::Grayscale8Bit,
                            TileKind::Mask,
                            [inv, inv, inv, inv],
                        )),
                    );
                }
            } else if let Ok(mut raw) = tile.materialize_raw(None) {
                for b in &mut raw {
                    *b = 255u8.saturating_sub(*b);
                }
                self.set_tile_raw(coord, raw);
            }
        }
        self.recompute_bounds();
        self.bump_version();
    }

    /// Expands (`pixels > 0`) or contracts (`pixels < 0`) the selection mask using an exact
    /// Felzenszwalb-Huttenlocher 2D Euclidean Distance Transform (isotropic circular kernel!).
    pub fn expand_or_contract(&mut self, pixels: i32) {
        if pixels == 0 || self.bounds.is_empty() {
            return;
        }
        let expand = pixels > 0;
        let r = pixels.unsigned_abs().clamp(1, 256) as i32;
        let doc_rect = RectI32::new(0, 0, self.doc_width, self.doc_height);
        let pad = r + 2;
        let work_rect = RectI32::new(
            (self.bounds.x - pad).max(0),
            (self.bounds.y - pad).max(0),
            (self.bounds.width as i32 + pad * 2) as u32,
            (self.bounds.height as i32 + pad * 2) as u32,
        )
        .intersect(doc_rect);
        if work_rect.is_empty() {
            return;
        }
        let w = work_rect.width as usize;
        let h = work_rect.height as usize;
        let src = self.read_rect(work_rect);

        // Compute squared EDT to foreground (expand) or background (contract)
        let r2 = (r as f64) * (r as f64);
        let inf = 1e12f64;

        // Pass 1: horizontal 1D EDT per row (parallelized with Rayon)
        let mut temp = vec![inf; w * h];
        temp.par_chunks_exact_mut(w)
            .enumerate()
            .for_each(|(y, out_row)| {
                let s_row = &src[y * w..(y + 1) * w];
                let mut f = vec![inf; w];
                for x in 0..w {
                    let is_seed = if expand { s_row[x] >= 128 } else { s_row[x] < 128 };
                    if is_seed {
                        f[x] = 0.0;
                    }
                }
                let mut v = vec![0i32; w];
                let mut z = vec![0.0f64; w + 1];
                edt_1d(&f, w, out_row, &mut v, &mut z);
            });

        // Pass 2: vertical 1D EDT per column (parallelized over column chunks)
        let mut dist2 = vec![inf; w * h];
        let col_results: Vec<Vec<f64>> = (0..w)
            .into_par_iter()
            .map(|x| {
                let mut f = vec![0.0f64; h];
                for y in 0..h {
                    f[y] = temp[y * w + x];
                }
                let mut d = vec![0.0f64; h];
                let mut v = vec![0i32; h];
                let mut z = vec![0.0f64; h + 1];
                edt_1d(&f, h, &mut d, &mut v, &mut z);
                d
            })
            .collect();
        for (x, col) in col_results.into_iter().enumerate() {
            for y in 0..h {
                dist2[y * w + x] = col[y];
            }
        }

        let mut out = vec![0u8; w * h];
        for i in 0..(w * h) {
            let d2 = dist2[i];
            if expand {
                if d2 <= r2 {
                    out[i] = 255;
                } else {
                    // 1px smooth anti-aliased fringe
                    let d = d2.sqrt();
                    let rf = r as f64;
                    if d < rf + 1.0 {
                        out[i] = ((1.0 - (d - rf)) * 255.0).round().clamp(0.0, 255.0) as u8;
                    }
                }
            } else {
                // Contract: pixels strictly farther than `r` from background remain selected
                if d2 >= r2 {
                    out[i] = 255;
                } else {
                    let d = d2.sqrt();
                    let rf = r as f64;
                    if d > rf - 1.0 {
                        out[i] = ((d - (rf - 1.0)) * 255.0).round().clamp(0.0, 255.0) as u8;
                    }
                }
            }
        }

        self.combine_rect(work_rect, &out, SelectionCombineMode::Replace);
    }

    /// Feathers the selection mask with a separable Gaussian blur of `radius` pixels.
    pub fn feather(&mut self, radius: f32) {
        if radius <= 0.1 || self.bounds.is_empty() {
            return;
        }
        let sigma = (radius.clamp(0.5, 128.0) * 0.5).max(0.4);
        let k_rad = (sigma * 3.0).ceil() as i32;
        let doc_rect = RectI32::new(0, 0, self.doc_width, self.doc_height);
        let work_rect = RectI32::new(
            (self.bounds.x - k_rad - 1).max(0),
            (self.bounds.y - k_rad - 1).max(0),
            (self.bounds.width as i32 + (k_rad + 1) * 2) as u32,
            (self.bounds.height as i32 + (k_rad + 1) * 2) as u32,
        )
        .intersect(doc_rect);
        if work_rect.is_empty() {
            return;
        }
        let w = work_rect.width as usize;
        let h = work_rect.height as usize;
        let src = self.read_rect(work_rect);

        let inv_2s2 = 1.0 / (2.0 * sigma * sigma);
        let mut kernel = Vec::with_capacity((k_rad * 2 + 1) as usize);
        let mut w_sum = 0.0f32;
        for d in -k_rad..=k_rad {
            let kw = (-(d * d) as f32 * inv_2s2).exp();
            kernel.push(kw);
            w_sum += kw;
        }
        for kw in &mut kernel {
            *kw /= w_sum;
        }

        let mut horiz = vec![0.0f32; w * h];
        horiz
            .par_chunks_exact_mut(w)
            .enumerate()
            .for_each(|(y, out_row)| {
                let s_row = &src[y * w..(y + 1) * w];
                for (x, dst_px) in out_row.iter_mut().enumerate().take(w) {
                    let mut acc = 0.0f32;
                    for (ki, &kw) in kernel.iter().enumerate() {
                        let sx = (x as i32 + ki as i32 - k_rad).clamp(0, w as i32 - 1) as usize;
                        acc += s_row[sx] as f32 * kw;
                    }
                    *dst_px = acc;
                }
            });

        let mut out = vec![0u8; w * h];
        out.par_chunks_exact_mut(w)
            .enumerate()
            .for_each(|(y, out_row)| {
                for (x, dst_px) in out_row.iter_mut().enumerate().take(w) {
                    let mut acc = 0.0f32;
                    for (ki, &kw) in kernel.iter().enumerate() {
                        let sy = (y as i32 + ki as i32 - k_rad).clamp(0, h as i32 - 1) as usize;
                        acc += horiz[sy * w + x] * kw;
                    }
                    *dst_px = acc.round().clamp(0.0, 255.0) as u8;
                }
            });

        self.combine_rect(work_rect, &out, SelectionCombineMode::Replace);
    }

    /// Commits GPU-rendered `256×256` RGBA8 select-pen / select-eraser tiles directly onto this
    /// sparse selection mask (`erase = true` subtracts stroke alpha; `false` unions/adds alpha).
    pub fn apply_brush_tiles(&mut self, committed: Vec<(TileCoord, Vec<u8>, u64)>, erase: bool) {
        if committed.is_empty() {
            return;
        }
        let alpha_tiles: Vec<(TileCoord, Vec<u8>)> = committed
            .into_iter()
            .map(|(coord, rgba8, _)| {
                let mut a = vec![0u8; BYTES_8BIT];
                for i in 0..BYTES_8BIT {
                    a[i] = rgba8[i * 4 + 3];
                }
                (coord, a)
            })
            .collect();
        self.apply_alpha_tiles(&alpha_tiles, erase);
    }

    /// Commits `256×256` 8-bit alpha tiles (from Select Pen / Select Eraser) onto this selection mask.
    pub fn apply_alpha_tiles(&mut self, alpha_tiles: &[(TileCoord, Vec<u8>)], erase: bool) {
        if alpha_tiles.is_empty() {
            return;
        }
        for (coord, alpha) in alpha_tiles {
            if alpha.len() < BYTES_8BIT {
                continue;
            }
            let mut cur = self.materialize_tile(*coord);
            for i in 0..BYTES_8BIT {
                let stroke_a = alpha[i];
                if stroke_a == 0 {
                    continue;
                }
                if erase {
                    cur[i] = cur[i].saturating_sub(stroke_a);
                } else {
                    let a = cur[i] as u32;
                    let s = stroke_a as u32;
                    let merged = a + ((255 - a) * s + 127) / 255;
                    cur[i] = merged.min(255) as u8;
                }
            }
            self.set_tile_raw(*coord, cur);
        }
        self.recompute_bounds();
        self.bump_version();
    }

    /// Helper to ensure `self.materialize_tile` works even when using an external scratch backend.
    pub fn read_mask_for_tile(
        &self,
        coord: TileCoord,
        _scratch: Option<&dyn ScratchBackend>,
    ) -> Vec<u8> {
        self.materialize_tile(coord)
    }
}

/// Felzenszwalb-Huttenlocher O(n) 1D squared Euclidean Distance Transform.
fn edt_1d(f: &[f64], n: usize, d: &mut [f64], v: &mut [i32], z: &mut [f64]) {
    if n == 0 {
        return;
    }
    let mut k: usize = 0;
    v[0] = 0;
    z[0] = f64::NEG_INFINITY;
    z[1] = f64::INFINITY;

    for q in 1..n {
        let qf = q as f64;
        let fq = f[q];
        loop {
            let vk = v[k] as usize;
            let vkf = vk as f64;
            let s = ((fq + qf * qf) - (f[vk] + vkf * vkf)) / (2.0 * (qf - vkf));
            if s <= z[k] {
                if k == 0 {
                    break;
                }
                k -= 1;
            } else {
                k += 1;
                v[k] = q as i32;
                z[k] = s;
                z[k + 1] = f64::INFINITY;
                break;
            }
        }
    }

    let mut k: usize = 0;
    for (q, dq) in d.iter_mut().enumerate().take(n) {
        let qf = q as f64;
        while z[k + 1] < qf {
            k += 1;
        }
        let vk = v[k] as usize;
        let dx = qf - vk as f64;
        *dq = dx * dx + f[vk];
    }
}