Skip to content

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

12.7 KB
Raw Blame
//! Exact 2D affine canvas camera math & native 120–240 Hz navigation controller.
//!
//! Matches `formatArtboardTransform` (`src/components/canvasArea/types.ts`),
//! `screenToCanvas` / `canvasToScreen` (`src/utils/canvasUtils.ts`), and
//! `useCanvasNavigation.ts` pixel-for-pixel.

use crate::types::{CameraState, NativeNavGesture};

pub const MIN_ZOOM: f32 = 0.01;
pub const MAX_ZOOM: f32 = 32.0;
pub const ROTATION_CENTER_DAMP_RADIUS: f32 = 64.0;

#[inline]
pub fn clamp_zoom(zoom: f32) -> f32 {
    if !zoom.is_finite() {
        1.0
    } else {
        zoom.clamp(MIN_ZOOM, MAX_ZOOM)
    }
}

/// Transforms a document-space point `(doc_x, doc_y)` into viewport-local CSS pixels,
/// matching `canvasToScreen` in `src/utils/canvasUtils.ts` and `formatArtboardTransform`.
#[inline]
pub fn doc_to_viewport_css(
    doc_x: f32,
    doc_y: f32,
    doc_width: f32,
    doc_height: f32,
    cam: &CameraState,
) -> (f32, f32) {
    let fx = if cam.flip_x { -1.0 } else { 1.0 };
    let fy = if cam.flip_y { -1.0 } else { 1.0 };

    let dx = (doc_x - doc_width * 0.5) * fx;
    let dy = (doc_y - doc_height * 0.5) * fy;

    let rad = cam.rotation.to_radians();
    let (sin, cos) = rad.sin_cos();

    let rx = cam.zoom * (dx * cos - dy * sin);
    let ry = cam.zoom * (dx * sin + dy * cos);

    (cam.pan_x + rx, cam.pan_y + ry)
}

/// Transforms viewport-local CSS pixels `(vx, vy)` into document-space pixels,
/// matching `screenToCanvasInto` in `src/utils/canvasUtils.ts` pixel-for-pixel.
#[inline]
pub fn viewport_css_to_doc(
    vx: f32,
    vy: f32,
    doc_width: f32,
    doc_height: f32,
    cam: &CameraState,
) -> (f32, f32) {
    let rx = vx - cam.pan_x;
    let ry = vy - cam.pan_y;

    let rad = cam.rotation.to_radians();
    let (sin, cos) = rad.sin_cos();

    let unrot_x = rx * cos + ry * sin;
    let unrot_y = -rx * sin + ry * cos;

    let fx = if cam.flip_x { -1.0 } else { 1.0 };
    let fy = if cam.flip_y { -1.0 } else { 1.0 };
    let safe_zoom = cam.zoom.max(MIN_ZOOM);

    (
        doc_width * 0.5 + (fx * unrot_x) / safe_zoom,
        doc_height * 0.5 + (fy * unrot_y) / safe_zoom,
    )
}

/// Continuous, branch-cut-free signed angular delta (degrees) around `center` with
/// smoothstep radial damping inside `ROTATION_CENTER_DAMP_RADIUS` (64px).
/// Matches `computeSmoothRotationDelta` in `src/hooks/useCanvasNavigation.ts`.
pub fn compute_smooth_rotation_delta(
    prev_x: f32,
    prev_y: f32,
    cur_x: f32,
    cur_y: f32,
    center_x: f32,
    center_y: f32,
) -> f32 {
    let v1x = prev_x - center_x;
    let v1y = prev_y - center_y;
    let v2x = cur_x - center_x;
    let v2y = cur_y - center_y;

    let r1 = v1x.hypot(v1y);
    let r2 = v2x.hypot(v2y);
    if r1 < 1e-4 || r2 < 1e-4 {
        return 0.0;
    }

    let cross = v1x * v2y - v1y * v2x;
    let dot = v1x * v2x + v1y * v2y;
    let raw_deg = cross.atan2(dot).to_degrees();

    let min_r = r1.min(r2);
    if min_r >= ROTATION_CENTER_DAMP_RADIUS {
        return raw_deg;
    }
    let t = (min_r / ROTATION_CENTER_DAMP_RADIUS).clamp(0.0, 1.0);
    let smooth_gain = t * t * (3.0 - 2.0 * t);
    raw_deg * smooth_gain
}

#[derive(Debug, Clone)]
enum ActiveGestureState {
    Pan {
        start_css_x: f32,
        start_css_y: f32,
        start_pan_x: f32,
        start_pan_y: f32,
    },
    Rotate {
        last_css_x: f32,
        last_css_y: f32,
        start_rotation: f32,
        total_delta_deg: f32,
        start_pan_x: f32,
        start_pan_y: f32,
        center_x: f32,
        center_y: f32,
    },
    ZoomDrag {
        start_css_x: f32,
        anchor_x: f32,
        anchor_y: f32,
        start_zoom: f32,
        start_pan_x: f32,
        start_pan_y: f32,
    },
}

