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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
use crate::error;
use crate::scheduler::into_workload_run_if::IntoWorkloadRunIf;
use crate::scheduler::label::WorkloadLabel;
use crate::scheduler::workload::Workload;
use crate::storage::StorageId;
use crate::type_id::TypeId;
use crate::AllStoragesViewMut;
use crate::AsLabel;
use crate::Component;
use crate::SparseSet;
use crate::Unique;
use crate::UniqueStorage;
use crate::World;
use alloc::boxed::Box;
use core::any::type_name;
use core::ops::Not;

/// Modifies a workload.
pub trait WorkloadModificator {
    /// Only run the workload if the function evaluates to `true`.
    fn run_if<RunB, Run: IntoWorkloadRunIf<RunB>>(self, run_if: Run) -> Workload;
    /// Only run the workload if the `T` storage is empty.
    ///
    /// If the storage is not present it is considered empty.
    /// If the storage is already borrowed, assume it's not empty.
    fn run_if_storage_empty<T: Component>(self) -> Workload
    where
        Self: Sized,
    {
        let storage_id = StorageId::of::<SparseSet<T>>();
        self.run_if_storage_empty_by_id(storage_id)
    }
    /// Only run the workload if the `T` unique storage is not present in the `World`.
    fn run_if_missing_unique<T: Unique>(self) -> Workload
    where
        Self: Sized,
    {
        let storage_id = StorageId::of::<UniqueStorage<T>>();
        self.run_if_storage_empty_by_id(storage_id)
    }
    /// Only run the workload if the storage is empty.
    ///
    /// If the storage is not present it is considered empty.
    /// If the storage is already borrowed, assume it's not empty.
    fn run_if_storage_empty_by_id(self, storage_id: StorageId) -> Workload
    where
        Self: Sized,
    {
        use crate::all_storages::CustomStorageAccess;

        let run_if = move |all_storages: AllStoragesViewMut<'_>| match all_storages
            .custom_storage_by_id(storage_id)
        {
            Ok(storage) => storage.is_empty(),
            Err(error::GetStorage::MissingStorage { .. }) => true,
            Err(_) => false,
        };

        self.run_if(run_if)
    }
    /// Do not run the workload if the function evaluates to `true`.
    fn skip_if<RunB, Run: IntoWorkloadRunIf<RunB>>(self, run_if: Run) -> Workload;
    /// Do not run the workload if the `T` storage is empty.
    ///
    /// If the storage is not present it is considered empty.
    /// If the storage is already borrowed, assume it's not empty.
    fn skip_if_storage_empty<T: Component>(self) -> Workload
    where
        Self: Sized,
    {
        let storage_id = StorageId::of::<SparseSet<T>>();
        self.skip_if_storage_empty_by_id(storage_id)
    }
    /// Do not run the workload if the `T` unique storage is not present in the `World`.
    fn skip_if_missing_unique<T: Unique>(self) -> Workload
    where
        Self: Sized,
    {
        let storage_id = StorageId::of::<UniqueStorage<T>>();
        self.skip_if_storage_empty_by_id(storage_id)
    }
    /// Do not run the workload if the storage is empty.
    ///
    /// If the storage is not present it is considered empty.
    /// If the storage is already borrowed, assume it's not empty.
    fn skip_if_storage_empty_by_id(self, storage_id: StorageId) -> Workload
    where
        Self: Sized,
    {
        use crate::all_storages::CustomStorageAccess;

        let should_skip = move |all_storages: AllStoragesViewMut<'_>| match all_storages
            .custom_storage_by_id(storage_id)
        {
            Ok(storage) => storage.is_empty(),
            Err(error::GetStorage::MissingStorage { .. }) => true,
            Err(_) => false,
        };

        self.skip_if(should_skip)
    }
    /// When building a workload, all systems within this workload will be placed before all invocation of the other system or workload.
    fn before_all<T>(self, other: impl AsLabel<T>) -> Workload;
    /// When building a workload, all systems within this workload will be placed after all invocation of the other system or workload.
    fn after_all<T>(self, other: impl AsLabel<T>) -> Workload;
    /// Changes the name of this workload.
    fn rename<T>(self, name: impl AsLabel<T>) -> Workload;
    /// Adds a tag to this workload. Tags can be used to control system ordering when running workloads.
    fn tag<T>(self, tag: impl AsLabel<T>) -> Workload;
}

