lyra-engine/lyra-ecs/src/system/mod.rs

310 lines
7.5 KiB
Rust
Raw Normal View History

2023-12-08 22:35:39 +00:00
use std::{ptr::NonNull, marker::PhantomData, cell::{Ref, RefMut}};
2023-12-04 04:14:27 +00:00
2023-12-08 22:35:39 +00:00
use crate::{world::World, View, Query, Access, ResourceObject};
2023-12-04 04:14:27 +00:00
2023-12-06 04:17:19 +00:00
pub mod graph;
2023-12-04 04:14:27 +00:00
/// A system that does not mutate the world
pub trait System {
fn world_access(&self) -> Access;
fn execute(&mut self, world: NonNull<World>) -> anyhow::Result<()>;
}
/// A trait for converting something into a system.
pub trait IntoSystem<T> {
type System: System;
fn into_system(self) -> Self::System;
}
pub trait FnArgFetcher {
type Arg<'a>: FnArg<Fetcher = Self>;
2023-12-04 04:14:27 +00:00
fn new() -> Self;
/// Return the appropriate world access if this fetcher gets the world directly.
/// Return [`Access::None`] if you're only fetching components, or resources.
fn world_access(&self) -> Access {
Access::None
}
2023-12-04 04:14:27 +00:00
/// Get the arg from the world
unsafe fn get<'a>(&mut self, world: NonNull<World>) -> Self::Arg<'a>;
2023-12-04 04:14:27 +00:00
}
pub trait FnArg {
type Fetcher: FnArgFetcher;
}
2023-12-04 04:14:27 +00:00
pub struct FnSystem<F, Args> {
inner: F,
args: Args,
}
2023-12-04 04:14:27 +00:00
impl<F, A> System for FnSystem<F, A>
where
A: FnArgFetcher,
2023-12-04 04:14:27 +00:00
F: for<'a> FnMut(A::Arg<'a>) -> anyhow::Result<()>,
{
fn world_access(&self) -> Access {
todo!()
}
fn execute(&mut self, world: NonNull<World>) -> anyhow::Result<()> {
let mut a = A::new();
let a = unsafe { a.get(world) };
(self.inner)(a)?;
Ok(())
}
}
impl<F, A> IntoSystem<A> for F
2023-12-04 04:14:27 +00:00
where
A: FnArg,
F: FnMut(A) -> anyhow::Result<()>,
F: for<'a> FnMut(<A::Fetcher as FnArgFetcher>::Arg<'a>) -> anyhow::Result<()>,
2023-12-04 04:14:27 +00:00
{
type System = FnSystem<F, A::Fetcher>;
2023-12-04 04:14:27 +00:00
fn into_system(self) -> Self::System {
FnSystem {
args: A::Fetcher::new(),
2023-12-04 04:14:27 +00:00
inner: self
}
}
}
2023-12-04 04:14:27 +00:00
/// An ArgFetcher implementation for query [`View`]s
pub struct ViewArgFetcher<Q> {
query: Q
}
2023-12-04 04:14:27 +00:00
impl<'a, Q: Query> FnArg for View<'a, Q> {
type Fetcher = ViewArgFetcher<Q>;
}
impl<Q: Query> FnArgFetcher for ViewArgFetcher<Q> {
type Arg<'a> = View<'a, Q>;
fn new() -> Self {
ViewArgFetcher {
query: Q::new(),
2023-12-04 04:14:27 +00:00
}
}
unsafe fn get<'a>(&mut self, world: NonNull<World>) -> Self::Arg<'a> {
let world = &*world.as_ptr();
let arch = world.archetypes.values().collect();
let v = View::new(world, self.query, arch);
2023-12-04 04:14:27 +00:00
v
2023-12-04 04:14:27 +00:00
}
}
/// An ArgFetcher implementation for borrowing the [`World`].
pub struct WorldArgFetcher;
impl<'a> FnArg for &'a World {
type Fetcher = WorldArgFetcher;
2023-12-04 04:14:27 +00:00
}
impl FnArgFetcher for WorldArgFetcher {
type Arg<'a> = &'a World;
2023-12-04 04:14:27 +00:00
fn new() -> Self {
WorldArgFetcher
2023-12-04 04:14:27 +00:00
}
fn world_access(&self) -> Access {
Access::Read
}
2023-12-04 04:14:27 +00:00
unsafe fn get<'a>(&mut self, world: NonNull<World>) -> Self::Arg<'a> {
&*world.as_ptr()
}
}
/// An ArgFetcher implementation for mutably borrowing the [`World`].
pub struct WorldMutArgFetcher;
impl<'a> FnArg for &'a mut World {
type Fetcher = WorldMutArgFetcher;
}
impl FnArgFetcher for WorldMutArgFetcher {
type Arg<'a> = &'a mut World;
fn new() -> Self {
WorldMutArgFetcher
}
fn world_access(&self) -> Access {
Access::Write
}
unsafe fn get<'a>(&mut self, world: NonNull<World>) -> Self::Arg<'a> {
&mut *world.as_ptr()
2023-12-04 04:14:27 +00:00
}
}
2023-12-08 22:35:39 +00:00
pub struct ResourceArgFetcher<R: ResourceObject> {
phantom: PhantomData<fn() -> R>
}
impl<'a, R: ResourceObject> FnArg for Ref<'a, R> {
type Fetcher = ResourceArgFetcher<R>;
}
impl<R: ResourceObject> FnArgFetcher for ResourceArgFetcher<R> {
type Arg<'a> = Ref<'a, R>;
fn new() -> Self {
ResourceArgFetcher {
phantom: PhantomData
}
}
unsafe fn get<'a>(&mut self, world: NonNull<World>) -> Self::Arg<'a> {
let world = world.as_ref();
world.get_resource::<R>()
}
}
pub struct ResourceMutArgFetcher<R: ResourceObject> {
phantom: PhantomData<fn() -> R>
}
impl<'a, R: ResourceObject> FnArg for RefMut<'a, R> {
type Fetcher = ResourceMutArgFetcher<R>;
}
impl<R: ResourceObject> FnArgFetcher for ResourceMutArgFetcher<R> {
type Arg<'a> = RefMut<'a, R>;
fn new() -> Self {
ResourceMutArgFetcher {
phantom: PhantomData
}
}
unsafe fn get<'a>(&mut self, world: NonNull<World>) -> Self::Arg<'a> {
let world = world.as_ref();
world.get_resource_mut::<R>()
}
}
2023-12-04 04:14:27 +00:00
#[cfg(test)]
mod tests {
2023-12-08 22:35:39 +00:00
use std::{ptr::NonNull, cell::RefMut};
2023-12-04 04:14:27 +00:00
2023-12-06 04:17:19 +00:00
use crate::{tests::{Vec2, Vec3}, View, QueryBorrow, world::World};
2023-12-04 04:14:27 +00:00
use super::{System, IntoSystem};
struct SomeCounter(u32);
2023-12-04 04:14:27 +00:00
#[test]
fn simple_system() {
let mut world = World::new();
let vecs = &[Vec2::rand(), Vec2::rand(), Vec2::rand(), Vec2::rand()];
world.spawn((vecs[0],));
world.spawn((vecs[1],));
world.spawn((vecs[2],));
world.spawn((vecs[3],));
2023-12-04 04:14:27 +00:00
let mut count = 0;
let test_system = |view: View<QueryBorrow<Vec2>>| -> anyhow::Result<()> {
let mut vecs = vecs.to_vec();
2023-12-04 04:14:27 +00:00
for v in view.into_iter() {
let pos = vecs.iter().position(|vec| *vec == *v)
.expect("Failure to find vec inside list");
vecs.remove(pos);
2023-12-04 04:14:27 +00:00
println!("Got v at: {:?}", v);
count += 1;
}
Ok(())
};
test_system.into_system().execute(NonNull::from(&world)).unwrap();
assert_eq!(count, 4);
}
2023-12-06 04:17:19 +00:00
#[test]
fn multi_system() {
let mut world = World::new();
world.spawn((Vec2::rand(), Vec3::rand()));
world.spawn((Vec2::rand(), Vec3::rand()));
world.spawn((Vec2::rand(),));
world.spawn((Vec2::rand(),));
let mut count = 0;
let test_system = |view: View<(QueryBorrow<Vec2>, QueryBorrow<Vec3>)>| -> anyhow::Result<()> {
for (v2, v3) in view.into_iter() {
println!("Got v2 at '{:?}' and v3 at: '{:?}'", v2, v3);
count += 1;
}
Ok(())
};
test_system.into_system().execute(NonNull::from(&world)).unwrap();
assert_eq!(count, 2);
}
#[test]
fn world_system() {
let mut world = World::new();
world.spawn((Vec2::rand(), Vec3::rand()));
world.spawn((Vec2::rand(), Vec3::rand()));
world.add_resource(SomeCounter(0));
let test_system = |world: &World| -> anyhow::Result<()> {
let mut counter = world.get_resource_mut::<SomeCounter>();
counter.0 += 10;
Ok(())
};
test_system.into_system().execute(NonNull::from(&world)).unwrap();
2023-12-08 22:35:39 +00:00
let test_system = |world: &mut World| -> anyhow::Result<()> {
let mut counter = world.get_resource_mut::<SomeCounter>();
counter.0 += 10;
Ok(())
};
test_system.into_system().execute(NonNull::from(&world)).unwrap();
let counter = world.get_resource::<SomeCounter>();
assert_eq!(counter.0, 20);
}
#[test]
fn resource_system() {
let mut world = World::new();
world.spawn((Vec2::rand(), Vec3::rand()));
world.spawn((Vec2::rand(), Vec3::rand()));
world.add_resource(SomeCounter(0));
let test_system = |mut counter: RefMut<SomeCounter>| -> anyhow::Result<()> {
counter.0 += 10;
Ok(())
};
test_system.into_system().execute(NonNull::from(&world)).unwrap();
let counter = world.get_resource::<SomeCounter>();
assert_eq!(counter.0, 10);
}
2023-12-04 04:14:27 +00:00
}