Skip to content

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

22.9 KB
Raw Blame
//! GPU Brush Tip & Paper Grain Texture Cache (`tip_cache.rs`).
//!
//! - Stores uploaded custom tips (`.sut`, `.inkb`, PNG/RGBA8) & built-in procedural tips
//!   keyed by content hash (`String`), so tips upload once and stay resident in GPU memory.
//! - Assembles multi-subTip sets (`Vec<String>`) into a single `wgpu::Texture` `D2Array`
//!   (resizing heterogeneous sub-tips cleanly into a shared slot dimension if needed) so an
//!   entire multi-tip stroke binds ONE `texture_2d_array<f32>` with zero draw-call breaks.
//! - Manages seamless 512×512 surface heightfields & custom paper grain textures with repeat sampling.

use super::procedural_tips::{generate_builtin_paper_texture, generate_builtin_tip};
use crate::io::png_codec::decode_png_rgba8;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};

static NEXT_TIP_CACHE_TEX_ID: AtomicU64 = AtomicU64::new(1);

/// Kind of uploaded brush image asset.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BrushTextureKind {
    Tip,
    Paper,
}

#[derive(Debug, Clone)]
struct CpuImageAsset {
    width: u32,
    height: u32,
    rgba8: Vec<u8>,
}

/// GPU-resident tip set (`texture_2d_array<f32>` of `1..=N` sub-tips).
pub struct GpuTipArray {
    pub id: u64,
    pub texture: wgpu::Texture,
    pub view: wgpu::TextureView,
    pub width: u32,
    pub height: u32,
    pub layer_count: u32,
    pub aspect_w_over_h: f32,
}

/// GPU-resident seamless paper / surface texture (`texture_2d<f32>`).
pub struct GpuPaperTexture {
    pub id: u64,
    pub texture: wgpu::Texture,
    pub view: wgpu::TextureView,
    pub width: u32,
    pub height: u32,
}

const MAX_GPU_TIP_ARRAYS: usize = 64;
const MAX_GPU_PAPERS: usize = 32;

/// Manages content-hashed CPU+GPU caches for brush tips, sub-tip arrays, and paper textures
/// with true LRU eviction (zero full-cache `.clear()` hitches).
pub struct TipTextureCache {
    /// Raw uploaded / lazily-generated single images keyed by content hash or built-in key.
    cpu_tips: HashMap<String, CpuImageAsset>,
    /// Assembled GPU `D2Array` tip sets keyed by canonical joined key list + monotonic LRU tick.
    gpu_tip_arrays: HashMap<String, (GpuTipArray, u64)>,
    /// GPU paper textures keyed by content hash or `SurfaceTextureId` + monotonic LRU tick.
    gpu_papers: HashMap<String, (GpuPaperTexture, u64)>,
    /// Monotonic access clock for LRU eviction.
    lru_clock: u64,
    /// Always-valid fallback 1×1 white tip `D2Array` (1 layer).
    fallback_tip: GpuTipArray,
    /// Always-valid default 512×512 cold-press paper texture.
    default_paper: GpuPaperTexture,
}

impl TipTextureCache {
    pub fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self {
        let fallback_tip =
            Self::upload_tip_array(device, queue, 1, 1, &[vec![255, 255, 255, 255]]);
        let (pw, ph, pdata) = generate_builtin_paper_texture("default")
            .expect("built-in default cold-press paper texture");
        let default_paper = Self::upload_paper_2d(device, queue, pw, ph, &pdata);

        Self {
            cpu_tips: HashMap::new(),
            gpu_tip_arrays: HashMap::new(),
            gpu_papers: HashMap::new(),
            lru_clock: 1,
            fallback_tip,
            default_paper,
        }
    }

    #[inline]
    fn next_lru_tick(&mut self) -> u64 {
        let t = self.lru_clock;
        self.lru_clock = self.lru_clock.wrapping_add(1);
        t
    }

    fn evict_lru_tip_arrays_if_needed(&mut self) {
        while self.gpu_tip_arrays.len() >= MAX_GPU_TIP_ARRAYS {
            if let Some(oldest_key) = self
                .gpu_tip_arrays
                .iter()
                .min_by_key(|(_, (_, tick))| *tick)
                .map(|(k, _)| k.clone())
            {
                self.gpu_tip_arrays.remove(&oldest_key);
            } else {
                break;
            }
        }
    }

