edict 0.6.1

Experimental entity-component-system library
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
use alloc::sync::Arc;
use amity::{flip_queue::FlipQueue, ring_buffer::RingBuffer};
use core::{
    any::TypeId,
    iter::FusedIterator,
    sync::atomic::{AtomicBool, Ordering},
};

use crate::{
    bundle::{Bundle, ComponentBundle, DynamicBundle, DynamicComponentBundle},
    component::Component,
    entity::EntityId,
    relation::Relation,
    type_id,
    world::{iter_reserve_hint, World},
};

use super::ActionFn;

struct Shared {
    queue: FlipQueue<ActionFn<'static>>,
    non_empty: AtomicBool,
    connected: AtomicBool,
}

pub(crate) struct ActionChannel {
    shared: Arc<Shared>,
    spare_buffer: RingBuffer<ActionFn<'static>>,
}

impl Drop for ActionChannel {
    fn drop(&mut self) {
        self.shared.connected.store(false, Ordering::Relaxed);
    }
}

impl ActionChannel {
    #[inline(always)]
    pub fn new() -> Self {
        ActionChannel {
            shared: Arc::new(Shared {
                queue: FlipQueue::new(),
                non_empty: AtomicBool::new(false),
                connected: AtomicBool::new(true),
            }),
            spare_buffer: RingBuffer::new(),
        }
    }

    #[inline(always)]
    pub fn sender(&self) -> ActionSender {
        ActionSender {
            shared: self.shared.clone(),
        }
    }

    /// Fetches actions recorded into the channel.
    #[inline(always)]
    pub fn fetch(&mut self) {
        debug_assert!(self.spare_buffer.is_empty());
        if self.shared.non_empty.swap(false, Ordering::Relaxed) {
            self.shared.queue.swap_buffer(&mut self.spare_buffer);
        }
    }

    #[inline(always)]
    pub(crate) fn pop(&mut self) -> Option<ActionFn<'static>> {
        self.spare_buffer.pop()
    }
}

/// A channel for encoding actions and sending to the [`World`] thread-safely.
///
/// Use this when actions need to be encoded not in a system
/// but in a thread separate from ECS executor or in async task.
///
/// The API is similar to [`crate::action::ActionEncoder`], but entity allocation is not supported
/// and [`spawn`](ActionSender::spawn) and other methods do not return [`EntityId`]s.
///
/// Unlike [`crate::action::ActionBuffer`], the channel is bound to a specific [`World`] instance.
/// If bound [`World`] is dropped, encoded actions will not be executed.
/// See [`ActionSender::is_connected`](ActionSender::is_connected) to check
/// if the channel is still connected to a world.
#[derive(Clone)]
pub struct ActionSender {
    shared: Arc<Shared>,
}

impl ActionSender {
    /// Encodes an action to spawn an entity with provided bundle.
    #[inline(always)]
    pub fn spawn<B>(&self, bundle: B)
    where
        B: DynamicComponentBundle + Send + 'static,
    {
        self.push_fn(move |world| {
            let _ = world.spawn(bundle);
        });
    }

    /// Encodes an action to spawn an entity with provided bundle.
    #[inline(always)]
    pub fn spawn_external<B>(&self, bundle: B)
    where
        B: DynamicBundle + Send + 'static,
    {
        self.push_fn(move |world| {
            let _ = world.spawn_external(bundle);
        });
    }

    /// Returns an iterator which encodes action to spawn entities
    /// using bundles yielded from provided bundles iterator.
    #[inline(always)]
    pub fn spawn_batch<I>(&self, bundles: I) -> SpawnBatchChannel<I>
    where
        I: IntoIterator,
        I::Item: ComponentBundle + Send + 'static,
    {
        self.push_fn(|world| {
            world.ensure_bundle_registered::<I::Item>();
        });

        SpawnBatchChannel {
            bundles,
            sender: self,
        }
    }

