Skip to content

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

54.2 KB
Raw Blame
//! Direct Native Rust Flood Fill, Lasso Fill, Smart Line Fill (`enclose-and-fill` &
//! `paint-unfilled`), and <0.1 ms Native Eyedropper / Pipette (`fill.rs`).
//!
//! Operates directly in-process on `Document`'s sparse tile grids with zero JS pixel IPC,
//! zero full-document WebView canvases, Rayon parallelism, Close Gap morphological closing,
//! centerline-guarded Area Scaling, active `SparseSelectionMask` clipping, `alphaLocked`
//! support, and atomic Copy-on-Write Undo/Redo!

use crate::document::{BlendMode, Document, LayerId, LayerNode};
use crate::io::compositor_cpu;
use crate::memory::ScratchBackend;
use crate::tiles::{
    parse_hex_rgba8, pixel_to_tile_coord, RectI32, TileKind, TILE_SIZE, TILE_SIZE_I32,
};
use rayon::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum FillReferMode {
    #[default]
    ReferAll,
    ReferActive,
    ReferReference,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum EncloseTarget {
    #[default]
    AllEnclosed,
    UnfilledOnly,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FloodFillParams {
    pub x: i32,
    pub y: i32,
    pub color: String,
    #[serde(default = "default_tolerance")]
    pub tolerance: u8,
    #[serde(default)]
    pub close_gap: u32,
    #[serde(default)]
    pub area_scale: i32,
    #[serde(default = "default_true")]
    pub anti_alias: bool,
    #[serde(default = "default_one")]
    pub opacity: f32,
    #[serde(default)]
    pub refer_mode: FillReferMode,
    #[serde(default)]
    pub layer_id: Option<LayerId>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LassoFillParams {
    pub points: Vec<[f32; 2]>,
    pub color: String,
    #[serde(default = "default_one")]
    pub opacity: f32,
    #[serde(default = "default_true")]
    pub anti_alias: bool,
    #[serde(default)]
    pub layer_id: Option<LayerId>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EncloseFillParams {
    pub points: Vec<[f32; 2]>,
    pub color: String,
    #[serde(default = "default_tolerance")]
    pub tolerance: u8,
    #[serde(default = "default_smart_gap")]
    pub close_gap: u32,
    #[serde(default)]
    pub area_scale: i32,
    #[serde(default = "default_true")]
    pub anti_alias: bool,
    #[serde(default = "default_one")]
    pub opacity: f32,
    #[serde(default)]
    pub refer_mode: FillReferMode,
    #[serde(default)]
    pub enclose_target: EncloseTarget,
    #[serde(default)]
    pub layer_id: Option<LayerId>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaintUnfilledParams {
    pub points: Vec<[f32; 2]>,
    pub brush_radius: f32,
    pub color: String,
    #[serde(default = "default_tolerance")]
    pub tolerance: u8,
    #[serde(default = "default_smart_gap")]
    pub close_gap: u32,
    #[serde(default)]
    pub area_scale: i32,
    #[serde(default = "default_true")]
    pub anti_alias: bool,
    #[serde(default = "default_one")]
    pub opacity: f32,
    #[serde(default)]
    pub refer_mode: FillReferMode,
    #[serde(default)]
    pub layer_id: Option<LayerId>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FillOutcome {
    pub modified: bool,
    pub layer_id: LayerId,
    pub dirty_rect: RectI32,
    pub filled_pixels: u64,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PickedColor {
    pub r: u8,
    pub g: u8,
    pub b: u8,
    pub a: u8,
    pub hex: [u8; 7],
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PickedColorDto {
    pub r: u8,
    pub g: u8,
    pub b: u8,
    pub a: u8,
    pub hex: String,
}

fn default_tolerance() -> u8 {
    32
}
fn default_smart_gap() -> u32 {
    4
}
fn default_true() -> bool {
    true
}
fn default_one() -> f32 {
    1.0
}

// ============================================================================
// Reference Buffer Builders & Fast Pixel Helpers
// ============================================================================

fn resolve_target_layer_id(doc: &Document, explicit: Option<&str>) -> Result<LayerId, String> {
    let lid = explicit
        .map(str::to_string)
        .or_else(|| doc.active_layer_id.clone())
        .ok_or_else(|| "No active layer for fill".to_string())?;
    let node = doc
        .layer(&lid)
        .ok_or_else(|| format!("Layer not found: {lid}"))?;
    if !node.meta.layer_type.has_tiles() {
        return Err("Target layer is not a raster/paintable layer".to_string());
    }
    if node.meta.locked {
        return Err("Target layer is locked".to_string());
    }
    Ok(lid)
}

fn build_reference_rgba(
    doc: &Document,
    target_layer_id: &str,
    refer_mode: FillReferMode,
    rect: RectI32,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<Vec<u8>, String> {
    let px_count = (rect.width as usize) * (rect.height as usize);
    match refer_mode {
        FillReferMode::ReferActive => {
            let layer = doc
                .layer(target_layer_id)
                .ok_or_else(|| format!("Layer not found: {target_layer_id}"))?;
            layer.grid.read_rgba8_rect(rect, false, scratch)
        }
        FillReferMode::ReferReference => {
            let ref_layers: Vec<&LayerNode> = doc
                .layers
                .iter()
                .rev()
                .filter(|l| {
                    l.meta.layer_type.has_tiles()
                        && l.meta.is_reference.unwrap_or(false)
                        && doc.is_layer_effectively_visible(&l.meta.id)
                })
                .collect();
            if ref_layers.is_empty() {
                // Fallback to ReferAll if no layer is marked as reference
                return build_reference_rgba(
                    doc,
                    target_layer_id,
                    FillReferMode::ReferAll,
                    rect,
                    scratch,
                );
            }
            let mut out = vec![0u8; px_count * 4];
            for l in ref_layers {
                if l.grid.tiles.is_empty() {
                    continue;
                }
                let mut src = l.grid.read_rgba8_rect(rect, false, scratch)?;
                apply_layer_mask_to_rgba(l, rect, &mut src, scratch)?;
                compositor_cpu::blend_rgba8_over(
                    &mut out,
                    &src,
                    l.meta.opacity.clamp(0.0, 1.0),
                    l.meta.blend_mode,
                );
            }
            Ok(out)
        }
        FillReferMode::ReferAll => {
            let mut out = vec![0u8; px_count * 4];
            for l in doc.layers.iter().rev() {
                if !l.meta.layer_type.has_tiles()
                    || !doc.is_layer_effectively_visible(&l.meta.id)
                    || l.grid.tiles.is_empty()
                {
                    continue;
                }
                let op = l.meta.opacity.clamp(0.0, 1.0);
                if op <= 0.001 {
                    continue;
                }
                let mut src = l.grid.read_rgba8_rect(rect, false, scratch)?;
                apply_layer_mask_to_rgba(l, rect, &mut src, scratch)?;
                compositor_cpu::blend_rgba8_over(&mut out, &src, op, l.meta.blend_mode);
            }
            Ok(out)
        }
    }
}

fn apply_layer_mask_to_rgba(
    layer: &LayerNode,
    rect: RectI32,
    rgba: &mut [u8],
    scratch: Option<&dyn ScratchBackend>,
) -> Result<(), String> {
    if layer.grid.has_mask && layer.meta.mask_enabled.unwrap_or(true) {
        let mask = layer.grid.read_mask8_rect(rect, scratch)?;
        for (px, &m) in rgba.as_chunks_mut::<4>().0.iter_mut().zip(mask.iter()) {
            px[3] = ((u32::from(px[3]) * u32::from(m) + 127) / 255) as u8;
        }
    }
    Ok(())
}

/// Parallel separable morphological closing (dilate then erode) with box radius `r` on a 0/1 mask.
fn morph_close_box(barrier: &[u8], w: usize, h: usize, radius: usize) -> Vec<u8> {
    if radius == 0 {
        return barrier.to_vec();
    }
    let dil_h = dilate_1d_horiz(barrier, w, h, radius);
    let dil = dilate_1d_vert(&dil_h, w, h, radius);
    let ero_h = erode_1d_horiz(&dil, w, h, radius);
    erode_1d_vert(&ero_h, w, h, radius)
}

/// 45° diamond / diagonal closing used by Smart Line Fill so diagonal lineart gaps bridge cleanly!
fn morph_close_isotropic(barrier: &[u8], w: usize, h: usize, gap: usize) -> Vec<u8> {
    if gap == 0 {
        return barrier.to_vec();
    }
    let r_box = gap.div_ceil(2);
    let closed_box = morph_close_box(barrier, w, h, r_box);
    if gap < 3 {
        return closed_box;
    }
    // Additional 45° diagonal dilation/erosion merged via max to close slanted gaps cleanly
    let r_diag = (gap * 7 / 20).max(1);
    let mut diag_dil = vec![0u8; w * h];
    diag_dil
        .par_chunks_mut(w)
        .enumerate()
        .for_each(|(y, row)| {
            for x in 0..w {
                let mut hit = barrier[y * w + x];
                if hit == 0 {
                    for d in 1..=r_diag {
                        if x >= d && y >= d && barrier[(y - d) * w + (x - d)] != 0 {
                            hit = 1;
                            break;
                        }
                        if x + d < w && y + d < h && barrier[(y + d) * w + (x + d)] != 0 {
                            hit = 1;
                            break;
                        }
                        if x + d < w && y >= d && barrier[(y - d) * w + (x + d)] != 0 {
                            hit = 1;
                            break;
                        }
                        if x >= d && y + d < h && barrier[(y + d) * w + (x - d)] != 0 {
                            hit = 1;
                            break;
                        }
                    }
                }
                row[x] = hit;
            }
        });
    let mut out = closed_box;
    out.par_chunks_mut(w).enumerate().for_each(|(y, row)| {
        for x in 0..w {
            if row[x] != 0 {
                continue;
            }
            // Erode along diagonals
            let mut keep = diag_dil[y * w + x] != 0;
            if keep {
                for d in 1..=r_diag {
                    let a = x >= d && y >= d && diag_dil[(y - d) * w + (x - d)] != 0;
                    let b = x + d < w && y + d < h && diag_dil[(y + d) * w + (x + d)] != 0;
                    let c = x + d < w && y >= d && diag_dil[(y - d) * w + (x + d)] != 0;
                    let e = x >= d && y + d < h && diag_dil[(y + d) * w + (x - d)] != 0;
                    if !((a && b) || (c && e)) {
                        keep = false;
                        break;
                    }
                }
            }
            if keep {
                row[x] = 1;
            }
        }
    });
    out
}

fn dilate_1d_horiz(src: &[u8], w: usize, h: usize, r: usize) -> Vec<u8> {
    let mut dst = vec![0u8; w * h];
    dst.par_chunks_mut(w).enumerate().for_each(|(y, row)| {
        let srow = &src[y * w..(y + 1) * w];
        let mut cnt: usize = 0;
        for &v in srow.iter().take((r + 1).min(w)) {
            cnt += usize::from(v != 0);
        }
        for x in 0..w {
            row[x] = u8::from(cnt > 0);
            if x + r + 1 < w {
                cnt += usize::from(srow[x + r + 1] != 0);
            }
            if x >= r {
                cnt = cnt.saturating_sub(usize::from(srow[x - r] != 0));
            }
        }
    });
    dst
}

fn dilate_1d_vert(src: &[u8], w: usize, h: usize, r: usize) -> Vec<u8> {
    let mut dst = vec![0u8; w * h];
    dst.par_chunks_mut(w).enumerate().for_each(|(y, row)| {
        let y0 = y.saturating_sub(r);
        let y1 = (y + r).min(h - 1);
        for yy in y0..=y1 {
            let srow = &src[yy * w..(yy + 1) * w];
            for x in 0..w {
                row[x] |= srow[x];
            }
        }
    });
    dst
}

fn erode_1d_horiz(src: &[u8], w: usize, h: usize, r: usize) -> Vec<u8> {
    let mut dst = vec![0u8; w * h];
    dst.par_chunks_mut(w).enumerate().for_each(|(y, row)| {
        let srow = &src[y * w..(y + 1) * w];
        let mut zeros: usize = 0;
        for &v in srow.iter().take((r + 1).min(w)) {
            zeros += usize::from(v == 0);
        }
        for x in 0..w {
            row[x] = u8::from(zeros == 0);
            if x + r + 1 < w {
                zeros += usize::from(srow[x + r + 1] == 0);
            }
            if x >= r {
                zeros = zeros.saturating_sub(usize::from(srow[x - r] == 0));
            }
        }
    });
    dst
}

fn erode_1d_vert(src: &[u8], w: usize, h: usize, r: usize) -> Vec<u8> {
    let mut dst = vec![1u8; w * h];
    dst.par_chunks_mut(w).enumerate().for_each(|(y, row)| {
        let y0 = y.saturating_sub(r);
        let y1 = (y + r).min(h - 1);
        for yy in y0..=y1 {
            let srow = &src[yy * w..(yy + 1) * w];
            for x in 0..w {
                row[x] &= srow[x];
            }
        }
    });
    dst
}

/// Centerline-guarded BFS area scaling:
/// - `scale > 0`: expands `mask` into barrier pixels (stopping strictly at the medial skeleton /
///   outer edge of thin lineart so ink never bleeds through onto the far side!).
/// - `scale < 0`: shrinks `mask` by `|scale|` pixels via morphological erosion.
fn apply_area_scale(mask: &mut [u8], barrier: &[u8], w: usize, h: usize, scale: i32) {
    let s = scale.clamp(-20, 20);
    if s == 0 {
        return;
    }
    if s < 0 {
        let r = (-s) as usize;
        let eh = erode_1d_horiz(mask, w, h, r);
        let ev = erode_1d_vert(&eh, w, h, r);
        mask.copy_from_slice(&ev);
        return;
    }

    // Centerline-guarded expansion: compute distance of every barrier pixel to non-barrier exterior
    // (outside pixels NOT in `mask`), and prevent expansion from crossing into pixels strictly closer
    // to the exterior than to the filled interior!
    let steps = s as usize;
    let total = w * h;
    let mut dist_ext = vec![u16::MAX; total];
    let mut q_ext: Vec<usize> = Vec::new();
    for i in 0..total {
        if barrier[i] == 0 && mask[i] == 0 {
            dist_ext[i] = 0;
            q_ext.push(i);
        }
    }
    let max_d = (steps + 2) as u16;
    let mut head = 0usize;
    while head < q_ext.len() {
        let cur = q_ext[head];
        head += 1;
        let d = dist_ext[cur];
        if d >= max_d {
            continue;
        }
        let cx = cur % w;
        let cy = cur / w;
        let nd = d + 1;
        if cx > 0 && dist_ext[cur - 1] == u16::MAX {
            dist_ext[cur - 1] = nd;
            q_ext.push(cur - 1);
        }
        if cx + 1 < w && dist_ext[cur + 1] == u16::MAX {
            dist_ext[cur + 1] = nd;
            q_ext.push(cur + 1);
        }
        if cy > 0 && dist_ext[cur - w] == u16::MAX {
            dist_ext[cur - w] = nd;
            q_ext.push(cur - w);
        }
        if cy + 1 < h && dist_ext[cur + w] == u16::MAX {
            dist_ext[cur + w] = nd;
            q_ext.push(cur + w);
        }
    }

    // Multi-source BFS outward from `mask`, stopping strictly at centerline (`dist_in <= dist_ext`)
    let mut dist_in = vec![u16::MAX; total];
    let mut frontier: Vec<usize> = Vec::new();
    for i in 0..total {
        if mask[i] != 0 {
            dist_in[i] = 0;
            frontier.push(i);
        }
    }
    let mut fhead = 0usize;
    while fhead < frontier.len() {
        let cur = frontier[fhead];
        fhead += 1;
        let d = dist_in[cur];
        if d >= steps as u16 {
            continue;
        }
        let cx = cur % w;
        let cy = cur / w;
        let nd = d + 1;
        let neighbors = [
            (cx > 0).then_some(cur.wrapping_sub(1)),
            (cx + 1 < w).then_some(cur + 1),
            (cy > 0).then_some(cur.wrapping_sub(w)),
            (cy + 1 < h).then_some(cur + w),
        ];
        for n_opt in neighbors {
            let Some(ni) = n_opt else {
                continue;
            };
            if dist_in[ni] != u16::MAX {
                continue;
            }
            // Centerline guard: allow stepping into barrier pixels up to the medial line
            if barrier[ni] != 0 && nd <= dist_ext[ni] {
                dist_in[ni] = nd;
                mask[ni] = 1;
                frontier.push(ni);
            }
        }
    }
}

/// Commits an alpha coverage buffer (`0..=255`) of `fill_rgba` inside `work_rect` onto `layer_id`
/// honoring active `SparseSelectionMask`, `opacity`, `alphaLocked`, and recording an atomic CoW Undo step!
#[allow(clippy::too_many_arguments)]
fn commit_fill_coverage_mask(
    doc: &mut Document,
    layer_id: &str,
    work_rect: RectI32,
    coverage: &[u8],
    fill_rgba: [u8; 4],
    opacity: f32,
    action_type: &str,
    label: &str,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<FillOutcome, String> {
    let w = work_rect.width as usize;
    let h = work_rect.height as usize;
    let is_erase = fill_rgba[3] == 0;
    let op = if is_erase {
        let clamped = opacity.clamp(0.0, 1.0);
        if clamped <= 0.0005 {
            1.0
        } else {
            clamped
        }
    } else {
        (opacity.clamp(0.0, 1.0) * (fill_rgba[3] as f32 / 255.0)).clamp(0.0, 1.0)
    };
    if op <= 0.0005 || w == 0 || h == 0 {
        return Ok(FillOutcome {
            modified: false,
            layer_id: layer_id.to_string(),
            dirty_rect: RectI32::empty(),
            filled_pixels: 0,
        });
    }

    // Read selection mask clipped to `work_rect` if active
    let sel_buf: Option<Vec<u8>> = doc
        .selection
        .as_ref()
        .filter(|s| !s.is_empty())
        .map(|s| s.read_rect(work_rect));

    // Compute tight dirty bounding box of non-zero coverage pixels
    let mut min_x = w;
    let mut min_y = h;
    let mut max_x = 0usize;
    let mut max_y = 0usize;
    let mut filled_pixels = 0u64;

    for y in 0..h {
        let row_off = y * w;
        for x in 0..w {
            let mut cov = coverage[row_off + x];
            if let Some(ref sb) = sel_buf {
                cov = ((u32::from(cov) * u32::from(sb[row_off + x]) + 127) / 255) as u8;
            }
            if cov > 0 {
                min_x = min_x.min(x);
                min_y = min_y.min(y);
                max_x = max_x.max(x);
                max_y = max_y.max(y);
                filled_pixels += 1;
            }
        }
    }

    if filled_pixels == 0 {
        return Ok(FillOutcome {
            modified: false,
            layer_id: layer_id.to_string(),
            dirty_rect: RectI32::empty(),
            filled_pixels: 0,
        });
    }

    let tight_rect = RectI32::new(
        work_rect.x + min_x as i32,
        work_rect.y + min_y as i32,
        (max_x - min_x + 1) as u32,
        (max_y - min_y + 1) as u32,
    );

    let (alpha_locked, mono_thresh) = {
        let l = doc
            .layer(layer_id)
            .ok_or_else(|| format!("Layer not found: {layer_id}"))?;
        (
            l.meta.alpha_locked.unwrap_or(false),
            l.meta.mono_threshold.unwrap_or(128),
        )
    };
    if is_erase && alpha_locked {
        return Ok(FillOutcome {
            modified: false,
            layer_id: layer_id.to_string(),
            dirty_rect: RectI32::empty(),
            filled_pixels: 0,
        });
    }

    let tw = tight_rect.width as usize;
    let mut dst_rgba = {
        let l = doc
            .layer(layer_id)
            .ok_or_else(|| format!("Layer not found: {layer_id}"))?;
        l.grid.read_rgba8_rect(tight_rect, false, scratch)?
    };

    let fr = fill_rgba[0] as f32 / 255.0;
    let fg = fill_rgba[1] as f32 / 255.0;
    let fb = fill_rgba[2] as f32 / 255.0;

    dst_rgba
        .par_chunks_mut(tw * 4)
        .enumerate()
        .for_each(|(ty, row)| {
            let wy = min_y + ty;
            let row_off = wy * w;
            for tx in 0..tw {
                let wx = min_x + tx;
                let mut cov = coverage[row_off + wx];
                if let Some(ref sb) = sel_buf {
                    cov = ((u32::from(cov) * u32::from(sb[row_off + wx]) + 127) / 255) as u8;
                }
                if cov == 0 {
                    continue;
                }
                let sa = (cov as f32 / 255.0) * op;
                let o = tx * 4;
                let da = row[o + 3] as f32 / 255.0;
                if is_erase {
                    if alpha_locked || da <= 1e-5 {
                        continue;
                    }
                    let out_a = (da * (1.0 - sa)).clamp(0.0, 1.0);
                    if out_a <= 1e-5 {
                        row[o] = 0;
                        row[o + 1] = 0;
                        row[o + 2] = 0;
                        row[o + 3] = 0;
                    } else {
                        row[o + 3] = (out_a * 255.0).round().clamp(0.0, 255.0) as u8;
                    }
                } else if alpha_locked {
                    if da <= 0.001 {
                        continue;
                    }
                    let dr = row[o] as f32 / 255.0;
                    let dg = row[o + 1] as f32 / 255.0;
                    let db = row[o + 2] as f32 / 255.0;
                    row[o] = ((dr + (fr - dr) * sa) * 255.0).round().clamp(0.0, 255.0) as u8;
                    row[o + 1] = ((dg + (fg - dg) * sa) * 255.0).round().clamp(0.0, 255.0) as u8;
                    row[o + 2] = ((db + (fb - db) * sa) * 255.0).round().clamp(0.0, 255.0) as u8;
                } else {
                    let out_a = sa + da * (1.0 - sa);
                    if out_a <= 1e-5 {
                        continue;
                    }
                    let dr = row[o] as f32 / 255.0;
                    let dg = row[o + 1] as f32 / 255.0;
                    let db = row[o + 2] as f32 / 255.0;
                    let out_r = (fr * sa + dr * da * (1.0 - sa)) / out_a;
                    let out_g = (fg * sa + dg * da * (1.0 - sa)) / out_a;
                    let out_b = (fb * sa + db * da * (1.0 - sa)) / out_a;
                    row[o] = (out_r * 255.0).round().clamp(0.0, 255.0) as u8;
                    row[o + 1] = (out_g * 255.0).round().clamp(0.0, 255.0) as u8;
                    row[o + 2] = (out_b * 255.0).round().clamp(0.0, 255.0) as u8;
                    row[o + 3] = (out_a * 255.0).round().clamp(0.0, 255.0) as u8;
                }
            }
        });

    let deltas = {
        let l = doc
            .layer_mut(layer_id)
            .ok_or_else(|| format!("Layer not found: {layer_id}"))?;
        let before = l.grid.snapshot_all_cow(TileKind::Raster);
        let touched = l
            .grid
            .write_rgba8_rect(&dst_rgba, tight_rect, mono_thresh, scratch)?;
        let mut d = Vec::with_capacity(touched.len());
        for coord in touched {
            let before_t = before.get(&coord).cloned();
            let after_t = l.grid.tiles.get(&coord).cloned();
            let same = match (&before_t, &after_t) {
                (None, None) => true,
                (Some(a), Some(b)) => std::sync::Arc::ptr_eq(a, b) || a.version == b.version,
                _ => false,
            };
            if !same {
                d.push(crate::tiles::CowTileDelta {
                    layer_id: layer_id.to_string(),
                    coord,
                    kind: TileKind::Raster,
                    before: before_t,
                    after: after_t,
                    remote_epoch: l.grid.remote_epochs.get(&coord).copied().unwrap_or(0),
                });
            }
        }
        d
    };

    if !deltas.is_empty() {
        doc.record_stroke_deltas(layer_id, action_type, label, deltas, None, None);
    }

    Ok(FillOutcome {
        modified: true,
        layer_id: layer_id.to_string(),
        dirty_rect: tight_rect,
        filled_pixels,
    })
}

/// Optional soft anti-aliased edge pass for binary fill masks (`0/1` -> `0..=255`).
fn binary_mask_to_coverage(mask: &[u8], w: usize, h: usize, anti_alias: bool) -> Vec<u8> {
    if !anti_alias {
        return mask.iter().map(|&v| if v != 0 { 255 } else { 0 }).collect();
    }
    let mut out = vec![0u8; w * h];
    out.par_chunks_mut(w).enumerate().for_each(|(y, row)| {
        for (x, dst_px) in row.iter_mut().enumerate().take(w) {
            let idx = y * w + x;
            if mask[idx] != 0 {
                *dst_px = 255;
            } else {
                // Smooth 4-neighbor outer AA fringe so curved fills have clean edges
                let mut n = 0u32;
                if x > 0 && mask[idx - 1] != 0 {
                    n += 1;
                }
                if x + 1 < w && mask[idx + 1] != 0 {
                    n += 1;
                }
                if y > 0 && mask[idx - w] != 0 {
                    n += 1;
                }
                if y + 1 < h && mask[idx + w] != 0 {
                    n += 1;
                }
                if n >= 2 {
                    *dst_px = (n * 54).min(200) as u8;
                }
            }
        }
    });
    out
}

// ============================================================================
// 1. Direct Rust Flood Fill (`refer-all`, `refer-active`, `refer-reference`)
// ============================================================================

pub fn flood_fill_document(
    doc: &mut Document,
    params: &FloodFillParams,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<FillOutcome, String> {
    let w = doc.dimensions.width as usize;
    let h = doc.dimensions.height as usize;
    if w == 0 || h == 0 || params.x < 0 || params.y < 0 || params.x >= w as i32 || params.y >= h as i32 {
        return Ok(FillOutcome {
            modified: false,
            layer_id: params
                .layer_id
                .clone()
                .or_else(|| doc.active_layer_id.clone())
                .unwrap_or_default(),
            dirty_rect: RectI32::empty(),
            filled_pixels: 0,
        });
    }

    let layer_id = resolve_target_layer_id(doc, params.layer_id.as_deref())?;
    let fill_rgba = parse_hex_rgba8(&params.color).unwrap_or([0, 0, 0, 255]);
    let full_rect = RectI32::new(0, 0, doc.dimensions.width, doc.dimensions.height);

    // If active selection exists and seed is strictly outside it, no-op cleanly
    if let Some(ref sel) = doc.selection {
        if !sel.is_empty() && sel.read_rect(RectI32::new(params.x, params.y, 1, 1))[0] == 0 {
            return Ok(FillOutcome {
                modified: false,
                layer_id,
                dirty_rect: RectI32::empty(),
                filled_pixels: 0,
            });
        }
    }

    let ref_rgba = build_reference_rgba(doc, &layer_id, params.refer_mode, full_rect, scratch)?;
    let sx = params.x as usize;
    let sy = params.y as usize;
    let seed_off = (sy * w + sx) * 4;
    let sr = ref_rgba[seed_off] as i32;
    let sg = ref_rgba[seed_off + 1] as i32;
    let sb = ref_rgba[seed_off + 2] as i32;
    let sa = ref_rgba[seed_off + 3] as i32;
    let tol = params.tolerance as i32;

    // Build binary barrier map (1 = differs from seed beyond tolerance)
    let mut barrier = vec![0u8; w * h];
    barrier
        .par_chunks_mut(w)
        .enumerate()
        .for_each(|(y, row)| {
            let roff = y * w * 4;
            for (x, cell) in row.iter_mut().enumerate().take(w) {
                let o = roff + x * 4;
                let dr = (ref_rgba[o] as i32 - sr).abs();
                let dg = (ref_rgba[o + 1] as i32 - sg).abs();
                let db = (ref_rgba[o + 2] as i32 - sb).abs();
                let da = (ref_rgba[o + 3] as i32 - sa).abs();
                if dr.max(dg).max(db).max(da) > tol {
                    *cell = 1;
                }
            }
        });

    let close_r = params.close_gap.min(20) as usize;
    let closed_barrier = if close_r > 0 {
        let mut cb = morph_close_box(&barrier, w, h, close_r.div_ceil(2));
        // Ensure seed point itself is never sealed off by close-gap
        cb[sy * w + sx] = 0;
        cb
    } else {
        barrier.clone()
    };

    // Fast horizontal scanline flood fill (zero recursion, cache-friendly!)
    let mut filled = vec![0u8; w * h];
    let mut stack: Vec<(usize, usize)> = Vec::with_capacity(4096);
    stack.push((sx, sy));

    while let Some((px, py)) = stack.pop() {
        let row = py * w;
        if filled[row + px] != 0 || closed_barrier[row + px] != 0 {
            continue;
        }
        let mut xl = px;
        while xl > 0 && filled[row + xl - 1] == 0 && closed_barrier[row + xl - 1] == 0 {
            xl -= 1;
        }
        let mut xr = px;
        while xr + 1 < w && filled[row + xr + 1] == 0 && closed_barrier[row + xr + 1] == 0 {
            xr += 1;
        }
        for x in xl..=xr {
            filled[row + x] = 1;
        }
        for ny in [py.checked_sub(1), (py + 1 < h).then_some(py + 1)]
            .into_iter()
            .flatten()
        {
            let nrow = ny * w;
            let mut in_span = false;
            for x in xl..=xr {
                let open = filled[nrow + x] == 0 && closed_barrier[nrow + x] == 0;
                if open && !in_span {
                    stack.push((x, ny));
                    in_span = true;
                } else if !open {
                    in_span = false;
                }
            }
        }
    }

    // V-tip recovery when closeGap is active: recover narrow interior wedge corners that
    // were pinched by morphological closing without escaping past the original barrier!
    if close_r > 0 {
        let mut tip_q: Vec<usize> = Vec::new();
        for y in 1..h.saturating_sub(1) {
            for x in 1..w.saturating_sub(1) {
                let idx = y * w + x;
                if filled[idx] == 0
                    && barrier[idx] == 0
                    && closed_barrier[idx] != 0
                    && (filled[idx - 1] != 0
                        || filled[idx + 1] != 0
                        || filled[idx - w] != 0
                        || filled[idx + w] != 0)
                {
                    filled[idx] = 1;
                    tip_q.push(idx);
                }
            }
        }
        let mut qh = 0usize;
        while qh < tip_q.len() {
            let cur = tip_q[qh];
            qh += 1;
            let cx = cur % w;
            let cy = cur / w;
            for ni in [
                (cx > 0).then_some(cur.wrapping_sub(1)),
                (cx + 1 < w).then_some(cur + 1),
                (cy > 0).then_some(cur.wrapping_sub(w)),
                (cy + 1 < h).then_some(cur + w),
            ]
            .into_iter()
            .flatten()
            {
                if filled[ni] == 0 && barrier[ni] == 0 && closed_barrier[ni] != 0 {
                    filled[ni] = 1;
                    tip_q.push(ni);
                }
            }
        }
    }

    // Centerline-guarded Area Scaling (-20..+20px)
    if params.area_scale != 0 {
        apply_area_scale(&mut filled, &barrier, w, h, params.area_scale);
    }

    let coverage = binary_mask_to_coverage(&filled, w, h, params.anti_alias);
    commit_fill_coverage_mask(
        doc,
        &layer_id,
        full_rect,
        &coverage,
        fill_rgba,
        params.opacity,
        "fill",
        "Flood Fill",
        scratch,
    )
}

// ============================================================================
// 2. Direct Rust Lasso Fill (4×4 Supersampled AA Scanline Polygon Fill)
// ============================================================================

fn rasterize_polygon_coverage(
    points: &[[f32; 2]],
    rect: RectI32,
    anti_alias: bool,
) -> Vec<u8> {
    let w = rect.width as usize;
    let h = rect.height as usize;
    let n = points.len();
    if w == 0 || h == 0 || n < 3 {
        return vec![0u8; w * h];
    }

    let sub_steps = if anti_alias { 4usize } else { 1usize };
    let mut out = vec![0u8; w * h];
    let ox = rect.x as f32;
    let oy = rect.y as f32;

    out.par_chunks_mut(w).enumerate().for_each(|(ry, row)| {
        let mut xs = Vec::with_capacity(32);
        let mut hits = vec![0u16; w];
        for sy in 0..sub_steps {
            let py = oy + ry as f32 + (sy as f32 + 0.5) / sub_steps as f32;
            xs.clear();
            let mut j = n - 1;
            for i in 0..n {
                let (x1, y1) = (points[j][0], points[j][1]);
                let (x2, y2) = (points[i][0], points[i][1]);
                if (y1 <= py && y2 > py) || (y2 <= py && y1 > py) {
                    let t = (py - y1) / (y2 - y1);
                    xs.push(x1 + t * (x2 - x1));
                }
                j = i;
            }
            xs.sort_by(|a, b| a.total_cmp(b));
            for pair in xs.as_chunks::<2>().0 {
                let x0 = pair[0] - ox;
                let x1 = pair[1] - ox;
                if x1 <= 0.0 || x0 >= w as f32 {
                    continue;
                }
                let ix0 = x0.floor().max(0.0) as usize;
                let ix1 = x1.ceil().min(w as f32) as usize;
                for (px, hit) in hits.iter_mut().enumerate().take(ix1).skip(ix0) {
                    if sub_steps == 1 {
                        let cx = px as f32 + 0.5;
                        if cx >= x0 && cx < x1 {
                            *hit += 1;
                        }
                    } else {
                        for sx in 0..4 {
                            let cx = px as f32 + (sx as f32 + 0.5) * 0.25;
                            if cx >= x0 && cx < x1 {
                                *hit += 1;
                            }
                        }
                    }
                }
            }
        }
        let denom = (sub_steps * sub_steps) as u32;
        for x in 0..w {
            if hits[x] > 0 {
                row[x] = ((u32::from(hits[x]) * 255 + denom / 2) / denom).min(255) as u8;
            }
        }
    });
    out
}

pub fn lasso_fill_document(
    doc: &mut Document,
    params: &LassoFillParams,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<FillOutcome, String> {
    if params.points.len() < 3 {
        return Ok(FillOutcome {
            modified: false,
            layer_id: params
                .layer_id
                .clone()
                .or_else(|| doc.active_layer_id.clone())
                .unwrap_or_default(),
            dirty_rect: RectI32::empty(),
            filled_pixels: 0,
        });
    }
    let layer_id = resolve_target_layer_id(doc, params.layer_id.as_deref())?;
    let fill_rgba = parse_hex_rgba8(&params.color).unwrap_or([0, 0, 0, 255]);

    let mut min_x = f32::INFINITY;
    let mut min_y = f32::INFINITY;
    let mut max_x = f32::NEG_INFINITY;
    let mut max_y = f32::NEG_INFINITY;
    for p in &params.points {
        min_x = min_x.min(p[0]);
        min_y = min_y.min(p[1]);
        max_x = max_x.max(p[0]);
        max_y = max_y.max(p[1]);
    }
    let doc_rect = RectI32::new(0, 0, doc.dimensions.width, doc.dimensions.height);
    let raw_rect = RectI32::new(
        min_x.floor() as i32 - 1,
        min_y.floor() as i32 - 1,
        ((max_x.ceil() - min_x.floor()) as i32 + 3).max(1) as u32,
        ((max_y.ceil() - min_y.floor()) as i32 + 3).max(1) as u32,
    );
    let work_rect = raw_rect.intersect(doc_rect);
    if work_rect.is_empty() {
        return Ok(FillOutcome {
            modified: false,
            layer_id,
            dirty_rect: RectI32::empty(),
            filled_pixels: 0,
        });
    }

    let coverage = rasterize_polygon_coverage(&params.points, work_rect, params.anti_alias);
    commit_fill_coverage_mask(
        doc,
        &layer_id,
        work_rect,
        &coverage,
        fill_rgba,
        params.opacity,
        "fill",
        "Lasso Fill",
        scratch,
    )
}

// ============================================================================
// 3. Direct Rust Smart Line Fill: `enclose-and-fill` & `paint-unfilled`
// ============================================================================

/// Detects lineart barrier pixels inside `ref_rgba` using adaptive alpha/luminance thresholding.
fn extract_lineart_barrier(ref_rgba: &[u8], w: usize, h: usize, tolerance: u8) -> Vec<u8> {
    // Check whether reference has an opaque white background (e.g. ReferAll with Background layer)
    let corner_alpha = ref_rgba.get(3).copied().unwrap_or(0);
    let has_opaque_bg = corner_alpha >= 250;
    let bg_r = ref_rgba.first().copied().unwrap_or(255) as i32;
    let bg_g = ref_rgba.get(1).copied().unwrap_or(255) as i32;
    let bg_b = ref_rgba.get(2).copied().unwrap_or(255) as i32;
    let tol = (tolerance as i32).max(16);

    let mut barrier = vec![0u8; w * h];
    barrier
        .par_chunks_mut(w)
        .enumerate()
        .for_each(|(y, row)| {
            let roff = y * w * 4;
            for (x, cell) in row.iter_mut().enumerate().take(w) {
                let o = roff + x * 4;
                let a = ref_rgba[o + 3] as i32;
                if has_opaque_bg {
                    let dr = (ref_rgba[o] as i32 - bg_r).abs();
                    let dg = (ref_rgba[o + 1] as i32 - bg_g).abs();
                    let db = (ref_rgba[o + 2] as i32 - bg_b).abs();
                    if dr.max(dg).max(db) > tol {
                        *cell = 1;
                    }
                } else if a > (255 - tol).min(36) {
                    *cell = 1;
                }
            }
        });
    barrier
}

/// Smart Line Fill — **Enclose & Fill**:
/// Traces user's lasso enclosure around lineart, bridges gaps up to `close_gap` (0..40px) with
/// isotropic box + 45° diamond closing, floods outside from the lasso boundary, and fills all
/// fully-enclosed interior regions (optionally restricting to `unfilled-only` pixels on the target layer)!
pub fn enclose_and_fill_document(
    doc: &mut Document,
    params: &EncloseFillParams,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<FillOutcome, String> {
    if params.points.len() < 3 {
        return Ok(FillOutcome {
            modified: false,
            layer_id: params
                .layer_id
                .clone()
                .or_else(|| doc.active_layer_id.clone())
                .unwrap_or_default(),
            dirty_rect: RectI32::empty(),
            filled_pixels: 0,
        });
    }

    let layer_id = resolve_target_layer_id(doc, params.layer_id.as_deref())?;
    let fill_rgba = parse_hex_rgba8(&params.color).unwrap_or([0, 0, 0, 255]);
    let pad = (params.close_gap.min(40) as i32) + params.area_scale.abs().min(20) + 8;

    let mut min_x = f32::INFINITY;
    let mut min_y = f32::INFINITY;
    let mut max_x = f32::NEG_INFINITY;
    let mut max_y = f32::NEG_INFINITY;
    for p in &params.points {
        min_x = min_x.min(p[0]);
        min_y = min_y.min(p[1]);
        max_x = max_x.max(p[0]);
        max_y = max_y.max(p[1]);
    }
    let doc_rect = RectI32::new(0, 0, doc.dimensions.width, doc.dimensions.height);
    let work_rect = RectI32::new(
        min_x.floor() as i32 - pad,
        min_y.floor() as i32 - pad,
        ((max_x.ceil() - min_x.floor()) as i32 + pad * 2 + 2).max(1) as u32,
        ((max_y.ceil() - min_y.floor()) as i32 + pad * 2 + 2).max(1) as u32,
    )
    .intersect(doc_rect);
    if work_rect.is_empty() {
        return Ok(FillOutcome {
            modified: false,
            layer_id,
            dirty_rect: RectI32::empty(),
            filled_pixels: 0,
        });
    }

    let w = work_rect.width as usize;
    let h = work_rect.height as usize;
    let poly_cov = rasterize_polygon_coverage(&params.points, work_rect, false);
    let ref_rgba = build_reference_rgba(doc, &layer_id, params.refer_mode, work_rect, scratch)?;
    let barrier = extract_lineart_barrier(&ref_rgba, w, h, params.tolerance);
    let gap = params.close_gap.min(40) as usize;
    let closed_barrier = morph_close_isotropic(&barrier, w, h, gap);

    // Flood-fill "exterior" starting from every non-barrier pixel outside the user's lasso enclosure
    let mut exterior = vec![0u8; w * h];
    let mut queue: Vec<usize> = Vec::with_capacity(w * 4);
    for y in 0..h {
        for x in 0..w {
            let idx = y * w + x;
            let on_border = x == 0 || y == 0 || x + 1 == w || y + 1 == h;
            if (poly_cov[idx] == 0 || on_border) && closed_barrier[idx] == 0 {
                exterior[idx] = 1;
                queue.push(idx);
            }
        }
    }
    let mut qh = 0usize;
    while qh < queue.len() {
        let cur = queue[qh];
        qh += 1;
        let cx = cur % w;
        let cy = cur / w;
        for ni in [
            (cx > 0).then_some(cur.wrapping_sub(1)),
            (cx + 1 < w).then_some(cur + 1),
            (cy > 0).then_some(cur.wrapping_sub(w)),
            (cy + 1 < h).then_some(cur + w),
        ]
        .into_iter()
        .flatten()
        {
            if exterior[ni] == 0 && closed_barrier[ni] == 0 {
                exterior[ni] = 1;
                queue.push(ni);
            }
        }
    }

    // Any pixel strictly inside the lasso that is NOT exterior and NOT barrier is an enclosed pocket!
    let mut filled = vec![0u8; w * h];
    for i in 0..(w * h) {
        if poly_cov[i] != 0 && exterior[i] == 0 && barrier[i] == 0 {
            filled[i] = 1;
        }
    }

    // Optional `unfilled-only` target mode: skip pixels already painted on target layer
    if params.enclose_target == EncloseTarget::UnfilledOnly {
        let active_rgba = doc
            .layer(&layer_id)
            .ok_or_else(|| format!("Layer not found: {layer_id}"))?
            .grid
            .read_rgba8_rect(work_rect, false, scratch)?;
        for i in 0..(w * h) {
            if filled[i] != 0 && active_rgba[i * 4 + 3] > 24 {
                filled[i] = 0;
            }
        }
    }

    if params.area_scale != 0 {
        apply_area_scale(&mut filled, &barrier, w, h, params.area_scale);
    }

    let coverage = binary_mask_to_coverage(&filled, w, h, params.anti_alias);
    commit_fill_coverage_mask(
        doc,
        &layer_id,
        work_rect,
        &coverage,
        fill_rgba,
        params.opacity,
        "fill",
        "Enclose & Fill",
        scratch,
    )
}

/// Smart Line Fill — **Paint Unfilled Areas**:
/// Traces a circular brush path along `params.points`, detects every enclosed transparent pocket
/// touched by the brush footprint (respecting lineart + `close_gap` + `area_scale`), and fills
/// only those enclosed pockets without ever leaking outside the artwork!
pub fn paint_unfilled_document(
    doc: &mut Document,
    params: &PaintUnfilledParams,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<FillOutcome, String> {
    if params.points.is_empty() {
        return Ok(FillOutcome {
            modified: false,
            layer_id: params
                .layer_id
                .clone()
                .or_else(|| doc.active_layer_id.clone())
                .unwrap_or_default(),
            dirty_rect: RectI32::empty(),
            filled_pixels: 0,
        });
    }

    let layer_id = resolve_target_layer_id(doc, params.layer_id.as_deref())?;
    let fill_rgba = parse_hex_rgba8(&params.color).unwrap_or([0, 0, 0, 255]);
    let radius = params.brush_radius.clamp(2.0, 256.0);
    let pad = radius.ceil() as i32 + (params.close_gap.min(40) as i32) + 24;

    let mut min_x = f32::INFINITY;
    let mut min_y = f32::INFINITY;
    let mut max_x = f32::NEG_INFINITY;
    let mut max_y = f32::NEG_INFINITY;
    for p in &params.points {
        min_x = min_x.min(p[0]);
        min_y = min_y.min(p[1]);
        max_x = max_x.max(p[0]);
        max_y = max_y.max(p[1]);
    }
    let doc_rect = RectI32::new(0, 0, doc.dimensions.width, doc.dimensions.height);
    let work_rect = RectI32::new(
        min_x.floor() as i32 - pad,
        min_y.floor() as i32 - pad,
        ((max_x.ceil() - min_x.floor()) as i32 + pad * 2 + 2).max(1) as u32,
        ((max_y.ceil() - min_y.floor()) as i32 + pad * 2 + 2).max(1) as u32,
    )
    .intersect(doc_rect);
    if work_rect.is_empty() {
        return Ok(FillOutcome {
            modified: false,
            layer_id,
            dirty_rect: RectI32::empty(),
            filled_pixels: 0,
        });
    }

    let w = work_rect.width as usize;
    let h = work_rect.height as usize;

    // Rasterize brush stroke capsule footprint inside `work_rect`
    let mut brush_mask = vec![0u8; w * h];
    let r2 = radius * radius;
    let ox = work_rect.x as f32;
    let oy = work_rect.y as f32;
    let seg_count = params.points.len().saturating_sub(1).max(1);
    brush_mask
        .par_chunks_mut(w)
        .enumerate()
        .for_each(|(ry, row)| {
            let py = oy + ry as f32 + 0.5;
            for (rx, cell) in row.iter_mut().enumerate().take(w) {
                let px = ox + rx as f32 + 0.5;
                let mut inside = false;
                if params.points.len() == 1 {
                    let dx = px - params.points[0][0];
                    let dy = py - params.points[0][1];
                    inside = dx * dx + dy * dy <= r2;
                } else {
                    for s in 0..seg_count {
                        let a = params.points[s];
                        let b = params.points[s + 1];
                        let abx = b[0] - a[0];
                        let aby = b[1] - a[1];
                        let ab2 = abx * abx + aby * aby;
                        let t = if ab2 > 1e-4 {
                            (((px - a[0]) * abx + (py - a[1]) * aby) / ab2).clamp(0.0, 1.0)
                        } else {
                            0.0
                        };
                        let dx = px - (a[0] + abx * t);
                        let dy = py - (a[1] + aby * t);
                        if dx * dx + dy * dy <= r2 {
                            inside = true;
                            break;
                        }
                    }
                }
                if inside {
                    *cell = 1;
                }
            }
        });

    let ref_rgba = build_reference_rgba(doc, &layer_id, params.refer_mode, work_rect, scratch)?;
    let active_rgba = doc
        .layer(&layer_id)
        .ok_or_else(|| format!("Layer not found: {layer_id}"))?
        .grid
        .read_rgba8_rect(work_rect, false, scratch)?;

    // Barrier = reference lineart OR already-painted target layer pixels
    let mut barrier = extract_lineart_barrier(&ref_rgba, w, h, params.tolerance);
    for i in 0..(w * h) {
        if active_rgba[i * 4 + 3] > 24 {
            barrier[i] = 1;
        }
    }
    let closed_barrier = morph_close_isotropic(&barrier, w, h, params.close_gap.min(40) as usize);

    // Flood from `work_rect` outer border to tag open/unenclosed exterior background
    let mut exterior = vec![0u8; w * h];
    let mut q: Vec<usize> = Vec::with_capacity(w * 4);
    for x in 0..w {
        for y in [0, h - 1] {
            let idx = y * w + x;
            if closed_barrier[idx] == 0 && exterior[idx] == 0 {
                exterior[idx] = 1;
                q.push(idx);
            }
        }
    }
    for y in 0..h {
        for x in [0, w - 1] {
            let idx = y * w + x;
            if closed_barrier[idx] == 0 && exterior[idx] == 0 {
                exterior[idx] = 1;
                q.push(idx);
            }
        }
    }
    let mut qh = 0usize;
    while qh < q.len() {
        let cur = q[qh];
        qh += 1;
        let cx = cur % w;
        let cy = cur / w;
        for ni in [
            (cx > 0).then_some(cur.wrapping_sub(1)),
            (cx + 1 < w).then_some(cur + 1),
            (cy > 0).then_some(cur.wrapping_sub(w)),
            (cy + 1 < h).then_some(cur + w),
        ]
        .into_iter()
        .flatten()
        {
            if exterior[ni] == 0 && closed_barrier[ni] == 0 {
                exterior[ni] = 1;
                q.push(ni);
            }
        }
    }

    // Flood every enclosed non-exterior pocket touched by `brush_mask`!
    let mut filled = vec![0u8; w * h];
    let mut fq: Vec<usize> = Vec::new();
    for i in 0..(w * h) {
        if brush_mask[i] != 0 && exterior[i] == 0 && barrier[i] == 0 && filled[i] == 0 {
            filled[i] = 1;
            fq.push(i);
        }
    }
    let mut fhead = 0usize;
    while fhead < fq.len() {
        let cur = fq[fhead];
        fhead += 1;
        let cx = cur % w;
        let cy = cur / w;
        for ni in [
            (cx > 0).then_some(cur.wrapping_sub(1)),
            (cx + 1 < w).then_some(cur + 1),
            (cy > 0).then_some(cur.wrapping_sub(w)),
            (cy + 1 < h).then_some(cur + w),
        ]
        .into_iter()
        .flatten()
        {
            if filled[ni] == 0 && exterior[ni] == 0 && barrier[ni] == 0 {
                filled[ni] = 1;
                fq.push(ni);
            }
        }
    }

    if params.area_scale != 0 {
        apply_area_scale(&mut filled, &barrier, w, h, params.area_scale);
    }

    let coverage = binary_mask_to_coverage(&filled, w, h, params.anti_alias);
    commit_fill_coverage_mask(
        doc,
        &layer_id,
        work_rect,
        &coverage,
        fill_rgba,
        params.opacity,
        "fill",
        "Paint Unfilled Areas",
        scratch,
    )
}

// ============================================================================
// 4. Instant Native Eyedropper / Pipette (<0.1 ms O(1) Sparse Tile Sampling)
// ============================================================================

/// Samples a single pixel from a `LayerNode` in O(1) without allocating a rectangle.
fn sample_layer_pixel(
    layer: &LayerNode,
    x: i32,
    y: i32,
    scratch: Option<&dyn ScratchBackend>,
) -> [u8; 4] {
    let coord = crate::tiles::TileCoord::new(pixel_to_tile_coord(x, 0), pixel_to_tile_coord(y, 0));
    let Some(tile) = layer.grid.tiles.get(&coord) else {
        return [0, 0, 0, 0];
    };
    let lx = (x - coord.tx * TILE_SIZE_I32) as usize;
    let ly = (y - coord.ty * TILE_SIZE_I32) as usize;
    let mut px = match &tile.storage {
        crate::tiles::TileStorage::SolidColor { rgba8, .. } => *rgba8,
        crate::tiles::TileStorage::Raw(buf) => match tile.format {
            crate::tiles::TileFormat::Monochrome1Bit => {
                let bit = ly * TILE_SIZE + lx;
                let byte_idx = bit >> 3;
                let on = byte_idx < buf.len() && (buf[byte_idx] & (0x80 >> (bit & 7))) != 0;
                if on {
                    [0, 0, 0, 255]
                } else {
                    [0, 0, 0, 0]
                }
            }
            crate::tiles::TileFormat::Grayscale8Bit => {
                let off = ly * TILE_SIZE + lx;
                let v = buf.get(off).copied().unwrap_or(0);
                if v == 0 {
                    [0, 0, 0, 0]
                } else {
                    [v, v, v, 255]
                }
            }
            crate::tiles::TileFormat::Color32Bit => {
                let off = (ly * TILE_SIZE + lx) * 4;
                if off + 3 < buf.len() {
                    [buf[off], buf[off + 1], buf[off + 2], buf[off + 3]]
                } else {
                    [0, 0, 0, 0]
                }
            }
            _ => {
                if let Ok(rgba) = tile.to_rgba8(scratch, false) {
                    let off = (ly * TILE_SIZE + lx) * 4;
                    if off + 3 < rgba.len() {
                        [rgba[off], rgba[off + 1], rgba[off + 2], rgba[off + 3]]
                    } else {
                        [0, 0, 0, 0]
                    }
                } else {
                    [0, 0, 0, 0]
                }
            }
        },
        _ => {
            if let Ok(rgba) = tile.to_rgba8(scratch, false) {
                let off = (ly * TILE_SIZE + lx) * 4;
                if off + 3 < rgba.len() {
                    [rgba[off], rgba[off + 1], rgba[off + 2], rgba[off + 3]]
                } else {
                    [0, 0, 0, 0]
                }
            } else {
                [0, 0, 0, 0]
            }
        }
    };

    if px[3] > 0 && layer.grid.has_mask && layer.meta.mask_enabled.unwrap_or(true) {
        let m = match layer.grid.mask_tiles.get(&coord) {
            Some(mt) => match &mt.storage {
                crate::tiles::TileStorage::SolidColor { rgba8, .. } => rgba8[0],
                crate::tiles::TileStorage::Raw(buf) => buf[ly * TILE_SIZE + lx],
                _ => mt
                    .materialize_raw(scratch)
                    .map(|b| b[ly * TILE_SIZE + lx])
                    .unwrap_or(layer.grid.mask_default_value),
            },
            None => layer.grid.mask_default_value,
        };
        px[3] = ((u32::from(px[3]) * u32::from(m) + 127) / 255) as u8;
    }
    px
}

/// Instant native Eyedropper (<0.1 ms) sampling either the active layer (`sample_all_layers = false`)
/// or the full composited visible layer stack (`sample_all_layers = true`) at document pixel `(x, y)`!
pub fn pick_color_document(
    doc: &Document,
    x: i32,
    y: i32,
    sample_all_layers: bool,
    scratch: Option<&dyn ScratchBackend>,
) -> PickedColorDto {
    pick_color_document_for_layer(doc, x, y, sample_all_layers, None, scratch)
}

/// Like [`pick_color_document`], honoring an explicit `layer_id` when `sample_all_layers` is `false`.
pub fn pick_color_document_for_layer(
    doc: &Document,
    x: i32,
    y: i32,
    sample_all_layers: bool,
    layer_id: Option<&str>,
    scratch: Option<&dyn ScratchBackend>,
) -> PickedColorDto {
    let px = if x < 0
        || y < 0
        || x >= doc.dimensions.width as i32
        || y >= doc.dimensions.height as i32
    {
        [0, 0, 0, 0]
    } else if !sample_all_layers {
        let target = layer_id
            .and_then(|lid| doc.layer(lid))
            .or_else(|| doc.active_layer());
        target
            .map(|l| sample_layer_pixel(l, x, y, scratch))
            .unwrap_or([0, 0, 0, 0])
    } else {
        let mut acc = [0u8; 4];
        for layer in doc.layers.iter().rev() {
            if !layer.meta.layer_type.has_tiles()
                || !doc.is_layer_effectively_visible(&layer.meta.id)
            {
                continue;
            }
            let op = layer.meta.opacity.clamp(0.0, 1.0);
            if op <= 0.001 {
                continue;
            }
            let src = sample_layer_pixel(layer, x, y, scratch);
            if src[3] == 0 {
                continue;
            }
            compositor_cpu::blend_rgba8_over(&mut acc, &src, op, layer.meta.blend_mode);
        }
        // If fully transparent (no background layer), report clean white fallback matching InkStudio UI
        if acc[3] == 0 {
            let _ = BlendMode::Normal;
            [255, 255, 255, 0]
        } else {
            acc
        }
    };

    PickedColorDto {
        r: px[0],
        g: px[1],
        b: px[2],
        a: px[3],
        hex: format!("#{:02x}{:02x}{:02x}", px[0], px[1], px[2]),
    }
}