    fn evict_lru_papers_if_needed(&mut self) {
        while self.gpu_papers.len() >= MAX_GPU_PAPERS {
            if let Some(oldest_key) = self
                .gpu_papers
                .iter()
                .min_by_key(|(_, (_, tick))| *tick)
                .map(|(k, _)| k.clone())
            {
                self.gpu_papers.remove(&oldest_key);
            } else {
                break;
            }
        }
    }

    pub fn fallback_tip(&self) -> &GpuTipArray {
        &self.fallback_tip
    }

    pub fn default_paper(&self) -> &GpuPaperTexture {
        &self.default_paper
    }

    /// True if `hash` is already resident in the requested cache (avoids redundant uploads).
    pub fn contains(&self, hash: &str, kind: BrushTextureKind) -> bool {
        match kind {
            BrushTextureKind::Tip => self.cpu_tips.contains_key(hash),
            BrushTextureKind::Paper => self.gpu_papers.contains_key(hash),
        }
    }

    /// Uploads a raw RGBA8 texture asset by content hash.
    #[allow(clippy::too_many_arguments)]
    pub fn upload_rgba8(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        hash: String,
        kind: BrushTextureKind,
        width: u32,
        height: u32,
        rgba8: Vec<u8>,
    ) -> Result<(), String> {
        let expected = (width as usize)
            .checked_mul(height as usize)
            .and_then(|n| n.checked_mul(4))
            .ok_or_else(|| "Texture size overflow".to_string())?;
        if width == 0 || height == 0 || rgba8.len() != expected {
            return Err(format!(
                "Invalid RGBA8 texture dimensions {}x{} for {} bytes",
                width,
                height,
                rgba8.len()
            ));
        }

        match kind {
            BrushTextureKind::Tip => {
                // Evict only the least-recently-used assembled tip array if at capacity (never .clear()!)
                self.evict_lru_tip_arrays_if_needed();
                self.cpu_tips.insert(
                    hash,
                    CpuImageAsset {
                        width,
                        height,
                        rgba8,
                    },
                );
            }
            BrushTextureKind::Paper => {
                if !self.gpu_papers.contains_key(&hash) {
                    self.evict_lru_papers_if_needed();
                }
                let tick = self.next_lru_tick();
                let gpu = Self::upload_paper_2d(device, queue, width, height, &rgba8);
                self.gpu_papers.insert(hash, (gpu, tick));
            }
        }
        Ok(())
    }

    /// Decodes a PNG byte slice natively in Rust and caches it by content hash.
    pub fn upload_png(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        hash: String,
        kind: BrushTextureKind,
        png_bytes: &[u8],
    ) -> Result<(u32, u32), String> {
        let (w, h, rgba8) = decode_png_rgba8(png_bytes)?;
        self.upload_rgba8(device, queue, hash, kind, w, h, rgba8)?;
        Ok((w, h))
    }

    /// Resolves a list of tip keys (1 single tip or N sub-tips) into a GPU `D2Array`.
    /// Returns `(is_textured, &GpuTipArray)`.
    pub fn resolve_tip_set(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        primary_tip: Option<&str>,
        sub_tips: &[String],
    ) -> (bool, &GpuTipArray) {
        let mut keys: Vec<&str> = Vec::new();
        if !sub_tips.is_empty() {
            for k in sub_tips {
                if !k.is_empty() {
                    keys.push(k.as_str());
                }
            }
        } else if let Some(pk) = primary_tip {
            if !pk.is_empty() {
                keys.push(pk);
            }
        }

        if keys.is_empty() {
            return (false, &self.fallback_tip);
        }

        let joined_key = keys.join("|");
        if self.gpu_tip_arrays.contains_key(&joined_key) {
            let tick = self.next_lru_tick();
            let entry = self.gpu_tip_arrays.get_mut(&joined_key).unwrap();
            entry.1 = tick;
            return (true, &entry.0);
        }

        // Ensure every requested key is loaded (either uploaded or lazily generated built-in)
        let mut images: Vec<CpuImageAsset> = Vec::with_capacity(keys.len());
        for &k in &keys {
            if let Some(asset) = self.cpu_tips.get(k) {
                images.push(asset.clone());
            } else if let Some((w, h, rgba8)) = generate_builtin_tip(k) {
                let asset = CpuImageAsset {
                    width: w,
                    height: h,
                    rgba8,
                };
                self.cpu_tips.insert(k.to_string(), asset.clone());
                images.push(asset);
            }
        }

        if images.is_empty() {
            return (false, &self.fallback_tip);
        }

        // Target array dimensions = max width & max height across sub-tips (clamped to 1024)
        let target_w = images.iter().map(|i| i.width).max().unwrap_or(256).clamp(1, 1024);
        let target_h = images.iter().map(|i| i.height).max().unwrap_or(256).clamp(1, 1024);
        let layers: Vec<Vec<u8>> = images
            .iter()
            .map(|img| {
                if img.width == target_w && img.height == target_h {
                    img.rgba8.clone()
                } else {
                    resize_rgba8_bilinear(&img.rgba8, img.width, img.height, target_w, target_h)
                }
            })
            .collect();

        self.evict_lru_tip_arrays_if_needed();
        let tick = self.next_lru_tick();
        let gpu = Self::upload_tip_array(device, queue, target_w, target_h, &layers);
        self.gpu_tip_arrays.insert(joined_key.clone(), (gpu, tick));
        (true, &self.gpu_tip_arrays.get(&joined_key).unwrap().0)
    }

