Skip to content

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

14.6 KB
Raw Blame
//! Phase 6 Native Interactive Raster/GPU Tool Engines (`tools/`):
//! - `liquify`: Interactive DX12 GPU `RG16Float` displacement field Liquify (all 8 modes + multi-layer)
//! - `fill`: Direct Rust Flood Fill, Lasso Fill, Smart Line Fill (`enclose-and-fill`, `paint-unfilled`),
//!   and <0.1 ms native Eyedropper / Pipette
//! - `transform`: Interactive DX12 GPU 5-mode Transform & Warp (`affine`, `perspective`, `mesh`, `puppet`, `cage`)
//! - `retouch`: Direct Rust Smudge (KM pigment), Blur, Dodge, Burn, Sponge, Clone Stamp, Heal
//! - `gradient`: Direct Rust + GPU Live Preview Gradients (`linear`, `radial`, `conical`, `diamond`, `mesh`)
//! - `shape`: Direct Rust + GPU Live Preview Shapes (8 kinds) + QuickShape auto-snap recognizer
//! - `filters`: Direct Rust + Live GPU Preview Spatial Filters (Gaussian, Motion, Unsharp, Film Grain),
//!   all 9 Tonal Corrections, and <2 ms Layer Histogram
//! - `vector`: Direct Rust Vector Layer & Cubic Bézier Pen rasterization

pub mod fill;
pub mod filters;
pub mod gradient;
pub mod liquify;
pub mod retouch;
pub mod shape;
pub mod transform;
pub mod vector;

use crate::tiles::RectI32;
use crate::types::CameraState;
use bytemuck::{Pod, Zeroable};
use std::borrow::Cow;

pub use fill::{
    enclose_and_fill_document, flood_fill_document, lasso_fill_document, paint_unfilled_document,
    pick_color_document, pick_color_document_for_layer, EncloseFillParams, EncloseTarget,
    FillOutcome, FillReferMode, FloodFillParams, LassoFillParams, PaintUnfilledParams,
    PickedColorDto,
};
pub use filters::{
    apply_filter_rgba8, apply_image_op_to_document, apply_tonal_rgba8, compute_layer_histogram,
    film_grain_rgba8, gaussian_blur_rgba8, motion_blur_rgba8, render_image_op_preview_rgba,
    unsharp_mask_rgba8, CurvePoint, FilterApplyResult, FilterSpec, GradientMapStop, ImageOpSpec,
    LayerHistogram, TonalSpec,
};
pub use gradient::{
    commit_gradient_to_document, render_gradient_rgba8, GradientBlendMode, GradientCommitResult,
    GradientMeshNode, GradientMeshParams, GradientParams, GradientRepeatMode, GradientStop,
    GradientType,
};
pub use liquify::{GpuLiquifyEngine, LiquifyMode, LiquifySettings, LiquifyStepParams};
pub use retouch::{
    CloneSampleMode, RetouchCommitResult, RetouchKind, RetouchSession, RetouchSettings,
    RetouchStepParams, SpongeMode, TonalRange,
};
pub use shape::{
    commit_shape_to_document, recognize_quick_shape, render_shape_rgba8, shape_bounds,
    QuickShapeKind, QuickShapeResult, ShapeCommitResult, ShapeKind, ShapeMode, ShapeParams,
};
pub use transform::{
    AffineState, CageState, GpuTransformEngine, MeshState, Point2D, PuppetPin, PuppetState,
    TransformCommitResult, TransformMode, TransformSessionSnapshot, TransformUpdatePayload,
};
pub use vector::{
    rasterize_bezier_path, rasterize_vector_layer, BezierAnchor, BezierPathParams,
    VectorRasterResult, VectorStrokePath, VectorStrokePoint,
};

// ============================================================================
// Unified Live GPU Overlay Preview Renderer (Gradients, Shapes, Filters/Tonal)
// ============================================================================

#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct ToolOverlayUniforms {
    viewport_size_phys: [f32; 2],
    doc_size: [f32; 2],
    pan_css: [f32; 2],
    zoom: f32,
    rotation_rad: f32,
    flip: [f32; 2],
    dpr: f32,
    opacity: f32,
    rect_doc: [f32; 4],
}