    /// Returns an iterator which encodes action to spawn entities
    /// using bundles yielded from provided bundles iterator.
    #[inline(always)]
    pub fn spawn_external_batch<I>(&self, bundles: I) -> SpawnBatchChannel<I>
    where
        I: IntoIterator,
        I::Item: Bundle + Send + 'static,
    {
        SpawnBatchChannel {
            bundles,
            sender: self,
        }
    }

    /// Encodes an action to despawn specified entity.
    #[inline(always)]
    pub fn despawn(&self, id: EntityId) {
        self.push_fn(move |world| {
            let _ = world.despawn(id);
        })
    }

    /// Encodes an action to insert component to the specified entity.
    #[inline(always)]
    pub fn insert<T>(&self, id: EntityId, component: T)
    where
        T: Component + Send,
    {
        self.push_fn(move |world| {
            let _ = world.insert(id, component);
        });
    }

    /// Encodes an action to insert component to the specified entity.
    #[inline(always)]
    pub fn insert_external<T>(&self, id: EntityId, component: T)
    where
        T: Send + 'static,
    {
        self.push_fn(move |world| {
            let _ = world.insert_external(id, component);
        });
    }

    /// Encodes an action to insert components from bundle to the specified entity.
    #[inline(always)]
    pub fn insert_bundle<B>(&self, id: EntityId, bundle: B)
    where
        B: DynamicComponentBundle + Send + 'static,
    {
        self.push_fn(move |world| {
            let _ = world.insert_bundle(id, bundle);
        });
    }

    /// Encodes an action to insert components from bundle to the specified entity.
    #[inline(always)]
    pub fn insert_external_bundle<B>(&self, id: EntityId, bundle: B)
    where
        B: DynamicBundle + Send + 'static,
    {
        self.push_fn(move |world| {
            let _ = world.insert_external_bundle(id, bundle);
        });
    }

    /// Encodes an action to drop component from specified entity.
    #[inline(always)]
    pub fn drop<T>(&self, id: EntityId)
    where
        T: 'static,
    {
        self.drop_erased(id, type_id::<T>())
    }

    /// Encodes an action to drop component from specified entity.
    #[inline(always)]
    pub fn drop_erased(&self, id: EntityId, ty: TypeId) {
        self.push_fn(move |world| {
            let _ = world.drop_erased(id, ty);
        })
    }

    /// Encodes an action to drop bundle of components from specified entity.
    #[inline(always)]
    pub fn drop_bundle<B>(&self, id: EntityId)
    where
        B: Bundle,
    {
        self.push_fn(move |world| {
            let _ = world.drop_bundle::<B>(id);
        });
    }

    /// Encodes an action to add relation between two entities to the [`World`].
    #[inline(always)]
    pub fn add_relation<R>(&self, origin: EntityId, relation: R, target: EntityId)
    where
        R: Relation + Send,
    {
        self.push_fn(move |world| {
            let _ = world.add_relation(origin, relation, target);
        });
    }

    /// Encodes an action to drop relation between two entities in the [`World`].
    #[inline(always)]
    pub fn drop_relation<R>(&self, origin: EntityId, target: EntityId)
    where
        R: Relation,
    {
        self.push_fn(move |world| {
            let _ = world.remove_relation::<R>(origin, target);
        });
    }

    /// Encodes action to insert resource instance.
    pub fn insert_resource<T>(&self, resource: T)
    where
        T: Send + 'static,
    {
        self.push_fn(move |world| {
            world.insert_resource(resource);
        });
    }

    /// Encodes an action to drop resource instance.
    pub fn drop_resource<T: 'static>(&self) {
        self.push_fn(move |world| {
            world.remove_resource::<T>();
        });
    }

    /// Encodes a custom action with a closure that takes mutable reference to `World`.
    #[inline(always)]
    pub fn closure(&self, fun: impl FnOnce(&mut World) + Send + 'static) {
        self.push_fn(fun)
    }

    /// Encodes an action to remove component from specified entity.
    #[inline(always)]
    fn push_fn(&self, fun: impl FnOnce(&mut World) + Send + 'static) {
        let action = ActionFn::new(fun);
        self.shared.queue.push(action);
        self.shared.non_empty.store(true, Ordering::Relaxed);
    }

    /// Returns `true` if the channel is still connected to a [`World`] instance.
    #[inline(always)]
    pub fn is_connected(&self) -> bool {
        self.shared.connected.load(Ordering::Relaxed)
    }
}