    /// Resolves a paper / surface heightfield texture (`paper_texture_key` > `surface_texture_id` > default).
    pub fn resolve_paper_texture(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        paper_key: Option<&str>,
        surface_id: Option<&str>,
    ) -> &GpuPaperTexture {
        let key_opt = paper_key
            .filter(|s| !s.is_empty())
            .or_else(|| surface_id.filter(|s| !s.is_empty()));

        let Some(key) = key_opt else {
            return &self.default_paper;
        };

        if self.gpu_papers.contains_key(key) {
            let tick = self.next_lru_tick();
            let entry = self.gpu_papers.get_mut(key).unwrap();
            entry.1 = tick;
            return &entry.0;
        }

        // Try built-in procedural surface heightfield / paper texture
        if let Some((w, h, rgba8)) = generate_builtin_paper_texture(key) {
            self.evict_lru_papers_if_needed();
            let tick = self.next_lru_tick();
            let gpu = Self::upload_paper_2d(device, queue, w, h, &rgba8);
            self.gpu_papers.insert(key.to_string(), (gpu, tick));
            return &self.gpu_papers.get(key).unwrap().0;
        }

        // Fall back to surface_id if paper_key wasn't uploaded yet
        if let Some(sid) = surface_id.filter(|s| !s.is_empty() && *s != key) {
            if self.gpu_papers.contains_key(sid) {
                let tick = self.next_lru_tick();
                let entry = self.gpu_papers.get_mut(sid).unwrap();
                entry.1 = tick;
                return &entry.0;
            }
            if let Some((w, h, rgba8)) = generate_builtin_paper_texture(sid) {
                self.evict_lru_papers_if_needed();
                let tick = self.next_lru_tick();
                let gpu = Self::upload_paper_2d(device, queue, w, h, &rgba8);
                self.gpu_papers.insert(sid.to_string(), (gpu, tick));
                return &self.gpu_papers.get(sid).unwrap().0;
            }
        }

        &self.default_paper
    }

    /// Resolves both tip array and paper texture in one call, returning immutable references
    /// to both without conflicting borrows.
    #[allow(clippy::too_many_arguments)]
    pub fn resolve_tip_and_paper(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        primary_tip: Option<&str>,
        sub_tips: &[String],
        paper_key: Option<&str>,
        surface_id: Option<&str>,
    ) -> (bool, &GpuTipArray, &GpuPaperTexture) {
        // Populate caches first
        let (is_tex, _) = self.resolve_tip_set(device, queue, primary_tip, sub_tips);
        let _ = self.resolve_paper_texture(device, queue, paper_key, surface_id);

        // Now look up immutable references from populated maps
        let mut keys: Vec<&str> = Vec::new();
        if !sub_tips.is_empty() {
            for k in sub_tips {
                if !k.is_empty() {
                    keys.push(k.as_str());
                }
            }
        } else if let Some(pk) = primary_tip {
            if !pk.is_empty() {
                keys.push(pk);
            }
        }
        let tip_ref = if is_tex && !keys.is_empty() {
            let joined = keys.join("|");
            self.gpu_tip_arrays
                .get(&joined)
                .map(|(t, _)| t)
                .unwrap_or(&self.fallback_tip)
        } else {
            &self.fallback_tip
        };

        let paper_ref = paper_key
            .filter(|s| !s.is_empty())
            .and_then(|k| self.gpu_papers.get(k).map(|(p, _)| p))
            .or_else(|| {
                surface_id
                    .filter(|s| !s.is_empty())
                    .and_then(|k| self.gpu_papers.get(k).map(|(p, _)| p))
            })
            .unwrap_or(&self.default_paper);

        (is_tex, tip_ref, paper_ref)
    }

