Skip to content

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

21.2 KB
Raw Blame
//! Native Stroke Input & Geometry Pipeline (`crates/ink-engine/src/stroke/`).
//!
//! End-to-end Rust port of InkStudio's stroke pipeline:
//! - `curves.rs`: PCHIP Fritsch–Carlson 256-entry LUT, global/brush pressure curves, gamma,
//!   and light-pressure anti-collapse width calculation.
//! - `stabilizer.rs`: 1-Euro pressure filter, CSP 0..50 stabilization, sharp-corner snapping,
//!   Frenet lateral twitch damping, backtrack spike guard, full-tail catch-up, and CSP
//!   post-correction (0..5).
//! - `spline.rs`: Centripetal Catmull–Rom + provisional Hermite stitching + exact arc-length
//!   carry-over resampler.
//! - `taper.rs`: G-Pen S-curve, ballistic flick taper, and full `CspTaperSettings` evaluator.
//! - `rulers.rs`: Straight ruler & 1/2/3-point perspective ruler snapping.
//! - `prediction.rs`: Ephemeral speculative stroke head prediction rendered natively in `wgpu`.

pub mod curves;
pub mod prediction;
pub mod rulers;
pub mod spline;
pub mod stabilizer;
pub mod taper;

pub use curves::{
    calculate_stroke_width, evaluate_fast_spline, CompiledCurveLut, GlobalPressureCurve,
};
pub use prediction::{build_predicted_segments, PredictionConfig};
pub use rulers::{
    ActiveRulerSession, LockedPerspectiveAxis, PerspectiveMode, PerspectiveRulerConfig,
    PerspectiveSnapSession, StraightRulerConfig, StraightRulerSnapSession, VanishingPoint,
};
pub use spline::{
    centripetal_catmull_rom_to_bezier, generate_provisional_segment, polyline_to_bezier_segments,
    ArcLengthResampler, ArcLengthTable, CubicBezierSegment, ResampledPoint, SplineGenerator,
};
pub use stabilizer::{
    apply_csp_post_correction, CornerConvergencePlan, InputStabilizer, OneEuroAxis,
    StabilizedSample, StabilizerConfig,
};
pub use taper::{
    evaluate_csp_taper_factors, CspTaperFactors, CspTaperSettings, FlickTaperConfig, TaperEngine,
};

use crate::types::BrushParams;
use bytemuck::{Pod, Zeroable};
use serde::{Deserialize, Serialize};

/// Canonical document-space stroke sample carrying all stylus telemetry.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StrokePoint {
    pub x: f64,
    pub y: f64,
    pub pressure: f32,
    pub width: f32,
    pub tilt_x: f32,
    pub tilt_y: f32,
    pub twist: f32,
    /// Document-space velocity (`px/ms`).
    pub velocity: f64,
    pub timestamp_ms: f64,
    #[serde(default)]
    pub is_corner: bool,
}

/// Compact committed stroke point emitted in `EngineEvent::StrokeCommitted` for
/// collaboration broadcast and Shift+Click straight-line continuity.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CommittedStrokePoint {
    pub x: f32,
    pub y: f32,
    pub pressure: f32,
    pub width: f32,
    pub tilt_x: f32,
    pub tilt_y: f32,
    pub twist: f32,
    pub timestamp_ms: f64,
    #[serde(default)]
    pub is_corner: bool,
}

impl From<StrokePoint> for CommittedStrokePoint {
    fn from(p: StrokePoint) -> Self {
        Self {
            x: p.x as f32,
            y: p.y as f32,
            pressure: p.pressure,
            width: p.width,
            tilt_x: p.tilt_x,
            tilt_y: p.tilt_y,
            twist: p.twist,
            timestamp_ms: p.timestamp_ms,
            is_corner: p.is_corner,
        }
    }
}

/// Parameters controlling [`NativeStrokePipeline`] geometry processing for one stroke.
#[derive(Debug, Clone)]
pub struct StrokePipelineConfig {
    pub base_size: f32,
    pub min_size_factor: f32,
    pub use_pressure: bool,
    pub pressure_curve_gamma: f32,
    pub brush_pressure_lut: Option<CompiledCurveLut>,
    pub global_pressure_curve: GlobalPressureCurve,
    pub global_pressure_lut: Option<CompiledCurveLut>,
    pub stabilization: f32,
    pub sharp_corners: bool,
    pub post_correction: u8,
    pub smoothing: bool,
    pub enable_flick_taper: bool,
    pub zoom: f64,
    pub straight_ruler: Option<StraightRulerConfig>,
    pub perspective_ruler: Option<PerspectiveRulerConfig>,
}