/// Stateful native camera navigation controller executed directly on the engine thread.
#[derive(Debug, Default)]
pub struct NativeCameraNavigator {
    active: Option<ActiveGestureState>,
}

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

    pub fn cancel(&mut self) {
        self.active = None;
    }

    pub fn begin(
        &mut self,
        gesture: NativeNavGesture,
        local_css_x: f32,
        local_css_y: f32,
        viewport_css_w: f32,
        viewport_css_h: f32,
        cam: &CameraState,
    ) {
        self.active = Some(match gesture {
            NativeNavGesture::Pan => ActiveGestureState::Pan {
                start_css_x: local_css_x,
                start_css_y: local_css_y,
                start_pan_x: cam.pan_x,
                start_pan_y: cam.pan_y,
            },
            NativeNavGesture::Rotate => ActiveGestureState::Rotate {
                last_css_x: local_css_x,
                last_css_y: local_css_y,
                start_rotation: cam.rotation,
                total_delta_deg: 0.0,
                start_pan_x: cam.pan_x,
                start_pan_y: cam.pan_y,
                center_x: viewport_css_w * 0.5,
                center_y: viewport_css_h * 0.5,
            },
            NativeNavGesture::ZoomDrag => ActiveGestureState::ZoomDrag {
                start_css_x: local_css_x,
                anchor_x: local_css_x,
                anchor_y: local_css_y,
                start_zoom: clamp_zoom(cam.zoom),
                start_pan_x: cam.pan_x,
                start_pan_y: cam.pan_y,
            },
        });
    }

    /// Updates camera in-place for a drag motion. Returns `true` if the camera changed.
    pub fn update(
        &mut self,
        local_css_x: f32,
        local_css_y: f32,
        snap_15_deg: bool,
        is_webtoon_mode: bool,
        cam: &mut CameraState,
    ) -> bool {
        let Some(state) = self.active.as_mut() else {
            return false;
        };

        match state {
            ActiveGestureState::Pan {
                start_css_x,
                start_css_y,
                start_pan_x,
                start_pan_y,
            } => {
                let dx = local_css_x - *start_css_x;
                let dy = local_css_y - *start_css_y;
                cam.pan_x = if is_webtoon_mode {
                    *start_pan_x
                } else {
                    *start_pan_x + dx
                };
                cam.pan_y = *start_pan_y + dy;
                true
            }
            ActiveGestureState::Rotate {
                last_css_x,
                last_css_y,
                start_rotation,
                total_delta_deg,
                start_pan_x,
                start_pan_y,
                center_x,
                center_y,
            } => {
                let diff = compute_smooth_rotation_delta(
                    *last_css_x,
                    *last_css_y,
                    local_css_x,
                    local_css_y,
                    *center_x,
                    *center_y,
                );
                *last_css_x = local_css_x;
                *last_css_y = local_css_y;
                *total_delta_deg += diff;

                let mut next_rot = *start_rotation + *total_delta_deg;
                if snap_15_deg {
                    next_rot = (next_rot / 15.0).round() * 15.0;
                }
                let d_rad = (next_rot - *start_rotation).to_radians();
                let (sin, cos) = d_rad.sin_cos();
                let rx = *start_pan_x - *center_x;
                let ry = *start_pan_y - *center_y;
                cam.rotation = next_rot;
                cam.pan_x = *center_x + rx * cos - ry * sin;
                cam.pan_y = *center_y + rx * sin + ry * cos;
                true
            }
            ActiveGestureState::ZoomDrag {
                start_css_x,
                anchor_x,
                anchor_y,
                start_zoom,
                start_pan_x,
                start_pan_y,
            } => {
                let dx = local_css_x - *start_css_x;
                let next_zoom = clamp_zoom(*start_zoom * (dx * 0.007).exp());
                let ratio = next_zoom / (*start_zoom).max(MIN_ZOOM);
                cam.zoom = next_zoom;
                cam.pan_x = *anchor_x - (*anchor_x - *start_pan_x) * ratio;
                cam.pan_y = *anchor_y - (*anchor_y - *start_pan_y) * ratio;
                true
            }
        }
    }

    pub fn end(&mut self) -> bool {
        self.active.take().is_some()
    }

    /// Applies mouse-wheel zoom anchored at `(anchor_css_x, anchor_css_y)`.
    /// Matches `useCanvasNavigation.ts` (`Math.exp(-delta * 0.0018)`).
    pub fn apply_wheel_zoom(
        anchor_css_x: f32,
        anchor_css_y: f32,
        delta_y: f32,
        cam: &mut CameraState,
    ) -> bool {
        let current_zoom = clamp_zoom(cam.zoom);
        let factor = (-delta_y * 0.0018).exp();
        let next_zoom = clamp_zoom(current_zoom * factor);
        if (next_zoom - current_zoom).abs() <= 1e-5 {
            return false;
        }
        let ratio = next_zoom / current_zoom;
        cam.pan_x = anchor_css_x - (anchor_css_x - cam.pan_x) * ratio;
        cam.pan_y = anchor_css_y - (anchor_css_y - cam.pan_y) * ratio;
        cam.zoom = next_zoom;
        true
    }

    /// Applies mouse-wheel scroll panning (used when wheel mode is `scroll` or Webtoon mode).
    pub fn apply_wheel_scroll(
        delta_x: f32,
        delta_y: f32,
        shift_held: bool,
        is_webtoon_mode: bool,
        cam: &mut CameraState,
    ) -> bool {
        let scroll_x = if shift_held { delta_y } else { delta_x };
        let scroll_y = if shift_held { 0.0 } else { delta_y };
        if scroll_x.abs() < 1e-5 && scroll_y.abs() < 1e-5 {
            return false;
        }
        if !is_webtoon_mode {
            cam.pan_x -= scroll_x;
        }
        cam.pan_y -= scroll_y;
        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_camera_roundtrip_matches_format_artboard_transform_all_combinations() {
        let doc_w = 2400.0;
        let doc_h = 1600.0;
        let cases = [
            CameraState {
                pan_x: 640.0,
                pan_y: 420.0,
                zoom: 1.0,
                rotation: 0.0,
                flip_x: false,
                flip_y: false,
            },
            CameraState {
                pan_x: 512.5,
                pan_y: 384.25,
                zoom: 2.75,
                rotation: 37.5,
                flip_x: true,
                flip_y: false,
            },
            CameraState {
                pan_x: -120.0,
                pan_y: 890.0,
                zoom: 0.15,
                rotation: -142.25,
                flip_x: false,
                flip_y: true,
            },
            CameraState {
                pan_x: 1024.0,
                pan_y: 768.0,
                zoom: 16.0,
                rotation: 180.0,
                flip_x: true,
                flip_y: true,
            },
        ];

        let points = [
            (0.0, 0.0),
            (doc_w, doc_h),
            (doc_w * 0.5, doc_h * 0.5),
            (317.25, 1189.75),
        ];

        for cam in &cases {
            for &(dx, dy) in &points {
                let (vx, vy) = doc_to_viewport_css(dx, dy, doc_w, doc_h, cam);
                let (rx, ry) = viewport_css_to_doc(vx, vy, doc_w, doc_h, cam);
                assert!(
                    (rx - dx).abs() < 1e-3 && (ry - dy).abs() < 1e-3,
                    "roundtrip mismatch for cam={cam:?} pt=({dx},{dy}) -> ({vx},{vy}) -> ({rx},{ry})"
                );
            }
        }
    }

    #[test]
    fn test_document_center_maps_to_pan() {
        let cam = CameraState {
            pan_x: 412.5,
            pan_y: 298.75,
            zoom: 3.5,
            rotation: 63.0,
            flip_x: true,
            flip_y: true,
        };
        let (vx, vy) = doc_to_viewport_css(1000.0, 500.0, 2000.0, 1000.0, &cam);
        assert!((vx - 412.5).abs() < 1e-4);
        assert!((vy - 298.75).abs() < 1e-4);
    }

    #[test]
    fn test_wheel_zoom_preserves_anchor_point_in_document_space() {
        let mut cam = CameraState {
            pan_x: 500.0,
            pan_y: 350.0,
            zoom: 1.25,
            rotation: 22.0,
            flip_x: true,
            flip_y: false,
        };
        let anchor_x = 610.0;
        let anchor_y = 240.0;
        let before = viewport_css_to_doc(anchor_x, anchor_y, 1920.0, 1080.0, &cam);
        assert!(NativeCameraNavigator::apply_wheel_zoom(
            anchor_x, anchor_y, -120.0, &mut cam
        ));
        let after = viewport_css_to_doc(anchor_x, anchor_y, 1920.0, 1080.0, &cam);
        assert!((before.0 - after.0).abs() < 1e-3);
        assert!((before.1 - after.1).abs() < 1e-3);
    }

    #[test]
    fn test_smooth_rotation_delta_damps_near_center() {
        let far = compute_smooth_rotation_delta(200.0, 0.0, 0.0, 200.0, 0.0, 0.0);
        assert!((far - 90.0).abs() < 1e-3);
        let near = compute_smooth_rotation_delta(16.0, 0.0, 0.0, 16.0, 0.0, 0.0);
        assert!(near > 0.0 && near < far * 0.3);
    }
}