    /// Same as [`Self::resolve_tip_and_paper`] while also returning the fallback tip and
    /// default paper texture views in the same borrow (avoids conflicting borrows on `self`).
    pub fn resolve_tip_and_paper_with_fallbacks(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        primary_tip: Option<&str>,
        sub_tips: &[String],
        paper_key: Option<&str>,
        surface_id: Option<&str>,
    ) -> (
        bool,
        &GpuTipArray,
        &GpuPaperTexture,
        &wgpu::TextureView,
        &wgpu::TextureView,
    ) {
        let (is_tex, _) = self.resolve_tip_set(device, queue, primary_tip, sub_tips);
        let _ = self.resolve_paper_texture(device, queue, paper_key, surface_id);

        let mut keys: Vec<&str> = Vec::new();
        if !sub_tips.is_empty() {
            for k in sub_tips {
                if !k.is_empty() {
                    keys.push(k.as_str());
                }
            }
        } else if let Some(pk) = primary_tip {
            if !pk.is_empty() {
                keys.push(pk);
            }
        }
        let tip_ref = if is_tex && !keys.is_empty() {
            let joined = keys.join("|");
            self.gpu_tip_arrays
                .get(&joined)
                .map(|(t, _)| t)
                .unwrap_or(&self.fallback_tip)
        } else {
            &self.fallback_tip
        };
        let paper_ref = paper_key
            .filter(|s| !s.is_empty())
            .and_then(|k| self.gpu_papers.get(k).map(|(p, _)| p))
            .or_else(|| {
                surface_id
                    .filter(|s| !s.is_empty())
                    .and_then(|k| self.gpu_papers.get(k).map(|(p, _)| p))
            })
            .unwrap_or(&self.default_paper);

        (
            is_tex,
            tip_ref,
            paper_ref,
            &self.fallback_tip.view,
            &self.default_paper.view,
        )
    }

    /// Resolves tip array, primary surface heightfield, optional dual surface heightfield,
    /// plus fallback tip and default paper views without conflicting borrows.
    #[allow(clippy::too_many_arguments, clippy::type_complexity)]
    pub fn resolve_natural_paint_assets(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        primary_tip: Option<&str>,
        sub_tips: &[String],
        paper_key: Option<&str>,
        surface_id: Option<&str>,
        dual_surface_id: Option<&str>,
    ) -> (
        bool,
        &GpuTipArray,
        &GpuPaperTexture,
        Option<&GpuPaperTexture>,
        &wgpu::TextureView,
        &wgpu::TextureView,
    ) {
        let (is_tex, _) = self.resolve_tip_set(device, queue, primary_tip, sub_tips);
        let eff_surf = surface_id
            .filter(|s| !s.is_empty())
            .or(Some("cold-press-default"));
        let _ = self.resolve_paper_texture(device, queue, paper_key, eff_surf);
        if let Some(ds) = dual_surface_id.filter(|s| !s.is_empty()) {
            let _ = self.resolve_paper_texture(device, queue, None, Some(ds));
        }

        let mut keys: Vec<&str> = Vec::new();
        if !sub_tips.is_empty() {
            for k in sub_tips {
                if !k.is_empty() {
                    keys.push(k.as_str());
                }
            }
        } else if let Some(pk) = primary_tip {
            if !pk.is_empty() {
                keys.push(pk);
            }
        }
        let tip_ref = if is_tex && !keys.is_empty() {
            let joined = keys.join("|");
            self.gpu_tip_arrays
                .get(&joined)
                .map(|(t, _)| t)
                .unwrap_or(&self.fallback_tip)
        } else {
            &self.fallback_tip
        };
        let paper_ref = paper_key
            .filter(|s| !s.is_empty())
            .and_then(|k| self.gpu_papers.get(k).map(|(p, _)| p))
            .or_else(|| eff_surf.and_then(|k| self.gpu_papers.get(k).map(|(p, _)| p)))
            .unwrap_or(&self.default_paper);
        let dual_ref = dual_surface_id
            .filter(|s| !s.is_empty())
            .and_then(|k| self.gpu_papers.get(k).map(|(p, _)| p));

        (
            is_tex,
            tip_ref,
            paper_ref,
            dual_ref,
            &self.fallback_tip.view,
            &self.default_paper.view,
        )
    }

