Skip to main content

sim_engine/
camera.rs

1use std::{error::Error, fmt};
2
3use crate::{
4    math::{Rect, Vec2},
5    tween::{Interpolate, Tween, TweenError},
6};
7
8const MIN_ZOOM: f32 = 0.0001;
9const MIN_PROJECTION_COSINE: f32 = 0.001;
10
11/// Point measured in logical screen pixels with a top-left origin.
12///
13/// Camera picking accepts this type so physical pointer coordinates require an
14/// explicit DPI conversion before they can enter camera math.
15#[derive(Debug, Clone, Copy, PartialEq, Default)]
16pub struct LogicalScreenPosition {
17    value: Vec2,
18}
19
20impl LogicalScreenPosition {
21    /// Builds a position from logical horizontal and vertical pixel coordinates.
22    pub const fn new(x: f32, y: f32) -> Self {
23        Self {
24            value: Vec2::new(x, y),
25        }
26    }
27
28    /// Builds a position from a vector whose units are explicitly logical pixels.
29    pub const fn from_vec2(value: Vec2) -> Self {
30        Self { value }
31    }
32
33    /// Returns the position as a logical-pixel vector.
34    pub const fn to_vec2(self) -> Vec2 {
35        self.value
36    }
37
38    /// Returns true when both coordinates are finite.
39    pub fn is_finite(self) -> bool {
40        self.value.is_finite()
41    }
42}
43
44/// Offset or size measured in logical screen pixels.
45///
46/// This is distinct from [`LogicalScreenPosition`] because vectors do not carry
47/// a screen origin. It prevents world-space and physical-pixel vectors from
48/// entering clipping and screen-effect APIs accidentally.
49#[derive(Debug, Clone, Copy, PartialEq, Default)]
50pub struct LogicalScreenVector {
51    value: Vec2,
52}
53
54impl LogicalScreenVector {
55    /// Builds a logical-pixel vector from horizontal and vertical components.
56    pub const fn new(x: f32, y: f32) -> Self {
57        Self {
58            value: Vec2::new(x, y),
59        }
60    }
61
62    /// Explicitly labels an existing vector as logical screen pixels.
63    pub const fn from_vec2(value: Vec2) -> Self {
64        Self { value }
65    }
66
67    /// Returns the underlying logical-pixel vector.
68    pub const fn to_vec2(self) -> Vec2 {
69        self.value
70    }
71
72    /// Returns true when both components are finite.
73    pub fn is_finite(self) -> bool {
74        self.value.is_finite()
75    }
76}
77
78/// Point measured in physical surface pixels with a top-left origin.
79///
80/// Window systems commonly report pointer positions in this space. A renderer
81/// converts them to [`LogicalScreenPosition`] using its validated DPI scale.
82#[derive(Debug, Clone, Copy, PartialEq, Default)]
83pub struct PhysicalScreenPosition {
84    value: Vec2,
85}
86
87impl PhysicalScreenPosition {
88    /// Builds a position from physical horizontal and vertical pixel coordinates.
89    pub const fn new(x: f32, y: f32) -> Self {
90        Self {
91            value: Vec2::new(x, y),
92        }
93    }
94
95    /// Builds a position from a vector whose units are explicitly physical pixels.
96    pub const fn from_vec2(value: Vec2) -> Self {
97        Self { value }
98    }
99
100    /// Returns the position as a physical-pixel vector.
101    pub const fn to_vec2(self) -> Vec2 {
102        self.value
103    }
104
105    /// Returns true when both coordinates are finite.
106    pub fn is_finite(self) -> bool {
107        self.value.is_finite()
108    }
109}
110
111/// Logical pixel dimensions of the viewport currently being drawn into.
112#[derive(Debug, Clone, Copy, PartialEq)]
113pub struct LogicalViewport {
114    width: f32,
115    height: f32,
116}
117
118/// A logical viewport positioned inside a larger presentation target.
119///
120/// The origin uses top-left logical screen coordinates. Scene-local camera
121/// projection and clips use the region's own `0..width`, `0..height` space.
122#[derive(Debug, Clone, Copy, PartialEq)]
123pub struct LogicalViewportRegion {
124    origin: LogicalScreenPosition,
125    viewport: LogicalViewport,
126}
127
128impl LogicalViewportRegion {
129    /// Builds a finite positioned logical viewport.
130    pub fn new(
131        origin: LogicalScreenPosition,
132        viewport: LogicalViewport,
133    ) -> Result<Self, LogicalViewportError> {
134        if !origin.is_finite() {
135            return Err(LogicalViewportError::InvalidOrigin { origin });
136        }
137        Ok(Self { origin, viewport })
138    }
139
140    /// Returns the top-left origin in target logical pixels.
141    pub const fn origin(self) -> LogicalScreenPosition {
142        self.origin
143    }
144
145    /// Returns the local camera viewport dimensions.
146    pub const fn viewport(self) -> LogicalViewport {
147        self.viewport
148    }
149}
150
151impl LogicalViewport {
152    /// Builds a viewport from logical pixel dimensions.
153    ///
154    /// Both dimensions must be finite and strictly positive.
155    pub fn new(width: f32, height: f32) -> Result<Self, LogicalViewportError> {
156        if width.is_finite() && height.is_finite() && width > 0.0 && height > 0.0 {
157            Ok(Self { width, height })
158        } else {
159            Err(LogicalViewportError::InvalidDimensions { width, height })
160        }
161    }
162
163    /// Returns viewport width in logical screen pixels.
164    pub fn width(self) -> f32 {
165        self.width
166    }
167
168    /// Returns viewport height in logical screen pixels.
169    pub fn height(self) -> f32 {
170        self.height
171    }
172
173    /// Returns the center point in logical screen pixel coordinates.
174    pub fn center(self) -> LogicalScreenPosition {
175        LogicalScreenPosition::new(self.width * 0.5, self.height * 0.5)
176    }
177
178    /// Returns viewport size in logical screen pixels.
179    pub fn size(self) -> Vec2 {
180        Vec2::new(self.width, self.height)
181    }
182}
183
184/// Invalid logical dimensions supplied to [`LogicalViewport`].
185#[derive(Debug, Clone, Copy, PartialEq)]
186pub enum LogicalViewportError {
187    /// Width and height must both be finite and strictly positive.
188    InvalidDimensions {
189        /// Rejected width in logical screen pixels.
190        width: f32,
191        /// Rejected height in logical screen pixels.
192        height: f32,
193    },
194    /// A positioned viewport origin must be finite.
195    InvalidOrigin {
196        /// Rejected logical target position.
197        origin: LogicalScreenPosition,
198    },
199}
200
201impl fmt::Display for LogicalViewportError {
202    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
203        match self {
204            Self::InvalidDimensions { width, height } => write!(
205                formatter,
206                "viewport dimensions must be finite and positive, got {width}x{height}"
207            ),
208            Self::InvalidOrigin { origin } => {
209                write!(formatter, "viewport origin must be finite, got {origin:?}")
210            }
211        }
212    }
213}
214
215impl Error for LogicalViewportError {}
216
217/// Lightweight pseudo-depth projection for 2D scenes.
218///
219/// This is not a mesh renderer or z-buffer. It offsets 2D points using a scalar
220/// depth value so host applications can create camera-like depth transitions
221/// without leaving the 2D rendering model.
222#[derive(Debug, Clone, Copy, PartialEq)]
223pub struct Projection2d {
224    tilt: f32,
225    depth_scale: f32,
226}
227
228impl Projection2d {
229    /// Projection that leaves points in their original 2D plane.
230    pub const FLAT: Self = Self {
231        tilt: 0.0,
232        depth_scale: 1.0,
233    };
234
235    /// Builds a projection from tilt in radians and depth conversion scale.
236    ///
237    /// `depth_scale` is measured in world units per caller-defined depth unit.
238    /// Both values must be finite.
239    pub fn new(tilt: f32, depth_scale: f32) -> Result<Self, Projection2dError> {
240        if tilt.is_finite() && depth_scale.is_finite() {
241            Ok(Self { tilt, depth_scale })
242        } else {
243            Err(Projection2dError::NonFinite { tilt, depth_scale })
244        }
245    }
246
247    /// Returns projection tilt in radians.
248    pub fn tilt(self) -> f32 {
249        self.tilt
250    }
251
252    /// Returns depth conversion in world units per caller-defined depth unit.
253    pub fn depth_scale(self) -> f32 {
254        self.depth_scale
255    }
256
257    /// Projects a camera-relative world-space point with caller-provided pseudo-depth.
258    ///
259    /// This is the same relative-coordinate operation used by [`Camera2d`].
260    /// It is not an absolute-world transform and must not be applied before
261    /// [`Camera2d::world_to_screen`], which performs it itself.
262    pub fn project_relative(self, point: Vec2, depth: f32) -> Result<Vec2, Projection2dError> {
263        if !point.is_finite() || !depth.is_finite() {
264            return Err(Projection2dError::InvalidInput { point, depth });
265        }
266        let lifted = depth * self.depth_scale;
267        let projected = Vec2::new(
268            point.x + lifted * self.tilt.sin() * 0.5,
269            point.y * self.tilt.cos() + lifted * self.tilt.sin(),
270        );
271        if projected.is_finite() {
272            Ok(projected)
273        } else {
274            Err(Projection2dError::Overflow { point, depth })
275        }
276    }
277}
278
279/// Invalid pseudo-depth projection parameters.
280#[derive(Debug, Clone, Copy, PartialEq)]
281pub enum Projection2dError {
282    /// Tilt and depth scale must both be finite.
283    NonFinite {
284        /// Rejected projection tilt in radians.
285        tilt: f32,
286        /// Rejected world units per depth unit.
287        depth_scale: f32,
288    },
289    /// Relative world coordinates or depth are non-finite.
290    InvalidInput {
291        /// Rejected camera-relative world point.
292        point: Vec2,
293        /// Rejected caller-defined depth.
294        depth: f32,
295    },
296    /// Finite inputs overflowed while applying projection.
297    Overflow {
298        /// Camera-relative world point.
299        point: Vec2,
300        /// Caller-defined depth.
301        depth: f32,
302    },
303}
304
305impl fmt::Display for Projection2dError {
306    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
307        match self {
308            Self::NonFinite { tilt, depth_scale } => write!(
309                formatter,
310                "projection tilt and depth scale must be finite, got tilt {tilt} and scale {depth_scale}"
311            ),
312            Self::InvalidInput { point, depth } => write!(
313                formatter,
314                "projection point and depth must be finite, got {point:?} at depth {depth}"
315            ),
316            Self::Overflow { point, depth } => write!(
317                formatter,
318                "projection overflowed for {point:?} at depth {depth}"
319            ),
320        }
321    }
322}
323
324impl Error for Projection2dError {}
325
326/// 2D camera mapping world coordinates into logical screen pixels.
327///
328/// `center` and all input positions are in world units. `zoom` is logical screen
329/// pixels per world unit. `rotation` is in radians.
330#[derive(Debug, Clone, Copy, PartialEq)]
331pub struct Camera2d {
332    center: Vec2,
333    zoom: f32,
334    rotation: f32,
335    projection: Projection2d,
336}
337
338/// Invalid camera configuration or inverse projection request.
339#[derive(Debug, Clone, Copy, PartialEq)]
340pub enum Camera2dError {
341    /// Camera center must contain finite world coordinates.
342    InvalidCenter {
343        /// Rejected world-space center.
344        center: Vec2,
345    },
346    /// Zoom must be finite and strictly positive because it is logical pixels per world unit.
347    InvalidZoom {
348        /// Rejected zoom value.
349        zoom: f32,
350    },
351    /// Camera rotation must be finite.
352    InvalidRotation {
353        /// Rejected clockwise rotation in radians.
354        rotation: f32,
355    },
356    /// Screen coordinates and pseudo-depth used for picking must be finite.
357    InvalidPickingInput {
358        /// Rejected point in logical screen pixels.
359        screen: LogicalScreenPosition,
360        /// Rejected caller-defined pseudo-depth.
361        depth: f32,
362    },
363    /// The current projection collapses the requested picking plane.
364    SingularProjection {
365        /// Projection tilt in radians.
366        tilt: f32,
367    },
368    /// World coordinates or depth supplied for forward projection are non-finite.
369    InvalidProjectionInput {
370        /// Rejected world-space point.
371        world: Vec2,
372        /// Rejected caller-defined pseudo-depth.
373        depth: f32,
374    },
375    /// Finite forward-projection inputs overflowed logical screen coordinates.
376    ProjectionOverflow {
377        /// World-space point that could not be represented on screen.
378        world: Vec2,
379        /// Caller-defined pseudo-depth.
380        depth: f32,
381    },
382    /// World-space panning delta was non-finite or overflowed the center.
383    InvalidPan {
384        /// Rejected world-space delta.
385        delta: Vec2,
386    },
387    /// Cursor-centered zoom needs a finite, strictly positive multiplier.
388    InvalidZoomFactor {
389        /// Rejected multiplier.
390        factor: f32,
391    },
392    /// Bounds fitting requires finite, non-empty bounds and usable padding.
393    InvalidFitBounds {
394        /// Rejected world-space bounds.
395        bounds: Rect,
396        /// Rejected logical-pixel padding.
397        padding: f32,
398    },
399}
400
401impl fmt::Display for Camera2dError {
402    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
403        match self {
404            Self::InvalidCenter { center } => {
405                write!(formatter, "camera center must be finite, got {center:?}")
406            }
407            Self::InvalidZoom { zoom } => {
408                write!(
409                    formatter,
410                    "camera zoom must be finite and positive, got {zoom}"
411                )
412            }
413            Self::InvalidRotation { rotation } => {
414                write!(formatter, "camera rotation must be finite, got {rotation}")
415            }
416            Self::InvalidPickingInput { screen, depth } => write!(
417                formatter,
418                "screen coordinates and picking depth must be finite, got {screen:?} at depth {depth}"
419            ),
420            Self::SingularProjection { tilt } => {
421                write!(
422                    formatter,
423                    "projection tilt is singular for screen picking: {tilt}"
424                )
425            }
426            Self::InvalidProjectionInput { world, depth } => write!(
427                formatter,
428                "world coordinates and projection depth must be finite, got {world:?} at depth {depth}"
429            ),
430            Self::ProjectionOverflow { world, depth } => write!(
431                formatter,
432                "world-to-screen projection overflowed for {world:?} at depth {depth}"
433            ),
434            Self::InvalidPan { delta } => {
435                write!(
436                    formatter,
437                    "camera pan delta must be finite and keep the center finite, got {delta:?}"
438                )
439            }
440            Self::InvalidZoomFactor { factor } => {
441                write!(
442                    formatter,
443                    "camera zoom factor must be finite and positive, got {factor}"
444                )
445            }
446            Self::InvalidFitBounds { bounds, padding } => write!(
447                formatter,
448                "camera fit bounds must be finite and non-empty with usable padding, got {bounds:?} and padding {padding}"
449            ),
450        }
451    }
452}
453
454impl Error for Camera2dError {}
455
456impl Camera2d {
457    /// Smallest zoom accepted by camera constructors and setters.
458    pub const MIN_ZOOM: f32 = MIN_ZOOM;
459}
460
461impl Camera2d {
462    /// Builds a camera centered on a world-space point.
463    ///
464    /// `zoom` is logical screen pixels per world unit and must be finite and
465    /// positive. Invalid values return [`Camera2dError::InvalidZoom`] instead of
466    /// being silently clamped.
467    pub fn new(center: Vec2, zoom: f32) -> Result<Self, Camera2dError> {
468        validate_center(center)?;
469        validate_zoom(zoom)?;
470
471        Ok(Self {
472            center,
473            zoom,
474            rotation: 0.0,
475            projection: Projection2d::FLAT,
476        })
477    }
478
479    /// Returns the world-space point displayed at the viewport center.
480    pub fn center(self) -> Vec2 {
481        self.center
482    }
483
484    /// Replaces the world-space point displayed at the viewport center.
485    /// Invalid coordinates leave the current center unchanged.
486    pub fn set_center(&mut self, center: Vec2) -> Result<(), Camera2dError> {
487        validate_center(center)?;
488        self.center = center;
489        Ok(())
490    }
491
492    /// Returns camera scale in logical screen pixels per world unit.
493    pub fn zoom(self) -> f32 {
494        self.zoom
495    }
496
497    /// Replaces camera scale in logical screen pixels per world unit.
498    ///
499    /// Invalid values return [`Camera2dError::InvalidZoom`] and leave the
500    /// current zoom unchanged.
501    pub fn set_zoom(&mut self, zoom: f32) -> Result<(), Camera2dError> {
502        validate_zoom(zoom)?;
503        self.zoom = zoom;
504        Ok(())
505    }
506
507    /// Returns clockwise screen rotation in radians.
508    pub fn rotation(self) -> f32 {
509        self.rotation
510    }
511
512    /// Replaces clockwise screen rotation in radians.
513    /// Non-finite values leave the current rotation unchanged.
514    pub fn set_rotation(&mut self, rotation: f32) -> Result<(), Camera2dError> {
515        validate_rotation(rotation)?;
516        self.rotation = rotation;
517        Ok(())
518    }
519
520    /// Returns the pseudo-depth projection applied to camera-relative coordinates.
521    pub fn projection(self) -> Projection2d {
522        self.projection
523    }
524
525    /// Replaces the pseudo-depth projection applied to camera-relative coordinates.
526    pub fn set_projection(&mut self, projection: Projection2d) {
527        self.projection = projection;
528    }
529
530    /// Pans the displayed world center by a finite world-space delta.
531    pub fn pan_by(&mut self, delta: Vec2) -> Result<(), Camera2dError> {
532        let center = self.center + delta;
533        if !delta.is_finite() || !center.is_finite() {
534            return Err(Camera2dError::InvalidPan { delta });
535        }
536        self.center = center;
537        Ok(())
538    }
539
540    /// Changes zoom while keeping the depth-zero world point under `anchor` fixed.
541    ///
542    /// `anchor` is measured in logical pixels. The operation is atomic: invalid
543    /// factors, singular projections, or overflows leave this camera unchanged.
544    pub fn zoom_about_screen(
545        &mut self,
546        factor: f32,
547        anchor: LogicalScreenPosition,
548        viewport: LogicalViewport,
549    ) -> Result<(), Camera2dError> {
550        if !factor.is_finite() || factor <= 0.0 {
551            return Err(Camera2dError::InvalidZoomFactor { factor });
552        }
553        let world_before = self.screen_to_world(anchor, viewport)?;
554        let zoom = self.zoom * factor;
555        validate_zoom(zoom)?;
556        let mut candidate = *self;
557        candidate.zoom = zoom;
558        let world_after = candidate.screen_to_world(anchor, viewport)?;
559        let center = candidate.center + (world_before - world_after);
560        validate_center(center)?;
561        candidate.center = center;
562        *self = candidate;
563        Ok(())
564    }
565
566    /// Centers and zooms the camera so finite non-empty world bounds fit a viewport.
567    ///
568    /// `padding` is measured in logical pixels on every edge. The extent
569    /// calculation accounts for this camera's rotation and depth-zero tilt.
570    pub fn fit_to_bounds(
571        &mut self,
572        bounds: Rect,
573        padding: f32,
574        viewport: LogicalViewport,
575    ) -> Result<(), Camera2dError> {
576        let bounds = bounds.normalized();
577        if !bounds.min.is_finite()
578            || !bounds.max.is_finite()
579            || !padding.is_finite()
580            || padding < 0.0
581        {
582            return Err(Camera2dError::InvalidFitBounds { bounds, padding });
583        }
584        let available = viewport.size() - Vec2::splat(padding * 2.0);
585        let size = bounds.size();
586        let projection_y = self.projection.tilt.cos().abs();
587        let cos = self.rotation.cos().abs();
588        let sin = self.rotation.sin().abs();
589        let screen_extent = Vec2::new(
590            cos * size.x + sin * size.y * projection_y,
591            sin * size.x + cos * size.y * projection_y,
592        );
593        if size.x <= 0.0
594            || size.y <= 0.0
595            || available.x <= 0.0
596            || available.y <= 0.0
597            || screen_extent.x <= 0.0
598            || screen_extent.y <= 0.0
599            || !screen_extent.is_finite()
600        {
601            return Err(Camera2dError::InvalidFitBounds { bounds, padding });
602        }
603        let zoom = (available.x / screen_extent.x).min(available.y / screen_extent.y);
604        validate_zoom(zoom)?;
605        let center = bounds.center();
606        validate_center(center)?;
607        self.center = center;
608        self.zoom = zoom;
609        Ok(())
610    }
611
612    /// Converts a world-space point into logical screen pixel coordinates.
613    ///
614    /// Returns an error if finite values overflow during the transform.
615    pub fn world_to_screen(
616        self,
617        world: Vec2,
618        viewport: LogicalViewport,
619    ) -> Result<LogicalScreenPosition, Camera2dError> {
620        self.projected_world_to_screen(world, 0.0, viewport)
621    }
622
623    /// Converts a world-space point and pseudo-depth into logical screen pixels.
624    pub fn projected_world_to_screen(
625        self,
626        world: Vec2,
627        depth: f32,
628        viewport: LogicalViewport,
629    ) -> Result<LogicalScreenPosition, Camera2dError> {
630        if !world.is_finite() || !depth.is_finite() {
631            return Err(Camera2dError::InvalidProjectionInput { world, depth });
632        }
633        let relative = world - self.center;
634        let translated = self
635            .projection
636            .project_relative(relative, depth)
637            .map_err(|_| Camera2dError::ProjectionOverflow { world, depth })?;
638        let cos = self.rotation.cos();
639        let sin = self.rotation.sin();
640        let rotated = Vec2::new(
641            translated.x * cos - translated.y * sin,
642            translated.x * sin + translated.y * cos,
643        );
644
645        let screen = LogicalScreenPosition::new(
646            viewport.width() * 0.5 + rotated.x * self.zoom,
647            viewport.height() * 0.5 - rotated.y * self.zoom,
648        );
649        if screen.is_finite() {
650            Ok(screen)
651        } else {
652            Err(Camera2dError::ProjectionOverflow { world, depth })
653        }
654    }
655
656    /// Converts logical screen pixel coordinates back into world coordinates.
657    ///
658    /// This is equivalent to [`Camera2d::screen_to_world_at_depth`] with
659    /// `depth = 0.0`.
660    pub fn screen_to_world(
661        self,
662        screen: LogicalScreenPosition,
663        viewport: LogicalViewport,
664    ) -> Result<Vec2, Camera2dError> {
665        self.screen_to_world_at_depth(screen, 0.0, viewport)
666    }
667
668    /// Converts logical screen pixel coordinates into world coordinates on a pseudo-depth plane.
669    ///
670    /// `depth` must match the same caller-defined scalar depth passed to
671    /// [`Camera2d::projected_world_to_screen`]. If projection tilt is close to
672    /// 90 degrees, the inverse mapping is singular and returns
673    /// [`Camera2dError::SingularProjection`].
674    pub fn screen_to_world_at_depth(
675        self,
676        screen: LogicalScreenPosition,
677        depth: f32,
678        viewport: LogicalViewport,
679    ) -> Result<Vec2, Camera2dError> {
680        if !screen.is_finite() || !depth.is_finite() {
681            return Err(Camera2dError::InvalidPickingInput { screen, depth });
682        }
683
684        let screen = screen.to_vec2();
685
686        let translated = Vec2::new(
687            (screen.x - viewport.width() * 0.5) / self.zoom,
688            -(screen.y - viewport.height() * 0.5) / self.zoom,
689        );
690        let cos = self.rotation.cos();
691        let sin = self.rotation.sin();
692        let projected_delta = Vec2::new(
693            translated.x * cos + translated.y * sin,
694            -translated.x * sin + translated.y * cos,
695        );
696        let projection_cos = self.projection.tilt.cos();
697
698        if projection_cos.abs() < MIN_PROJECTION_COSINE {
699            return Err(Camera2dError::SingularProjection {
700                tilt: self.projection.tilt,
701            });
702        }
703
704        let lifted = depth * self.projection.depth_scale;
705        let relative = Vec2::new(
706            projected_delta.x - lifted * self.projection.tilt.sin() * 0.5,
707            (projected_delta.y - lifted * self.projection.tilt.sin()) / projection_cos,
708        );
709        let world = self.center + relative;
710        if world.is_finite() {
711            Ok(world)
712        } else {
713            Err(Camera2dError::InvalidPickingInput {
714                screen: LogicalScreenPosition::from_vec2(screen),
715                depth,
716            })
717        }
718    }
719
720    /// Creates a tween initialized with this camera state.
721    pub fn tween(self) -> Result<Tween<Self>, TweenError> {
722        Tween::new(self)
723    }
724}
725
726impl Default for Camera2d {
727    fn default() -> Self {
728        Self {
729            center: Vec2::ZERO,
730            zoom: 1.0,
731            rotation: 0.0,
732            projection: Projection2d::FLAT,
733        }
734    }
735}
736
737impl Interpolate for Projection2d {
738    fn interpolate(self, end: Self, amount: f32) -> Self {
739        let amount = finite_interpolation_amount(amount);
740        let tilt = self.tilt.interpolate(end.tilt, amount);
741        let depth_scale = self.depth_scale.interpolate(end.depth_scale, amount);
742        Self {
743            tilt: finite_or(tilt, self.tilt),
744            depth_scale: finite_or(depth_scale, self.depth_scale),
745        }
746    }
747
748    fn is_valid_interpolation_value(self) -> bool {
749        self.tilt.is_finite() && self.depth_scale.is_finite()
750    }
751}
752
753impl Interpolate for Camera2d {
754    fn interpolate(self, end: Self, amount: f32) -> Self {
755        let amount = finite_interpolation_amount(amount);
756        let center = self.center.interpolate(end.center, amount);
757        let zoom = self.zoom.interpolate(end.zoom, amount);
758        let rotation = self.rotation.interpolate(end.rotation, amount);
759        Self {
760            center: if center.is_finite() {
761                center
762            } else {
763                self.center
764            },
765            zoom: if zoom.is_finite() {
766                zoom.max(MIN_ZOOM)
767            } else {
768                self.zoom
769            },
770            rotation: finite_or(rotation, self.rotation),
771            projection: self.projection.interpolate(end.projection, amount),
772        }
773    }
774
775    fn is_valid_interpolation_value(self) -> bool {
776        self.center.is_finite()
777            && self.zoom.is_finite()
778            && self.zoom >= MIN_ZOOM
779            && self.rotation.is_finite()
780            && self.projection.is_valid_interpolation_value()
781    }
782}
783
784fn validate_zoom(zoom: f32) -> Result<(), Camera2dError> {
785    if zoom.is_finite() && zoom >= MIN_ZOOM {
786        Ok(())
787    } else {
788        Err(Camera2dError::InvalidZoom { zoom })
789    }
790}
791
792fn validate_center(center: Vec2) -> Result<(), Camera2dError> {
793    if center.is_finite() {
794        Ok(())
795    } else {
796        Err(Camera2dError::InvalidCenter { center })
797    }
798}
799
800fn validate_rotation(rotation: f32) -> Result<(), Camera2dError> {
801    if rotation.is_finite() {
802        Ok(())
803    } else {
804        Err(Camera2dError::InvalidRotation { rotation })
805    }
806}
807
808fn finite_interpolation_amount(amount: f32) -> f32 {
809    if amount.is_finite() { amount } else { 0.0 }
810}
811
812fn finite_or(value: f32, fallback: f32) -> f32 {
813    if value.is_finite() { value } else { fallback }
814}
815
816#[cfg(test)]
817mod tests {
818    use crate::{
819        Camera2d, Camera2dError, Interpolate, LogicalScreenPosition, LogicalViewport,
820        LogicalViewportError, PhysicalScreenPosition, Projection2d, Projection2dError, Vec2,
821    };
822
823    fn test_viewport() -> LogicalViewport {
824        let Ok(viewport) = LogicalViewport::new(1280.0, 720.0) else {
825            panic!("test viewport should be valid");
826        };
827        viewport
828    }
829
830    fn test_projection(tilt: f32, depth_scale: f32) -> Projection2d {
831        let Ok(projection) = Projection2d::new(tilt, depth_scale) else {
832            panic!("test projection should be valid");
833        };
834        projection
835    }
836
837    #[test]
838    fn camera_roundtrip_without_projection() {
839        let Ok(mut camera) = Camera2d::new(Vec2::new(20.0, -10.0), 2.5) else {
840            panic!("test camera should be valid");
841        };
842        assert!(camera.set_rotation(0.35).is_ok());
843
844        let viewport = test_viewport();
845        let world = Vec2::new(44.0, 12.0);
846
847        let screen = camera.world_to_screen(world, viewport).unwrap();
848        let Ok(roundtrip) = camera.screen_to_world(screen, viewport) else {
849            panic!("flat projection should be invertible");
850        };
851
852        assert!((roundtrip.x - world.x).abs() < 0.001);
853        assert!((roundtrip.y - world.y).abs() < 0.001);
854    }
855
856    #[test]
857    fn camera_roundtrip_at_depth() {
858        let Ok(mut camera) = Camera2d::new(Vec2::new(20.0, -10.0), 2.5) else {
859            panic!("test camera should be valid");
860        };
861        assert!(camera.set_rotation(0.35).is_ok());
862        camera.set_projection(test_projection(0.5, 1.25));
863
864        let viewport = test_viewport();
865        let world = Vec2::new(44.0, 12.0);
866        let depth = 9.0;
867
868        let screen = camera
869            .projected_world_to_screen(world, depth, viewport)
870            .unwrap();
871        let Ok(roundtrip) = camera.screen_to_world_at_depth(screen, depth, viewport) else {
872            panic!("projection should be invertible at this tilt");
873        };
874
875        assert!((roundtrip.x - world.x).abs() < 0.001);
876        assert!((roundtrip.y - world.y).abs() < 0.001);
877    }
878
879    #[test]
880    fn camera_rejects_invalid_zoom() {
881        let result = Camera2d::new(Vec2::ZERO, 0.0);
882
883        assert!(matches!(
884            result,
885            Err(Camera2dError::InvalidZoom { zoom }) if zoom == 0.0
886        ));
887    }
888
889    #[test]
890    fn projected_camera_center_stays_at_viewport_center() {
891        let center = Vec2::new(0.0, 100.0);
892        let Ok(mut camera) = Camera2d::new(center, 2.0) else {
893            panic!("test camera should be valid");
894        };
895        camera.set_projection(test_projection(std::f32::consts::FRAC_PI_3, 1.0));
896        assert!(camera.set_rotation(0.4).is_ok());
897        let viewport = test_viewport();
898
899        let screen = camera.world_to_screen(center, viewport).unwrap();
900
901        assert_eq!(screen, viewport.center());
902    }
903
904    #[test]
905    fn picking_requires_a_logical_screen_position_at_hidpi() {
906        let viewport = test_viewport();
907        let camera = Camera2d::default();
908        let physical_pointer = PhysicalScreenPosition::new(1_280.0, 720.0);
909        let logical_pointer = LogicalScreenPosition::from_vec2(physical_pointer.to_vec2() / 2.0);
910
911        let Ok(world) = camera.screen_to_world(logical_pointer, viewport) else {
912            panic!("logical center should be pickable");
913        };
914
915        assert_eq!(world, Vec2::ZERO);
916    }
917
918    #[test]
919    fn large_camera_center_uses_relative_projection_math() {
920        let center = Vec2::new(2.0e38, 0.0);
921        let world = Vec2::new(center.x + 1.0e33, 0.0);
922        let Ok(camera) = Camera2d::new(center, 2.0) else {
923            panic!("large finite camera should be valid");
924        };
925        let viewport = test_viewport();
926
927        let screen = camera.world_to_screen(world, viewport).unwrap();
928
929        assert!(screen.is_finite());
930        assert!(screen.to_vec2().x > viewport.center().to_vec2().x);
931    }
932
933    #[test]
934    fn forward_projection_reports_finite_overflow() {
935        let camera = Camera2d::new(Vec2::ZERO, f32::MAX).unwrap();
936        let viewport = test_viewport();
937
938        assert!(matches!(
939            camera.world_to_screen(Vec2::new(f32::MAX, 0.0), viewport),
940            Err(Camera2dError::ProjectionOverflow { .. })
941        ));
942    }
943
944    #[test]
945    fn pan_cursor_zoom_and_fit_preserve_coordinate_contracts() {
946        let viewport = test_viewport();
947        let mut camera = Camera2d::new(Vec2::new(5.0, -3.0), 2.0).unwrap();
948        camera.pan_by(Vec2::new(4.0, 7.0)).unwrap();
949        assert_eq!(camera.center(), Vec2::new(9.0, 4.0));
950
951        let anchor = LogicalScreenPosition::new(192.0, 531.0);
952        let world_before = camera.screen_to_world(anchor, viewport).unwrap();
953        camera.zoom_about_screen(1.75, anchor, viewport).unwrap();
954        let world_after = camera.screen_to_world(anchor, viewport).unwrap();
955        assert!((world_before.x - world_after.x).abs() < 0.0001);
956        assert!((world_before.y - world_after.y).abs() < 0.0001);
957
958        camera.set_rotation(0.35).unwrap();
959        camera.set_projection(test_projection(0.4, 1.0));
960        let bounds = crate::Rect::from_center_size(Vec2::new(30.0, -20.0), Vec2::new(80.0, 40.0));
961        camera.fit_to_bounds(bounds, 24.0, viewport).unwrap();
962        assert_eq!(camera.center(), bounds.center());
963        for corner in [bounds.min, bounds.max] {
964            let screen = camera.world_to_screen(corner, viewport).unwrap().to_vec2();
965            assert!(screen.x >= 24.0 && screen.x <= viewport.width() - 24.0);
966            assert!(screen.y >= 24.0 && screen.y <= viewport.height() - 24.0);
967        }
968    }
969
970    #[test]
971    fn camera_helpers_reject_invalid_inputs_without_mutation() {
972        let viewport = test_viewport();
973        let mut camera = Camera2d::default();
974        let before = camera;
975        assert!(matches!(
976            camera.pan_by(Vec2::new(f32::NAN, 0.0)),
977            Err(Camera2dError::InvalidPan { .. })
978        ));
979        assert_eq!(camera, before);
980        assert!(matches!(
981            camera.zoom_about_screen(0.0, viewport.center(), viewport),
982            Err(Camera2dError::InvalidZoomFactor { .. })
983        ));
984        assert_eq!(camera, before);
985        assert!(matches!(
986            camera.fit_to_bounds(
987                crate::Rect::from_center_size(Vec2::ZERO, Vec2::new(0.0, 1.0)),
988                0.0,
989                viewport
990            ),
991            Err(Camera2dError::InvalidFitBounds { .. })
992        ));
993        assert_eq!(camera, before);
994    }
995
996    #[test]
997    fn relative_projection_matches_camera_centered_pipeline() {
998        let center = Vec2::new(10.0, 100.0);
999        let mut camera = Camera2d::new(center, 2.0).unwrap();
1000        let projection = test_projection(0.6, 1.25);
1001        camera.set_projection(projection);
1002        let viewport = test_viewport();
1003
1004        assert_eq!(
1005            projection.project_relative(Vec2::ZERO, 0.0).unwrap(),
1006            Vec2::ZERO
1007        );
1008        assert_eq!(
1009            camera
1010                .projected_world_to_screen(center, 0.0, viewport)
1011                .unwrap(),
1012            viewport.center()
1013        );
1014    }
1015
1016    #[test]
1017    fn picking_rejects_non_finite_and_near_singular_inputs() {
1018        let Ok(mut camera) = Camera2d::new(Vec2::ZERO, 1.0) else {
1019            panic!("test camera should be valid");
1020        };
1021        let viewport = test_viewport();
1022
1023        assert!(matches!(
1024            camera.screen_to_world(LogicalScreenPosition::new(f32::NAN, 0.0), viewport),
1025            Err(Camera2dError::InvalidPickingInput { .. })
1026        ));
1027
1028        camera.set_projection(test_projection(std::f32::consts::FRAC_PI_2 - 0.00001, 1.0));
1029        assert!(matches!(
1030            camera.screen_to_world(viewport.center(), viewport),
1031            Err(Camera2dError::SingularProjection { .. })
1032        ));
1033    }
1034
1035    #[test]
1036    fn camera_projection_and_viewport_reject_non_finite_configuration() {
1037        assert!(matches!(
1038            Camera2d::new(Vec2::new(f32::INFINITY, 0.0), 1.0),
1039            Err(Camera2dError::InvalidCenter { .. })
1040        ));
1041        assert!(matches!(
1042            Projection2d::new(f32::NAN, 1.0),
1043            Err(Projection2dError::NonFinite { .. })
1044        ));
1045        assert!(matches!(
1046            LogicalViewport::new(0.0, f32::INFINITY),
1047            Err(LogicalViewportError::InvalidDimensions { .. })
1048        ));
1049    }
1050
1051    #[test]
1052    fn camera_interpolation_preserves_finite_invariants() {
1053        let Ok(start) = Camera2d::new(Vec2::splat(f32::MAX), f32::MAX) else {
1054            panic!("finite extreme camera should be valid");
1055        };
1056        let Ok(end) = Camera2d::new(Vec2::splat(-f32::MAX), 1.0) else {
1057            panic!("finite extreme camera should be valid");
1058        };
1059
1060        let interpolated = start.interpolate(end, 0.5);
1061
1062        assert!(interpolated.center().is_finite());
1063        assert!(interpolated.zoom().is_finite());
1064    }
1065}