Skip to content

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

18.4 KB
Raw Blame
//! Pure-Rust Adjustment Layer LUT generators & GPU `256×1` `Rgba8Unorm` LUT cache.
//!
//! Matches `src/utils/tonalEngine.ts` bit-for-bit:
//! - `curves`: Fritsch-Carlson monotonic cubic spline per channel (R, G, B) composed with Master RGB
//! - `levels`: input black/white point, gamma, output min/max, optional channel (`rgb`/`r`/`g`/`b`)
//! - `gradient-map`: sorted hex color stops with `linear` or `smooth` (Hermite smoothstep) interpolation
//! - `color-balance`: shadows/midtones/highlights shifts + `preserveLuminosity`

use crate::tiles::parse_hex_rgba8;
use std::collections::HashMap;

/// Parsed non-destructive adjustment layer payload (from `LayerNodeMeta::adjustment_data`).
#[derive(Debug, Clone)]
pub enum ParsedAdjustment {
    Curves {
        rgb: Vec<(f64, f64)>,
        r: Vec<(f64, f64)>,
        g: Vec<(f64, f64)>,
        b: Vec<(f64, f64)>,
    },
    Levels {
        black_point: f64,
        white_point: f64,
        gamma: f64,
        output_min: f64,
        output_max: f64,
        channel: LevelsChannel,
    },
    GradientMap {
        stops: Vec<(f64, [u8; 3])>,
        smooth: bool,
    },
    ColorBalance {
        shadows: [f32; 3],
        midtones: [f32; 3],
        highlights: [f32; 3],
        preserve_luminosity: bool,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LevelsChannel {
    Rgb,
    R,
    G,
    B,
}

/// Parses `LayerNodeMeta::adjustment_data` JSON into [`ParsedAdjustment`].
pub fn parse_adjustment_data(val: &serde_json::Value) -> Option<ParsedAdjustment> {
    let obj = val.as_object()?;
    let adj_type = obj.get("type")?.as_str()?;
    match adj_type {
        "curves" => {
            let curves = obj.get("curves").and_then(|c| c.as_object());
            let parse_pts = |key: &str| -> Vec<(f64, f64)> {
                curves
                    .and_then(|c| c.get(key))
                    .and_then(|a| a.as_array())
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|p| {
                                let pair = p.as_array()?;
                                Some((pair.first()?.as_f64()?, pair.get(1)?.as_f64()?))
                            })
                            .collect()
                    })
                    .filter(|v: &Vec<(f64, f64)>| !v.is_empty())
                    .unwrap_or_else(|| vec![(0.0, 0.0), (255.0, 255.0)])
            };
            Some(ParsedAdjustment::Curves {
                rgb: parse_pts("rgb"),
                r: parse_pts("r"),
                g: parse_pts("g"),
                b: parse_pts("b"),
            })
        }
        "levels" => {
            let black_point = obj.get("blackPoint").and_then(|v| v.as_f64()).unwrap_or(0.0);
            let white_point = obj
                .get("whitePoint")
                .and_then(|v| v.as_f64())
                .unwrap_or(255.0);
            let gamma = obj.get("gamma").and_then(|v| v.as_f64()).unwrap_or(1.0);
            let output_min = obj.get("outputMin").and_then(|v| v.as_f64()).unwrap_or(0.0);
            let output_max = obj
                .get("outputMax")
                .and_then(|v| v.as_f64())
                .unwrap_or(255.0);
            let channel = match obj.get("channel").and_then(|v| v.as_str()) {
                Some("r") => LevelsChannel::R,
                Some("g") => LevelsChannel::G,
                Some("b") => LevelsChannel::B,
                _ => LevelsChannel::Rgb,
            };
            Some(ParsedAdjustment::Levels {
                black_point,
                white_point,
                gamma,
                output_min,
                output_max,
                channel,
            })
        }
        "gradient-map" => {
            let stops: Vec<(f64, [u8; 3])> = obj
                .get("stops")
                .and_then(|v| v.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|s| {
                            let so = s.as_object()?;
                            let pos = so.get("position").or_else(|| so.get("pos"))?.as_f64()?;
                            let hex = so.get("color")?.as_str()?;
                            let rgba = parse_hex_rgba8(hex).unwrap_or([0, 0, 0, 255]);
                            Some((pos.clamp(0.0, 1.0), [rgba[0], rgba[1], rgba[2]]))
                        })
                        .collect()
                })
                .unwrap_or_default();
            let smooth = obj
                .get("interpolation")
                .and_then(|v| v.as_str())
                .is_some_and(|s| s == "smooth");
            Some(ParsedAdjustment::GradientMap { stops, smooth })
        }
        "color-balance" => {
            let parse_triple = |key: &str| -> [f32; 3] {
                obj.get(key)
                    .and_then(|v| v.as_array())
                    .map(|a| {
                        [
                            a.first().and_then(|x| x.as_f64()).unwrap_or(0.0) as f32,
                            a.get(1).and_then(|x| x.as_f64()).unwrap_or(0.0) as f32,
                            a.get(2).and_then(|x| x.as_f64()).unwrap_or(0.0) as f32,
                        ]
                    })
                    .unwrap_or([0.0, 0.0, 0.0])
            };
            let preserve_luminosity = obj
                .get("preserveLuminosity")
                .and_then(|v| v.as_bool())
                .unwrap_or(false);
            Some(ParsedAdjustment::ColorBalance {
                shadows: parse_triple("shadows"),
                midtones: parse_triple("midtones"),
                highlights: parse_triple("highlights"),
                preserve_luminosity,
            })
        }
        _ => None,
    }
}

