summaryrefslogtreecommitdiff
path: root/ecs/src/system/stateful.rs
blob: ae6a5b57a4c33a221224eb65cde534afa40b17d1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
use std::any::{type_name, Any, TypeId};
use std::collections::HashMap;
use std::panic::{RefUnwindSafe, UnwindSafe};

use seq_macro::seq;

use crate::component::{Component, Id as ComponentId};
use crate::lock::Lock;
use crate::system::util::check_params_are_compatible;
use crate::system::{
    ComponentRefMut,
    Into as IntoSystem,
    Param,
    ParamWithInputFilter,
    System,
    TypeErased,
};
use crate::tuple::{
    IntoInOptions as TupleIntoInOptions,
    Reduce as TupleReduce,
    TakeOptionElementResult as TupleTakeOptionElementResult,
    WithOptionElements as TupleWithOptionElements,
};
use crate::WorldData;

/// A stateful system.
pub struct Stateful<Func>
{
    func: Func,
    local_components: HashMap<ComponentId, Lock<Box<dyn Component>>>,
}

macro_rules! impl_system {
    ($c: tt) => {
        seq!(I in 0..$c {
            impl<'world, Func, #(TParam~I,)*> System<'world, fn(&'world (), #(TParam~I,)*)>
                for Stateful<Func>
            where
                Func: Fn(#(TParam~I,)*) + Copy + RefUnwindSafe + UnwindSafe + 'static,
                #(TParam~I: Param<'world>,)*
                #(TParam~I::Input: 'static,)*
                (#(TParam~I::Input,)*): TupleReduce<ParamWithInputFilter>,
                <(#(TParam~I::Input,)*) as TupleReduce<ParamWithInputFilter>>::Out:
                    TupleIntoInOptions
            {
                type Input =
                    <(#(TParam~I::Input,)*) as TupleReduce<ParamWithInputFilter>>::Out;

                fn initialize(mut self, input: Self::Input) -> Self
                {
                    let mut option_input = input.into_in_options();

                    #(
                        if TypeId::of::<TParam~I::Input>() !=
                            TypeId::of::<()>()
                        {
                            let input = match option_input.take::<TParam~I::Input>() {
                                TupleTakeOptionElementResult::Found(input) => input,
                                TupleTakeOptionElementResult::NotFound => {
                                    panic!(
                                        "Parameter input {} not found",
                                        type_name::<TParam~I::Input>()
                                    );
                                }
                                TupleTakeOptionElementResult::AlreadyTaken => {
                                    panic!(
                                        concat!(
                                            "Parameter {} is already initialized. ",
                                            "System cannot contain multiple inputs with ",
                                            "the same type",
                                        ),
                                        type_name::<TParam~I>()
                                    );

                                }
                            };

                            TParam~I::initialize(
                                &mut self,
                                input
                            );
                        }
                    )*

                    self
                }

                fn prepare(&self, world_data: &WorldData)
                {
                    #(
                        TParam~I::handle_pre_run(world_data);
                    )*
                }

                fn run<'this>(&'this self, world_data: &'world WorldData)
                where
                    'this: 'world
                {
                    #(
                        check_params_are_compatible!(I, TParam~I, $c);
                    )*

                    let func = self.func;

                    func(#({
                        TParam~I::new(self, world_data)
                    },)*);
                }

                fn into_type_erased(self) -> TypeErased
                {
                    TypeErased {
                        data: Box::new(self),
                        func: Box::new(|data, world_data| {
                            // SAFETY: The caller of TypeErased::run ensures the lifetime
                            // is correct
                            let data = unsafe { &*(data as *const dyn Any) };

                            let me = data.downcast_ref::<Self>().unwrap();

                            // SAFETY: The caller of TypeErased::run ensures the lifetime
                            // is correct
                            let world_data = unsafe {
                                &*(world_data as *const WorldData)
                            };

                            me.run(world_data);
                        }),
                    }
                }

                fn get_local_component_mut<LocalComponent: Component>(
                    &self,
                ) -> Option<ComponentRefMut<LocalComponent>>
                {
                    let local_component = self.local_components
                        .get(&ComponentId::of::<LocalComponent>())?
                        .write_nonblock()
                        .expect("Failed to aquire read-write local component lock");

                    Some(ComponentRefMut::new(local_component))
                }

                fn set_local_component<LocalComponent: Component>(
                    &mut self,
                    local_component: LocalComponent,
                )
                {
                    self.local_components
                        .insert(
                            ComponentId::of::<LocalComponent>(),
                            Lock::new(Box::new(local_component))
                        );
                }
            }

            impl<Func, #(TParam~I,)*> IntoSystem<fn(#(TParam~I,)*)>
                for Func
            where
                Func: Fn(#(TParam~I,)*) + Copy + 'static,
            {
                type System = Stateful<Func>;

                fn into_system(self) -> Self::System
                {
                    Self::System {
                        func: self,
                        local_components: HashMap::new(),
                    }
                }
            }
        });
    };
}

seq!(C in 1..16 {
    impl_system!(C);
});