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
//! Composable ECS systems.

use std::cmp::Ord;
use std::fmt::Debug;
use std::fmt::Display;

use async_trait::async_trait;
use futures::{FutureExt, StreamExt};
use futures::future::BoxFuture;
use futures::stream::FuturesUnordered;

/// A token which represents a system in a `SystemSet`.
/// 
/// These tokens are not unique between `SystemSet`s.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct SystemID(pub u32);

/// System wraps a single system in
#[async_trait]
pub trait System {
    async fn update(&mut self);
}

#[async_trait]
impl<F> System for F
    where F: (Fn() -> BoxFuture<'static, ()>) + Send + Sync
{
    async fn update(&mut self) {
        (self)().await
    }
}

/// A registration used for building `SystemGroups`s.
pub struct BoxSystem {
    system: Box<dyn System + Send>,
    before: Vec<SystemID>,
    after: Vec<SystemID>,
}

impl BoxSystem {
    /// Create a new system from the given function.
    pub fn new<S: System + Send + 'static>(s: S) -> BoxSystem {
        BoxSystem {
            system: Box::new(s),

            before: Vec::new(),
            after: Vec::new(),
        }
    }

    /// Require that this system is updated before the system represented
    /// by the given token.
    pub fn before(mut self, system: SystemID) -> Self {
        if let Err(insert_idx) = self.before.binary_search(&system) {
            self.before.insert(insert_idx, system);
        }

        self
    }

    /// Require that this system is updated after the system represented
    /// by the given token.
    pub fn after(mut self, system: SystemID) -> Self {
        if let Err(insert_idx) = self.after.binary_search(&system) {
            self.after.insert(insert_idx, system);
        }

        self
    }

    /// Run one update of this system.
    pub fn update(&mut self) -> BoxFuture<()> {
        self.system.update()
    }
}

/// The error returned when the requirements for a system cannot be met.
#[derive(Clone, Debug)]
pub struct SystemRegistrationError;

impl Display for SystemRegistrationError {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(fmt, "conflicting system requirements")
    }
}

impl std::error::Error for SystemRegistrationError {}

/// A set of systems which are used to modify a world.
pub struct SystemGroup {
    next_system_id: u32,

    dependencies: Vec<SystemID>,
    system_dependencies: Vec<(usize, usize)>,
    systems: Vec<BoxSystem>,
}

impl SystemGroup {
    /// Create a new empty `SystemSet`.
    pub fn new() -> SystemGroup {
        SystemGroup {
            next_system_id: 0,

            dependencies: Vec::new(),
            system_dependencies: Vec::new(),
            systems: Vec::new(),
        }
    }

    fn calculate_dependencies(&mut self) {
        self.dependencies.clear();
        self.system_dependencies.clear();

        fn add_dep(deps: &mut Vec<SystemID>, offset: usize, id: SystemID) {
            if let Err(idx) = deps[offset..].binary_search(&id) {
                deps.insert(idx + offset, id);
            }
        }

        for (idx_a, system) in self.systems.iter().enumerate() {
            let id_a = SystemID(idx_a as u32);
            let start = self.dependencies.len();

            for dep in system.after.iter().copied() {
                if dep.0 >= self.systems.len() as u32 {
                    break;
                }

                add_dep(&mut self.dependencies, start, dep);
            }

            for (idx_b, system) in self.systems.iter().enumerate() {
                let id_b = SystemID(idx_b as u32);
                if idx_b == idx_a {
                    continue;
                }

                if system.before.binary_search(&id_a).is_ok() {
                    add_dep(&mut self.dependencies, start, id_b);
                }
            }

            self.system_dependencies.push((start, self.dependencies.len()));
        }
    }

    /// Insert a system to the set according to its requirements.
    pub fn insert(&mut self, system: BoxSystem) -> SystemID {
        let token = SystemID(self.next_system_id);
        self.next_system_id += 1;
        self.systems.push(system);
        self.calculate_dependencies();
        token
    }

    /// Run an update for every system.
    pub async fn update(&mut self) {
        let mut pending = self.systems.iter_mut()
            .enumerate()
            .map(|(idx, s)| (idx, s, 0))
            .collect::<Vec<_>>();
        let mut running = FuturesUnordered::new();
        let mut last_completed = None;

        loop {
            let mut idx = 0;
            while idx < pending.len() {
                let (system_id, _, n) = &mut pending[idx];
                let (start, end) = self.system_dependencies[*system_id];
                let rest = &self.dependencies[start + *n..end];

                if !rest.is_empty() && rest.first().copied() == last_completed {
                    *n += 1;
                }

                if start + *n >= end {
                    let (id, sys, _) = pending.remove(idx);

                    let f = async move {
                        sys.update().await;
                        SystemID(id as u32)
                    }.boxed();
                    running.push(f);
                    continue;
                }

                idx += 1;
            }

            if running.is_empty() {
                // If `pending` is not empty here, there is a bad dependency.
                break;
            }

            let finished = running.next().await.unwrap();
            last_completed = Some(finished);
        }
    }
}