Struct GameSession

Source
pub struct GameSession { /* private fields */ }
Expand description

A local game lifecycle with an owned, deterministic FixedClock.

Only Playing consumes elapsed time. Pausing and finishing preserve clock state; restarting and resetting clear both ticks and fractional time. Lifecycle transitions do not reset game-specific data: callers must reset their simulation alongside restart. Inspectors can explicitly issue one tick while paused using step_paused, without resuming or consuming elapsed time.

Implementations§

Source§

impl GameSession

Source

pub fn new(hz: f64, max_steps: u32, autoplay: bool) -> Self

Creates a session in Ready, or Playing when autoplay is true.

§Panics

Like FixedClock::new, panics if hz is not finite or outside 1..=1000, or if max_steps is zero. Use Self::try_new to report invalid settings without panicking.

Source

pub fn try_new( hz: f64, max_steps: u32, autoplay: bool, ) -> Result<Self, FixedClockError>

Creates a session with checked settings and the same behavior as Self::new.

Returns FixedClockError if hz is not finite or outside 1..=1000, or if max_steps is zero. The tick rate is checked first if both are invalid. For reusable validated settings, see SessionConfig.

use ferravex_core::{FixedClockError, session::GameSession};

assert!(matches!(
    GameSession::try_new(60.0, 0, false),
    Err(FixedClockError::ZeroCatchUpBudget)
));
let mut session = GameSession::try_new(64.0, 4, true)?;
assert_eq!(session.advance(2.0 / 64.0).steps, 2);
Source

pub fn from_config(config: SessionConfig) -> Self

Creates a fresh session from reusable, already validated settings.

Starts at tick zero with no fractional time. config.autoplay() selects Playing instead of Ready. See the SessionConfig example.

Source

pub fn state(&self) -> SessionState

Returns the current host lifecycle state.

Source

pub fn is_started(&self) -> bool

Whether this session has started, including paused or finished sessions.

Source

pub fn is_playing(&self) -> bool

Whether elapsed time currently advances the simulation clock.

Source

pub fn is_paused(&self) -> bool

Whether this session is temporarily paused.

Source

pub fn start(&mut self) -> bool

Starts a ready session. Returns true only for Ready -> Playing.

To resume use set_paused(false); to retry a finished game use restart.

Source

pub fn restart(&mut self)

Clears ticks and fractional time and enters Playing from any state.

Source

pub fn reset(&mut self)

Clears ticks and fractional time and enters Ready from any state.

Source

pub fn set_paused(&mut self, paused: bool) -> bool

Pauses or resumes an active session, returning true only when changed.

Ready and finished sessions are unchanged. Repeated requests for the current pause state are harmless and return false.

Source

pub fn toggle_pause(&mut self) -> bool

Toggles Playing and Paused, returning true only when changed.

Ready and finished sessions are unchanged.

Source

pub fn finish(&mut self, won: bool) -> bool

Finishes a playing or paused session as Won or Lost.

Returns true only when changed. A ready session cannot finish, and an existing result cannot be overwritten without resetting or restarting.

Source

pub fn advance(&mut self, elapsed_seconds: f64) -> FrameStep

Produces bounded fixed steps from the elapsed seconds of one host frame.

While inactive, returns zero steps, alpha and dropped time with the normal fixed dt, and leaves the clock completely unchanged. Time submitted while inactive is discarded, so resuming does not catch up on that time. Fractional time from earlier playing frames is retained.

Callers must measure elapsed time between host frames, including while inactive. If the host itself stops delivering frames, rebase its elapsed time measurement on resume instead of submitting the whole suspension. In Playing, invalid durations and catch-up use FixedClock::advance semantics. The tick counter includes all steps returned by this call.

Source

pub fn advance_batch(&mut self, elapsed_seconds: f64) -> TickBatch

Schedule a frame with per-update IDs, using Self::advance semantics.

Inactive sessions return an empty batch without consuming time or IDs. The clock counts the entire issued batch, even if the caller stops early. Consume input and count execution only when actually invoking an update. TickBatch documents wrapping, copying and reset semantics.

