yaks 0.1.0

Minimalistic framework for automatic multithreading of hecs via rayon
Documentation
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use std::{collections::HashMap, fmt::Debug, hash::Hash};

#[cfg(feature = "parallel")]
use hecs::World;

use crate::{
    DerefTuple, Executor, Fetch, QueryBundle, ResourceTuple, SystemClosure, SystemContext,
    WrappedResources,
};

#[cfg(feature = "parallel")]
use crate::{ArchetypeSet, ComponentTypeSet, ResourceSet, TypeSet};

#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct SystemId(usize);

pub struct System<'closure, Resources>
where
    Resources: ResourceTuple + 'closure,
{
    pub closure: Box<SystemClosure<'closure, Resources::Cells>>,
    pub dependencies: Vec<SystemId>,
    #[cfg(feature = "parallel")]
    pub resource_set: ResourceSet,
    #[cfg(feature = "parallel")]
    pub component_type_set: ComponentTypeSet,
    #[cfg(feature = "parallel")]
    pub archetype_writer: Box<dyn Fn(&World, &mut ArchetypeSet) + Send>,
}

/// A factory for [`Executor`](struct.Executor.html) (and the only way of creating one).
pub struct ExecutorBuilder<'closures, Resources, Handle = DummyHandle>
where
    Resources: ResourceTuple,
{
    pub(crate) systems: HashMap<SystemId, System<'closures, Resources>>,
    pub(crate) handles: HashMap<Handle, SystemId>,
    #[cfg(feature = "parallel")]
    pub(crate) all_component_types: TypeSet,
}