/// Builds a 256-entry Fritsch-Carlson monotonic cubic spline LUT (zero overshoot).
pub fn build_monotonic_cubic_spline_lut(points: &[(f64, f64)]) -> [u8; 256] {
    let mut lut = [0u8; 256];
    if points.is_empty() {
        for (i, slot) in lut.iter_mut().enumerate() {
            *slot = i as u8;
        }
        return lut;
    }

    let mut sorted = points.to_vec();
    sorted.sort_by(|a, b| a.0.total_cmp(&b.0));

    let mut unique: Vec<(f64, f64)> = Vec::with_capacity(sorted.len());
    for pt in sorted {
        if let Some(last) = unique.last_mut() {
            if (last.0 - pt.0).abs() <= f64::EPSILON {
                *last = pt;
                continue;
            }
        }
        unique.push(pt);
    }

    let n = unique.len();
    if n == 1 {
        let val = unique[0].1.round().clamp(0.0, 255.0) as u8;
        lut.fill(val);
        return lut;
    }

    let mut deltas = vec![0.0f64; n - 1];
    for k in 0..(n - 1) {
        let dx = unique[k + 1].0 - unique[k].0;
        let dy = unique[k + 1].1 - unique[k].1;
        deltas[k] = if dx == 0.0 { 0.0 } else { dy / dx };
    }

    let mut m = vec![0.0f64; n];
    m[0] = deltas[0];
    m[n - 1] = deltas[n - 2];
    for k in 1..(n - 1) {
        m[k] = (deltas[k - 1] + deltas[k]) * 0.5;
    }

    // Fritsch-Carlson monotonicity clamp
    for k in 0..(n - 1) {
        if deltas[k] == 0.0 {
            m[k] = 0.0;
            m[k + 1] = 0.0;
        } else {
            let alpha = m[k] / deltas[k];
            let beta = m[k + 1] / deltas[k];
            if alpha < 0.0 {
                m[k] = 0.0;
            }
            if beta < 0.0 {
                m[k + 1] = 0.0;
            }
            let hyp_sq = alpha * alpha + beta * beta;
            if hyp_sq > 9.0 {
                let tau = 3.0 / hyp_sq.sqrt();
                m[k] = tau * alpha * deltas[k];
                m[k + 1] = tau * beta * deltas[k];
            }
        }
    }

    for (x_idx, slot) in lut.iter_mut().enumerate() {
        let x = x_idx as f64;
        if x <= unique[0].0 {
            *slot = unique[0].1.round().clamp(0.0, 255.0) as u8;
            continue;
        }
        if x >= unique[n - 1].0 {
            *slot = unique[n - 1].1.round().clamp(0.0, 255.0) as u8;
            continue;
        }

        let mut k = 0usize;
        while k < n - 1 && x > unique[k + 1].0 {
            k += 1;
        }

        let (x0, y0) = unique[k];
        let (x1, y1) = unique[k + 1];
        let h = x1 - x0;
        let t = if h == 0.0 { 0.0 } else { (x - x0) / h };
        let t2 = t * t;
        let t3 = t2 * t;

        let h00 = 2.0 * t3 - 3.0 * t2 + 1.0;
        let h10 = t3 - 2.0 * t2 + t;
        let h01 = -2.0 * t3 + 3.0 * t2;
        let h11 = t3 - t2;

        let y = h00 * y0 + h10 * h * m[k] + h01 * y1 + h11 * h * m[k + 1];
        *slot = y.round().clamp(0.0, 255.0) as u8;
    }

    lut
}