use ferravex_core::session::GameSession;
let mut session = GameSession::new(64.0, 4, true);
let batch = session.advance_batch(3.0 / 64.0);
let mut executed = 0;
for context in batch.ticks() {
    if !session.is_playing() { break; }
    assert_eq!(context.tick, 1);
    executed += 1; // Invoke game rules; this update wins the game.
    session.finish(true);
}
assert_eq!(executed, 1);
assert_eq!(session.tick(), 3);
assert_eq!(session.advance_batch(60.0).ticks().len(), 0);
session.restart();
assert_eq!(session.advance_batch(1.0 / 64.0).ticks().next().unwrap().tick, 1);
Source

pub fn step_paused(&mut self) -> Result<FrameStep, SessionStepError>

Issues exactly one fixed simulation tick while remaining Paused.

Returns SessionStepError::NotPaused in every other state, leaving both lifecycle and clock unchanged. An accepted step increments tick once (wrapping at u64::MAX), preserves all fractional time from earlier playing frames, and consumes no elapsed time. Repeated calls each issue one tick, independent of the per-frame catch-up limit. Ordinary paused advance calls still discard their elapsed time and issue no ticks.

The returned frame has steps = 1, the normal fixed dt, no dropped time, and alpha = 1.0 so an inspector can display the current pose after the update. This presentation alpha does not change the clock’s stored fractional time or the alpha returned by later advance calls.

Like advance, this method only schedules work: the tick is counted before the caller executes the update. Consume gameplay input edges and emit accepted game feedback inside that update. Game rules can still finish a session after the step.

use ferravex_core::session::{GameSession, SessionState};

let mut session = GameSession::new(64.0, 4, true);
session.advance(0.5 / 64.0); // Retain half a normal tick for resume.
assert!(session.set_paused(true));
let frame = session.step_paused()?;
let mut simulated_seconds = 0.0;
for dt in frame.ticks() {
    simulated_seconds += dt; // Execute the inspector's fixed update.
}
assert_eq!(simulated_seconds, session.dt());
assert_eq!(frame.alpha, 1.0); // Present the current simulation pose.
assert_eq!(session.tick(), 1);
assert_eq!(session.state(), SessionState::Paused);
assert_eq!(session.advance(30.0).steps, 0);
assert!(session.set_paused(false));
assert_eq!(session.advance(0.5 / 64.0).steps, 1);
assert_eq!(session.tick(), 2);
Source

pub fn step_paused_batch(&mut self) -> Result<TickBatch, SessionStepError>

Issue one paused inspector update with its scheduled ID and index zero.

Uses Self::step_paused unchanged: rejects non-Paused states without mutation, preserves fractional time and returns presentation alpha 1. The caller must execute the tick; this does not invoke application hooks.

use ferravex_core::session::GameSession;
let mut session = GameSession::new(64.0, 4, true);
session.advance_batch(1.5 / 64.0);
session.set_paused(true);
let batch = session.step_paused_batch()?;
let context = batch.ticks().next().unwrap();
assert_eq!((context.tick, context.batch_index), (2, 0));
assert_eq!(context.dt, session.dt()); // Execute the inspector update here.
assert_eq!(batch.frame().alpha, 1.0);
assert!(session.is_paused());
session.set_paused(false);
assert_eq!(session.advance_batch(0.5 / 64.0).ticks().next().unwrap().tick, 3);
Source

pub fn tick(&self) -> u64

Returns the number of fixed steps issued since creation or the last reset/restart.

Counts both playing advance batches and accepted step_paused calls, wrapping at u64::MAX like FixedClock::tick. Dropped catch-up ticks and rejected requests do not count. This is scheduled work, not a count of updates the caller actually executed: the whole returned batch is already counted when advance returns, even if game rules finish before the caller executes every step.

Source

pub fn dt(&self) -> f32

Returns the fixed simulation step duration in seconds in every state.

Trait Implementations§

Source§

impl Clone for GameSession

Source§

fn clone(&self) -> GameSession

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for GameSession

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.