impl Default for StrokePipelineConfig {
    fn default() -> Self {
        Self {
            base_size: 16.0,
            min_size_factor: 0.05,
            use_pressure: true,
            pressure_curve_gamma: 1.0,
            brush_pressure_lut: None,
            global_pressure_curve: GlobalPressureCurve::default(),
            global_pressure_lut: None,
            stabilization: 0.0,
            sharp_corners: false,
            post_correction: 0,
            smoothing: true,
            enable_flick_taper: false,
            zoom: 1.0,
            straight_ruler: None,
            perspective_ruler: None,
        }
    }
}

/// Output from advancing [`NativeStrokePipeline`] with a pointer-down, move, or up sample.
#[derive(Debug, Clone, Default)]
pub struct PipelineStepOutput {
    /// Newly sealed cubic Bézier segments ready for incremental dab generation.
    pub sealed_segments: Vec<CubicBezierSegment>,
    /// True if this was the initial contact dot (single-point stamp before movement).
    pub initial_point: Option<StrokePoint>,
    /// Finalized post-corrected / flick-tapered full point list (populated on `end()`).
    pub finalized_points: Option<Vec<StrokePoint>>,
}

/// Stateful per-stroke geometry pipeline orchestrating:
/// raw sample -> ruler snap -> global pressure curve -> stabilizer -> width calc ->
/// spline sealing -> ephemeral prediction -> catch-up / flick-taper / post-correction on lift.
#[derive(Debug, Clone)]
pub struct NativeStrokePipeline {
    active: bool,
    config: StrokePipelineConfig,
    stabilizer: InputStabilizer,
    spline: SplineGenerator,
    ruler: ActiveRulerSession,
    committed_points: Vec<StrokePoint>,
    last_timestamp_ms: f64,
}

impl Default for NativeStrokePipeline {
    fn default() -> Self {
        Self::new()
    }
}

impl NativeStrokePipeline {
    pub fn new() -> Self {
        Self {
            active: false,
            config: StrokePipelineConfig::default(),
            stabilizer: InputStabilizer::new(StabilizerConfig::default()),
            spline: SplineGenerator::new(0.0),
            ruler: ActiveRulerSession::None,
            committed_points: Vec::with_capacity(256),
            last_timestamp_ms: 0.0,
        }
    }

    #[inline]
    pub fn is_active(&self) -> bool {
        self.active
    }

    #[inline]
    pub fn committed_points(&self) -> &[StrokePoint] {
        &self.committed_points
    }

    #[inline]
    pub fn stabilizer(&self) -> &InputStabilizer {
        &self.stabilizer
    }

    #[inline]
    pub fn spline(&self) -> &SplineGenerator {
        &self.spline
    }

    pub fn reset(&mut self) {
        self.active = false;
        self.stabilizer.reset();
        self.spline.reset();
        self.ruler = ActiveRulerSession::None;
        self.committed_points.clear();
        self.last_timestamp_ms = 0.0;
    }

    #[inline]
    fn eval_pressure_and_width(&self, raw_pressure: f32) -> (f32, f32) {
        let global_p = self
            .config
            .global_pressure_curve
            .evaluate_raw(raw_pressure, self.config.global_pressure_lut.as_ref());
        let width = calculate_stroke_width(
            global_p,
            self.config.base_size,
            self.config.use_pressure,
            self.config.min_size_factor,
            self.config.pressure_curve_gamma,
            self.config.brush_pressure_lut.as_ref(),
        );
        (global_p, width)
    }