/// Builds a 256-entry Levels LUT matching `buildLevelsLut` in `tonalEngine.ts`.
pub fn build_levels_lut(
    input_min: f64,
    input_max: f64,
    gamma: f64,
    output_min: f64,
    output_max: f64,
) -> [u8; 256] {
    let mut lut = [0u8; 256];
    let in_range = (input_max - input_min).max(1.0);
    let out_range = output_max - output_min;
    let safe_gamma = gamma.clamp(0.1, 9.99);
    let inv_gamma = 1.0 / safe_gamma;

    for (i, slot) in lut.iter_mut().enumerate() {
        let norm = ((i as f64 - input_min) / in_range).clamp(0.0, 1.0);
        let mapped = output_min + norm.powf(inv_gamma) * out_range;
        *slot = mapped.round().clamp(0.0, 255.0) as u8;
    }
    lut
}

/// Builds a 256×1 RGBA8 LUT (`1024` bytes) for a Gradient Map adjustment.
pub fn build_gradient_map_lut(stops: &[(f64, [u8; 3])], smooth: bool) -> [u8; 1024] {
    let mut out = [255u8; 1024];
    if stops.is_empty() {
        for i in 0..256 {
            let o = i * 4;
            out[o] = i as u8;
            out[o + 1] = i as u8;
            out[o + 2] = i as u8;
            out[o + 3] = 255;
        }
        return out;
    }

    let mut sorted = stops.to_vec();
    sorted.sort_by(|a, b| a.0.total_cmp(&b.0));

    for i in 0..256 {
        let t = i as f64 / 255.0;
        let o = i * 4;
        let rgb = if t <= sorted[0].0 {
            sorted[0].1
        } else if t >= sorted[sorted.len() - 1].0 {
            sorted[sorted.len() - 1].1
        } else {
            let mut s_idx = 0usize;
            while s_idx < sorted.len() - 1 && t > sorted[s_idx + 1].0 {
                s_idx += 1;
            }
            let (p0, c0) = sorted[s_idx];
            let (p1, c1) = sorted[s_idx + 1];
            let span = p1 - p0;
            let mut f = if span <= 0.0 { 0.0 } else { (t - p0) / span };
            if smooth {
                f = f * f * (3.0 - 2.0 * f);
            }
            [
                (c0[0] as f64 + (c1[0] as f64 - c0[0] as f64) * f)
                    .round()
                    .clamp(0.0, 255.0) as u8,
                (c0[1] as f64 + (c1[1] as f64 - c0[1] as f64) * f)
                    .round()
                    .clamp(0.0, 255.0) as u8,
                (c0[2] as f64 + (c1[2] as f64 - c0[2] as f64) * f)
                    .round()
                    .clamp(0.0, 255.0) as u8,
            ]
        };
        out[o] = rgb[0];
        out[o + 1] = rgb[1];
        out[o + 2] = rgb[2];
        out[o + 3] = 255;
    }
    out
}