    #[inline]
    pub fn fallback_tip_view(&self) -> &wgpu::TextureView {
        &self.fallback_tip.view
    }

    #[inline]
    pub fn default_paper_view(&self) -> &wgpu::TextureView {
        &self.default_paper.view
    }

    fn upload_tip_array(
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        width: u32,
        height: u32,
        layers: &[Vec<u8>],
    ) -> GpuTipArray {
        let layer_count = layers.len().max(1) as u32;
        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("ink-brush-tip-array"),
            size: wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: layer_count,
            },
            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: &[],
        });

        for (i, pixels) in layers.iter().enumerate() {
            queue.write_texture(
                wgpu::TexelCopyTextureInfo {
                    texture: &texture,
                    mip_level: 0,
                    origin: wgpu::Origin3d {
                        x: 0,
                        y: 0,
                        z: i as u32,
                    },
                    aspect: wgpu::TextureAspect::All,
                },
                pixels,
                wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(width * 4),
                    rows_per_image: Some(height),
                },
                wgpu::Extent3d {
                    width,
                    height,
                    depth_or_array_layers: 1,
                },
            );
        }

        let view = texture.create_view(&wgpu::TextureViewDescriptor {
            label: Some("ink-brush-tip-array-view"),
            dimension: Some(wgpu::TextureViewDimension::D2Array),
            base_array_layer: 0,
            array_layer_count: Some(layer_count),
            ..Default::default()
        });

        GpuTipArray {
            id: NEXT_TIP_CACHE_TEX_ID.fetch_add(1, Ordering::Relaxed),
            texture,
            view,
            width,
            height,
            layer_count,
            aspect_w_over_h: (width as f32 / height.max(1) as f32).clamp(0.05, 20.0),
        }
    }

    fn upload_paper_2d(
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        width: u32,
        height: u32,
        rgba8: &[u8],
    ) -> GpuPaperTexture {
        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("ink-paper-grain-tex"),
            size: wgpu::Extent3d {
                width,
                height,
                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: &[],
        });
        queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            rgba8,
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(width * 4),
                rows_per_image: Some(height),
            },
            wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
        );
        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        GpuPaperTexture {
            id: NEXT_TIP_CACHE_TEX_ID.fetch_add(1, Ordering::Relaxed),
            texture,
            view,
            width,
            height,
        }
    }
}

fn resize_rgba8_bilinear(
    src: &[u8],
    sw: u32,
    sh: u32,
    dw: u32,
    dh: u32,
) -> Vec<u8> {
    let mut dst = vec![0u8; (dw as usize) * (dh as usize) * 4];
    for y in 0..dh {
        let fy = ((y as f32 + 0.5) * sh as f32 / dh as f32) - 0.5;
        let y0 = (fy.floor() as i32).clamp(0, sh as i32 - 1) as u32;
        let y1 = (y0 + 1).min(sh - 1);
        let ty = (fy - fy.floor()).clamp(0.0, 1.0);
        for x in 0..dw {
            let fx = ((x as f32 + 0.5) * sw as f32 / dw as f32) - 0.5;
            let x0 = (fx.floor() as i32).clamp(0, sw as i32 - 1) as u32;
            let x1 = (x0 + 1).min(sw - 1);
            let tx = (fx - fx.floor()).clamp(0.0, 1.0);

            let i00 = ((y0 * sw + x0) * 4) as usize;
            let i10 = ((y0 * sw + x1) * 4) as usize;
            let i01 = ((y1 * sw + x0) * 4) as usize;
            let i11 = ((y1 * sw + x1) * 4) as usize;
            let di = ((y * dw + x) * 4) as usize;
            for c in 0..4 {
                let top = src[i00 + c] as f32 * (1.0 - tx) + src[i10 + c] as f32 * tx;
                let bot = src[i01 + c] as f32 * (1.0 - tx) + src[i11 + c] as f32 * tx;
                dst[di + c] = (top * (1.0 - ty) + bot * ty + 0.5).clamp(0.0, 255.0) as u8;
            }
        }
    }
    dst
}