use crate::audio::MusicId;
use crate::{
assets::{Assets, MaterialId, MeshId, ModelId, ShaderId, SoundId, TextureId},
input::Bindings,
render::Frame,
runtime::{CursorMode, Error, Game, InitContext, Update},
};
use rayengine_core::input::Input;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct StatePolicy {
pub update_below: bool,
pub draw_below: bool,
pub input_below: bool,
}
pub trait State {
fn policy(&self) -> StatePolicy {
StatePolicy::default()
}
fn cursor_mode(&self) -> CursorMode {
CursorMode::Free
}
fn enter(
&mut self,
_context: &mut InitContext<'_, '_>,
_resources: &mut StateResources,
) -> Result<(), Error> {
Ok(())
}
fn exit(&mut self, _context: &mut InitContext<'_, '_>) {}
fn fixed_update(&mut self, _context: &mut Update<'_, '_>, _commands: &mut StateCommands) {}
fn draw(&mut self, frame: &mut Frame<'_, '_>, commands: &mut StateCommands);
}
pub enum Transition {
Push(Box<dyn State>),
Pop,
Replace(Box<dyn State>),
Reset(Box<dyn State>),
Clear,
}
#[derive(Default)]
pub struct StateCommands {
pending: Option<Transition>,
}
impl StateCommands {
pub fn request(&mut self, transition: Transition) -> Result<(), Transition> {
if self.pending.is_some() {
Err(transition)
} else {
self.pending = Some(transition);
Ok(())
}
}
pub fn is_pending(&self) -> bool {
self.pending.is_some()
}
}
#[derive(Default)]
pub struct StateResources {
targets: Vec<crate::targets::RenderTargetId>,
materials: Vec<MaterialId>,
meshes: Vec<MeshId>,
models: Vec<ModelId>,
textures: Vec<TextureId>,
sounds: Vec<SoundId>,
music: Vec<MusicId>,
shaders: Vec<ShaderId>,
}
macro_rules! own_asset {
($method:ident, $field:ident, $ty:ty, $doc:literal) => {
#[doc = $doc]
pub fn $method(&mut self, id: $ty) -> $ty {
if !self.$field.contains(&id) {
self.$field.push(id);
}
id
}
};
}
impl StateResources {
own_asset!(
own_render_target,
targets,
crate::targets::RenderTargetId,
"Transfer an exclusive render target handle; returns it for storage in the state."
);
own_asset!(
own_material,
materials,
MaterialId,
"Transfer an exclusive material handle; returns it for storage in the state."
);
own_asset!(
own_mesh,
meshes,
MeshId,
"Transfer an exclusive generated mesh handle; returns it for storage in the state."
);
own_asset!(
own_model,
models,
ModelId,
"Transfer an exclusive model handle; returns it for storage in the state."
);
own_asset!(
own_texture,
textures,
TextureId,
"Transfer an exclusive texture handle; returns it for storage in the state."
);
own_asset!(
own_sound,
sounds,
SoundId,
"Transfer an exclusive sound handle; returns it for storage in the state."
);
own_asset!(
own_music,
music,
MusicId,
"Transfer an exclusive music stream; returns it for storage in the state."
);
own_asset!(
own_shader,
shaders,
ShaderId,
"Transfer an exclusive shader handle; returns it for storage in the state."
);
fn release(&mut self, assets: &mut Assets<'_>) {
for id in self.materials.drain(..).rev() {
assets.unload_material(id);
}
for id in self.meshes.drain(..).rev() {
assets.unload_mesh(id);
}
for id in self.models.drain(..).rev() {
assets.unload_model(id);
}
for id in self.targets.drain(..).rev() {
assets.unload_render_target(id);
}
for id in self.textures.drain(..).rev() {
assets.unload_texture(id);
}
for id in self.sounds.drain(..).rev() {
assets.unload_sound(id);
}
for id in self.music.drain(..).rev() {
assets.unload_music(id);
}
for id in self.shaders.drain(..).rev() {
assets.unload_shader(id);
}
}
}
struct Entry {
state: Box<dyn State>,
resources: StateResources,
}
impl Entry {
fn enter(mut state: Box<dyn State>, context: &mut InitContext<'_, '_>) -> Result<Self, Error> {
let mut resources = StateResources::default();
if let Err(error) = state.enter(context, &mut resources) {
state.exit(context);
resources.release(context.assets);
return Err(error);
}
Ok(Self { state, resources })
}
fn exit(mut self, context: &mut InitContext<'_, '_>) {
self.state.exit(context);
self.resources.release(context.assets);
}
}
#[derive(Default)]
pub struct StateStack {
entries: Vec<Entry>,
bindings: Bindings,
commands: StateCommands,
last_error: Option<Error>,
blocked_input: Input,
suppress_input: bool,
}
impl StateStack {
pub fn new(initial: impl State + 'static, bindings: Bindings) -> Self {
Self {
bindings,
commands: StateCommands {
pending: Some(Transition::Push(Box::new(initial))),
},
..Self::default()
}
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn request(&mut self, transition: Transition) -> Result<(), Transition> {
self.commands.request(transition)
}
pub fn take_error(&mut self) -> Option<Error> {
self.last_error.take()
}
pub fn apply(&mut self, context: &mut InitContext<'_, '_>) -> Result<(), Error> {
let Some(transition) = self.commands.pending.take() else {
return Ok(());
};
self.suppress_input = true;
match transition {
Transition::Push(state) => self.entries.push(Entry::enter(state, context)?),
Transition::Replace(state) => {
let entry = Entry::enter(state, context)?;
if let Some(old) = self.entries.pop() {
old.exit(context);
}
self.entries.push(entry);
}
Transition::Reset(state) => {
let entry = Entry::enter(state, context)?;
self.clear(context);
self.entries.push(entry);
}
Transition::Pop => {
if let Some(old) = self.entries.pop() {
old.exit(context);
}
}
Transition::Clear => self.clear(context),
}
Ok(())
}
fn clear(&mut self, context: &mut InitContext<'_, '_>) {
while let Some(entry) = self.entries.pop() {
entry.exit(context);
}
}
fn policies(&self) -> Vec<StatePolicy> {
self.entries.iter().map(|e| e.state.policy()).collect()
}
}
fn update_route(policies: &[StatePolicy]) -> Vec<(usize, bool)> {
let mut route = Vec::new();
let mut input = true;
for (index, policy) in policies.iter().enumerate().rev() {
route.push((index, input));
if !policy.update_below {
break;
}
input &= policy.input_below;
}
route
}
fn draw_start(policies: &[StatePolicy]) -> usize {
policies.iter().rposition(|p| !p.draw_below).unwrap_or(0)
}
impl Game for StateStack {
fn bindings(&self) -> Bindings {
self.bindings.clone()
}
fn cursor_mode(&self) -> CursorMode {
self.entries
.last()
.map_or(CursorMode::Free, |e| e.state.cursor_mode())
}
fn init(&mut self, context: &mut InitContext<'_, '_>) -> Result<(), Error> {
self.apply(context)
}
fn boundary(&mut self, context: &mut InitContext<'_, '_>) -> Result<(), Error> {
if let Err(error) = self.apply(context) {
self.last_error = Some(error);
}
Ok(())
}
fn shutdown(&mut self, context: &mut InitContext<'_, '_>) {
self.commands.pending = None;
self.clear(context);
}
fn fixed_update(&mut self, context: &mut Update<'_, '_>) {
let suppress_input = std::mem::take(&mut self.suppress_input);
for (index, input) in update_route(&self.policies()) {
let input = input && !suppress_input;
if self.commands.is_pending() {
break;
}
self.blocked_input.consume_edges();
if context.input.reset_pending() {
self.blocked_input.release_all();
}
let mut routed = Update {
input: if input {
context.input
} else {
&self.blocked_input
},
bindings: &mut *context.bindings,
pointer: if input { context.pointer } else { None },
tick: context.tick,
viewport: context.viewport,
window_focused: context.window_focused,
assets: context.assets,
quit: &mut *context.quit,
};
self.entries[index]
.state
.fixed_update(&mut routed, &mut self.commands);
}
}
fn draw(&mut self, frame: &mut Frame<'_, '_>) {
let start = draw_start(&self.policies());
for entry in &mut self.entries[start..] {
entry.state.draw(frame, &mut self.commands);
}
}
}
#[cfg(test)]
mod tests;