Skip to content

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

20.5 KB
Raw Blame
//! Sparse-tile software compositor for 64×64 layer/mask thumbnails, `.ink` previews,
//! timelapse keyframes (`720p`/`1080p`/`2k`/`4k`), and CPU layer merges.
//!
//! Operates directly on populated sparse tiles without allocating full-resolution canvases
//! when rendering downscaled thumbnails or previews.

use crate::document::{BlendMode, Document, LayerNode, LayerType};
use crate::memory::ScratchBackend;
use crate::tiles::{
    parse_hex_rgba8, RectI32, TileCoord, TileData, TileStorage, TILE_SIZE, TILE_SIZE_I32,
};
use std::collections::HashMap;
use std::sync::Arc;

#[inline]
fn blend_channel(mode: BlendMode, cb: f32, cs: f32) -> f32 {
    match mode {
        BlendMode::Normal | BlendMode::PassThrough => cs,
        BlendMode::Multiply => cb * cs,
        BlendMode::Screen => cb + cs - cb * cs,
        BlendMode::Overlay => {
            if cb <= 0.5 {
                2.0 * cb * cs
            } else {
                1.0 - 2.0 * (1.0 - cb) * (1.0 - cs)
            }
        }
        BlendMode::Darken | BlendMode::DarkerColor => cb.min(cs),
        BlendMode::Lighten | BlendMode::LighterColor => cb.max(cs),
        BlendMode::ColorDodge | BlendMode::ColorDodgeGlow => {
            if cs >= 0.999 {
                1.0
            } else {
                (cb / (1.0 - cs)).min(1.0)
            }
        }
        BlendMode::ColorBurn => {
            if cs <= 0.001 {
                0.0
            } else {
                (1.0 - ((1.0 - cb) / cs).min(1.0)).max(0.0)
            }
        }
        BlendMode::LinearBurn => (cb + cs - 1.0).max(0.0),
        BlendMode::AddGlow => (cb + cs).min(1.0),
        BlendMode::HardLight => {
            if cs <= 0.5 {
                2.0 * cb * cs
            } else {
                1.0 - 2.0 * (1.0 - cb) * (1.0 - cs)
            }
        }
        BlendMode::SoftLight => {
            if cs <= 0.5 {
                cb - (1.0 - 2.0 * cs) * cb * (1.0 - cb)
            } else {
                let d = if cb <= 0.25 {
                    ((16.0 * cb - 12.0) * cb + 4.0) * cb
                } else {
                    cb.sqrt()
                };
                cb + (2.0 * cs - 1.0) * (d - cb)
            }
        }
        BlendMode::Difference => (cb - cs).abs(),
        BlendMode::Exclusion => cb + cs - 2.0 * cb * cs,
        BlendMode::Subtract => (cb - cs).max(0.0),
        BlendMode::Divide => {
            if cs <= 0.001 {
                1.0
            } else {
                (cb / cs).min(1.0)
            }
        }
        BlendMode::VividLight => {
            if cs <= 0.5 {
                let s2 = (2.0 * cs).max(0.001);
                (1.0 - (1.0 - cb) / s2).clamp(0.0, 1.0)
            } else {
                let s2 = (2.0 * (1.0 - cs)).max(0.001);
                (cb / s2).clamp(0.0, 1.0)
            }
        }
        BlendMode::LinearLight => (cb + 2.0 * cs - 1.0).clamp(0.0, 1.0),
        BlendMode::PinLight => {
            if cs <= 0.5 {
                cb.min(2.0 * cs)
            } else {
                cb.max(2.0 * cs - 1.0)
            }
        }
        BlendMode::HardMix => {
            if cb + cs >= 1.0 {
                1.0
            } else {
                0.0
            }
        }
        BlendMode::Hue | BlendMode::Saturation | BlendMode::Color | BlendMode::Luminosity => cs,
    }
}