const TOOL_OVERLAY_QUAD_WGSL: &str = r#"
struct ToolOverlayUniforms {
    viewport_size_phys: vec2<f32>,
    doc_size: vec2<f32>,
    pan_css: vec2<f32>,
    zoom: f32,
    rotation_rad: f32,
    flip: vec2<f32>,
    dpr: f32,
    opacity: f32,
    rect_doc: vec4<f32>,
};

@group(0) @binding(0) var<uniform> u: ToolOverlayUniforms;
@group(0) @binding(1) var src_tex: texture_2d<f32>;
@group(0) @binding(2) var src_sampler: sampler;

struct VsOut {
    @builtin(position) pos: vec4<f32>,
    @location(0) uv: vec2<f32>,
};

@vertex
fn vs_main(@builtin(vertex_index) vid: u32) -> VsOut {
    var uv: vec2<f32>;
    switch (vid) {
        case 0u: { uv = vec2<f32>(0.0, 0.0); }
        case 1u: { uv = vec2<f32>(1.0, 0.0); }
        case 2u: { uv = vec2<f32>(0.0, 1.0); }
        case 3u: { uv = vec2<f32>(0.0, 1.0); }
        case 4u: { uv = vec2<f32>(1.0, 0.0); }
        default: { uv = vec2<f32>(1.0, 1.0); }
    }
    let doc_pos = u.rect_doc.xy + uv * u.rect_doc.zw;
    let centered = (doc_pos - u.doc_size * 0.5) * u.flip;
    let c = cos(u.rotation_rad);
    let s = sin(u.rotation_rad);
    let rot = vec2<f32>(centered.x * c - centered.y * s, centered.x * s + centered.y * c);
    let screen_phys = (u.pan_css + rot * u.zoom) * u.dpr;
    let ndc = vec2<f32>(
        (2.0 * screen_phys.x / max(1.0, u.viewport_size_phys.x)) - 1.0,
        1.0 - (2.0 * screen_phys.y / max(1.0, u.viewport_size_phys.y)),
    );
    var out: VsOut;
    out.pos = vec4<f32>(ndc, 0.0, 1.0);
    out.uv = uv;
    return out;
}

@fragment
fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
    let px = textureSampleLevel(src_tex, src_sampler, in.uv, 0.0);
    let a = clamp(px.a * u.opacity, 0.0, 1.0);
    if (a <= 0.001) {
        discard;
    }
    return vec4<f32>(px.rgb * a, a);
}
"#;

/// Lightweight DX12 GPU quad overlay used for live interactive previews of Gradients,
/// Shapes, and live Filter/Tonal previews (zero WebView2 `<canvas>`!).
pub struct GpuToolPreviewOverlay {
    bgl: wgpu::BindGroupLayout,
    pipeline: wgpu::RenderPipeline,
    uniform_buf: wgpu::Buffer,
    sampler: wgpu::Sampler,
    active_tex: Option<(wgpu::Texture, wgpu::TextureView, wgpu::BindGroup, RectI32, f32)>,
    /// When set, hides this layer in the base compositor while a live Filter/Tonal replacement preview is shown.
    pub replaced_layer_id: Option<String>,
}

