use std::{error::Error, fmt, time::Duration};
use sim_engine::LogicalViewport;
use crate::{
ExtractionError,
commands::CommandBatchError,
component::ComponentApprovalError,
identity::{WorldFactoryId, WorldGeneration},
input::{InputCollectionError, InputEvent},
system::{Stage, SystemRunFailure, SystemSetupError},
time::{DroppedFixedTime, FixedFramePlan, TimeAdvanceError},
transition::{ConvergentTransitionWarning, TransitionRejection},
world::WorldBuildError,
};
pub struct FrameRequest<'a> {
elapsed: Duration,
events: &'a [InputEvent],
viewport: LogicalViewport,
}
impl<'a> FrameRequest<'a> {
pub const fn new(
elapsed: Duration,
events: &'a [InputEvent],
viewport: LogicalViewport,
) -> Self {
Self {
elapsed,
events,
viewport,
}
}
pub const fn elapsed(&self) -> Duration {
self.elapsed
}
pub const fn events(&self) -> &'a [InputEvent] {
self.events
}
pub const fn viewport(&self) -> LogicalViewport {
self.viewport
}
}
#[derive(Debug)]
pub enum BeginFrameRejection {
FrameIdentityExhausted,
Input(InputCollectionError),
Time(TimeAdvanceError),
}
impl fmt::Display for BeginFrameRejection {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::FrameIdentityExhausted => {
formatter.write_str("application frame identity space is exhausted")
}
Self::Input(error) => write!(formatter, "frame input was rejected: {error}"),
Self::Time(error) => write!(formatter, "frame time was rejected: {error}"),
}
}
}
impl Error for BeginFrameRejection {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Input(error) => Some(error),
Self::Time(error) => Some(error),
Self::FrameIdentityExhausted => None,
}
}
}
#[derive(Debug)]
pub enum CandidateFailure {
InvalidFactory,
GenerationExhausted,
Components(ComponentApprovalError),
Factory(WorldBuildError),
SystemSetup(SystemSetupError),
StartupSystem(SystemRunFailure),
StartupCommands(CommandBatchError),
StartupTransition,
Extraction(ExtractionError),
RuntimeInvariant,
}
impl fmt::Display for CandidateFailure {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidFactory => formatter.write_str("World factory handle is not registered"),
Self::GenerationExhausted => {
formatter.write_str("World generation identity space is exhausted")
}
Self::Components(error) => write!(formatter, "component registry failed: {error}"),
Self::Factory(error) => write!(formatter, "World factory failed: {error}"),
Self::SystemSetup(error) => write!(formatter, "System setup failed: {error}"),
Self::StartupSystem(error) => write!(formatter, "Startup failed: {error}"),
Self::StartupCommands(error) => write!(formatter, "Startup Commands failed: {error}"),
Self::StartupTransition => {
formatter.write_str("Startup cannot request World replacement in this slice")
}
Self::Extraction(error) => write!(formatter, "candidate extraction failed: {error}"),
Self::RuntimeInvariant => {
formatter.write_str("candidate is missing a private runtime Resource")
}
}
}
}
impl Error for CandidateFailure {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Components(error) => Some(error),
Self::Factory(error) => Some(error),
Self::SystemSetup(error) => Some(error),
Self::StartupSystem(error) => Some(error),
Self::StartupCommands(error) => Some(error),
Self::Extraction(error) => Some(error),
Self::InvalidFactory
| Self::GenerationExhausted
| Self::StartupTransition
| Self::RuntimeInvariant => None,
}
}
}
#[derive(Debug)]
pub enum RunnerBuildError {
InvalidInitialFactory,
Input(InputCollectionError),
LifecycleTraceAllocation {
limit: usize,
},
MissingApplicationResource {
resource: &'static str,
stage: Stage,
system: &'static str,
},
ApplicationResourceInvariant,
InitialWorld(CandidateFailure),
}
impl fmt::Display for RunnerBuildError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidInitialFactory => {
formatter.write_str("initial World factory is not registered by this application")
}
Self::Input(error) => write!(formatter, "input initialization failed: {error}"),
Self::LifecycleTraceAllocation { limit } => write!(
formatter,
"failed to reserve lifecycle trace capacity of {limit} records"
),
Self::MissingApplicationResource {
resource,
stage,
system,
} => write!(
formatter,
"{stage:?} System `{system}` requests unregistered Application Resource `{resource}`"
),
Self::ApplicationResourceInvariant => formatter
.write_str("Application Resource staging failed a private runtime invariant"),
Self::InitialWorld(error) => write!(formatter, "initial World failed: {error}"),
}
}
}
impl Error for RunnerBuildError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Input(error) => Some(error),
Self::InitialWorld(error) => Some(error),
Self::InvalidInitialFactory
| Self::LifecycleTraceAllocation { .. }
| Self::MissingApplicationResource { .. }
| Self::ApplicationResourceInvariant => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LifecycleEvent {
WorldEnter,
WorldExit,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LifecycleRecord {
pub(super) event: LifecycleEvent,
pub(super) generation: WorldGeneration,
pub(super) factory: WorldFactoryId,
}
impl LifecycleRecord {
pub const fn event(self) -> LifecycleEvent {
self.event
}
pub const fn generation(self) -> WorldGeneration {
self.generation
}
pub const fn factory(self) -> WorldFactoryId {
self.factory
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransitionRequestFailure {
InvalidFactory,
InvalidIntent,
}
#[derive(Debug)]
pub enum FrameTransition {
None,
Rejected(TransitionRejection),
Invalid(TransitionRequestFailure),
PreparationFailed {
target: WorldFactoryId,
error: CandidateFailure,
},
Committed {
old: WorldGeneration,
new: WorldGeneration,
target: WorldFactoryId,
warning: Option<ConvergentTransitionWarning>,
},
}
#[derive(Debug)]
pub enum FrameFailure {
System {
stage: Stage,
error: SystemRunFailure,
},
Commands {
stage: Stage,
error: CommandBatchError,
},
Time(TimeAdvanceError),
Extraction(ExtractionError),
RuntimeInvariant,
}
impl fmt::Display for FrameFailure {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::System { stage, error } => {
write!(formatter, "{stage:?} System failed: {error}")
}
Self::Commands { stage, error } => {
write!(formatter, "{stage:?} Commands failed: {error}")
}
Self::Time(error) => write!(formatter, "fixed-time cleanup failed: {error}"),
Self::Extraction(error) => write!(formatter, "render extraction failed: {error}"),
Self::RuntimeInvariant => {
formatter.write_str("a private frame runtime invariant was violated")
}
}
}
}
impl Error for FrameFailure {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::System { error, .. } => Some(error),
Self::Commands { error, .. } => Some(error),
Self::Time(error) => Some(error),
Self::Extraction(error) => Some(error),
Self::RuntimeInvariant => None,
}
}
}
#[derive(Debug)]
pub struct LogicFrameReport {
pub(super) frame_index: u64,
pub(super) timing: FixedFramePlan,
pub(super) fixed_ticks_attempted: u32,
pub(super) spawned: usize,
pub(super) despawned: usize,
pub(super) exit_requested: bool,
pub(super) transitions_suppressed_by_exit: usize,
pub(super) dropped_for_transition: Option<DroppedFixedTime>,
pub(super) transition: FrameTransition,
pub(super) extracted_generation: Option<WorldGeneration>,
pub(super) failure: Option<FrameFailure>,
}
impl LogicFrameReport {
pub const fn frame_index(&self) -> u64 {
self.frame_index
}
pub const fn timing(&self) -> FixedFramePlan {
self.timing
}
pub const fn fixed_ticks_attempted(&self) -> u32 {
self.fixed_ticks_attempted
}
pub const fn spawned(&self) -> usize {
self.spawned
}
pub const fn despawned(&self) -> usize {
self.despawned
}
pub const fn exit_requested(&self) -> bool {
self.exit_requested
}
pub const fn transitions_suppressed_by_exit(&self) -> usize {
self.transitions_suppressed_by_exit
}
pub const fn dropped_for_transition(&self) -> Option<DroppedFixedTime> {
self.dropped_for_transition
}
pub const fn transition(&self) -> &FrameTransition {
&self.transition
}
pub const fn extracted_generation(&self) -> Option<WorldGeneration> {
self.extracted_generation
}
pub const fn failure(&self) -> Option<&FrameFailure> {
self.failure.as_ref()
}
}
#[derive(Debug)]
#[expect(
clippy::large_enum_variant,
reason = "keeping the hot-path frame report inline avoids one allocation per frame"
)]
pub enum FrameOutcome {
Rejected(BeginFrameRejection),
Advanced(LogicFrameReport),
}