    /// Starts a new stroke on pointer-down (optionally connecting from `shift_anchor` for Shift+Click straight lines).
    #[allow(clippy::too_many_arguments)]
    pub fn begin(
        &mut self,
        doc_x: f64,
        doc_y: f64,
        raw_pressure: f32,
        tilt_x: f32,
        tilt_y: f32,
        twist: f32,
        timestamp_ms: f64,
        alt_override: bool,
        shift_anchor: Option<StrokePoint>,
        config: StrokePipelineConfig,
    ) -> PipelineStepOutput {
        self.config = config;
        self.active = true;
        self.committed_points.clear();
        self.spline.reset();

        self.ruler = ActiveRulerSession::begin(
            self.config.straight_ruler.as_ref(),
            self.config.perspective_ruler.as_ref(),
            doc_x,
            doc_y,
            self.config.zoom,
            alt_override,
        );

        let (sx, sy) = self.ruler.snap(doc_x, doc_y, alt_override);

        // When snapping to a straight/perspective ruler, bypass heavy stabilization lag
        // so the line tracks the ruler cleanly without fighting the constraint.
        let eff_stab = if self.ruler.is_active() {
            self.config.stabilization.min(2.0)
        } else {
            self.config.stabilization
        };
        self.stabilizer = InputStabilizer::new(StabilizerConfig {
            stabilization: eff_stab,
            sharp_corners: self.config.sharp_corners,
            zoom: self.config.zoom as f32,
            pressure_smoothing: 0.35,
        });

        let (gp, _) = self.eval_pressure_and_width(raw_pressure);
        let sample = self
            .stabilizer
            .process(sx, sy, gp, tilt_x, tilt_y, twist, timestamp_ms);
        let width = calculate_stroke_width(
            sample.pressure,
            self.config.base_size,
            self.config.use_pressure,
            self.config.min_size_factor,
            self.config.pressure_curve_gamma,
            self.config.brush_pressure_lut.as_ref(),
        );
        let pt = StrokePoint {
            x: sample.x,
            y: sample.y,
            pressure: sample.pressure,
            width,
            tilt_x: sample.tilt_x,
            tilt_y: sample.tilt_y,
            twist: sample.twist,
            velocity: 0.0,
            timestamp_ms,
            is_corner: false,
        };
        self.last_timestamp_ms = timestamp_ms;

        let mut out = PipelineStepOutput::default();
        if let Some(anchor) = shift_anchor {
            // Shift+Click straight line bridge from previous stroke end to current point
            let mut start_pt = anchor;
            start_pt.timestamp_ms = (timestamp_ms - 8.0).max(0.0);
            start_pt.is_corner = true;
            self.committed_points.push(start_pt);
            self.spline.push_knot(start_pt);
            let mut end_pt = pt;
            end_pt.is_corner = true;
            self.committed_points.push(end_pt);
            out.sealed_segments = self.spline.push_knot(end_pt);
        } else {
            self.committed_points.push(pt);
            self.spline.push_knot(pt);
            out.initial_point = Some(pt);
        }
        out
    }

    /// Processes a pointer-move sample in document coordinates.
    #[allow(clippy::too_many_arguments)]
    pub fn push_move(
        &mut self,
        doc_x: f64,
        doc_y: f64,
        raw_pressure: f32,
        tilt_x: f32,
        tilt_y: f32,
        twist: f32,
        timestamp_ms: f64,
        alt_override: bool,
    ) -> PipelineStepOutput {
        if !self.active {
            return PipelineStepOutput::default();
        }
        let (sx, sy) = self.ruler.snap(doc_x, doc_y, alt_override);
        let (gp, _) = self.eval_pressure_and_width(raw_pressure);
        let sample = self
            .stabilizer
            .process(sx, sy, gp, tilt_x, tilt_y, twist, timestamp_ms);
        self.last_timestamp_ms = timestamp_ms;

        if !sample.should_emit {
            return PipelineStepOutput::default();
        }

        let mut sealed_segments = Vec::new();

        // If sharp-corner convergence planned a bounded midpoint, push midpoint before apex
        if let Some(conv) = sample.corner_convergence {
            let mid_w = calculate_stroke_width(
                sample.pressure,
                self.config.base_size,
                self.config.use_pressure,
                self.config.min_size_factor,
                self.config.pressure_curve_gamma,
                self.config.brush_pressure_lut.as_ref(),
            );
            let mid_pt = StrokePoint {
                x: conv.mid_x,
                y: conv.mid_y,
                pressure: sample.pressure,
                width: mid_w,
                tilt_x: sample.tilt_x,
                tilt_y: sample.tilt_y,
                twist: sample.twist,
                velocity: sample.velocity,
                timestamp_ms: timestamp_ms - 0.5,
                is_corner: false,
            };
            self.committed_points.push(mid_pt);
            sealed_segments.extend(self.spline.push_knot(mid_pt));
        }

        let width = calculate_stroke_width(
            sample.pressure,
            self.config.base_size,
            self.config.use_pressure,
            self.config.min_size_factor,
            self.config.pressure_curve_gamma,
            self.config.brush_pressure_lut.as_ref(),
        );
        let pt = StrokePoint {
            x: sample.x,
            y: sample.y,
            pressure: sample.pressure,
            width,
            tilt_x: sample.tilt_x,
            tilt_y: sample.tilt_y,
            twist: sample.twist,
            velocity: sample.velocity,
            timestamp_ms,
            is_corner: sample.is_corner,
        };
        self.committed_points.push(pt);
        sealed_segments.extend(self.spline.push_knot(pt));

        PipelineStepOutput {
            sealed_segments,
            initial_point: None,
            finalized_points: None,
        }
    }

