ferravex_play/camera/
composition.rs

1//! Authored world-space composition zones. Presentation offsets never alter the
2//! tracked body or shooter aim; first-person input is passed through unchanged.
3//!
4//! Perspective group framing is a separate, stateless calculation: it fits
5//! authored subject bounds before camera damping, obstruction and shake. Those
6//! later effects can move a subject outside the requested screen margins.
7use super::*;
8use ferravex_math::Vec2;
9
10/// Maximum number of subject boxes examined by one framing calculation.
11pub const MAX_FRAMING_SUBJECTS: usize = 256;
12
13/// An axis-aligned world-space subject box. Equal endpoints on any axis are
14/// allowed, including a point subject. Each coordinate must be within ±1e6.
15/// Bounds are checked by [`FramingSettings::frame`], including public-field edits.
16#[derive(Clone, Copy, Debug, PartialEq)]
17pub struct FramingBounds {
18    pub min: Vec3,
19    pub max: Vec3,
20}
21
22impl FramingBounds {
23    fn valid(self) -> bool {
24        bounded(self.min)
25            && bounded(self.max)
26            && (0..3).all(|axis| self.min[axis] <= self.max[axis])
27    }
28
29    fn corners(self) -> impl Iterator<Item = Vec3> {
30        (0..8).map(move |bits| {
31            Vec3::new(
32                if bits & 1 == 0 {
33                    self.min.x
34                } else {
35                    self.max.x
36                },
37                if bits & 2 == 0 {
38                    self.min.y
39                } else {
40                    self.max.y
41                },
42                if bits & 4 == 0 {
43                    self.min.z
44                } else {
45                    self.max.z
46                },
47            )
48        })
49    }
50}
51
52/// A rejected framing request. No camera or composer state is changed.
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub enum FramingError {
55    /// Invalid aspect, field of view, margins, near plane or distance limits.
56    InvalidSettings,
57    /// The view quaternion is non-finite or not unit length (tolerance 0.001).
58    InvalidRotation,
59    EmptyGroup,
60    /// More than [`MAX_FRAMING_SUBJECTS`] boxes were supplied; none are ignored.
61    TooManySubjects,
62    /// The first non-finite, inverted or out-of-range box, in input order.
63    InvalidBounds {
64        index: usize,
65    },
66    /// The required distance overflows f32, the eye exceeds ±1e6, or rounding
67    /// the computed pose loses its separation/framing at the supplied world scale.
68    Unrepresentable,
69}
70
71impl std::fmt::Display for FramingError {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        write!(f, "camera framing: {self:?}")
74    }
75}
76
77impl std::error::Error for FramingError {}
78
79/// How authored distance limits affected a framing result.
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81pub enum FramingLimit {
82    /// The computed fit distance lies inside the configured inclusive limits.
83    None,
84    /// A small/degenerate group uses the configured minimum distance.
85    MinimumDistance,
86    /// The camera cannot back away far enough to satisfy all framing constraints.
87    MaximumDistance,
88}
89
90/// A perspective framing solution, before damping, obstruction and shake.
91/// The host must use the same aspect and vertical FOV, a near clip plane no
92/// larger than the requested `near`, and a sufficiently distant far clip plane.
93/// Floating-point projection retains ordinary f32 rounding error.
94#[derive(Clone, Copy, Debug, PartialEq)]
95pub struct FramingResult {
96    /// Looks at the center of the group's world-space enclosing box.
97    pub pose: Pose3,
98    /// Selected boom length after applying the configured distance limits.
99    pub distance: f32,
100    /// Unclamped distance needed for the margins and near plane, rounded upward
101    /// to f32. It may exceed `distance` when the maximum prevents a complete fit.
102    pub required_distance: f32,
103    pub limit: FramingLimit,
104}
105
106/// Checked perspective framing constraints. All fields are revalidated on use.
107///
108/// A box's eight corners are projected independently, including their depth;
109/// framing does not approximate a subject by a point or use vertical FOV for
110/// both axes. The fit holds the orientation and group center fixed. It is not
111/// an optimization over alternative orientations or target positions.
112///
113/// ```
114/// use ferravex_math::{Quat, Vec2, Vec3};
115/// use ferravex_play::camera::{FramingBounds, FramingLimit, FramingSettings};
116/// let subjects = [FramingBounds { min: -Vec3::ONE, max: Vec3::ONE }];
117/// let settings = FramingSettings {
118///     aspect_ratio: 9. / 16., // width / height of a portrait viewport
119///     margin: Vec2::splat(0.1), // reserve 10% along each screen edge
120///     ..Default::default()
121/// };
122/// let frame = settings.frame(&subjects, Quat::IDENTITY)?;
123/// assert_ne!(frame.limit, FramingLimit::MaximumDistance);
124/// assert_eq!(frame.pose.target, Vec3::ZERO);
125/// // Copy frame.pose into the presentation camera using the same aspect ratio.
126/// # Ok::<(), ferravex_play::camera::FramingError>(())
127/// ```
128#[derive(Clone, Copy, Debug, PartialEq)]
129pub struct FramingSettings {
130    /// Finite positive viewport width / height.
131    pub aspect_ratio: f32,
132    /// Vertical field of view in radians, in `0.05..=3.1`, matching [`Input3`].
133    pub fov_y: f32,
134    /// Symmetric per-edge fractions of the full viewport width and height.
135    /// Each component must be finite and in `0..0.5`. For example, `x = 0.1`
136    /// leaves 80% of the width for subjects, independent of the aspect ratio.
137    pub margin: Vec2,
138    /// Minimum view-space depth of every corner, in `0.001..=1e5` world units.
139    pub near: f32,
140    /// Positive boom floor, in `0.01..=1e5`; prevents point subjects collapsing
141    /// the eye onto the target. Must not exceed `max_distance`.
142    pub min_distance: f32,
143    /// Boom ceiling in `min_distance..=1e5`. A constrained fit is returned with
144    /// [`FramingLimit::MaximumDistance`], rather than silently claiming success.
145    pub max_distance: f32,
146}
147
148impl Default for FramingSettings {
149    fn default() -> Self {
150        Self {
151            aspect_ratio: 16. / 9.,
152            fov_y: std::f32::consts::FRAC_PI_3,
153            margin: Vec2::splat(0.05),
154            near: 0.1,
155            min_distance: 0.5,
156            max_distance: 1e5,
157        }
158    }
159}
160
161impl FramingSettings {
162    fn valid(self) -> bool {
163        self.aspect_ratio.is_finite()
164            && self.aspect_ratio > 0.
165            && self.fov_y.is_finite()
166            && (0.05..=3.1).contains(&self.fov_y)
167            && self.margin.is_finite()
168            && (0. ..0.5).contains(&self.margin.x)
169            && (0. ..0.5).contains(&self.margin.y)
170            && self.near.is_finite()
171            && (0.001..=1e5).contains(&self.near)
172            && self.min_distance.is_finite()
173            && (0.01..=1e5).contains(&self.min_distance)
174            && self.max_distance.is_finite()
175            && (self.min_distance..=1e5).contains(&self.max_distance)
176    }
177
178    /// Frame one subject or a group without allocations or camera mutation.
179    ///
180    /// `view_rotation` maps camera-local -Z to the viewing direction and +Y to
181    /// up; identity places the eye on the group's +Z side. Accepted quaternions
182    /// are normalized before use. Each call examines at most 256 boxes, with
183    /// two passes over their 2048 corners and constant storage. Duplicate boxes
184    /// do not change the fit.
185    ///
186    /// Errors are checked in this order: settings, rotation, group length,
187    /// individual bounds, then the representability of the result. Empty groups
188    /// return an error so the caller can retain its last presentation pose.
189    /// A maximum-distance result may violate both margins and near clearance;
190    /// callers must inspect `limit` before relying on the fit.
191    ///
192    /// ```
193    /// use ferravex_math::{Quat, Vec3};
194    /// use ferravex_play::camera::{FramingBounds, FramingError, FramingLimit, FramingSettings};
195    /// let point = FramingBounds { min: Vec3::ZERO, max: Vec3::ZERO };
196    /// let settings = FramingSettings::default();
197    /// let frame = settings.frame(&[point], Quat::IDENTITY)?;
198    /// assert_eq!(frame.limit, FramingLimit::MinimumDistance);
199    /// assert_eq!(frame.distance, settings.min_distance);
200    /// assert_eq!(settings.frame(&[], Quat::IDENTITY), Err(FramingError::EmptyGroup));
201    /// # Ok::<(), FramingError>(())
202    /// ```
203    pub fn frame(
204        self,
205        subjects: &[FramingBounds],
206        view_rotation: Quat,
207    ) -> Result<FramingResult, FramingError> {
208        if !self.valid() {
209            return Err(FramingError::InvalidSettings);
210        }
211        if !view_rotation.is_finite() || (view_rotation.length_squared() - 1.).abs() > 0.001 {
212            return Err(FramingError::InvalidRotation);
213        }
214        if subjects.is_empty() {
215            return Err(FramingError::EmptyGroup);
216        }
217        if subjects.len() > MAX_FRAMING_SUBJECTS {
218            return Err(FramingError::TooManySubjects);
219        }
220        let mut min = subjects[0].min;
221        let mut max = subjects[0].max;
222        for (index, subject) in subjects.iter().enumerate() {
223            if !subject.valid() {
224                return Err(FramingError::InvalidBounds { index });
225            }
226            min = min.min(subject.min);
227            max = max.max(subject.max);
228        }
229        let center = (min + max) * 0.5;
230        let rotation = view_rotation.normalize();
231        let back = (rotation * Vec3::Z).normalize();
232        let (right, up) = basis(-back, rotation * Vec3::Y);
233        let tangent = (f64::from(self.fov_y) * 0.5).tan();
234        let horizontal =
235            tangent * f64::from(self.aspect_ratio) * (1. - 2. * f64::from(self.margin.x));
236        let vertical = tangent * (1. - 2. * f64::from(self.margin.y));
237        let mut required = 0_f64;
238        for point in subjects.iter().flat_map(|subject| subject.corners()) {
239            // Subtract in f64 so tiny extents at a large world position do not
240            // disappear in intermediate math, and extreme valid aspects do not
241            // overflow before the final explicit representability check.
242            let project = |axis: Vec3| -> f64 {
243                (0..3)
244                    .map(|i| (f64::from(point[i]) - f64::from(center[i])) * f64::from(axis[i]))
245                    .sum()
246            };
247            let z = project(back);
248            required = required
249                .max(z + project(right).abs() / horizontal)
250                .max(z + project(up).abs() / vertical)
251                .max(z + f64::from(self.near));
252        }
253        let mut required_distance = required as f32;
254        if f64::from(required_distance) < required {
255            required_distance = required_distance.next_up();
256        }
257        if !required_distance.is_finite() {
258            return Err(FramingError::Unrepresentable);
259        }
260        let limit = if required_distance > self.max_distance {
261            FramingLimit::MaximumDistance
262        } else if required_distance < self.min_distance {
263            FramingLimit::MinimumDistance
264        } else {
265            FramingLimit::None
266        };
267        let distance = required_distance.clamp(self.min_distance, self.max_distance);
268        let position = center + back * distance;
269        if !bounded(position) || position.distance_squared(center) <= 1e-6 {
270            return Err(FramingError::Unrepresentable);
271        }
272        // Rounding a small boom at a large world coordinate can lose a sizable
273        // part of the near clearance or change the view direction. Do not report
274        // a complete fit when the actual stored pose cannot retain it. Allow
275        // ordinary f32 basis rounding, but not scale-dependent clipping.
276        if limit != FramingLimit::MaximumDistance {
277            let actual_back = (position - center).normalize();
278            let (actual_right, actual_up) = basis(-actual_back, up);
279            let tolerance = 32. * f64::from(f32::EPSILON);
280            for point in subjects.iter().flat_map(|subject| subject.corners()) {
281                let project = |axis: Vec3| -> f64 {
282                    (0..3)
283                        .map(|i| {
284                            (f64::from(point[i]) - f64::from(position[i])) * f64::from(axis[i])
285                        })
286                        .sum()
287                };
288                let depth = -project(actual_back);
289                if depth < f64::from(self.near) * (1. - tolerance)
290                    || project(actual_right).abs() > depth * horizontal * (1. + tolerance)
291                    || project(actual_up).abs() > depth * vertical * (1. + tolerance)
292                {
293                    return Err(FramingError::Unrepresentable);
294                }
295            }
296        }
297        Ok(FramingResult {
298            pose: Pose3 {
299                position,
300                target: center,
301                up,
302                fov_y: self.fov_y,
303            },
304            distance,
305            required_distance,
306            limit,
307        })
308    }
309}
310
311#[derive(Clone, Copy, Debug, PartialEq)]
312pub struct CameraZone {
313    pub min: Vec3,
314    pub max: Vec3,
315    pub feather: f32,
316    pub priority: i16,
317    pub focus_offset: Vec3,
318    pub boom_scale: f32,
319    pub fov_scale: f32,
320}
321impl CameraZone {
322    fn valid(self) -> bool {
323        bounded(self.min)
324            && bounded(self.max)
325            && (self.max - self.min).min_element() > 0.
326            && nonnegative(self.feather, 10000.)
327            && bounded(self.focus_offset)
328            && self.boom_scale.is_finite()
329            && (0.5..=2.).contains(&self.boom_scale)
330            && self.fov_scale.is_finite()
331            && (0.5..=1.5).contains(&self.fov_scale)
332    }
333    fn weight(self, p: Vec3) -> f32 {
334        let margin = (p - self.min).min(self.max - p).min_element();
335        if margin < 0. {
336            0.
337        } else if self.feather == 0. {
338            1.
339        } else {
340            (margin / self.feather).clamp(0., 1.)
341        }
342    }
343}
344#[derive(Clone, Copy, Debug, PartialEq)]
345pub struct CameraComposer<const N: usize> {
346    zones: [CameraZone; N],
347    anticipation: f32,
348    max_lead: f32,
349    half_life: f32,
350    offset: Vec3,
351    boom: f32,
352    fov: f32,
353}
354impl<const N: usize> CameraComposer<N> {
355    pub fn new(
356        zones: [CameraZone; N],
357        anticipation: f32,
358        max_lead: f32,
359        half_life: f32,
360    ) -> Result<Self, CameraError> {
361        if N > 32
362            || zones.iter().any(|z| !z.valid())
363            || !nonnegative(anticipation, 1.)
364            || !nonnegative(max_lead, 100.)
365            || !nonnegative(half_life, 10.)
366        {
367            return Err(CameraError::InvalidSettings);
368        }
369        Ok(Self {
370            zones,
371            anticipation,
372            max_lead,
373            half_life,
374            offset: Vec3::ZERO,
375            boom: 1.,
376            fov: 1.,
377        })
378    }
379    pub fn clear(&mut self) {
380        self.offset = Vec3::ZERO;
381        self.boom = 1.;
382        self.fov = 1.;
383    }
384    pub fn update(
385        &mut self,
386        mut input: Input3,
387        acceleration: Vec3,
388        dt: f32,
389    ) -> Result<Input3, CameraError> {
390        if !valid_dt(dt)
391            || !bounded(input.target.position)
392            || !bounded(input.target.velocity)
393            || !bounded(acceleration)
394            || !input.target.rotation.is_finite()
395            || (input.target.rotation.length_squared() - 1.).abs() > 0.001
396            || !input.fov_y.is_finite()
397            || !(0.05..=3.1).contains(&input.fov_y)
398        {
399            return Err(CameraError::InvalidInput);
400        }
401        input.mode.desired(input.target)?;
402        if matches!(input.mode, Mode3::FirstPerson { .. }) {
403            return Ok(input);
404        }
405        let mut selected = None;
406        let mut priority = i16::MIN;
407        for zone in self.zones {
408            let weight = zone.weight(input.target.position);
409            if weight > 0. && (selected.is_none() || zone.priority > priority) {
410                selected = Some((zone, weight));
411                priority = zone.priority;
412            }
413        }
414        let (focus, boom, fov) = selected.map_or((Vec3::ZERO, 1., 1.), |(z, w)| {
415            (
416                z.focus_offset * w,
417                1. + (z.boom_scale - 1.) * w,
418                1. + (z.fov_scale - 1.) * w,
419            )
420        });
421        let lead = (input.target.velocity * self.anticipation
422            + acceleration * (0.5 * self.anticipation * self.anticipation))
423            .clamp_length_max(self.max_lead);
424        let alpha = if self.half_life == 0. {
425            1.
426        } else {
427            1. - (-std::f32::consts::LN_2 * dt / self.half_life).exp()
428        };
429        let mut next = *self;
430        next.offset = next.offset.lerp(focus + lead, alpha);
431        next.boom += (boom - next.boom) * alpha;
432        next.fov += (fov - next.fov) * alpha;
433        input.target.position += next.offset;
434        input.fov_y = (input.fov_y * next.fov).clamp(0.05, 3.1);
435        match &mut input.mode {
436            Mode3::Follow {
437                eye_offset,
438                look_offset,
439            } => *eye_offset = *look_offset + (*eye_offset - *look_offset) * next.boom,
440            Mode3::Orbit { distance, .. } => *distance *= next.boom,
441            Mode3::Chase {
442                distance, height, ..
443            } => {
444                *distance *= next.boom;
445                *height *= next.boom;
446            }
447            Mode3::FirstPerson { .. } => {}
448        }
449        input.mode.desired(input.target)?;
450        if !bounded(input.target.position) {
451            return Err(CameraError::InvalidInput);
452        }
453        *self = next;
454        Ok(input)
455    }
456}
457#[cfg(test)]
458mod tests {
459    use super::*;
460    use ferravex_math::Mat4;
461
462    fn box_at(center: Vec3, half: Vec3) -> FramingBounds {
463        FramingBounds {
464            min: center - half,
465            max: center + half,
466        }
467    }
468
469    fn assert_framed(settings: FramingSettings, subjects: &[FramingBounds], frame: FramingResult) {
470        assert_ne!(frame.limit, FramingLimit::MaximumDistance);
471        assert!(frame.distance >= settings.min_distance);
472        assert!(frame.distance <= settings.max_distance);
473        assert!(frame.distance >= frame.required_distance);
474        assert_eq!(frame.pose.fov_y, settings.fov_y);
475        let view = Mat4::look_at_rh(frame.pose.position, frame.pose.target, frame.pose.up);
476        let projection =
477            Mat4::perspective_rh_gl(settings.fov_y, settings.aspect_ratio, settings.near, 1e7);
478        assert!(view.is_finite());
479        for point in subjects.iter().flat_map(|subject| subject.corners()) {
480            let camera = view.transform_point3(point);
481            assert!(-camera.z >= settings.near - 1e-5, "depth: {camera:?}");
482            let screen = projection.project_point3(camera);
483            assert!(
484                screen.x.abs() <= 1. - 2. * settings.margin.x + 1e-5,
485                "x: {screen:?}"
486            );
487            assert!(
488                screen.y.abs() <= 1. - 2. * settings.margin.y + 1e-5,
489                "y: {screen:?}"
490            );
491        }
492    }
493
494    #[test]
495    fn portrait_and_ultrawide_use_both_fov_axes() {
496        let subjects = [box_at(Vec3::ZERO, Vec3::new(4., 2., 1.))];
497        let mut distances = [0.; 2];
498        for (index, aspect_ratio) in [9. / 16., 32. / 9.].into_iter().enumerate() {
499            let settings = FramingSettings {
500                aspect_ratio,
501                fov_y: std::f32::consts::FRAC_PI_2,
502                margin: Vec2::ZERO,
503                ..Default::default()
504            };
505            let frame = settings.frame(&subjects, Quat::IDENTITY).unwrap();
506            assert_framed(settings, &subjects, frame);
507            let expected = 1. + (4. / aspect_ratio).max(2.);
508            assert!((frame.distance - expected).abs() < 1e-5);
509            assert_eq!(frame.limit, FramingLimit::None);
510            distances[index] = frame.distance;
511        }
512        assert!(distances[0] > distances[1] * 2.);
513    }
514
515    #[test]
516    fn margins_are_per_edge_and_independent_of_aspect() {
517        let subjects = [box_at(Vec3::ZERO, Vec3::new(2., 1., 0.))];
518        for aspect_ratio in [9. / 16., 1., 32. / 9.] {
519            let plain = FramingSettings {
520                aspect_ratio,
521                margin: Vec2::ZERO,
522                ..Default::default()
523            };
524            let padded = FramingSettings {
525                margin: Vec2::splat(0.25),
526                ..plain
527            };
528            let small = plain.frame(&subjects, Quat::IDENTITY).unwrap();
529            let large = padded.frame(&subjects, Quat::IDENTITY).unwrap();
530            assert!((large.distance - small.distance * 2.).abs() < 1e-5);
531            assert_framed(padded, &subjects, large);
532            let unequal = FramingSettings {
533                margin: Vec2::new(0.1, 0.35),
534                ..plain
535            };
536            assert_framed(
537                unequal,
538                &subjects,
539                unequal.frame(&subjects, Quat::IDENTITY).unwrap(),
540            );
541        }
542    }
543
544    #[test]
545    fn rotated_group_includes_each_subjects_depth_and_bounds() {
546        let subjects = [
547            box_at(Vec3::new(-3., 2., -6.), Vec3::new(1., 2., 0.5)),
548            box_at(Vec3::new(5., -1., 3.), Vec3::new(2., 1., 2.)),
549            box_at(Vec3::new(0., 3., 2.), Vec3::ZERO),
550        ];
551        for aspect_ratio in [9. / 16., 32. / 9.] {
552            for rotation in [
553                Quat::IDENTITY,
554                Quat::from_rotation_y(0.8) * Quat::from_rotation_x(-0.4),
555                Quat::from_rotation_z(0.6) * Quat::from_rotation_x(1.5),
556            ] {
557                let settings = FramingSettings {
558                    aspect_ratio,
559                    ..Default::default()
560                };
561                let frame = settings.frame(&subjects, rotation).unwrap();
562                assert_eq!(frame.pose.target, Vec3::new(1.5, 1., -0.75));
563                assert_framed(settings, &subjects, frame);
564            }
565        }
566    }
567
568    #[test]
569    fn points_lines_and_near_zero_bounds_have_a_usable_boom() {
570        let settings = FramingSettings::default();
571        for half in [
572            Vec3::ZERO,
573            Vec3::splat(1e-30),
574            Vec3::splat(1e-8),
575            Vec3::Y * 1e-8,
576        ] {
577            let subjects = [box_at(Vec3::ZERO, half)];
578            let frame = settings.frame(&subjects, Quat::IDENTITY).unwrap();
579            assert_eq!(frame.distance, settings.min_distance);
580            assert_eq!(frame.limit, FramingLimit::MinimumDistance);
581            assert_framed(settings, &subjects, frame);
582        }
583        let line = [box_at(Vec3::ZERO, Vec3::Z * 10.)];
584        let frame = settings.frame(&line, Quat::IDENTITY).unwrap();
585        assert!((frame.distance - 10.1).abs() < 1e-5);
586        assert_framed(settings, &line, frame);
587    }
588
589    #[test]
590    fn near_plane_is_checked_even_for_a_point_or_very_wide_fov() {
591        let settings = FramingSettings {
592            fov_y: 3.1,
593            near: 5.,
594            ..Default::default()
595        };
596        for half in [Vec3::ZERO, Vec3::ONE] {
597            let subjects = [box_at(Vec3::ZERO, half)];
598            let frame = settings.frame(&subjects, Quat::IDENTITY).unwrap();
599            assert_eq!(frame.distance, 5. + half.z);
600            assert_framed(settings, &subjects, frame);
601        }
602    }
603
604    #[test]
605    fn maximum_distance_reports_unmet_screen_and_near_constraints() {
606        for (half, near) in [(Vec3::splat(10.), 0.1), (Vec3::ZERO, 5.)] {
607            let settings = FramingSettings {
608                max_distance: 2.,
609                near,
610                ..Default::default()
611            };
612            let frame = settings
613                .frame(&[box_at(Vec3::ZERO, half)], Quat::IDENTITY)
614                .unwrap();
615            assert_eq!(frame.limit, FramingLimit::MaximumDistance);
616            assert_eq!(frame.distance, 2.);
617            assert!(frame.required_distance > frame.distance);
618        }
619        let settings = FramingSettings {
620            min_distance: 0.5,
621            max_distance: 0.5,
622            near: 0.5,
623            ..Default::default()
624        };
625        let point = [box_at(Vec3::ZERO, Vec3::ZERO)];
626        let frame = settings.frame(&point, Quat::IDENTITY).unwrap();
627        assert_eq!(frame.limit, FramingLimit::None);
628        assert_framed(settings, &point, frame);
629    }
630
631    #[test]
632    fn group_order_duplicates_and_capacity_do_not_change_the_fit() {
633        let a = box_at(Vec3::X * -4., Vec3::ONE);
634        let b = box_at(Vec3::X * 2., Vec3::ONE);
635        let settings = FramingSettings::default();
636        let frame = settings.frame(&[a, b], Quat::IDENTITY).unwrap();
637        assert_eq!(settings.frame(&[b, a, b], Quat::IDENTITY), Ok(frame));
638        let mut maximum = [a; MAX_FRAMING_SUBJECTS];
639        maximum[MAX_FRAMING_SUBJECTS - 1] = b;
640        assert_eq!(settings.frame(&maximum, Quat::IDENTITY), Ok(frame));
641        assert_eq!(
642            settings.frame(&[], Quat::IDENTITY),
643            Err(FramingError::EmptyGroup)
644        );
645        assert_eq!(
646            settings.frame(&[a; MAX_FRAMING_SUBJECTS + 1], Quat::IDENTITY),
647            Err(FramingError::TooManySubjects)
648        );
649    }
650
651    #[test]
652    fn invalid_bounds_report_the_first_index_instead_of_dropping_subjects() {
653        let valid = box_at(Vec3::ZERO, Vec3::ONE);
654        for bad in [
655            FramingBounds {
656                min: Vec3::ONE,
657                max: Vec3::ZERO,
658            },
659            FramingBounds {
660                min: Vec3::splat(f32::NAN),
661                max: Vec3::ZERO,
662            },
663            FramingBounds {
664                min: Vec3::ZERO,
665                max: Vec3::splat(f32::INFINITY),
666            },
667            FramingBounds {
668                min: Vec3::ZERO,
669                max: Vec3::splat(1e6 + 1.),
670            },
671        ] {
672            assert_eq!(
673                FramingSettings::default().frame(&[valid, bad, bad], Quat::IDENTITY),
674                Err(FramingError::InvalidBounds { index: 1 })
675            );
676        }
677    }
678
679    #[test]
680    fn invalid_settings_are_rejected_on_every_call() {
681        let base = FramingSettings::default();
682        let point = [box_at(Vec3::ZERO, Vec3::ZERO)];
683        for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1., 0.] {
684            for settings in [
685                FramingSettings {
686                    aspect_ratio: invalid,
687                    ..base
688                },
689                FramingSettings {
690                    fov_y: invalid,
691                    ..base
692                },
693                FramingSettings {
694                    near: invalid,
695                    ..base
696                },
697                FramingSettings {
698                    min_distance: invalid,
699                    ..base
700                },
701                FramingSettings {
702                    max_distance: invalid,
703                    ..base
704                },
705            ] {
706                assert_eq!(
707                    settings.frame(&point, Quat::IDENTITY),
708                    Err(FramingError::InvalidSettings)
709                );
710            }
711        }
712        for settings in [
713            FramingSettings {
714                margin: Vec2::new(-0.01, 0.),
715                ..base
716            },
717            FramingSettings {
718                margin: Vec2::new(0., 0.5),
719                ..base
720            },
721            FramingSettings {
722                margin: Vec2::splat(f32::NAN),
723                ..base
724            },
725            FramingSettings {
726                margin: Vec2::splat(f32::INFINITY),
727                ..base
728            },
729            FramingSettings {
730                fov_y: 0.049,
731                ..base
732            },
733            FramingSettings {
734                fov_y: 3.11,
735                ..base
736            },
737            FramingSettings {
738                min_distance: 0.001,
739                ..base
740            },
741            FramingSettings {
742                near: 0.0001,
743                ..base
744            },
745            FramingSettings {
746                min_distance: 2.,
747                max_distance: 1.,
748                ..base
749            },
750            FramingSettings {
751                max_distance: 1e6,
752                ..base
753            },
754        ] {
755            assert_eq!(
756                settings.frame(&point, Quat::IDENTITY),
757                Err(FramingError::InvalidSettings)
758            );
759        }
760        // The same value remains usable after an error; nothing is cached/mutated.
761        assert_framed(base, &point, base.frame(&point, Quat::IDENTITY).unwrap());
762    }
763
764    #[test]
765    fn invalid_rotations_and_unrepresentable_results_are_errors() {
766        let settings = FramingSettings::default();
767        let point = [box_at(Vec3::ZERO, Vec3::ZERO)];
768        for rotation in [
769            Quat::from_xyzw(0., 0., 0., 0.),
770            Quat::from_xyzw(0., 0., 0., 2.),
771            Quat::from_xyzw(f32::NAN, 0., 0., 1.),
772            Quat::from_xyzw(0., f32::INFINITY, 0., 1.),
773        ] {
774            assert_eq!(
775                settings.frame(&point, rotation),
776                Err(FramingError::InvalidRotation)
777            );
778        }
779        let extreme_aspect = FramingSettings {
780            aspect_ratio: f32::from_bits(1),
781            ..settings
782        };
783        assert_eq!(
784            extreme_aspect.frame(&[box_at(Vec3::ZERO, Vec3::ONE)], Quat::IDENTITY),
785            Err(FramingError::Unrepresentable)
786        );
787        let boundary = [box_at(Vec3::splat(1e6), Vec3::ZERO)];
788        assert_eq!(
789            settings.frame(&boundary, Quat::IDENTITY),
790            Err(FramingError::Unrepresentable)
791        );
792        let tiny_boom = FramingSettings {
793            min_distance: 0.01,
794            near: 0.001,
795            ..settings
796        };
797        assert_eq!(
798            tiny_boom.frame(&[box_at(Vec3::splat(9e5), Vec3::ZERO)], Quat::IDENTITY),
799            Err(FramingError::Unrepresentable)
800        );
801        // The eye remains distinct, but 900000 + 0.2 rounds to 900000.1875,
802        // placing the target inside the requested near plane.
803        let rounded_near = FramingSettings {
804            min_distance: 0.2,
805            near: 0.2,
806            ..settings
807        };
808        assert_eq!(
809            rounded_near.frame(&[box_at(Vec3::splat(9e5), Vec3::ZERO)], Quat::IDENTITY),
810            Err(FramingError::Unrepresentable)
811        );
812    }
813
814    #[test]
815    fn fitting_a_rotated_pose_is_compatible_with_the_existing_rig() {
816        let settings = FramingSettings::default();
817        let subjects = [box_at(Vec3::new(1., 2., 3.), Vec3::new(2., 1., 0.5))];
818        let frame = settings
819            .frame(&subjects, Quat::from_rotation_y(0.6))
820            .unwrap();
821        let input = Input3 {
822            target: Target3::at(frame.pose.target),
823            mode: Mode3::Follow {
824                eye_offset: frame.pose.position - frame.pose.target,
825                look_offset: Vec3::ZERO,
826            },
827            fov_y: frame.pose.fov_y,
828        };
829        let rig_frame = Rig3::default().snap(input, &NoObstructions).unwrap();
830        assert!(rig_frame.pose.position.distance(frame.pose.position) < 1e-5);
831        assert!(rig_frame.pose.target.distance(frame.pose.target) < 1e-5);
832        assert_eq!(rig_frame.pose.fov_y, frame.pose.fov_y);
833        assert_framed(settings, &subjects, frame);
834    }
835
836    fn input() -> Input3 {
837        Input3 {
838            target: Target3 {
839                velocity: Vec3::X * 20.,
840                ..Target3::at(Vec3::ZERO)
841            },
842            mode: Mode3::Follow {
843                eye_offset: Vec3::Y * 10.,
844                look_offset: Vec3::ZERO,
845            },
846            fov_y: 1.,
847        }
848    }
849    fn zone() -> CameraZone {
850        CameraZone {
851            min: Vec3::splat(-10.),
852            max: Vec3::splat(10.),
853            feather: 2.,
854            priority: 1,
855            focus_offset: Vec3::Z,
856            boom_scale: 1.,
857            fov_scale: 1.,
858        }
859    }
860    #[test]
861    fn anticipation_is_bounded_and_does_not_zoom() {
862        let mut c = CameraComposer::new([zone()], 0.5, 2., 0.).unwrap();
863        let i = c.update(input(), Vec3::ZERO, 0.1).unwrap();
864        assert_eq!(i.target.position, Vec3::X * 2. + Vec3::Z);
865        if let Mode3::Follow {
866            eye_offset,
867            look_offset,
868        } = i.mode
869        {
870            assert_eq!(eye_offset.distance(look_offset), 10.);
871        }
872        let old = c;
873        assert!(c.update(input(), Vec3::splat(f32::NAN), 0.1).is_err());
874        assert_eq!(c, old);
875    }
876    #[test]
877    fn priority_feather_and_first_person_are_explicit() {
878        let mut high = zone();
879        high.priority = 2;
880        high.focus_offset = -Vec3::Z;
881        let mut c = CameraComposer::new([zone(), high], 0., 0., 0.).unwrap();
882        assert_eq!(
883            c.update(input(), Vec3::ZERO, 0.1).unwrap().target.position,
884            -Vec3::Z
885        );
886        let mut fp = input();
887        fp.mode = Mode3::FirstPerson {
888            eye_offset: Vec3::Y,
889            yaw: 0.,
890            pitch: 0.,
891        };
892        assert_eq!(c.update(fp, Vec3::ZERO, 0.1).unwrap(), fp);
893    }
894}