//! Presentation playback ownership, read-only view context and cleanup transitions. use glam::DVec3; /// The one active presentation mode. Export owns its playback so it cannot outlive its film. pub enum State { Live, Replay(P), Export { playback: P, export: E }, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ExitCause { UserStop, WorldChange, Replaced, Finished, Failed, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Mode { Live, Replay, Export, } /// Clocks are deliberately tagged: recording time can seek or slow down without being confused /// with the live simulation tick that ages durable combat state and live sound delays. #[derive(Clone, Copy, Debug, PartialEq)] pub enum Clock { Live(u64), Recording(f64), } impl Clock { pub fn value(self) -> f64 { match self { Self::Live(tick) => tick as f64, Self::Recording(tick) => tick, } } pub fn deadline_after(self, delay: u64) -> f64 { self.value().max(0.0) + delay as f64 } pub fn has_reached(self, deadline: f64) -> bool { self.value() >= deadline } pub fn same_domain(self, other: Self) -> bool { matches!( (self, other), (Self::Live(_), Self::Live(_)) | (Self::Recording(_), Self::Recording(_)) ) } } /// Immutable inputs for everything that presents a scene: clock, listener and environment. /// The context is a snapshot; consumers cannot advance playback or mutate the live world through it. #[derive(Clone, Debug, PartialEq)] pub struct Context { pub mode: Mode, pub generation: u64, pub world: Option>, /// Combat/simulation time. pub combat_tick: u64, /// Host/UI callback time; it must not be substituted for recorded or combat time. pub ui_tick: u64, pub clock: Clock, pub listener: DVec3, pub day_time: Option, /// Share of a live tick represented by the current presentation step. pub rate: f32, pub filming: bool, } impl Context { pub fn live( generation: u64, world: Option>, ui_tick: u64, combat_tick: u64, day_time: Option, listener: DVec3, ) -> Self { Self { mode: Mode::Live, generation, world, combat_tick, ui_tick, clock: Clock::Live(combat_tick), listener, day_time, rate: 1.0, filming: false, } } pub fn playback( mode: Mode, generation: u64, world: Option>, ui_tick: u64, combat_tick: u64, time: f64, day_time: Option, rate: f32, listener: DVec3, filming: bool, ) -> Self { debug_assert!(matches!(mode, Mode::Replay | Mode::Export)); Self { mode, generation, world, combat_tick, ui_tick, clock: Clock::Recording(time), listener, day_time, rate, filming, } } pub fn is_playback(&self) -> bool { !matches!(self.mode, Mode::Live) } /// Map playback presents the current world view; only a filmed replay advances recorded effects. pub fn display_clock(&self) -> Clock { if self.is_playback() && self.filming { self.clock } else { Clock::Live(self.combat_tick) } } /// The clock used to age audible delays: filmed playback follows its recording; live and map /// playback follow the current combat timeline. pub fn sound_clock(&self) -> Clock { self.display_clock() } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CleanupAction { CancelCapture, ClearPendingSounds, RestoreFilmQuality, RestoreEffects, RestoreWorldView, ClearTimeOverride, ClearMainView, ReleaseWheel, ClearHud, ClearViews, HideMonitor, } /// A cleanup plan is produced once when an active presentation ends. A successful export has /// already drained its capture, so its plan omits `CancelCapture`. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Cleanup { pub actions: Vec, } pub trait CleanupHost { fn apply_cleanup_action(&mut self, action: CleanupAction); } impl Cleanup { pub fn apply(&self, host: &mut impl CleanupHost) { for &action in &self.actions { host.apply_cleanup_action(action); } } } pub struct Session { state: State, generation: u64, } impl Default for Session { fn default() -> Self { Self { state: State::Live, generation: 0, } } } impl Session { pub fn is_live(&self) -> bool { matches!(self.state, State::Live) } pub fn is_exporting(&self) -> bool { matches!(self.state, State::Export { .. }) } pub fn generation(&self) -> u64 { self.generation } pub fn playback(&self) -> Option<&P> { match &self.state { State::Live => None, State::Replay(player) | State::Export { playback: player, .. } => Some(player), } } pub fn playback_mut(&mut self) -> Option<&mut P> { match &mut self.state { State::Live => None, State::Replay(player) | State::Export { playback: player, .. } => Some(player), } } pub fn replay(&mut self, playback: P) { assert!( self.is_live(), "end the current presentation before replacing it" ); self.generation = self.generation.wrapping_add(1).max(1); self.state = State::Replay(playback); } /// Promote the current replay into an export without changing its generation. pub fn export(&mut self, playback: P, export: E) { assert!( self.is_live(), "end the current presentation before starting export" ); assert!( self.generation != 0, "an export must belong to a started presentation" ); self.state = State::Export { playback, export }; } /// Temporarily move the active state out while a tick mutates the player and export together. pub fn take(&mut self) -> State { std::mem::replace(&mut self.state, State::Live) } pub fn restore(&mut self, state: State) { assert!(self.is_live(), "restore only into a detached live session"); self.state = state; } /// Return no plan for an already-live session, so repeated stop/unload paths cannot repeat host cleanup. pub fn end(&mut self, cause: ExitCause) -> Option { let was_export = self.is_exporting(); if self.is_live() { return None; } let mut actions = Vec::with_capacity(11); if was_export && cause != ExitCause::Finished { actions.push(CleanupAction::CancelCapture); } actions.extend([ CleanupAction::ClearPendingSounds, CleanupAction::RestoreFilmQuality, CleanupAction::RestoreEffects, CleanupAction::RestoreWorldView, CleanupAction::ClearTimeOverride, CleanupAction::ClearMainView, CleanupAction::ReleaseWheel, CleanupAction::ClearHud, CleanupAction::ClearViews, CleanupAction::HideMonitor, ]); self.state = State::Live; self.generation = self.generation.wrapping_add(1).max(1); Some(Cleanup { actions }) } /// The world is gone (the title screen): the game stops ticking there, so an active export /// would otherwise go on recording the title with its playback clock frozen. Nothing to do /// in Live, and a world still open is not a leave. pub fn world_left(&mut self, world: Option<&str>) -> Option { if self.is_live() || world.is_some() { return None; } self.end(ExitCause::WorldChange) } /// A world change invalidates live work too. Active playback uses the normal cleanup path, /// which advances generation exactly once; Live advances generation without host cleanup. pub fn world_changed(&mut self) -> Option { if self.is_live() { self.generation = self.generation.wrapping_add(1).max(1); None } else { self.end(ExitCause::WorldChange) } } } #[cfg(test)] mod tests { use super::{CleanupAction, CleanupHost, Clock, Context, ExitCause, Mode, Session, State}; use glam::DVec3; #[derive(Default)] struct HostFixture { actions: Vec, } impl HostFixture { fn apply(&mut self, cleanup: &super::Cleanup) { cleanup.apply(self); } } impl CleanupHost for HostFixture { fn apply_cleanup_action(&mut self, action: CleanupAction) { self.actions.push(action); } } #[test] fn playback_context_uses_recording_clock_and_captured_environment() { let live = Context::live( 4, Some(Some("world-a".into())), 890, 900, Some(12000), DVec3::X, ); assert_eq!(live.clock, Clock::Live(900)); let replay = Context::playback( Mode::Replay, 5, live.world.clone(), 9010, 901, 31.25, Some(13000), 0.3, DVec3::Z, true, ); let slow = Context::playback( Mode::Replay, 5, live.world.clone(), 9020, 902, 31.55, Some(13000), 0.3, DVec3::Z, true, ); assert_eq!(replay.clock, Clock::Recording(31.25)); assert_eq!(replay.sound_clock(), Clock::Recording(31.25)); assert_eq!(replay.day_time, Some(13000)); assert_eq!(replay.listener, DVec3::Z); assert_eq!(slow.clock, Clock::Recording(31.55)); let map = Context::playback( Mode::Replay, 5, live.world.clone(), 9011, 901, 31.25, Some(13000), 1.0, DVec3::Z, false, ); assert_eq!(map.sound_clock(), Clock::Live(901)); assert!(replay.is_playback()); assert_ne!(replay.clock.value(), live.clock.value()); assert_eq!(replay.generation, slow.generation); } #[test] fn seek_and_slow_motion_change_only_the_recording_clock() { let at = |live_tick, record_tick, rate| { Context::playback( Mode::Replay, 12, Some(Some("w".into())), live_tick * 10, live_tick, record_tick, Some(8000), rate, DVec3::ZERO, true, ) }; let before = at(400, 80.0, 1.0); let seek = at(401, 20.0, 0.0); let slow = at(402, 20.3, 0.3); assert_eq!(before.display_clock(), Clock::Recording(80.0)); assert_eq!(seek.display_clock(), Clock::Recording(20.0)); assert_eq!(slow.display_clock(), Clock::Recording(20.3)); assert_eq!(slow.sound_clock(), Clock::Recording(20.3)); assert_eq!(slow.sound_clock().deadline_after(5), 25.3); assert!(!slow.sound_clock().has_reached(25.3)); assert!(Clock::Recording(25.5).has_reached(25.5)); assert_eq!((seek.ui_tick, slow.ui_tick), (4010, 4020)); assert_eq!((seek.combat_tick, slow.combat_tick), (401, 402)); assert_eq!(seek.world, slow.world); assert_eq!(seek.day_time, slow.day_time); assert_eq!(seek.generation, slow.generation); assert_eq!( seek.clock, Clock::Recording(20.0), "a context snapshot is not advanced by live ticks" ); } #[test] fn world_change_invalidates_live_generation_and_cleans_active_once() { let mut session = Session::::default(); let initial = session.generation(); assert!( session.world_changed().is_none(), "Live has no presentation resources to clean up" ); assert_ne!(session.generation(), initial); session.replay(1); let active = session.generation(); let cleanup = session .world_changed() .expect("active playback needs cleanup"); assert_ne!(session.generation(), active); let mut host = HostFixture::default(); host.apply(&cleanup); let action_count = host.actions.len(); assert_eq!( host.actions .iter() .filter(|a| **a == CleanupAction::ClearPendingSounds) .count(), 1 ); assert!( session.world_changed().is_none(), "a second call sees Live state" ); assert_eq!(host.actions.len(), action_count, "cleanup is not repeated"); } #[test] fn restart_gets_new_generation_and_export_keeps_its_parent_generation() { let mut session = Session::::default(); session.replay(1); let first = session.generation(); assert_ne!(first, 0); let State::Replay(player) = session.take() else { panic!("replay state lost") }; session.export(player, "capture"); assert_eq!(session.generation(), first); let _ = session.end(ExitCause::UserStop); session.replay(2); assert_ne!(session.generation(), first); } #[test] fn a_gone_world_ends_an_active_export_once() { let mut session = Session::<(), ()>::default(); assert!(session.world_left(None).is_none(), "Live has nothing to clean up"); session.replay(()); assert!(session.world_left(Some("world:w")).is_none(), "the world is still open"); let State::Replay(playback) = session.take() else { panic!("replay state lost") }; session.export(playback, ()); let cleanup = session.world_left(None).expect("the title screen ends the export"); assert!(cleanup.actions.contains(&CleanupAction::CancelCapture)); let mut host = HostFixture::default(); host.apply(&cleanup); let count = host.actions.len(); assert!(session.world_left(None).is_none(), "a second frame sees Live"); assert_eq!(host.actions.len(), count, "cleanup is not repeated"); assert_eq!( host.actions.iter().filter(|a| **a == CleanupAction::CancelCapture).count(), 1 ); } #[test] fn end_and_restart_emit_cleanup_once_for_stop_unload_failure_and_success() { for cause in [ ExitCause::UserStop, ExitCause::WorldChange, ExitCause::Failed, ExitCause::Finished, ] { let mut session = Session::<(), ()>::default(); session.replay(()); let State::Replay(()) = session.take() else { panic!("replay state lost") }; session.restore(State::Replay(())); let mut host = HostFixture::default(); let cleanup = session.end(cause).expect("active session must clean up"); host.apply(&cleanup); assert!( session.end(cause).is_none(), "second end repeated cleanup for {cause:?}" ); for action in cleanup.actions { assert_eq!( host.actions.iter().filter(|a| **a == action).count(), 1, "{action:?} for {cause:?}" ); } assert!( !host.actions.contains(&CleanupAction::CancelCapture), "a replay has no capture to cancel" ); } } #[test] fn export_cleanup_cancels_only_interrupted_captures_and_success_drains() { for (cause, cancels) in [ (ExitCause::UserStop, true), (ExitCause::WorldChange, true), (ExitCause::Failed, true), (ExitCause::Finished, false), ] { let mut session = Session::<(), ()>::default(); session.replay(()); let State::Replay(playback) = session.take() else { panic!("replay state lost") }; session.export(playback, ()); let cleanup = session.end(cause).expect("export must clean up"); let mut host = HostFixture::default(); host.apply(&cleanup); assert_eq!( host.actions.contains(&CleanupAction::CancelCapture), cancels, "{cause:?}" ); for action in cleanup.actions { assert_eq!( host.actions.iter().filter(|a| **a == action).count(), 1, "{action:?} for {cause:?}" ); } assert!( session.end(cause).is_none(), "second end repeated cleanup for {cause:?}" ); } } }