impl<'closures, Resources, Handle> ExecutorBuilder<'closures, Resources, Handle>
where
    Resources: ResourceTuple,
    Handle: Eq + Hash,
{
    fn box_system<'a, Closure, ResourceRefs, Queries, Markers>(
        mut closure: Closure,
    ) -> System<'closures, Resources>
    where
        Resources::Cells: 'a,
        Closure: FnMut(SystemContext<'a>, ResourceRefs, Queries) + Send + Sync + 'closures,
        ResourceRefs: Fetch<'a, WrappedResources<'a, Resources::Cells>, Markers> + 'a,
        Queries: QueryBundle,
    {
        let closure = Box::new(
            move |context: SystemContext<'a>, resources: &'a WrappedResources<Resources::Cells>| {
                let mut fetched = ResourceRefs::fetch(resources);
                closure(context, unsafe { fetched.deref() }, Queries::markers());
                ResourceRefs::release(resources, fetched);
            },
        );
        let closure = unsafe {
            std::mem::transmute::<
                Box<dyn FnMut(_, &'a _) + Send + Sync + 'closures>,
                Box<
                    dyn FnMut(SystemContext, &WrappedResources<Resources::Cells>)
                        + Send
                        + Sync
                        + 'closures,
                >,
            >(closure)
        };
        #[cfg(feature = "parallel")]
        {
            let mut resource_set = ResourceSet::with_capacity(Resources::LENGTH);
            ResourceRefs::set_resource_bits(&mut resource_set);
            let mut component_type_set =
                ComponentTypeSet::with_capacity(Queries::COMPONENT_TYPE_SET_LENGTH);
            Queries::insert_component_types(&mut component_type_set);
            let archetype_writer = Box::new(|world: &World, archetype_set: &mut ArchetypeSet| {
                Queries::set_archetype_bits(world, archetype_set)
            });
            System {
                closure,
                dependencies: vec![],
                resource_set,
                component_type_set,
                archetype_writer,
            }
        }
        #[cfg(not(feature = "parallel"))]
        System {
            closure,
            dependencies: vec![],
        }
    }

    /// Creates a new system from a closure or a function, and inserts it into the builder.
    ///
    /// The system-to-be must return nothing and have these 3 arguments:
    /// - [`SystemContext`](struct.SystemContext.html),
    /// - any tuple (up to 16) or a single one of "resources": references or mutable references
    /// to `Send + Sync` values not contained in a [`hecs::World`](../hecs/struct.World.html)
    /// that the system will be accessing,
    /// - any tuple (up to 16) or a single one of [`QueryMarker`](struct.QueryMarker.html) that
    /// represent the queries the system will be making.
    ///
    /// Additionally, closures may mutably borrow from their environment for the lifetime
    /// of the executor, but must be `Send + Sync`.
    ///
    /// All resources the system requires must correspond to a type in the executor's
    /// signature; e.g., if any number of systems require a `&f32` or a `&mut f32`,
    /// executor's generic parameter must contain `f32`.
    ///
    /// # Example
    /// ```rust
    /// # use yaks::{QueryMarker, SystemContext, Executor};
    /// # let world = hecs::World::new();
    /// # struct A;
    /// # struct B;
    /// # struct C;
    /// fn system_0(
    ///     context: SystemContext,
    ///     res_a: &A,
    ///     (query_0, query_1): (
    ///         QueryMarker<(&B, &mut C)>,
    ///         QueryMarker<hecs::Without<B, &C>>
    ///     ),
    /// ) {
    ///     // This system may read resource of type `A`, and may prepare & execute queries
    ///     // of `(&B, &mut C)` and `hecs::Without<B, &C>`.
    /// }
    ///
    /// fn system_1(
    ///     context: SystemContext,
    ///     (res_a, res_b): (&mut A, &B),
    ///     query_0: QueryMarker<(&mut B, &mut C)>,
    /// ) {
    ///     // This system may read or write resource of type `A`, may read resource of type `B`,
    ///     // and may prepare & execute queries of `(&mut B, &mut C)`.
    /// }
    ///
    /// let mut increment = 0;
    /// // All together, systems require resources of types `A`, `B`, and `C`.
    /// let mut executor = Executor::<(A, B, C)>::builder()
    ///     .system(system_0)
    ///     .system(system_1)
    ///     .system(|context, res_c: &C, _queries: ()| {
    ///         // This system may read resource of type `C` and will not perform any queries.
    ///         increment += 1; // `increment` will be borrowed by the executor.
    ///     })
    ///     .build();
    /// let (mut a, mut b, mut c) = (A, B, C);
    /// executor.run(&world, (&mut a, &mut b, &mut c));
    /// executor.run(&world, (&mut a, &mut b, &mut c));
    /// executor.run(&world, (&mut a, &mut b, &mut c));
    /// drop(executor); // This releases the borrow of `increment`.
    /// assert_eq!(increment, 3);
    /// ```
    pub fn system<'a, Closure, ResourceRefs, Queries, Markers>(mut self, closure: Closure) -> Self
    where
        Resources::Cells: 'a,
        Closure: FnMut(SystemContext<'a>, ResourceRefs, Queries) + Send + Sync + 'closures,
        ResourceRefs: Fetch<'a, WrappedResources<'a, Resources::Cells>, Markers> + 'a,
        Queries: QueryBundle,
    {
        let id = SystemId(self.systems.len());
        let system = Self::box_system::<'a, Closure, ResourceRefs, Queries, Markers>(closure);
        #[cfg(feature = "parallel")]
        {
            self.all_component_types
                .extend(&system.component_type_set.immutable);
            self.all_component_types
                .extend(&system.component_type_set.mutable);
        }
        self.systems.insert(id, system);
        self
    }

    /// Creates a new system from a closure or a function, and inserts it into
    /// the builder with given handle; see [`::system()`](#method.system).
    ///
    /// Handles allow defining relative order of execution between systems,
    /// and using them is optional. They can be of any type that is `Sized + Eq + Hash + Debug`
    /// and do not persist after [`::build()`](struct.ExecutorBuilder.html#method.build) - the
    /// resulting executor relies on lightweight opaque IDs;
    /// see [`SystemContext::id()`](struct.SystemContext.html#method.id).
    ///
    /// Handles must be unique, and systems with dependencies must be inserted
    /// into the builder after said dependencies.
    /// If the default `parallel` feature is disabled the systems will be executed in insertion
    /// order, which these rules guarantee to be a valid order.
    ///
    /// Since specifying a dependency between systems forbids them to run concurrently, this
    /// functionality should be used only when necessary. In fact, for executors where systems
    /// form a single chain of execution it is more performant to call them as functions,
    /// in a sequence, inside a single [`rayon::scope()`](../rayon/fn.scope.html) or
    /// [`rayon::ThreadPool::install()`](../rayon/struct.ThreadPool.html#method.install) block.
    ///
    /// # Examples
    /// These two executors are identical.
    /// ```rust
    /// # use yaks::{QueryMarker, SystemContext, Executor};
    /// # let world = hecs::World::new();
    /// # fn system_0(_: SystemContext, _: (), _: ()) {}
    /// # fn system_1(_: SystemContext, _: (), _: ()) {}
    /// # fn system_2(_: SystemContext, _: (), _: ()) {}
    /// # fn system_3(_: SystemContext, _: (), _: ()) {}
    /// # fn system_4(_: SystemContext, _: (), _: ()) {}
    /// let _ = Executor::<()>::builder()
    ///     .system_with_handle(system_0, 0)
    ///     .system_with_handle(system_1, 1)
    ///     .system_with_handle_and_deps(system_2, 2, vec![0, 1])
    ///     .system_with_deps(system_3, vec![2])
    ///     .system_with_deps(system_4, vec![0])
    ///     .build();
    /// let _ = Executor::<()>::builder()
    ///     .system_with_handle(system_0, "system_0")
    ///     .system_with_handle(system_1, "system_1")
    ///     .system_with_handle_and_deps(system_2, "system_2", vec!["system_1", "system_0"])
    ///     .system_with_deps(system_3, vec!["system_2"])
    ///     .system_with_deps(system_4, vec!["system_0"])
    ///     .build();
    /// ```
    /// The order of execution (with the default `parallel` feature enabled) is:
    /// - systems 0 ***and*** 1,
    /// - system 4 as soon as 0 is finished ***and*** system 2 as soon as both 0 and 1 is finished,
    /// - system 3 as soon as 2 is finished.
    ///
    /// This executor will behave identically to the two above if the default `parallel`
    /// feature is enabled; otherwise, the execution order will be different, but
    /// that doesn't matter as long as the given dependencies truthfully reflect any
    /// relationships the systems may have.
    /// ```rust
    /// # use yaks::{QueryMarker, SystemContext, Executor};
    /// # let world = hecs::World::new();
    /// # fn system_0(_: SystemContext, _: (), _: ()) {}
    /// # fn system_1(_: SystemContext, _: (), _: ()) {}
    /// # fn system_2(_: SystemContext, _: (), _: ()) {}
    /// # fn system_3(_: SystemContext, _: (), _: ()) {}
    /// # fn system_4(_: SystemContext, _: (), _: ()) {}
    /// let _ = Executor::<()>::builder()
    ///     .system_with_handle(system_1, 1)
    ///     .system_with_handle(system_0, 0)
    ///     .system_with_deps(system_4, vec![0])
    ///     .system_with_handle_and_deps(system_2, 2, vec![0, 1])
    ///     .system_with_deps(system_3, vec![2])
    ///     .build();
    /// ```
    ///
    /// # Panics
    /// This function will panic if:
    /// - a system with given handle is already present in the builder.
    pub fn system_with_handle<'a, Closure, ResourceRefs, Queries, Markers, NewHandle>(
        mut self,
        closure: Closure,
        handle: NewHandle,
    ) -> ExecutorBuilder<'closures, Resources, NewHandle>
    where
        Resources::Cells: 'a,
        Closure: FnMut(SystemContext<'a>, ResourceRefs, Queries) + Send + Sync + 'closures,
        ResourceRefs: Fetch<'a, WrappedResources<'a, Resources::Cells>, Markers> + 'a,
        Queries: QueryBundle,
        NewHandle: HandleConversion<Handle> + Debug,
    {
        let mut handles = NewHandle::convert_hash_map(self.handles);
        if handles.contains_key(&handle) {
            panic!("system {:?} already exists", handle);
        }
        let id = SystemId(self.systems.len());
        let system = Self::box_system::<'a, Closure, ResourceRefs, Queries, Markers>(closure);
        #[cfg(feature = "parallel")]
        {
            self.all_component_types
                .extend(&system.component_type_set.immutable);
            self.all_component_types
                .extend(&system.component_type_set.mutable);
        }
        self.systems.insert(id, system);
        handles.insert(handle, id);
        ExecutorBuilder {
            systems: self.systems,
            handles,
            #[cfg(feature = "parallel")]
            all_component_types: self.all_component_types,
        }
    }

    /// Creates a new system from a closure or a function, and inserts it into
    /// the builder with given dependencies; see [`::system()`](#method.system).
    ///
    /// Given system will start running only after all systems in given list of dependencies
    /// have finished running.
    ///
    /// This function cannot be used unless the builder already has
    /// at least one system with a handle;
    /// see [`::system_with_handle()`](#method.system_with_handle).
    ///
    /// # Panics
    /// This function will panic if:
    /// - given list of dependencies contains a handle that
    /// doesn't correspond to any system in the builder.
    pub fn system_with_deps<'a, Closure, ResourceRefs, Queries, Markers>(
        mut self,
        closure: Closure,
        dependencies: Vec<Handle>,
    ) -> Self
    where
        Resources::Cells: 'a,
        Closure: FnMut(SystemContext<'a>, ResourceRefs, Queries) + Send + Sync + 'closures,
        ResourceRefs: Fetch<'a, WrappedResources<'a, Resources::Cells>, Markers> + 'a,
        Queries: QueryBundle,
        Handle: Eq + Hash + Debug,
    {
        let id = SystemId(self.systems.len());
        let mut system = Self::box_system::<'a, Closure, ResourceRefs, Queries, Markers>(closure);
        #[cfg(feature = "parallel")]
        {
            self.all_component_types
                .extend(&system.component_type_set.immutable);
            self.all_component_types
                .extend(&system.component_type_set.mutable);
        }
        system
            .dependencies
            .extend(dependencies.iter().map(|dep_handle| {
                *self.handles.get(dep_handle).unwrap_or_else(|| {
                    panic!(
                    "could not resolve dependencies of a handle-less system: no system {:?} found",
                    dep_handle
                )
                })
            }));
        self.systems.insert(id, system);
        self
    }

    /// Creates a new system from a closure or a function, and inserts it into
    /// the builder with given handle and dependencies; see [`::system()`](#method.system).
    ///
    /// Given system will start running only after all systems in given list of dependencies
    /// have finished running.
    ///
    /// This function cannot be used unless the builder already has
    /// at least one system with a handle;
    /// see [`::system_with_handle()`](#method.system_with_handle).
    ///
    /// # Panics
    /// This function will panic if:
    /// - a system with given handle is already present in the builder,
    /// - given list of dependencies contains a handle that
    /// doesn't correspond to any system in the builder,
    /// - given handle appears in given list of dependencies.
    pub fn system_with_handle_and_deps<'a, Closure, ResourceRefs, Queries, Markers>(
        mut self,
        closure: Closure,
        handle: Handle,
        dependencies: Vec<Handle>,
    ) -> Self
    where
        Resources::Cells: 'a,
        Closure: FnMut(SystemContext<'a>, ResourceRefs, Queries) + Send + Sync + 'closures,
        ResourceRefs: Fetch<'a, WrappedResources<'a, Resources::Cells>, Markers> + 'a,
        Queries: QueryBundle,
        Handle: Eq + Hash + Debug,
    {
        if self.handles.contains_key(&handle) {
            panic!("system {:?} already exists", handle);
        }
        if dependencies.contains(&handle) {
            panic!("system {:?} depends on itself", handle);
        }
        let id = SystemId(self.systems.len());
        let mut system = Self::box_system::<'a, Closure, ResourceRefs, Queries, Markers>(closure);
        #[cfg(feature = "parallel")]
        {
            self.all_component_types
                .extend(&system.component_type_set.immutable);
            self.all_component_types
                .extend(&system.component_type_set.mutable);
        }
        system
            .dependencies
            .extend(dependencies.iter().map(|dep_handle| {
                *self.handles.get(dep_handle).unwrap_or_else(|| {
                    panic!(
                        "could not resolve dependencies of system {:?}: no system {:?} found",
                        handle, dep_handle
                    )
                })
            }));
        self.systems.insert(id, system);
        self.handles.insert(handle, id);
        self
    }

    /// Consumes the builder and returns the finalized executor.
    pub fn build(self) -> Executor<'closures, Resources> {
        Executor::build(self)
    }
}

#[derive(PartialEq, Eq, Hash)]
pub struct DummyHandle;

pub trait HandleConversion<T>: Sized + Eq + Hash {
    fn convert_hash_map(map: HashMap<T, SystemId>) -> HashMap<Self, SystemId>;
}

impl<T> HandleConversion<DummyHandle> for T
where
    T: Debug + Eq + Hash,
{
    fn convert_hash_map(_: HashMap<DummyHandle, SystemId>) -> HashMap<Self, SystemId> {
        HashMap::new()
    }
}

impl<T> HandleConversion<T> for T
where
    T: Debug + Eq + Hash,
{
    fn convert_hash_map(map: HashMap<T, SystemId>) -> HashMap<Self, SystemId> {
        map
    }
}