impl WorkloadModificator for Workload {
    #[track_caller]
    fn run_if<RunB, Run: IntoWorkloadRunIf<RunB>>(mut self, run_if: Run) -> Workload {
        let run_if = run_if.into_workload_run_if().unwrap();

        self.run_if = if let Some(prev_run_if) = self.run_if.take() {
            Some(Box::new(move |world: &World| {
                Ok(prev_run_if.run(world)? && run_if.run(world)?)
            }))
        } else {
            Some(run_if)
        };

        self
    }
    fn run_if_storage_empty<T: Component>(self) -> Workload {
        let storage_id = StorageId::of::<SparseSet<T>>();
        self.run_if_storage_empty_by_id(storage_id)
    }
    fn run_if_missing_unique<T: Unique>(self) -> Workload {
        let storage_id = StorageId::of::<UniqueStorage<T>>();
        self.run_if_storage_empty_by_id(storage_id)
    }
    fn run_if_storage_empty_by_id(self, storage_id: StorageId) -> Workload {
        use crate::all_storages::CustomStorageAccess;

        let run_if = move |all_storages: AllStoragesViewMut<'_>| match all_storages
            .custom_storage_by_id(storage_id)
        {
            Ok(storage) => storage.is_empty(),
            Err(error::GetStorage::MissingStorage { .. }) => true,
            Err(_) => false,
        };

        self.run_if(run_if)
    }
    fn skip_if<RunB, Run: IntoWorkloadRunIf<RunB>>(mut self, should_skip: Run) -> Self {
        let mut should_skip = should_skip.into_workload_run_if().unwrap();

        should_skip = Box::new(move |world: &World| should_skip.run(world).map(Not::not));

        self.run_if = if let Some(prev_run_if) = self.run_if.take() {
            Some(Box::new(move |world: &World| {
                Ok(prev_run_if.run(world)? && should_skip.run(world)?)
            }))
        } else {
            Some(should_skip)
        };

        self
    }
    fn skip_if_storage_empty<T: Component>(self) -> Self {
        let storage_id = StorageId::of::<SparseSet<T>>();
        self.skip_if_storage_empty_by_id(storage_id)
    }
    fn skip_if_missing_unique<T: Unique>(self) -> Self {
        let storage_id = StorageId::of::<UniqueStorage<T>>();
        self.skip_if_storage_empty_by_id(storage_id)
    }
    fn skip_if_storage_empty_by_id(self, storage_id: StorageId) -> Self {
        use crate::all_storages::CustomStorageAccess;

        let should_skip = move |all_storages: AllStoragesViewMut<'_>| match all_storages
            .custom_storage_by_id(storage_id)
        {
            Ok(storage) => storage.is_empty(),
            Err(error::GetStorage::MissingStorage { .. }) => true,
            Err(_) => false,
        };

        self.skip_if(should_skip)
    }
    fn before_all<T>(mut self, other: impl AsLabel<T>) -> Workload {
        self.before_all.add(other);

        self
    }
    fn after_all<T>(mut self, other: impl AsLabel<T>) -> Workload {
        self.after_all.add(other);

        self
    }
    fn rename<T>(mut self, name: impl AsLabel<T>) -> Workload {
        self.name = name.as_label();
        self.overwritten_name = true;
        self.tags.push(self.name.clone());

        self
    }
    fn tag<T>(mut self, tag: impl AsLabel<T>) -> Workload {
        self.tags.push(tag.as_label());

        self
    }
}

impl<W> WorkloadModificator for W
where
    W: 'static + Send + Sync + Fn() -> Workload,
{
    fn run_if<RunB, Run: IntoWorkloadRunIf<RunB>>(self, run_if: Run) -> Workload {
        let mut workload = (self)();

        let label = WorkloadLabel {
            type_id: TypeId::of::<W>(),
            name: type_name::<W>().as_label(),
        };

        workload = workload.tag(label.clone());
        workload.name = Box::new(label);

        workload.run_if(run_if)
    }
    fn skip_if<RunB, Run: IntoWorkloadRunIf<RunB>>(self, should_skip: Run) -> Workload {
        let mut workload = (self)();

        let label = WorkloadLabel {
            type_id: TypeId::of::<W>(),
            name: type_name::<W>().as_label(),
        };

        workload = workload.tag(label.clone());
        workload.name = Box::new(label);

        workload.skip_if(should_skip)
    }
    fn before_all<T>(self, other: impl AsLabel<T>) -> Workload {
        let mut workload = (self)();

        let label = WorkloadLabel {
            type_id: TypeId::of::<W>(),
            name: type_name::<W>().as_label(),
        };

        workload = workload.tag(label.clone());
        workload.name = Box::new(label);

        workload.before_all(other)
    }
    fn after_all<T>(self, other: impl AsLabel<T>) -> Workload {
        let mut workload = (self)();

        let label = WorkloadLabel {
            type_id: TypeId::of::<W>(),
            name: type_name::<W>().as_label(),
        };

        workload = workload.tag(label.clone());
        workload.name = Box::new(label);

        workload.after_all(other)
    }
    fn rename<T>(self, name: impl AsLabel<T>) -> Workload {
        let mut workload = (self)();

        let label = WorkloadLabel {
            type_id: TypeId::of::<W>(),
            name: type_name::<W>().as_label(),
        };

        workload = workload.tag(label.clone());
        workload.name = Box::new(label);

        workload.rename(name)
    }
    fn tag<T>(self, tag: impl AsLabel<T>) -> Workload {
        let mut workload = (self)();

        let label = WorkloadLabel {
            type_id: TypeId::of::<W>(),
            name: type_name::<W>().as_label(),
        };

        workload = workload.tag(label.clone());
        workload.name = Box::new(label);

        workload.tag(tag)
    }
}