/// Composites straight-alpha `src` over straight-alpha `dst` using `opacity` and `blend_mode`.
pub fn blend_rgba8_over(dst: &mut [u8], src: &[u8], opacity: f32, mode: BlendMode) {
    let op = opacity.clamp(0.0, 1.0);
    if op <= 0.001 {
        return;
    }
    for (d, s) in dst.chunks_exact_mut(4).zip(src.chunks_exact(4)) {
        let sa = (s[3] as f32 / 255.0) * op;
        if sa <= 0.001 {
            continue;
        }
        let da = d[3] as f32 / 255.0;
        let sr = s[0] as f32 / 255.0;
        let sg = s[1] as f32 / 255.0;
        let sb = s[2] as f32 / 255.0;

        if da <= 0.001 {
            d[0] = s[0];
            d[1] = s[1];
            d[2] = s[2];
            d[3] = (sa * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
            continue;
        }

        let dr = d[0] as f32 / 255.0;
        let dg = d[1] as f32 / 255.0;
        let db = d[2] as f32 / 255.0;

        let br = blend_channel(mode, dr, sr);
        let bg = blend_channel(mode, dg, sg);
        let bb = blend_channel(mode, db, sb);

        let out_a = sa + da * (1.0 - sa);
        if out_a <= 1e-5 {
            d.fill(0);
            continue;
        }

        // Standard W3C Compositing & Blending Level 1 formula
        let cr = (1.0 - sa) * da * dr + (1.0 - da) * sa * sr + da * sa * br;
        let cg = (1.0 - sa) * da * dg + (1.0 - da) * sa * sg + da * sa * bg;
        let cb = (1.0 - sa) * da * db + (1.0 - da) * sa * sb + da * sa * bb;

        d[0] = ((cr / out_a) * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
        d[1] = ((cg / out_a) * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
        d[2] = ((cb / out_a) * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
        d[3] = (out_a * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
    }
}

/// Computes aspect-ratio-preserving thumbnail dimensions fitting within `(max_w, max_h)`.
pub fn fit_thumbnail_dims(doc_w: u32, doc_h: u32, max_w: u32, max_h: u32) -> (u32, u32) {
    let dw = doc_w.max(1) as f64;
    let dh = doc_h.max(1) as f64;
    let scale = (max_w.max(1) as f64 / dw).min(max_h.max(1) as f64 / dh).min(1.0);
    let tw = (dw * scale).round().max(1.0) as u32;
    let th = (dh * scale).round().max(1.0) as u32;
    (tw, th)
}

/// Extracts optional two-tone layer tint `(primary_rgba8, sub_rgba8)` from a `LayerNode`.
pub fn extract_layer_tint(layer: &LayerNode) -> Option<([u8; 4], [u8; 4])> {
    if layer.meta.layer_color_enabled.unwrap_or(false) {
        let primary = layer
            .meta
            .layer_color
            .as_deref()
            .and_then(parse_hex_rgba8)
            .unwrap_or([28, 115, 194, 255]);
        let sub = layer
            .meta
            .layer_sub_color
            .as_deref()
            .and_then(parse_hex_rgba8)
            .unwrap_or([255, 255, 255, 255]);
        Some((primary, sub))
    } else {
        None
    }
}

/// Renders a downscaled RGBA8 thumbnail directly from a layer's populated sparse tiles
/// (zero full-canvas intermediate buffer!).
pub fn render_layer_thumbnail_rgba(
    layer: &LayerNode,
    doc_w: u32,
    doc_h: u32,
    max_w: u32,
    max_h: u32,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<(u32, u32, Vec<u8>), String> {
    render_layer_thumbnail_rgba_from_tiles(
        &layer.grid.tiles,
        extract_layer_tint(layer),
        doc_w,
        doc_h,
        max_w,
        max_h,
        scratch,
    )
}

/// Renders a downscaled RGBA8 thumbnail directly from a zero-copy `Arc<TileData>` snapshot
/// (safe to run completely off the DX12 render thread without holding any document locks!).
pub fn render_layer_thumbnail_rgba_from_tiles(
    tiles: &HashMap<TileCoord, Arc<TileData>>,
    tint: Option<([u8; 4], [u8; 4])>,
    doc_w: u32,
    doc_h: u32,
    max_w: u32,
    max_h: u32,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<(u32, u32, Vec<u8>), String> {
    let (tw, th) = fit_thumbnail_dims(doc_w, doc_h, max_w, max_h);
    let mut out = vec![0u8; (tw as usize) * (th as usize) * 4];
    if tiles.is_empty() || doc_w == 0 || doc_h == 0 {
        return Ok((tw, th, out));
    }

    let scale_x = tw as f64 / doc_w as f64;
    let scale_y = th as f64 / doc_h as f64;

    // Accumulate premultiplied RGBA + coverage weight per thumbnail pixel directly from populated tiles
    let pixel_count = (tw as usize) * (th as usize);
    let mut acc_r = vec![0.0f32; pixel_count];
    let mut acc_g = vec![0.0f32; pixel_count];
    let mut acc_b = vec![0.0f32; pixel_count];
    let mut acc_a = vec![0.0f32; pixel_count];
    let mut acc_w = vec![0.0f32; pixel_count];

    for (&coord, tile) in tiles {
        let tile_x0 = coord.tx * TILE_SIZE_I32;
        let tile_y0 = coord.ty * TILE_SIZE_I32;
        let tile_x1 = tile_x0 + TILE_SIZE_I32;
        let tile_y1 = tile_y0 + TILE_SIZE_I32;
        if tile_x1 <= 0 || tile_y1 <= 0 || tile_x0 >= doc_w as i32 || tile_y0 >= doc_h as i32 {
            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 start_lx >= end_lx || start_ly >= end_ly {
            continue;
        }

        // Stride sampling for huge canvases (keeps 600 DPI 70MP thumbnail under 1ms!)
        let stride_x = ((doc_w as usize) / (tw as usize * 2)).max(1);
        let stride_y = ((doc_h as usize) / (th as usize * 2)).max(1);

        if let TileStorage::SolidColor { rgba8, .. } = tile.storage {
            if rgba8[3] == 0 {
                continue;
            }
            let c = apply_layer_color_tint(rgba8, tint);
            let a = c[3] as f32 / 255.0;
            let pr = (c[0] as f32 / 255.0) * a;
            let pg = (c[1] as f32 / 255.0) * a;
            let pb = (c[2] as f32 / 255.0) * a;

            let ty_start = (((tile_y0 + start_ly as i32) as f64) * scale_y).floor().max(0.0) as usize;
            let ty_end = (((tile_y0 + end_ly as i32) as f64) * scale_y)
                .ceil()
                .min(th as f64) as usize;
            let tx_start = (((tile_x0 + start_lx as i32) as f64) * scale_x).floor().max(0.0) as usize;
            let tx_end = (((tile_x0 + end_lx as i32) as f64) * scale_x)
                .ceil()
                .min(tw as f64) as usize;
            for py in ty_start..ty_end {
                for px in tx_start..tx_end {
                    let idx = py * (tw as usize) + px;
                    acc_r[idx] += pr;
                    acc_g[idx] += pg;
                    acc_b[idx] += pb;
                    acc_a[idx] += a;
                    acc_w[idx] += 1.0;
                }
            }
            continue;
        }

        let tile_rgba = tile.to_rgba8(scratch, false)?;
        let mut ly = start_ly;
        while ly < end_ly {
            let doc_y = (tile_y0 + ly as i32) as f64;
            let py = (doc_y * scale_y).floor().clamp(0.0, (th - 1) as f64) as usize;
            let mut lx = start_lx;
            while lx < end_lx {
                let doc_x = (tile_x0 + lx as i32) as f64;
                let px = (doc_x * scale_x).floor().clamp(0.0, (tw - 1) as f64) as usize;
                let off = (ly * TILE_SIZE + lx) * 4;
                let raw_px = [
                    tile_rgba[off],
                    tile_rgba[off + 1],
                    tile_rgba[off + 2],
                    tile_rgba[off + 3],
                ];
                let idx = py * (tw as usize) + px;
                acc_w[idx] += 1.0;
                if raw_px[3] > 0 {
                    let c = apply_layer_color_tint(raw_px, tint);
                    let a = c[3] as f32 / 255.0;
                    acc_r[idx] += (c[0] as f32 / 255.0) * a;
                    acc_g[idx] += (c[1] as f32 / 255.0) * a;
                    acc_b[idx] += (c[2] as f32 / 255.0) * a;
                    acc_a[idx] += a;
                }
                lx += stride_x;
            }
            ly += stride_y;
        }
    }

    for i in 0..pixel_count {
        let w = acc_w[i];
        if w <= 0.0 || acc_a[i] <= 1e-4 {
            continue;
        }
        let avg_a = (acc_a[i] / w).clamp(0.0, 1.0);
        let off = i * 4;
        out[off] = ((acc_r[i] / acc_a[i]) * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
        out[off + 1] = ((acc_g[i] / acc_a[i]) * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
        out[off + 2] = ((acc_b[i] / acc_a[i]) * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
        out[off + 3] = (avg_a * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
    }

    Ok((tw, th, out))
}

/// Renders a downscaled RGBA8 thumbnail of a layer's non-destructive 8-bit mask.
pub fn render_mask_thumbnail_rgba(
    layer: &LayerNode,
    doc_w: u32,
    doc_h: u32,
    max_w: u32,
    max_h: u32,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<(u32, u32, Vec<u8>), String> {
    render_mask_thumbnail_rgba_from_tiles(
        &layer.grid.mask_tiles,
        layer.grid.mask_default_value,
        doc_w,
        doc_h,
        max_w,
        max_h,
        scratch,
    )
}

/// Renders a downscaled RGBA8 mask thumbnail directly from a zero-copy `Arc<TileData>` snapshot.
pub fn render_mask_thumbnail_rgba_from_tiles(
    mask_tiles: &HashMap<TileCoord, Arc<TileData>>,
    mask_default_value: u8,
    doc_w: u32,
    doc_h: u32,
    max_w: u32,
    max_h: u32,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<(u32, u32, Vec<u8>), String> {
    let (tw, th) = fit_thumbnail_dims(doc_w, doc_h, max_w, max_h);
    let mut out = vec![0u8; (tw as usize) * (th as usize) * 4];
    if doc_w == 0 || doc_h == 0 {
        return Ok((tw, th, out));
    }

    // Materialize populated mask tiles once so pixel lookups are O(1)
    let mut materialized: HashMap<TileCoord, Vec<u8>> = HashMap::with_capacity(mask_tiles.len());
    for (&coord, tile) in mask_tiles {
        if let Ok(raw) = tile.materialize_raw(scratch) {
            materialized.insert(coord, raw);
        }
    }

    for py in 0..th {
        let doc_y = ((py as f64 + 0.5) * (doc_h as f64 / th as f64))
            .floor()
            .clamp(0.0, (doc_h.saturating_sub(1)) as f64) as i32;
        let ty = doc_y.div_euclid(TILE_SIZE_I32);
        let ly = doc_y.rem_euclid(TILE_SIZE_I32) as usize;
        for px in 0..tw {
            let doc_x = ((px as f64 + 0.5) * (doc_w as f64 / tw as f64))
                .floor()
                .clamp(0.0, (doc_w.saturating_sub(1)) as f64) as i32;
            let tx = doc_x.div_euclid(TILE_SIZE_I32);
            let lx = doc_x.rem_euclid(TILE_SIZE_I32) as usize;
            let v = materialized
                .get(&TileCoord::new(tx, ty))
                .and_then(|raw| raw.get(ly * TILE_SIZE + lx).copied())
                .unwrap_or(mask_default_value);
            let off = ((py * tw + px) as usize) * 4;
            out[off] = v;
            out[off + 1] = v;
            out[off + 2] = v;
            out[off + 3] = 255;
        }
    }
    Ok((tw, th, out))
}

/// Composites all visible layers of `doc` into a downscaled RGBA8 buffer fitting within `max_dim`
/// (with even dimensions when `max_dim >= 2` for video/timelapse encoder friendliness).
pub fn composite_document_downscaled_rgba(
    doc: &Document,
    max_dim: u32,
    fill_white_bg: bool,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<(u32, u32, Vec<u8>), String> {
    let (out_w, out_h) = fit_thumbnail_dims(
        doc.dimensions.width,
        doc.dimensions.height,
        max_dim,
        max_dim,
    );
    let mut canvas = vec![0u8; (out_w as usize) * (out_h as usize) * 4];
    if fill_white_bg {
        for px in canvas.chunks_exact_mut(4) {
            px.copy_from_slice(&[255, 255, 255, 255]);
        }
    }

    // Iterate bottom-to-top (reverse of InkStudio's top-to-bottom stack)
    let mut last_base_alpha: Option<Vec<u8>> = None;
    for layer in doc.layers.iter().rev() {
        if layer.meta.layer_type.is_folder_like() || layer.meta.layer_type == LayerType::Adjustment
        {
            continue;
        }
        if !doc.is_layer_effectively_visible(&layer.meta.id) {
            if !layer.meta.clipped.unwrap_or(false) {
                last_base_alpha = None;
            }
            continue;
        }
        let eff_opacity = doc.effective_opacity(&layer.meta.id);
        if eff_opacity <= 0.001 || layer.grid.tiles.is_empty() {
            if !layer.meta.clipped.unwrap_or(false) {
                last_base_alpha = Some(vec![0u8; (out_w as usize) * (out_h as usize)]);
            }
            continue;
        }

        let (_, _, mut layer_rgba) = render_layer_thumbnail_rgba(
            layer,
            doc.dimensions.width,
            doc.dimensions.height,
            out_w,
            out_h,
            scratch,
        )?;

        // Apply non-destructive 8-bit layer mask
        if layer.grid.has_mask && layer.meta.mask_enabled.unwrap_or(true) {
            let (_, _, mask_rgba) = render_mask_thumbnail_rgba(
                layer,
                doc.dimensions.width,
                doc.dimensions.height,
                out_w,
                out_h,
                scratch,
            )?;
            for (px, mpx) in layer_rgba
                .chunks_exact_mut(4)
                .zip(mask_rgba.chunks_exact(4))
            {
                px[3] = ((u32::from(px[3]) * u32::from(mpx[0]) + 127) / 255) as u8;
            }
        }

        // Clip to base layer alpha if `clipped == true`
        if layer.meta.clipped.unwrap_or(false) {
            if let Some(ref base_a) = last_base_alpha {
                for (px, &ba) in layer_rgba.chunks_exact_mut(4).zip(base_a.iter()) {
                    px[3] = ((u32::from(px[3]) * u32::from(ba) + 127) / 255) as u8;
                }
            } else {
                continue;
            }
        } else {
            last_base_alpha = Some(
                layer_rgba
                    .chunks_exact(4)
                    .map(|px| px[3])
                    .collect(),
            );
        }

        blend_rgba8_over(&mut canvas, &layer_rgba, eff_opacity, layer.meta.blend_mode);
    }

    Ok((out_w, out_h, canvas))
}

/// Composites a full-resolution RGBA8 document buffer (used for exact rendering sync & tests).
pub fn composite_document_full_rgba(
    doc: &Document,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<Vec<u8>, String> {
    let w = doc.dimensions.width;
    let h = doc.dimensions.height;
    let rect = RectI32::new(0, 0, w, h);
    let mut out = vec![0u8; (w as usize) * (h as usize) * 4];
    let mut last_base_alpha: Option<Vec<u8>> = None;

    for layer in doc.layers.iter().rev() {
        if layer.meta.layer_type.is_folder_like() || layer.meta.layer_type == LayerType::Adjustment
        {
            continue;
        }
        if !doc.is_layer_effectively_visible(&layer.meta.id) {
            if !layer.meta.clipped.unwrap_or(false) {
                last_base_alpha = None;
            }
            continue;
        }
        let eff_opacity = doc.effective_opacity(&layer.meta.id);
        if eff_opacity <= 0.001 || layer.grid.tiles.is_empty() {
            if !layer.meta.clipped.unwrap_or(false) {
                last_base_alpha = Some(vec![0u8; (w as usize) * (h as usize)]);
            }
            continue;
        }

        let mut layer_rgba = layer.grid.read_rgba8_rect(rect, false, scratch)?;
        if layer.meta.layer_color_enabled.unwrap_or(false) {
            let primary = layer
                .meta
                .layer_color
                .as_deref()
                .and_then(parse_hex_rgba8)
                .unwrap_or([28, 115, 194, 255]);
            let sub = layer
                .meta
                .layer_sub_color
                .as_deref()
                .and_then(parse_hex_rgba8)
                .unwrap_or([255, 255, 255, 255]);
            for px in layer_rgba.chunks_exact_mut(4) {
                if px[3] > 0 {
                    let c = apply_layer_color_tint([px[0], px[1], px[2], px[3]], Some((primary, sub)));
                    px.copy_from_slice(&c);
                }
            }
        }
        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 layer_rgba.chunks_exact_mut(4).zip(mask.iter()) {
                px[3] = ((u32::from(px[3]) * u32::from(m) + 127) / 255) as u8;
            }
        }
        if layer.meta.clipped.unwrap_or(false) {
            if let Some(ref base_a) = last_base_alpha {
                for (px, &ba) in layer_rgba.chunks_exact_mut(4).zip(base_a.iter()) {
                    px[3] = ((u32::from(px[3]) * u32::from(ba) + 127) / 255) as u8;
                }
            } else {
                continue;
            }
        } else {
            last_base_alpha = Some(layer_rgba.chunks_exact(4).map(|px| px[3]).collect());
        }

        blend_rgba8_over(&mut out, &layer_rgba, eff_opacity, layer.meta.blend_mode);
    }

    Ok(out)
}

#[inline]
fn apply_layer_color_tint(px: [u8; 4], tint: Option<([u8; 4], [u8; 4])>) -> [u8; 4] {
    let Some((primary, sub)) = tint else {
        return px;
    };
    let lum = (u32::from(px[0]) * 299 + u32::from(px[1]) * 587 + u32::from(px[2]) * 114) as f32
        / 255_000.0;
    let r = (primary[0] as f32 * (1.0 - lum) + sub[0] as f32 * lum + 0.5).clamp(0.0, 255.0) as u8;
    let g = (primary[1] as f32 * (1.0 - lum) + sub[1] as f32 * lum + 0.5).clamp(0.0, 255.0) as u8;
    let b = (primary[2] as f32 * (1.0 - lum) + sub[2] as f32 * lum + 0.5).clamp(0.0, 255.0) as u8;
    [r, g, b, px[3]]
}