flax 0.7.1

An ergonomic archetypical ECS
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 alloc::vec::Vec;
use itertools::Itertools;

use crate::{
    archetype::{Archetype, Slice, Storage},
    component::{ComponentDesc, ComponentKey, ComponentValue},
    filter::StaticFilter,
    sink::Sink,
    Component, Entity,
};

#[derive(Debug, Clone, PartialEq, Eq)]
/// Represents a single ECS event
pub struct Event {
    /// The affected entity
    pub id: Entity,
    /// The affected component
    pub key: ComponentKey,
    /// The type of event
    pub kind: EventKind,
}

impl Event {
    /// Construct a new event
    pub fn new(id: Entity, key: ComponentKey, kind: EventKind) -> Self {
        Self { id, key, kind }
    }

    /// Construct a modified event
    pub fn modified(id: Entity, key: ComponentKey) -> Self {
        Self::new(id, key, EventKind::Modified)
    }

    /// Construct an added event
    pub fn added(id: Entity, key: ComponentKey) -> Self {
        Self::new(id, key, EventKind::Added)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// The type of ECS event
pub enum EventKind {
    /// The component was added to the entity
    Added,
    /// The component was removed from the entity
    Removed,
    /// The component was modified
    Modified,
}

/// Represents the raw form of an event, where the archetype is available
pub struct EventData<'a> {
    /// The affected entities
    pub ids: &'a [Entity],
    /// The affected slots
    pub slots: Slice,
    /// The affected component
    pub key: ComponentKey,
}

/// Allows subscribing to events *inside* the ECS, such as components being added, removed, or
/// modified.
///
/// Most implementations are through the [`Sink`] implementation, which sends a static event for
/// each entity affected by the event.
pub trait EventSubscriber: ComponentValue {
    /// Handle an incoming event
    fn on_added(&self, storage: &Storage, event: &EventData);
    /// Handle an incoming event
    ///
    /// **Note**: Component storage is inaccessible during this call as it may be called *during*
    /// itereation or while a query borrow is alive.
    ///
    /// Prefer to use this for cache validation and alike, as it *will* be called for intermediate
    /// events.
    fn on_modified(&self, event: &EventData);
    /// Handle an incoming event
    fn on_removed(&self, storage: &Storage, event: &EventData);

    /// Returns true if the subscriber is still connected
    fn is_connected(&self) -> bool;

    /// Returns true if the subscriber is interested in this archetype
    #[inline]
    fn matches_arch(&self, _: &Archetype) -> bool {
        true
    }

    /// Returns true if the subscriber is interested in this component
    #[inline]
    fn matches_component(&self, _: ComponentDesc) -> bool {
        true
    }

    /// Filter each event before it is generated through a custom function
    fn filter<F>(self, func: F) -> FilterFunc<Self, F>
    where
        Self: Sized,
        F: Fn(EventKind, &EventData) -> bool,
    {
        FilterFunc {
            subscriber: self,
            filter: func,
        }
    }

    /// Filter the archetypes for which the subscriber will receive events
    fn filter_arch<F: StaticFilter>(self, filter: F) -> FilterArch<Self, F>
    where
        Self: Sized,
    {
        FilterArch {
            filter,
            subscriber: self,
        }
    }

    /// Filter a subscriber to only receive events for a specific set of components
    fn filter_components<I: IntoIterator<Item = ComponentKey>>(
        self,
        components: I,
    ) -> FilterComponents<Self>
    where
        Self: Sized,
    {
        FilterComponents {
            components: components.into_iter().collect(),
            subscriber: self,
        }
    }