/// Spawning iterator. Produced by [`World::spawn_batch`].
pub struct SpawnBatchChannel<'a, I> {
    bundles: I,
    sender: &'a ActionSender,
}

impl<B, I> SpawnBatchChannel<'_, I>
where
    I: Iterator<Item = B>,
    B: Bundle + Send + 'static,
{
    /// Spawns the rest of the entities, dropping their ids.
    #[inline(always)]
    pub fn spawn_all(self) {
        self.for_each(|_| {});
    }
}

impl<B, I> Iterator for SpawnBatchChannel<'_, I>
where
    I: Iterator<Item = B>,
    B: Bundle + Send + 'static,
{
    type Item = ();

    #[inline(always)]
    fn next(&mut self) -> Option<()> {
        let bundle = self.bundles.next()?;
        Some(self.sender.spawn_external(bundle))
    }

    #[inline(always)]
    fn nth(&mut self, n: usize) -> Option<()> {
        // `SpawnBatchChannel` explicitly does NOT spawn entities that are skipped.
        let bundle = self.bundles.nth(n)?;
        Some(self.sender.spawn_external(bundle))
    }

    #[inline(always)]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.bundles.size_hint()
    }

    #[inline(always)]
    fn fold<T, F>(self, init: T, mut f: F) -> T
    where
        F: FnMut(T, ()) -> T,
    {
        let additional = iter_reserve_hint(&self.bundles);
        self.sender.push_fn(move |world| {
            world.spawn_reserve::<B>(additional);
        });

        self.bundles.fold(init, |acc, bundle| {
            f(acc, self.sender.spawn_external(bundle))
        })
    }

    #[inline(always)]
    fn collect<T>(self) -> T
    where
        T: FromIterator<()>,
    {
        // `FromIterator::from_iter` would probably just call `fn next()`
        // until the end of the iterator.
        //
        // Hence we should reserve space in archetype here.

        let additional = iter_reserve_hint(&self.bundles);
        self.sender.push_fn(move |world| {
            world.spawn_reserve::<B>(additional);
        });

        FromIterator::from_iter(self)
    }
}

impl<B, I> ExactSizeIterator for SpawnBatchChannel<'_, I>
where
    I: ExactSizeIterator<Item = B>,
    B: Bundle + Send + 'static,
{
    #[inline(always)]
    fn len(&self) -> usize {
        self.bundles.len()
    }
}

impl<B, I> DoubleEndedIterator for SpawnBatchChannel<'_, I>
where
    I: DoubleEndedIterator<Item = B>,
    B: Bundle + Send + 'static,
{
    #[inline(always)]
    fn next_back(&mut self) -> Option<()> {
        let bundle = self.bundles.next_back()?;
        Some(self.sender.spawn_external(bundle))
    }

    #[inline(always)]
    fn nth_back(&mut self, n: usize) -> Option<()> {
        // `SpawnBatchChannel` explicitly does NOT spawn entities that are skipped.
        let bundle = self.bundles.nth_back(n)?;
        Some(self.sender.spawn_external(bundle))
    }

    #[inline(always)]
    fn rfold<T, F>(self, init: T, mut f: F) -> T
    where
        Self: Sized,
        F: FnMut(T, ()) -> T,
    {
        let additional = iter_reserve_hint(&self.bundles);
        self.sender.push_fn(move |world| {
            world.spawn_reserve::<B>(additional);
        });

        self.bundles.rfold(init, |acc, bundle| {
            f(acc, self.sender.spawn_external(bundle))
        })
    }
}

impl<B, I> FusedIterator for SpawnBatchChannel<'_, I>
where
    I: FusedIterator<Item = B>,
    B: Bundle + Send + 'static,
{
}