ferravex_core/
session.rs

1//! Shared start, pause, retry and fixed-timestep timing for local game sessions.
2//!
3//! Game-specific rules still decide when a session has been won or lost. A local
4//! menu or overlay must not pause an authoritative remote match's clock.
5//!
6//! ```
7//! use ferravex_core::session::{GameSession, SessionState};
8//!
9//! let mut session = GameSession::new(60.0, 8, false);
10//! assert!(session.start());
11//! let frame = session.advance(1.0 / 30.0);
12//! let mut simulated_seconds = 0.0;
13//! for _ in 0..frame.steps {
14//!     simulated_seconds += frame.dt; // Update game rules with this fixed dt.
15//! }
16//! assert_eq!(session.tick(), 2);
17//! assert!(simulated_seconds > 0.0);
18//! assert!(session.set_paused(true));
19//! assert_eq!(session.advance(10.0).steps, 0);
20//! assert!(session.toggle_pause());
21//! assert!(session.finish(true));
22//! assert_eq!(session.state(), SessionState::Won);
23//! session.restart();
24//! assert_eq!(session.tick(), 0);
25//! ```
26
27use crate::{FixedClock, FixedClockError, FrameStep, TickBatch};
28
29/// Validated, reusable settings for a [`GameSession`].
30///
31/// Fields cannot be changed after validation. Use [`Self::try_new`] to check
32/// settings from a host or inspector, then [`GameSession::from_config`] to
33/// create independent sessions with the same settings.
34///
35/// ```
36/// use ferravex_core::session::{GameSession, SessionConfig, SessionState};
37///
38/// let config = SessionConfig::try_new(64.0, 4, false)?;
39/// assert_eq!(config.hz(), 64.0);
40/// assert_eq!(config.max_steps(), 4);
41/// assert!(!config.autoplay());
42/// let first = GameSession::from_config(config);
43/// let second = GameSession::from_config(config);
44/// assert_eq!(first.state(), SessionState::Ready);
45/// assert_eq!(second.tick(), 0);
46/// # Ok::<(), ferravex_core::FixedClockError>(())
47/// ```
48#[derive(Clone, Copy, Debug, PartialEq)]
49pub struct SessionConfig {
50    hz: f64,
51    max_steps: u32,
52    autoplay: bool,
53}
54
55impl SessionConfig {
56    /// Validates settings using [`FixedClock::try_new`].
57    ///
58    /// `hz` must be finite and in `1..=1000`, and `max_steps` must be nonzero.
59    /// The tick rate is checked first if both values are invalid. `autoplay`
60    /// selects `Playing` instead of `Ready` for each newly created session.
61    /// See the [`SessionConfig`] example for constructing and reusing settings.
62    pub fn try_new(hz: f64, max_steps: u32, autoplay: bool) -> Result<Self, FixedClockError> {
63        FixedClock::try_new(hz, max_steps)?;
64        Ok(Self {
65            hz,
66            max_steps,
67            autoplay,
68        })
69    }
70
71    /// Returns the validated fixed tick rate in Hz; see [`SessionConfig`].
72    pub fn hz(&self) -> f64 {
73        self.hz
74    }
75
76    /// Returns the nonzero per-frame catch-up limit; see [`SessionConfig`].
77    pub fn max_steps(&self) -> u32 {
78        self.max_steps
79    }
80
81    /// Whether a newly created session starts in `Playing`; see [`SessionConfig`].
82    pub fn autoplay(&self) -> bool {
83        self.autoplay
84    }
85}
86
87/// Host lifecycle state, independent of a game's simulation-specific phases.
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
89pub enum SessionState {
90    /// Waiting for an explicit start.
91    Ready,
92    /// Accepting elapsed time and producing simulation steps.
93    Playing,
94    /// Suspended; elapsed time is ignored, but an explicit inspector step is allowed.
95    /// Fractional time is retained, and ticks change only via [`GameSession::step_paused`].
96    Paused,
97    /// Finished successfully; only reset or restart can leave this state.
98    Won,
99    /// Finished unsuccessfully; only reset or restart can leave this state.
100    Lost,
101}
102
103/// A rejected request to issue an inspector tick with [`GameSession::step_paused`].
104///
105/// ```
106/// use ferravex_core::session::{GameSession, SessionState, SessionStepError};
107///
108/// let mut session = GameSession::new(60.0, 8, false);
109/// let error = session.step_paused().unwrap_err();
110/// assert_eq!(error, SessionStepError::NotPaused { state: SessionState::Ready });
111/// assert_eq!(session.tick(), 0);
112/// ```
113#[derive(Clone, Copy, Debug, PartialEq, Eq)]
114pub enum SessionStepError {
115    /// The session must be `Paused`; the state and clock were left unchanged.
116    NotPaused {
117        /// The state in which stepping was requested.
118        state: SessionState,
119    },
120}
121
122impl std::fmt::Display for SessionStepError {
123    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
124        match self {
125            Self::NotPaused { state } => write!(
126                f,
127                "single stepping requires a Paused session; current state is {state:?}"
128            ),
129        }
130    }
131}
132
133impl std::error::Error for SessionStepError {}
134
135/// A local game lifecycle with an owned, deterministic [`FixedClock`].
136///
137/// Only [`Playing`](SessionState::Playing) consumes elapsed time. Pausing and
138/// finishing preserve clock state; restarting and resetting clear both ticks
139/// and fractional time. Lifecycle transitions do not reset game-specific data:
140/// callers must reset their simulation alongside [`restart`](Self::restart).
141/// Inspectors can explicitly issue one tick while paused using
142/// [`step_paused`](Self::step_paused), without resuming or consuming elapsed time.
143#[derive(Clone, Debug)]
144pub struct GameSession {
145    state: SessionState,
146    clock: FixedClock,
147}
148
149impl GameSession {
150    /// Creates a session in `Ready`, or `Playing` when `autoplay` is true.
151    ///
152    /// # Panics
153    ///
154    /// Like [`FixedClock::new`], panics if `hz` is not finite or outside
155    /// `1..=1000`, or if `max_steps` is zero.
156    /// Use [`Self::try_new`] to report invalid settings without panicking.
157    pub fn new(hz: f64, max_steps: u32, autoplay: bool) -> Self {
158        Self {
159            state: if autoplay {
160                SessionState::Playing
161            } else {
162                SessionState::Ready
163            },
164            clock: FixedClock::new(hz, max_steps),
165        }
166    }
167
168    /// Creates a session with checked settings and the same behavior as [`Self::new`].
169    ///
170    /// Returns [`FixedClockError`] if `hz` is not finite or outside `1..=1000`,
171    /// or if `max_steps` is zero. The tick rate is checked first if both are
172    /// invalid. For reusable validated settings, see [`SessionConfig`].
173    ///
174    /// ```
175    /// use ferravex_core::{FixedClockError, session::GameSession};
176    ///
177    /// assert!(matches!(
178    ///     GameSession::try_new(60.0, 0, false),
179    ///     Err(FixedClockError::ZeroCatchUpBudget)
180    /// ));
181    /// let mut session = GameSession::try_new(64.0, 4, true)?;
182    /// assert_eq!(session.advance(2.0 / 64.0).steps, 2);
183    /// # Ok::<(), FixedClockError>(())
184    /// ```
185    pub fn try_new(hz: f64, max_steps: u32, autoplay: bool) -> Result<Self, FixedClockError> {
186        let config = SessionConfig::try_new(hz, max_steps, autoplay)?;
187        Ok(Self::from_config(config))
188    }
189
190    /// Creates a fresh session from reusable, already validated settings.
191    ///
192    /// Starts at tick zero with no fractional time. `config.autoplay()` selects
193    /// `Playing` instead of `Ready`. See the [`SessionConfig`] example.
194    pub fn from_config(config: SessionConfig) -> Self {
195        Self::new(config.hz, config.max_steps, config.autoplay)
196    }
197
198    /// Returns the current host lifecycle state.
199    pub fn state(&self) -> SessionState {
200        self.state
201    }
202
203    /// Whether this session has started, including paused or finished sessions.
204    pub fn is_started(&self) -> bool {
205        self.state != SessionState::Ready
206    }
207
208    /// Whether elapsed time currently advances the simulation clock.
209    pub fn is_playing(&self) -> bool {
210        self.state == SessionState::Playing
211    }
212
213    /// Whether this session is temporarily paused.
214    pub fn is_paused(&self) -> bool {
215        self.state == SessionState::Paused
216    }
217
218    /// Starts a ready session. Returns true only for `Ready -> Playing`.
219    ///
220    /// To resume use [`set_paused(false)`](Self::set_paused); to retry a finished
221    /// game use [`restart`](Self::restart).
222    pub fn start(&mut self) -> bool {
223        if self.state != SessionState::Ready {
224            return false;
225        }
226        self.state = SessionState::Playing;
227        true
228    }
229
230    /// Clears ticks and fractional time and enters `Playing` from any state.
231    pub fn restart(&mut self) {
232        self.clock.reset();
233        self.state = SessionState::Playing;
234    }
235
236    /// Clears ticks and fractional time and enters `Ready` from any state.
237    pub fn reset(&mut self) {
238        self.clock.reset();
239        self.state = SessionState::Ready;
240    }
241
242    /// Pauses or resumes an active session, returning true only when changed.
243    ///
244    /// Ready and finished sessions are unchanged. Repeated requests for the
245    /// current pause state are harmless and return false.
246    pub fn set_paused(&mut self, paused: bool) -> bool {
247        match (self.state, paused) {
248            (SessionState::Playing, true) => self.state = SessionState::Paused,
249            (SessionState::Paused, false) => self.state = SessionState::Playing,
250            _ => return false,
251        }
252        true
253    }
254
255    /// Toggles `Playing` and `Paused`, returning true only when changed.
256    ///
257    /// Ready and finished sessions are unchanged.
258    pub fn toggle_pause(&mut self) -> bool {
259        self.set_paused(!self.is_paused())
260    }
261
262    /// Finishes a playing or paused session as `Won` or `Lost`.
263    ///
264    /// Returns true only when changed. A ready session cannot finish, and an
265    /// existing result cannot be overwritten without resetting or restarting.
266    pub fn finish(&mut self, won: bool) -> bool {
267        if !matches!(self.state, SessionState::Playing | SessionState::Paused) {
268            return false;
269        }
270        self.state = if won {
271            SessionState::Won
272        } else {
273            SessionState::Lost
274        };
275        true
276    }
277
278    /// Produces bounded fixed steps from the elapsed seconds of one host frame.
279    ///
280    /// While inactive, returns zero steps, alpha and dropped time with the
281    /// normal fixed `dt`, and leaves the clock completely unchanged. Time
282    /// submitted while inactive is discarded, so resuming does not catch up
283    /// on that time. Fractional time from earlier playing frames is retained.
284    ///
285    /// Callers must measure elapsed time between host frames, including while
286    /// inactive. If the host itself stops delivering frames, rebase its elapsed
287    /// time measurement on resume instead of submitting the whole suspension.
288    /// In `Playing`, invalid durations and catch-up use [`FixedClock::advance`]
289    /// semantics. The tick counter includes all steps returned by this call.
290    pub fn advance(&mut self, elapsed_seconds: f64) -> FrameStep {
291        if self.is_playing() {
292            self.clock.advance(elapsed_seconds)
293        } else {
294            FrameStep {
295                steps: 0,
296                dt: self.clock.dt(),
297                alpha: 0.0,
298                dropped_seconds: 0.0,
299            }
300        }
301    }
302
303    /// Schedule a frame with per-update IDs, using [`Self::advance`] semantics.
304    ///
305    /// Inactive sessions return an empty batch without consuming time or IDs.
306    /// The clock counts the entire issued batch, even if the caller stops early.
307    /// Consume input and count execution only when actually invoking an update.
308    /// [`TickBatch`] documents wrapping, copying and reset semantics.
309    ///
310    /// ```
311    /// use ferravex_core::session::GameSession;
312    /// let mut session = GameSession::new(64.0, 4, true);
313    /// let batch = session.advance_batch(3.0 / 64.0);
314    /// let mut executed = 0;
315    /// for context in batch.ticks() {
316    ///     if !session.is_playing() { break; }
317    ///     assert_eq!(context.tick, 1);
318    ///     executed += 1; // Invoke game rules; this update wins the game.
319    ///     session.finish(true);
320    /// }
321    /// assert_eq!(executed, 1);
322    /// assert_eq!(session.tick(), 3);
323    /// assert_eq!(session.advance_batch(60.0).ticks().len(), 0);
324    /// session.restart();
325    /// assert_eq!(session.advance_batch(1.0 / 64.0).ticks().next().unwrap().tick, 1);
326    /// ```
327    pub fn advance_batch(&mut self, elapsed_seconds: f64) -> TickBatch {
328        let tick_before = self.tick();
329        let frame = self.advance(elapsed_seconds);
330        TickBatch { frame, tick_before }
331    }
332
333    /// Issues exactly one fixed simulation tick while remaining `Paused`.
334    ///
335    /// Returns [`SessionStepError::NotPaused`] in every other state, leaving
336    /// both lifecycle and clock unchanged. An accepted step increments
337    /// [`tick`](Self::tick) once (wrapping at `u64::MAX`), preserves all
338    /// fractional time from earlier playing frames, and consumes no elapsed
339    /// time. Repeated calls each issue one tick, independent of the per-frame
340    /// catch-up limit. Ordinary paused [`advance`](Self::advance) calls still
341    /// discard their elapsed time and issue no ticks.
342    ///
343    /// The returned frame has `steps = 1`, the normal fixed `dt`, no dropped
344    /// time, and `alpha = 1.0` so an inspector can display the current pose after
345    /// the update. This presentation alpha does not change the clock's stored
346    /// fractional time or the alpha returned by later `advance` calls.
347    ///
348    /// Like `advance`, this method only schedules work: the tick is counted
349    /// before the caller executes the update. Consume gameplay input edges and
350    /// emit accepted game feedback inside that update. Game rules can still
351    /// [`finish`](Self::finish) a session after the step.
352    ///
353    /// ```
354    /// use ferravex_core::session::{GameSession, SessionState};
355    ///
356    /// let mut session = GameSession::new(64.0, 4, true);
357    /// session.advance(0.5 / 64.0); // Retain half a normal tick for resume.
358    /// assert!(session.set_paused(true));
359    /// let frame = session.step_paused()?;
360    /// let mut simulated_seconds = 0.0;
361    /// for dt in frame.ticks() {
362    ///     simulated_seconds += dt; // Execute the inspector's fixed update.
363    /// }
364    /// assert_eq!(simulated_seconds, session.dt());
365    /// assert_eq!(frame.alpha, 1.0); // Present the current simulation pose.
366    /// assert_eq!(session.tick(), 1);
367    /// assert_eq!(session.state(), SessionState::Paused);
368    /// assert_eq!(session.advance(30.0).steps, 0);
369    /// assert!(session.set_paused(false));
370    /// assert_eq!(session.advance(0.5 / 64.0).steps, 1);
371    /// assert_eq!(session.tick(), 2);
372    /// # Ok::<(), ferravex_core::session::SessionStepError>(())
373    /// ```
374    pub fn step_paused(&mut self) -> Result<FrameStep, SessionStepError> {
375        if !self.is_paused() {
376            return Err(SessionStepError::NotPaused { state: self.state });
377        }
378        // Adding dt to the accumulator would round/consume its remainder and
379        // could issue multiple steps near a tick boundary. Only count the
380        // explicitly requested tick, retaining the exact accumulator bits.
381        self.clock.tick = self.clock.tick.wrapping_add(1);
382        Ok(FrameStep {
383            steps: 1,
384            dt: self.clock.dt(),
385            alpha: 1.0,
386            dropped_seconds: 0.0,
387        })
388    }
389
390    /// Issue one paused inspector update with its scheduled ID and index zero.
391    ///
392    /// Uses [`Self::step_paused`] unchanged: rejects non-Paused states without
393    /// mutation, preserves fractional time and returns presentation alpha 1.
394    /// The caller must execute the tick; this does not invoke application hooks.
395    ///
396    /// ```
397    /// use ferravex_core::session::GameSession;
398    /// let mut session = GameSession::new(64.0, 4, true);
399    /// session.advance_batch(1.5 / 64.0);
400    /// session.set_paused(true);
401    /// let batch = session.step_paused_batch()?;
402    /// let context = batch.ticks().next().unwrap();
403    /// assert_eq!((context.tick, context.batch_index), (2, 0));
404    /// assert_eq!(context.dt, session.dt()); // Execute the inspector update here.
405    /// assert_eq!(batch.frame().alpha, 1.0);
406    /// assert!(session.is_paused());
407    /// session.set_paused(false);
408    /// assert_eq!(session.advance_batch(0.5 / 64.0).ticks().next().unwrap().tick, 3);
409    /// # Ok::<(), ferravex_core::session::SessionStepError>(())
410    /// ```
411    pub fn step_paused_batch(&mut self) -> Result<TickBatch, SessionStepError> {
412        let tick_before = self.tick();
413        let frame = self.step_paused()?;
414        Ok(TickBatch { frame, tick_before })
415    }
416
417    /// Returns the number of fixed steps issued since creation or the last reset/restart.
418    ///
419    /// Counts both playing [`advance`](Self::advance) batches and accepted
420    /// [`step_paused`](Self::step_paused) calls, wrapping at `u64::MAX` like
421    /// [`FixedClock::tick`]. Dropped catch-up ticks and rejected requests do not
422    /// count. This is scheduled work, not a count of updates the caller actually
423    /// executed: the whole returned batch is already counted when `advance`
424    /// returns, even if game rules finish before the caller executes every step.
425    pub fn tick(&self) -> u64 {
426        self.clock.tick()
427    }
428
429    /// Returns the fixed simulation step duration in seconds in every state.
430    pub fn dt(&self) -> f32 {
431        self.clock.dt()
432    }
433}
434
435#[cfg(test)]
436mod tests {
437    use super::*;
438
439    #[test]
440    fn contextual_inactive_and_rejected_steps_preserve_state_and_clock() {
441        for state in [
442            SessionState::Ready,
443            SessionState::Playing,
444            SessionState::Won,
445            SessionState::Lost,
446        ] {
447            let mut session = GameSession::new(64.0, 4, false);
448            if state != SessionState::Ready {
449                session.start();
450                session.advance_batch(2.5 / 64.0);
451                if state != SessionState::Playing {
452                    session.finish(state == SessionState::Won);
453                }
454            }
455            let before = session.tick();
456            let fraction = session.clock.accumulator.to_bits();
457            assert_eq!(
458                session.step_paused_batch().unwrap_err(),
459                SessionStepError::NotPaused { state }
460            );
461            assert_eq!(session.state(), state);
462            assert_eq!(session.tick(), before);
463            assert_eq!(session.clock.accumulator.to_bits(), fraction);
464            if state != SessionState::Playing {
465                let batch = session.advance_batch(100.0);
466                assert_eq!(batch.ticks().len(), 0);
467                assert_eq!(batch.frame().dt, session.dt());
468                assert_eq!(batch.frame().alpha, 0.0);
469                assert_eq!(batch.frame().dropped_seconds, 0.0);
470                assert_eq!(session.tick(), before);
471                assert_eq!(session.clock.accumulator.to_bits(), fraction);
472            }
473        }
474    }
475
476    #[test]
477    fn contextual_paused_steps_wrap_and_resume_with_exact_retained_fraction() {
478        for hz in [1.0, 60.0, 64.0, 1000.0] {
479            let mut session = GameSession::new(hz, 1, true);
480            session.advance_batch(0.375 / hz);
481            session.set_paused(true);
482            session.clock.tick = u64::MAX;
483            let fraction = session.clock.accumulator.to_bits();
484            for tick in 0..3 {
485                let batch = session.step_paused_batch().unwrap();
486                let contexts: Vec<_> = batch.ticks().collect();
487                assert_eq!(
488                    contexts,
489                    [crate::TickContext {
490                        tick,
491                        batch_index: 0,
492                        dt: session.dt()
493                    }]
494                );
495                assert_eq!(batch.frame().steps, 1);
496                assert_eq!(batch.frame().alpha, 1.0);
497                assert_eq!(batch.frame().dropped_seconds, 0.0);
498                assert_eq!(session.tick(), tick);
499                assert_eq!(session.state(), SessionState::Paused);
500                assert_eq!(session.advance_batch(100.0).ticks().len(), 0);
501                assert_eq!(session.clock.accumulator.to_bits(), fraction);
502            }
503            // Mixing the old and new manual APIs uses the same ID sequence.
504            session.step_paused().unwrap();
505            session.set_paused(false);
506            assert_eq!(
507                session
508                    .advance_batch(0.625 / hz)
509                    .ticks()
510                    .next()
511                    .unwrap()
512                    .tick,
513                4
514            );
515        }
516    }
517
518    #[test]
519    fn contextual_early_finish_reset_and_restart_preserve_scheduled_accounting() {
520        let mut session = GameSession::new(64.0, 4, true);
521        let batch = session.advance_batch(4.5 / 64.0);
522        let mut executed = 0;
523        for context in batch.ticks() {
524            if !session.is_playing() {
525                break;
526            }
527            assert_eq!(context.tick, 1);
528            executed += 1;
529            session.finish(true);
530        }
531        assert_eq!(executed, 1);
532        assert_eq!(session.tick(), 4);
533        assert_eq!(session.advance_batch(100.0).ticks().len(), 0);
534        for restart in [false, true] {
535            if restart {
536                session.restart();
537            } else {
538                session.reset();
539                assert_eq!(session.advance_batch(1.0).ticks().len(), 0);
540                session.start();
541            }
542            assert_eq!(session.tick(), 0);
543            assert_eq!(session.advance_batch(0.5 / 64.0).ticks().len(), 0);
544            assert_eq!(
545                session
546                    .advance_batch(0.5 / 64.0)
547                    .ticks()
548                    .next()
549                    .unwrap()
550                    .tick,
551                1
552            );
553            session.set_paused(true);
554            assert_eq!(
555                session
556                    .step_paused_batch()
557                    .unwrap()
558                    .ticks()
559                    .next()
560                    .unwrap()
561                    .tick,
562                2
563            );
564        }
565    }
566
567    #[test]
568    fn paused_step_wraps_tick_and_preserves_exact_fraction() {
569        let mut session = GameSession::new(60.0, 8, true);
570        session.advance(0.375 / 60.0);
571        session.set_paused(true);
572        session.clock.tick = u64::MAX;
573        let accumulator = session.clock.accumulator.to_bits();
574
575        let frame = session.step_paused().unwrap();
576        assert_eq!(frame.steps, 1);
577        assert_eq!(session.tick(), 0);
578        assert_eq!(session.clock.accumulator.to_bits(), accumulator);
579        assert_eq!(session.state(), SessionState::Paused);
580
581        session.step_paused().unwrap();
582        assert_eq!(session.tick(), 1);
583        assert_eq!(session.clock.accumulator.to_bits(), accumulator);
584        session.set_paused(false);
585        assert_eq!(session.advance(0.625 / 60.0).steps, 1);
586        assert_eq!(session.tick(), 2);
587    }
588}