    /// Generates ephemeral predicted head segments WITHOUT mutating committed knots or bounds.
    pub fn build_predicted_head(&self) -> Vec<CubicBezierSegment> {
        if !self.active || self.committed_points.is_empty() {
            return Vec::new();
        }
        build_predicted_segments(
            &self.spline,
            &self.stabilizer,
            self.config.zoom,
            PredictionConfig::default(),
        )
    }

    /// Finalizes the stroke on pen-up:
    /// 1. Flushes stabilizer catch-up all the way to the exact final stylus coordinate,
    /// 2. Optionally extrapolates ballistic exit flick taper,
    /// 3. Seals remaining spline segments,
    /// 4. Applies CSP post-correction (`post_correction` 0..5) when enabled.
    pub fn end(&mut self, lift_timestamp_ms: f64) -> PipelineStepOutput {
        if !self.active {
            return PipelineStepOutput::default();
        }
        let mut sealed_segments = Vec::new();

        // 1. Flush full stabilizer catch-up tail to exact lift coordinate
        let catchup = self.stabilizer.flush_catch_up(lift_timestamp_ms);
        for s in catchup {
            let width = calculate_stroke_width(
                s.pressure,
                self.config.base_size,
                self.config.use_pressure,
                self.config.min_size_factor,
                self.config.pressure_curve_gamma,
                self.config.brush_pressure_lut.as_ref(),
            );
            let pt = StrokePoint {
                x: s.x,
                y: s.y,
                pressure: s.pressure,
                width,
                tilt_x: s.tilt_x,
                tilt_y: s.tilt_y,
                twist: s.twist,
                velocity: s.velocity,
                timestamp_ms: s.timestamp_ms,
                is_corner: false,
            };
            self.committed_points.push(pt);
            sealed_segments.extend(self.spline.push_knot(pt));
        }

        // 2. Ballistic flick taper (when enabled and not ruler-constrained)
        if self.config.enable_flick_taper && !self.ruler.is_active() {
            let flick_pts = TaperEngine::compute_flick_taper(
                &self.committed_points,
                lift_timestamp_ms,
                self.config.zoom,
                self.config.base_size as f64,
                FlickTaperConfig::default(),
            );
            for fp in flick_pts {
                self.committed_points.push(fp);
                sealed_segments.extend(self.spline.push_knot(fp));
            }
        }

        // 3. Seal trailing spline segments
        sealed_segments.extend(self.spline.finish());

        // 4. CSP Post-Correction
        let finalized = if self.config.post_correction > 0 && self.committed_points.len() >= 4 {
            apply_csp_post_correction(&self.committed_points, self.config.post_correction)
        } else {
            self.committed_points.clone()
        };

        self.active = false;
        PipelineStepOutput {
            sealed_segments,
            initial_point: None,
            finalized_points: Some(finalized),
        }
    }
}

// =============================================================================
// Legacy Phase 1–3 compatibility types (retained for existing tests / incremental wiring)
// =============================================================================

/// GPU vertex-instance payload for a simple radial dab (`32 bytes`, 16-byte aligned).
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
pub struct DabInstance {
    pub center_doc: [f32; 2],
    pub radius_doc: f32,
    pub hardness: f32,
    pub color_rgba: [f32; 4],
}

#[derive(Debug, Default)]
pub struct StrokeDabGenerator {
    active: bool,
    last_doc_x: f32,
    last_doc_y: f32,
    last_pressure: f32,
    residual_dist: f32,
    stroke_is_eraser: bool,
}

impl StrokeDabGenerator {
    #[inline]
    pub fn is_active(&self) -> bool {
        self.active
    }

    #[inline]
    pub fn stroke_is_eraser(&self) -> bool {
        self.stroke_is_eraser
    }