/// Evaluates a single Color Balance pixel matching `evaluateColorBalancePixel` in `tonalEngine.ts`.
pub fn evaluate_color_balance_pixel(
    r: u8,
    g: u8,
    b: u8,
    shadows: [f32; 3],
    midtones: [f32; 3],
    highlights: [f32; 3],
    preserve_luminosity: bool,
) -> [u8; 3] {
    let rf = r as f32;
    let gf = g as f32;
    let bf = b as f32;
    let lum = (0.299 * rf + 0.587 * gf + 0.114 * bf) / 255.0;

    let w_shad = (1.0 - lum * 2.0).max(0.0).powi(2);
    let w_high = (lum * 2.0 - 1.0).max(0.0).powi(2);
    let w_mid = (1.0 - w_shad - w_high).max(0.0);

    let dr = (shadows[0] * w_shad + midtones[0] * w_mid + highlights[0] * w_high) * 1.28;
    let dg = (shadows[1] * w_shad + midtones[1] * w_mid + highlights[1] * w_high) * 1.28;
    let db = (shadows[2] * w_shad + midtones[2] * w_mid + highlights[2] * w_high) * 1.28;

    let mut nr = (rf + dr).clamp(0.0, 255.0);
    let mut ng = (gf + dg).clamp(0.0, 255.0);
    let mut nb = (bf + db).clamp(0.0, 255.0);

    if preserve_luminosity {
        let orig_lum = lum * 255.0;
        let new_lum = 0.299 * nr + 0.587 * ng + 0.114 * nb;
        if new_lum > 0.001 {
            let scale = orig_lum / new_lum;
            nr = (nr * scale).clamp(0.0, 255.0);
            ng = (ng * scale).clamp(0.0, 255.0);
            nb = (nb * scale).clamp(0.0, 255.0);
        }
    }

    [nr.round() as u8, ng.round() as u8, nb.round() as u8]
}

/// Builds the 256×1 RGBA8 LUT bytes and returns `(adj_mode, lut_bytes)`:
/// - `0`: per-channel LUT (`curves`, `levels`)
/// - `1`: luminance LUT (`gradient-map`)
/// - `2`: analytic color-balance (also populates a neutral LUT fallback)
pub fn build_adjustment_lut_rgba8(adj: &ParsedAdjustment) -> (u32, [u8; 1024]) {
    let mut out = [255u8; 1024];
    match adj {
        ParsedAdjustment::Curves { rgb, r, g, b } => {
            let master = build_monotonic_cubic_spline_lut(rgb);
            let rl = build_monotonic_cubic_spline_lut(r);
            let gl = build_monotonic_cubic_spline_lut(g);
            let bl = build_monotonic_cubic_spline_lut(b);
            for i in 0..256 {
                let o = i * 4;
                out[o] = master[rl[i] as usize];
                out[o + 1] = master[gl[i] as usize];
                out[o + 2] = master[bl[i] as usize];
                out[o + 3] = 255;
            }
            (0, out)
        }
        ParsedAdjustment::Levels {
            black_point,
            white_point,
            gamma,
            output_min,
            output_max,
            channel,
        } => {
            let l = build_levels_lut(*black_point, *white_point, *gamma, *output_min, *output_max);
            for (i, &lv) in l.iter().enumerate() {
                let o = i * 4;
                let id = i as u8;
                out[o] = match channel {
                    LevelsChannel::Rgb | LevelsChannel::R => lv,
                    _ => id,
                };
                out[o + 1] = match channel {
                    LevelsChannel::Rgb | LevelsChannel::G => lv,
                    _ => id,
                };
                out[o + 2] = match channel {
                    LevelsChannel::Rgb | LevelsChannel::B => lv,
                    _ => id,
                };
                out[o + 3] = 255;
            }
            (0, out)
        }
        ParsedAdjustment::GradientMap { stops, smooth } => {
            (1, build_gradient_map_lut(stops, *smooth))
        }
        ParsedAdjustment::ColorBalance {
            shadows,
            midtones,
            highlights,
            preserve_luminosity,
        } => {
            for i in 0..256 {
                let [r, g, b] = evaluate_color_balance_pixel(
                    i as u8,
                    i as u8,
                    i as u8,
                    *shadows,
                    *midtones,
                    *highlights,
                    *preserve_luminosity,
                );
                let o = i * 4;
                out[o] = r;
                out[o + 1] = g;
                out[o + 2] = b;
                out[o + 3] = 255;
            }
            (2, out)
        }
    }
}