impl GpuToolPreviewOverlay {
    pub fn new(device: &wgpu::Device, surface_format: wgpu::TextureFormat) -> Self {
        let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("ink-tool-overlay-bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
            ],
        });
        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("ink-tool-overlay-shader"),
            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(TOOL_OVERLAY_QUAD_WGSL)),
        });
        let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("ink-tool-overlay-pl"),
            bind_group_layouts: &[Some(&bgl)],
            immediate_size: 0,
        });
        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("ink-tool-overlay-pipeline"),
            layout: Some(&pl),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("vs_main"),
                buffers: &[],
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: surface_format,
                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            primitive: wgpu::PrimitiveState::default(),
            depth_stencil: None,
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        });
        let uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-tool-overlay-uniforms"),
            size: std::mem::size_of::<ToolOverlayUniforms>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("ink-tool-overlay-sampler"),
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            ..Default::default()
        });

        Self {
            bgl,
            pipeline,
            uniform_buf,
            sampler,
            active_tex: None,
            replaced_layer_id: None,
        }
    }

    pub fn is_active(&self) -> bool {
        self.active_tex.is_some()
    }

    pub fn set_rgba8_preview(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        rect: RectI32,
        rgba: &[u8],
        opacity: f32,
        replaced_layer_id: Option<String>,
    ) {
        if rect.is_empty() || rgba.len() != (rect.width as usize) * (rect.height as usize) * 4 {
            self.clear();
            return;
        }
        let tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("ink-tool-preview-rgba8"),
            size: wgpu::Extent3d {
                width: rect.width,
                height: rect.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: &[],
        });
        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
        queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &tex,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            rgba,
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(rect.width * 4),
                rows_per_image: Some(rect.height),
            },
            wgpu::Extent3d {
                width: rect.width,
                height: rect.height,
                depth_or_array_layers: 1,
            },
        );
        let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("ink-tool-overlay-bg"),
            layout: &self.bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: self.uniform_buf.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::TextureView(&view),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::Sampler(&self.sampler),
                },
            ],
        });
        self.active_tex = Some((tex, view, bg, rect, opacity.clamp(0.0, 1.0)));
        self.replaced_layer_id = replaced_layer_id;
    }

    pub fn clear(&mut self) {
        self.active_tex = None;
        self.replaced_layer_id = None;
    }

    #[allow(clippy::too_many_arguments)]
    pub fn encode(
        &self,
        queue: &wgpu::Queue,
        encoder: &mut wgpu::CommandEncoder,
        doc_w: u32,
        doc_h: u32,
        camera: &CameraState,
        vp_w: u32,
        vp_h: u32,
        dpr: f32,
        target_view: &wgpu::TextureView,
    ) {
        let Some((_, _, ref bg, rect, opacity)) = self.active_tex else {
            return;
        };
        if vp_w == 0 || vp_h == 0 || rect.is_empty() {
            return;
        }
        let u = ToolOverlayUniforms {
            viewport_size_phys: [vp_w as f32, vp_h as f32],
            doc_size: [doc_w as f32, doc_h as f32],
            pan_css: [camera.pan_x, camera.pan_y],
            zoom: camera.zoom.max(0.01),
            rotation_rad: camera.rotation.to_radians(),
            flip: [
                if camera.flip_x { -1.0 } else { 1.0 },
                if camera.flip_y { -1.0 } else { 1.0 },
            ],
            dpr: dpr.max(0.05),
            opacity,
            rect_doc: [
                rect.x as f32,
                rect.y as f32,
                rect.width as f32,
                rect.height as f32,
            ],
        };
        queue.write_buffer(&self.uniform_buf, 0, bytemuck::bytes_of(&u));
        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("ink-tool-overlay-pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                view: target_view,
                depth_slice: None,
                resolve_target: None,
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Load,
                    store: wgpu::StoreOp::Store,
                },
            })],
            depth_stencil_attachment: None,
            timestamp_writes: None,
            occlusion_query_set: None,
            multiview_mask: None,
        });
        pass.set_pipeline(&self.pipeline);
        pass.set_bind_group(0, bg, &[]);
        pass.draw(0..6, 0..1);
    }

    #[allow(clippy::too_many_arguments)]
    pub fn render(
        &self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        doc_w: u32,
        doc_h: u32,
        camera: &CameraState,
        vp_w: u32,
        vp_h: u32,
        dpr: f32,
        target_view: &wgpu::TextureView,
    ) {
        if self.active_tex.is_none() || vp_w == 0 || vp_h == 0 {
            return;
        }
        let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("ink-tool-overlay-enc"),
        });
        self.encode(queue, &mut enc, doc_w, doc_h, camera, vp_w, vp_h, dpr, target_view);
        queue.submit(Some(enc.finish()));
    }
}