    /// Filter a subscriber to only receive events of a specific kind
    fn filter_event_kind(self, event_kind: EventKind) -> FilterEventKind<Self>
    where
        Self: Sized,
    {
        FilterEventKind {
            event_kind,
            subscriber: self,
        }
    }
}

impl<S> EventSubscriber for S
where
    S: 'static + Send + Sync + Sink<Event>,
{
    fn on_added(&self, _: &Storage, event: &EventData) {
        for &id in event.ids {
            self.send(Event {
                id,
                key: event.key,
                kind: EventKind::Added,
            });
        }
    }

    fn on_modified(&self, event: &EventData) {
        for &id in event.ids {
            self.send(Event {
                id,
                key: event.key,
                kind: EventKind::Modified,
            });
        }
    }

    fn on_removed(&self, _: &Storage, event: &EventData) {
        for &id in event.ids {
            self.send(Event {
                id,
                key: event.key,
                kind: EventKind::Removed,
            });
        }
    }

    fn is_connected(&self) -> bool {
        <Self as Sink<Event>>::is_connected(self)
    }
}

/// Receive the component value of an event
///
/// This is a convenience wrapper around [`EventSubscriber`] that sends the component value along
///
/// **Note**: This only tracks addition and removal of components, not modification. This is due to
/// a limitation with references lifetimes during iteration, as the values can't be accessed by the
/// subscriber simultaneously.
pub struct WithValue<T, S> {
    component: Component<T>,
    sink: S,
}

impl<T, S> WithValue<T, S> {
    /// Create a new `WithValue` subscriber
    pub fn new(component: Component<T>, sink: S) -> Self {
        Self { component, sink }
    }
}

impl<T: ComponentValue + Clone, S: 'static + Send + Sync + Sink<(Event, T)>> EventSubscriber
    for WithValue<T, S>
{
    fn on_added(&self, storage: &Storage, event: &EventData) {
        let values = storage.downcast_ref::<T>();
        for (&id, slot) in event.ids.iter().zip_eq(event.slots.as_range()) {
            let value = values[slot].clone();

            self.sink.send((
                Event {
                    id,
                    key: event.key,
                    kind: EventKind::Added,
                },
                value,
            ));
        }
    }

    fn on_modified(&self, _: &EventData) {}

    fn on_removed(&self, storage: &Storage, event: &EventData) {
        let values = storage.downcast_ref::<T>();
        for (&id, slot) in event.ids.iter().zip_eq(event.slots.as_range()) {
            let value = values[slot].clone();

            self.sink.send((
                Event {
                    id,
                    key: event.key,
                    kind: EventKind::Removed,
                },
                value,
            ));
        }
    }

    fn is_connected(&self) -> bool {
        self.sink.is_connected()
    }

    fn matches_component(&self, desc: ComponentDesc) -> bool {
        self.component.desc() == desc
    }

    fn matches_arch(&self, arch: &Archetype) -> bool {
        arch.has(self.component.key())
    }
}

/// Filter the archetypes for which the subscriber will receive events
pub struct FilterArch<S, F> {
    filter: F,
    subscriber: S,
}

impl<S, F> EventSubscriber for FilterArch<S, F>
where
    S: EventSubscriber,
    F: ComponentValue + StaticFilter,
{
    fn on_added(&self, storage: &Storage, event: &EventData) {
        self.subscriber.on_added(storage, event)
    }

    fn on_modified(&self, event: &EventData) {
        self.subscriber.on_modified(event);
    }

    fn on_removed(&self, storage: &Storage, event: &EventData) {
        self.subscriber.on_removed(storage, event)
    }

    #[inline]
    fn is_connected(&self) -> bool {
        self.subscriber.is_connected()
    }

    #[inline]
    fn matches_arch(&self, arch: &Archetype) -> bool {
        self.filter.filter_static(arch) && self.subscriber.matches_arch(arch)
    }

    #[inline]
    fn matches_component(&self, desc: ComponentDesc) -> bool {
        self.subscriber.matches_component(desc)
    }
}

/// Filter the archetypes for which the subscriber will receive events
pub struct FilterFunc<S, F> {
    filter: F,
    subscriber: S,
}

impl<S, F> EventSubscriber for FilterFunc<S, F>
where
    S: EventSubscriber,
    F: ComponentValue + Fn(EventKind, &EventData) -> bool,
{
    fn on_added(&self, storage: &Storage, event: &EventData) {
        if (self.filter)(EventKind::Added, event) {
            self.subscriber.on_added(storage, event)
        }
    }

    fn on_modified(&self, event: &EventData) {
        if (self.filter)(EventKind::Modified, event) {
            self.subscriber.on_modified(event)
        }
    }

    fn on_removed(&self, storage: &Storage, event: &EventData) {
        if (self.filter)(EventKind::Removed, event) {
            self.subscriber.on_removed(storage, event)
        }
    }

    #[inline]
    fn matches_arch(&self, arch: &Archetype) -> bool {
        self.subscriber.matches_arch(arch)
    }

    #[inline]
    fn matches_component(&self, desc: ComponentDesc) -> bool {
        self.subscriber.matches_component(desc)
    }

    #[inline]
    fn is_connected(&self) -> bool {
        self.subscriber.is_connected()
    }
}

/// Filter a subscriber to only receive events for a specific set of components
pub struct FilterComponents<S> {
    components: Vec<ComponentKey>,
    subscriber: S,
}

impl<S> EventSubscriber for FilterComponents<S>
where
    S: EventSubscriber,
{
    fn on_added(&self, storage: &Storage, event: &EventData) {
        self.subscriber.on_added(storage, event)
    }

    fn on_modified(&self, event: &EventData) {
        self.subscriber.on_modified(event)
    }

    fn on_removed(&self, storage: &Storage, event: &EventData) {
        self.subscriber.on_removed(storage, event)
    }

    #[inline]
    fn matches_arch(&self, arch: &Archetype) -> bool {
        self.components.iter().any(|&key| arch.has(key)) && self.subscriber.matches_arch(arch)
    }

    #[inline]
    fn matches_component(&self, desc: ComponentDesc) -> bool {
        self.components.contains(&desc.key()) && self.subscriber.matches_component(desc)
    }

    #[inline]
    fn is_connected(&self) -> bool {
        self.subscriber.is_connected()
    }
}

/// Filter a subscriber to only receive events of a specific kind
pub struct FilterEventKind<S> {
    event_kind: EventKind,
    subscriber: S,
}

impl<S> EventSubscriber for FilterEventKind<S>
where
    S: EventSubscriber,
{
    fn on_added(&self, storage: &Storage, event: &EventData) {
        if self.event_kind == EventKind::Added {
            self.subscriber.on_added(storage, event)
        }
    }

    fn on_modified(&self, event: &EventData) {
        if self.event_kind == EventKind::Modified {
            self.subscriber.on_modified(event)
        }
    }

    fn on_removed(&self, storage: &Storage, event: &EventData) {
        if self.event_kind == EventKind::Removed {
            self.subscriber.on_removed(storage, event)
        }
    }

    fn is_connected(&self) -> bool {
        self.subscriber.is_connected()
    }
}

/// Maps an event to the associated entity id.
pub struct WithIds<S> {
    sink: S,
}

impl<S> WithIds<S> {
    /// Create a new entity id sink
    pub fn new(sink: S) -> Self {
        Self { sink }
    }
}

impl<S: Sink<Entity>> Sink<Event> for WithIds<S> {
    fn send(&self, event: Event) {
        self.sink.send(event.id);
    }

    fn is_connected(&self) -> bool {
        self.sink.is_connected()
    }
}