alpha2-model 0.9.0

Versioned project and timeline model for alpha2.
Documentation
//! The project's shutter: the part of each frame over which marked transforms are averaged.

use alpha2_time::{FrameRate, MediaTime, TICKS_PER_SECOND};
use serde::{Deserialize, Serialize};
use std::fmt;

/// Most samples a [`Shutter`] averages.
pub const MAX_SHUTTER_SAMPLES: u32 = 64;
/// Fewest samples a [`Shutter`] averages.
pub const MIN_SHUTTER_SAMPLES: u32 = 2;
/// Largest [`Shutter::angle_degrees`]: two frames.
pub const MAX_SHUTTER_ANGLE_DEGREES: f32 = 720.0;
/// Largest magnitude of [`Shutter::phase_degrees`]: one frame.
pub const MAX_SHUTTER_PHASE_DEGREES: f32 = 360.0;

/// A rotary shutter: the part of each frame during which motion is recorded.
///
/// A clip or transform node marked `motion_blur` is drawn as the average of its placements at the
/// midpoints of equal parts of the open interval; the picture placed is the one at the frame
/// time.
#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Shutter {
    /// How long the shutter is open, 360 being one whole frame. Above 0, at most
    /// [`MAX_SHUTTER_ANGLE_DEGREES`].
    #[serde(default = "Shutter::default_angle")]
    pub angle_degrees: f32,
    /// Where the open interval starts relative to the frame time, 360 being one frame. Within
    /// [`MAX_SHUTTER_PHASE_DEGREES`] either way; -90 with an angle of 180 centres the interval on
    /// the frame time.
    #[serde(default = "Shutter::default_phase")]
    pub phase_degrees: f32,
    /// Most samples averaged: a power of two from [`MIN_SHUTTER_SAMPLES`] to
    /// [`MAX_SHUTTER_SAMPLES`]. Slow motion uses fewer.
    #[serde(default = "Shutter::default_samples")]
    pub samples: u32,
}

/// The [`Shutter`] field a [`crate::ModelError::InvalidShutter`] names.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ShutterProblem {
    /// [`Shutter::angle_degrees`] is not above 0 and at most [`MAX_SHUTTER_ANGLE_DEGREES`].
    Angle,
    /// [`Shutter::phase_degrees`] is beyond [`MAX_SHUTTER_PHASE_DEGREES`] either way.
    Phase,
    /// [`Shutter::samples`] is not a power of two from [`MIN_SHUTTER_SAMPLES`] to
    /// [`MAX_SHUTTER_SAMPLES`].
    Samples,
}

impl fmt::Display for ShutterProblem {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Angle => write!(
                formatter,
                "the shutter angle must be above 0 and at most {MAX_SHUTTER_ANGLE_DEGREES} degrees"
            ),
            Self::Phase => write!(
                formatter,
                "the shutter phase must be within -{MAX_SHUTTER_PHASE_DEGREES}..={MAX_SHUTTER_PHASE_DEGREES} degrees"
            ),
            Self::Samples => write!(
                formatter,
                "the shutter samples must be a power of two from {MIN_SHUTTER_SAMPLES} to {MAX_SHUTTER_SAMPLES}"
            ),
        }
    }
}

impl Default for Shutter {
    fn default() -> Self {
        Self {
            angle_degrees: Self::default_angle(),
            phase_degrees: Self::default_phase(),
            samples: Self::default_samples(),
        }
    }
}

impl Shutter {
    const fn default_angle() -> f32 {
        180.0
    }

    const fn default_phase() -> f32 {
        -90.0
    }

    const fn default_samples() -> u32 {
        16
    }

    /// Whether every field has its default, in which case a document leaves the shutter out.
    #[must_use]
    pub fn is_default(&self) -> bool {
        *self == Self::default()
    }

    /// Checks that every field is finite and in range.
    ///
    /// # Errors
    /// Returns the first field out of range.
    pub fn validate(&self) -> Result<(), ShutterProblem> {
        if !(self.angle_degrees > 0.0 && self.angle_degrees <= MAX_SHUTTER_ANGLE_DEGREES) {
            return Err(ShutterProblem::Angle);
        }
        if !(self.phase_degrees >= -MAX_SHUTTER_PHASE_DEGREES
            && self.phase_degrees <= MAX_SHUTTER_PHASE_DEGREES)
        {
            return Err(ShutterProblem::Phase);
        }
        if !(self.samples.is_power_of_two()
            && (MIN_SHUTTER_SAMPLES..=MAX_SHUTTER_SAMPLES).contains(&self.samples))
        {
            return Err(ShutterProblem::Samples);
        }
        Ok(())
    }

    /// The instant sample `index` of `count` reads for the frame at `time`: the midpoint of the
    /// `index`-th of `count` equal parts of the open interval, to the nearest tick (a half rounds
    /// up). One frame is `frame`'s.
    #[must_use]
    pub fn sample_time(
        &self,
        time: MediaTime,
        frame: FrameRate,
        index: u32,
        count: u32,
    ) -> MediaTime {
        #[expect(
            clippy::cast_precision_loss,
            reason = "the tick rate is far below 2^53"
        )]
        let frame_ticks =
            TICKS_PER_SECOND as f64 * f64::from(frame.denominator()) / f64::from(frame.numerator());
        let open = f64::from(self.phase_degrees) / 360.0;
        let length = f64::from(self.angle_degrees) / 360.0;
        let part = (f64::from(index) + 0.5) / f64::from(count.max(1));
        let shift = (frame_ticks * (open + length * part) + 0.5).floor();
        #[expect(
            clippy::cast_possible_truncation,
            reason = "a float to integer cast saturates"
        )]
        MediaTime(time.ticks().saturating_add(shift as i64))
    }
}