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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
use crate::*;

/// A builder that accumulates systems to be inserted into a `Dispatcher`.
#[derive(Default)]
pub struct DispatcherBuilder {
    systems: Vec<System>,
}

impl DispatcherBuilder {
    /// Creates a new `DispatcherBuilder`.
    pub fn new() -> Self {
        Self {
            systems: Vec::default(),
        }
    }

    /// Adds a function implementing `IntoSystem` to the system pool.
    pub fn add<R, F: IntoSystem<R>>(mut self, into_system: F) -> Self {
        self.systems.push(into_system.system());
        self
    }
    /// Adds a `System` to the system pool.
    pub fn add_system(mut self, system: System) -> Self {
        self.systems.push(system);
        self
    }
    /// Builds a `Dispatcher` from the accumulated set of `System`.
    /// This preserves the order from the inserted systems.
    pub fn build(self, world: &mut World) -> Dispatcher {
        for sys in self.systems.iter() {
            (sys.initialize)(world);
        }
        let mut stages: Vec<Vec<System>> = vec![];
        let mut stage: Vec<System> = vec![];
        let mut locks = vec![];
        for sys in self.systems {
            let mut fetch = (sys.lock)(world, &mut locks);
            if let Err(_) = fetch {
                stages.push(stage);
                stage = vec![];
                locks.clear();
                fetch = (sys.lock)(world, &mut locks);
            }
            if let Err(_) = fetch {
                panic!(
                    "System cannot be borrowed at all. This means it 
                    uses the same resource twice it its signature."
                );
            }
            stage.push(sys);
        }
        stages.push(stage);
        Dispatcher { stages }
    }
}

/// A dispatcher is used to execute a collection of `System` in order and
/// possibly in parallel using `World`'s resources.
/// A dispatcher automatically avoids mutable borrow collisions which would
/// normally lead to data corruption, dead locks and more.
pub struct Dispatcher {
    stages: Vec<Vec<System>>,
}
impl Dispatcher {
    /// Runs the systems one after the other, one at a time.
    pub fn run_seq(&mut self, world: &World) -> SystemResult {
        #[cfg(feature = "profiler")]
        profile_scope!("dispatcher_run_seq");

        for stage in &mut self.stages {
            let errors = stage.iter_mut().map(|s| s.run(world)).flat_map(|r| r.err()).collect::<Vec<_>>();
            if errors.len() > 0 {
                return Err(EcsError::DispatcherExecutionFailed(errors));
            }
        }
        Ok(())
    }
    /// Runs the systems in parallel. Systems having conflicts in their
    /// dependencies (the resource reference they use are the same and at least
    /// one is mutable) are run sequentially relative to each other, while
    /// systems without conflict run in parallel.
    #[cfg(feature = "parallel")]
    pub fn run_par(&mut self, world: &World) -> SystemResult {
        #[cfg(feature = "profiler")]
        profile_scope!("dispatcher_run_par");

        for stage in &mut self.stages {
            let errors = stage.par_iter_mut().map(|s| s.run(world)).flat_map(|r| r.err()).collect::<Vec<_>>();
            if errors.len() > 0 {
                return Err(EcsError::DispatcherExecutionFailed(errors));
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use crate::*;
    use wasm_bindgen_test::*;

    #[test]
    #[wasm_bindgen_test]
    fn simple_dispatcher() {
        #[derive(Default)]
        pub struct A;
        let mut world = World::default();
        let sys = (|_comps: &A| Ok(())).system();
        let mut dispatch = DispatcherBuilder::new().add_system(sys).build(&mut world);
        dispatch.run_seq(&world).unwrap();
        dispatch.run_seq(&world).unwrap();
        dispatch.run_seq(&world).unwrap();
        assert!(world.get::<A>().is_ok());
        assert!(world.get_mut::<A>().is_ok());
    }

    #[test]
    #[wasm_bindgen_test]
    fn generic_simple_dispatcher() {
        #[derive(Default)]
        pub struct A;
        let mut world = World::default();
        fn sys<T>(_t: &T) -> SystemResult {
            Ok(())
        }
        let mut dispatch = DispatcherBuilder::new()
            .add(sys::<A>)
            .add_system(sys::<A>.system())
            .build(&mut world);
        dispatch.run_seq(&world).unwrap();
        dispatch.run_seq(&world).unwrap();
        dispatch.run_seq(&world).unwrap();
        assert!(world.get::<A>().is_ok());
        assert!(world.get_mut::<A>().is_ok());
    }

    #[cfg(feature = "parallel")]
    #[test]
    #[wasm_bindgen_test]
    fn par_distpach() {
        #[derive(Default)]
        pub struct A;
        let mut world = World::default();
        let sys = (|_comps: &A| Ok(())).system();
        let mut dispatch = DispatcherBuilder::new().add_system(sys).build(&mut world);
        dispatch.run_par(&world).unwrap();
        dispatch.run_par(&world).unwrap();
        dispatch.run_par(&world).unwrap();
        assert!(world.get::<A>().is_ok());
        assert!(world.get_mut::<A>().is_ok());
    }

    #[cfg(feature = "parallel")]
    #[test]
    #[wasm_bindgen_test]
    fn dispatch_par_stages() {
        #[derive(Default)]
        struct A;
        #[derive(Default)]
        struct B;
        let mut world = World::default();
        world.initialize::<A>();
        world.initialize::<B>();
        // Stage 1
        fn sys1(_a: &A, _b: &B) -> SystemResult {
            Ok(())
        }
        fn sys2(_a: &A, _b: &B) -> SystemResult {
            Ok(())
        }
        // Stage 2
        fn sys3(_a: &A, _b: &mut B) -> SystemResult {
            Ok(())
        }
        // Stage 3
        fn sys4(_a: &A, _b: &mut B) -> SystemResult {
            Ok(())
        }
        let mut dispatch = DispatcherBuilder::new()
            .add(sys1)
            .add(sys2)
            .add(sys3)
            .add(sys4)
            .build(&mut world);
        assert_eq!(dispatch.stages.len(), 3);
        assert_eq!(dispatch.stages[0].len(), 2);
        assert_eq!(dispatch.stages[1].len(), 1);
        assert_eq!(dispatch.stages[2].len(), 1);
        dispatch.run_par(&world).unwrap();

        let mut dispatch = DispatcherBuilder::new()
            .add(sys1)
            .add(sys2)
            .build(&mut world);
        assert_eq!(dispatch.stages.len(), 1);
        assert_eq!(dispatch.stages[0].len(), 2);
        dispatch.run_par(&world).unwrap();

        let mut dispatch = DispatcherBuilder::new().add(sys1).build(&mut world);
        assert_eq!(dispatch.stages.len(), 1);
        assert_eq!(dispatch.stages[0].len(), 1);
        dispatch.run_par(&world).unwrap();
    }
}