    pub fn reset(&mut self) {
        self.active = false;
        self.residual_dist = 0.0;
        self.stroke_is_eraser = false;
    }

    #[inline]
    fn eval_radius(params: &BrushParams, pressure: f32) -> f32 {
        let base_size = params.size.clamp(0.5, 2000.0);
        let p = pressure.clamp(0.0, 1.0);
        let diam = if params.use_pressure_size {
            let min_r = params.min_size_ratio.clamp(0.0, 1.0);
            let scaled = base_size * (min_r + (1.0 - min_r) * p);
            if p > 0.005 {
                scaled.max(0.35_f32.min(base_size))
            } else {
                scaled.max(0.15)
            }
        } else {
            base_size
        };
        (diam * 0.5).max(0.25)
    }

    #[inline]
    fn eval_dab_alpha(params: &BrushParams, pressure: f32, spacing_ratio: f32) -> f32 {
        let base_opacity = params.opacity.clamp(0.01, 1.0);
        let p = pressure.clamp(0.0, 1.0);
        let target = if params.use_pressure_opacity {
            base_opacity * (0.1 + 0.9 * p)
        } else {
            base_opacity
        };
        let flow_scale = if target >= 0.98 {
            1.0
        } else {
            1.0 - (1.0 - target).powf((spacing_ratio * 2.5).clamp(0.15, 1.0))
        };
        flow_scale.clamp(0.01, 1.0)
    }

    pub fn begin(
        &mut self,
        doc_x: f32,
        doc_y: f32,
        pressure: f32,
        inverted_eraser: bool,
        params: &BrushParams,
        out: &mut Vec<DabInstance>,
    ) {
        self.active = true;
        self.last_doc_x = doc_x;
        self.last_doc_y = doc_y;
        self.last_pressure = pressure.clamp(0.0, 1.0);
        self.residual_dist = 0.0;
        self.stroke_is_eraser = params.is_eraser || inverted_eraser;

        let spacing_ratio = params.spacing.clamp(0.03, 1.0);
        let radius = Self::eval_radius(params, self.last_pressure);
        let alpha = Self::eval_dab_alpha(params, self.last_pressure, spacing_ratio);
        out.push(DabInstance {
            center_doc: [doc_x, doc_y],
            radius_doc: radius,
            hardness: params.hardness.clamp(0.0, 1.0),
            color_rgba: [params.color[0], params.color[1], params.color[2], alpha],
        });
    }

    pub fn push_move(
        &mut self,
        doc_x: f32,
        doc_y: f32,
        pressure: f32,
        params: &BrushParams,
        out: &mut Vec<DabInstance>,
    ) {
        if !self.active {
            return;
        }
        let p1 = pressure.clamp(0.0, 1.0);
        let dx = doc_x - self.last_doc_x;
        let dy = doc_y - self.last_doc_y;
        let seg_len = dx.hypot(dy);
        if seg_len < 1e-4 {
            self.last_pressure = p1;
            return;
        }

        let spacing_ratio = params.spacing.clamp(0.03, 1.0);
        let hardness = params.hardness.clamp(0.0, 1.0);
        let p0 = self.last_pressure;
        let x0 = self.last_doc_x;
        let y0 = self.last_doc_y;

        let mut dist = self.residual_dist;
        let mut emitted = 0u32;
        const MAX_DABS_PER_SEGMENT: u32 = 1024;

        while dist <= seg_len && emitted < MAX_DABS_PER_SEGMENT {
            let t = (dist / seg_len).clamp(0.0, 1.0);
            let p = p0 + (p1 - p0) * t;
            let radius = Self::eval_radius(params, p);
            let step = (radius * 2.0 * spacing_ratio).max(0.5);
            if dist > 0.0 || self.residual_dist == 0.0 {
                let cx = x0 + dx * t;
                let cy = y0 + dy * t;
                let alpha = Self::eval_dab_alpha(params, p, spacing_ratio);
                out.push(DabInstance {
                    center_doc: [cx, cy],
                    radius_doc: radius,
                    hardness,
                    color_rgba: [params.color[0], params.color[1], params.color[2], alpha],
                });
                emitted += 1;
            }
            dist += step;
        }

        self.residual_dist = (dist - seg_len).max(0.0);
        self.last_doc_x = doc_x;
        self.last_doc_y = doc_y;
        self.last_pressure = p1;
    }

    pub fn end(&mut self) {
        self.active = false;
        self.residual_dist = 0.0;
    }
}