static NEXT_LUT_VIEW_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);

/// GPU 256×1 `Rgba8Unorm` LUT texture cache keyed per adjustment layer ID & content hash.
pub struct CachedLutEntry {
    pub texture: wgpu::Texture,
    pub view: wgpu::TextureView,
    pub view_id: u64,
    pub hash: u64,
    pub adj_mode: u32,
}

#[derive(Default)]
pub struct AdjustmentLutCache {
    entries: HashMap<String, CachedLutEntry>,
}

impl AdjustmentLutCache {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn get_or_update(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        layer_id: &str,
        adj_hash: u64,
        parsed: &ParsedAdjustment,
    ) -> &CachedLutEntry {
        let needs_upload = match self.entries.get(layer_id) {
            Some(e) => e.hash != adj_hash,
            None => true,
        };

        if !self.entries.contains_key(layer_id) {
            let texture = device.create_texture(&wgpu::TextureDescriptor {
                label: Some("ink-adj-lut-256x1"),
                size: wgpu::Extent3d {
                    width: 256,
                    height: 1,
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: wgpu::TextureFormat::Rgba8Unorm,
                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
                view_formats: &[],
            });
            let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
            self.entries.insert(
                layer_id.to_string(),
                CachedLutEntry {
                    texture,
                    view,
                    view_id: NEXT_LUT_VIEW_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
                    hash: u64::MAX,
                    adj_mode: 0,
                },
            );
        }

        let entry = self.entries.get_mut(layer_id).expect("entry inserted");
        if needs_upload {
            let (adj_mode, bytes) = build_adjustment_lut_rgba8(parsed);
            queue.write_texture(
                wgpu::TexelCopyTextureInfo {
                    texture: &entry.texture,
                    mip_level: 0,
                    origin: wgpu::Origin3d::ZERO,
                    aspect: wgpu::TextureAspect::All,
                },
                &bytes,
                wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(256 * 4), // 1024 bytes (aligned to 256!)
                    rows_per_image: Some(1),
                },
                wgpu::Extent3d {
                    width: 256,
                    height: 1,
                    depth_or_array_layers: 1,
                },
            );
            entry.hash = adj_hash;
            entry.adj_mode = adj_mode;
        }
        entry
    }

    pub fn get_view(&self, layer_id: &str) -> Option<&wgpu::TextureView> {
        self.entries.get(layer_id).map(|e| &e.view)
    }

    pub fn get_view_with_id(&self, layer_id: &str) -> Option<(&wgpu::TextureView, u64)> {
        self.entries.get(layer_id).map(|e| (&e.view, e.view_id))
    }

    pub fn retain_layers(&mut self, valid_ids: &std::collections::HashSet<&str>) {
        self.entries.retain(|k, _| valid_ids.contains(k.as_str()));
    }

    pub fn clear(&mut self) {
        self.entries.clear();
    }
}