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
use core::fmt;

use alloc::{boxed::Box, format, vec::Vec};
use anyhow::Context;

use crate::{
    buffer::MultiComponentBuffer,
    component::{ComponentDesc, ComponentValue},
    writer::{MissingDyn, SingleComponentWriter, WriteDedupDyn},
    BatchSpawn, Component, Entity, EntityBuilder, World,
};

type DeferFn = Box<dyn Fn(&mut World) -> anyhow::Result<()> + Send + Sync>;

/// A recorded action to be applied to the world.
enum Command {
    /// Spawn a new entity
    Spawn(EntityBuilder),
    AppendTo(EntityBuilder, Entity),
    SpawnAt(EntityBuilder, Entity),
    /// Spawn a batch of entities with the same components
    SpawnBatch(BatchSpawn),
    SpawnBatchAt(BatchSpawn, Vec<Entity>),
    /// Set a component for an entity
    Set {
        id: Entity,
        desc: ComponentDesc,
        offset: usize,
    },
    SetDedup {
        id: Entity,
        desc: ComponentDesc,
        offset: usize,
        cmp: unsafe fn(*const u8, *const u8) -> bool,
    },
    SetMissing {
        id: Entity,
        desc: ComponentDesc,
        offset: usize,
    },
    /// Despawn an entity
    Despawn(Entity),
    /// Remove a component from an entity
    Remove {
        id: Entity,
        desc: ComponentDesc,
    },

    /// Execute an arbitrary function with a mutable reference to the world.
    Defer(DeferFn),
}

impl fmt::Debug for Command {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Spawn(v) => f.debug_tuple("Spawn").field(v).finish(),
            Self::SpawnAt(id, v) => f.debug_tuple("SpawnAt").field(&v).field(&id).finish(),
            Self::AppendTo(id, v) => f.debug_tuple("AppendTo").field(&v).field(&id).finish(),
            Self::SpawnBatch(batch) => f.debug_tuple("SpawnBatch").field(batch).finish(),
            Self::SpawnBatchAt(batch, ids) => f
                .debug_tuple("SpawnBatchAt")
                .field(&batch)
                .field(&ids.len())
                .finish(),
            Self::Set { id, desc, offset } => f
                .debug_struct("Set")
                .field("id", id)
                .field("desc", desc)
                .field("offset", offset)
                .finish(),
            Self::SetDedup {
                id,
                desc,
                offset,
                cmp: _,
            } => f
                .debug_struct("SetDedup")
                .field("id", id)
                .field("desc", desc)
                .field("offset", offset)
                .finish(),
            Self::SetMissing { id, desc, offset } => f
                .debug_struct("SetMissing")
                .field("id", id)
                .field("desc", desc)
                .field("offset", offset)
                .finish(),
            Self::Despawn(arg0) => f.debug_tuple("Despawn").field(arg0).finish(),
            Self::Remove {
                id,
                desc: component,
            } => f
                .debug_struct("Remove")
                .field("id", id)
                .field("component", component)
                .finish(),
            Self::Defer(_) => f.debug_tuple("Defer").field(&"...").finish(),
        }
    }
}

/// Records commands into the world.
/// Allows insertion and removal of components when the world is not available
/// mutably, such as in systems or during iteration.
#[derive(Default)]
pub struct CommandBuffer {
    inserts: MultiComponentBuffer,
    commands: Vec<Command>,
}

impl fmt::Debug for CommandBuffer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CommandBuffer")
            .field("commands", &self.commands)
            .finish()
    }
}

/// Since all components are Send + Sync, the commandbuffer is as well
unsafe impl Send for CommandBuffer {}
unsafe impl Sync for CommandBuffer {}

impl CommandBuffer {
    /// Creates a new commandbuffer
    pub fn new() -> Self {
        Self::default()
    }

    /// Set a component for `id`.
    pub fn set<T: ComponentValue>(
        &mut self,
        id: Entity,
        component: Component<T>,
        value: T,
    ) -> &mut Self {
        let offset = self.inserts.push(value);
        self.commands.push(Command::Set {
            id,
            desc: component.desc(),
            offset,
        });

        self
    }

    /// Set a component for `id`.
    ///
    /// Does not trigger a modification event if the value is the same
    pub fn set_dedup<T: ComponentValue + PartialEq>(
        &mut self,
        id: Entity,
        component: Component<T>,
        value: T,
    ) -> &mut Self {
        let offset = self.inserts.push(value);
        unsafe fn cmp<T: PartialEq>(a: *const u8, b: *const u8) -> bool {
            let a = &*(a as *const T);
            let b = &*(b as *const T);

            a == b
        }
        self.commands.push(Command::SetDedup {
            id,
            desc: component.desc(),
            offset,
            cmp: cmp::<T>,
        });

        self
    }

    /// Set a component for `id` if it does not exist when the commandbuffer is applied.
    ///
    /// This avoid accidentally overwriting a component that was added by another system.
    pub fn set_missing<T: ComponentValue>(
        &mut self,
        id: Entity,
        component: Component<T>,
        value: T,
    ) -> &mut Self {
        let offset = self.inserts.push(value);
        self.commands.push(Command::SetMissing {
            id,
            desc: component.desc(),
            offset,
        });

        self
    }
    /// Deferred removal of a component for `id`.
    /// Unlike, [`World::remove`] it does not return the old value as that is
    /// not known at call time.
    pub fn remove<T: ComponentValue>(&mut self, id: Entity, component: Component<T>) -> &mut Self {
        self.commands.push(Command::Remove {
            id,
            desc: component.desc(),
        });

        self
    }

    /// Spawn a new entity with the given components of the builder
    pub fn spawn(&mut self, entity: impl Into<EntityBuilder>) -> &mut Self {
        self.commands.push(Command::Spawn(entity.into()));

        self
    }

    /// Spawn a new entity with the given components of the builder
    pub fn spawn_at(&mut self, id: Entity, entity: impl Into<EntityBuilder>) -> &mut Self {
        self.commands.push(Command::SpawnAt(entity.into(), id));

        self
    }

    /// Append components to an existing entity
    pub fn append_to(&mut self, id: Entity, entity: impl Into<EntityBuilder>) -> &mut Self {
        self.commands.push(Command::AppendTo(entity.into(), id));

        self
    }

    /// Spawn a new batch with the given components of the builder
    pub fn spawn_batch(&mut self, chunk: impl Into<BatchSpawn>) -> &mut Self {
        self.commands.push(Command::SpawnBatch(chunk.into()));

        self
    }

    /// Spawn a new batch with the given components of the builder
    pub fn spawn_batch_at(&mut self, ids: Vec<Entity>, chunk: impl Into<BatchSpawn>) -> &mut Self {
        self.commands.push(Command::SpawnBatchAt(chunk.into(), ids));

        self
    }

    /// Despawn an entity by id
    pub fn despawn(&mut self, id: Entity) -> &mut Self {
        self.commands.push(Command::Despawn(id));
        self
    }

    /// Defer a function to execute upon the world.
    ///
    /// Errors will be propagated.
    pub fn defer(
        &mut self,
        func: impl Fn(&mut World) -> anyhow::Result<()> + Send + Sync + 'static,
    ) -> &mut Self {
        self.commands.push(Command::Defer(Box::new(func)));
        self
    }

    /// Applies all contents of the command buffer to the world.
    /// The commandbuffer is cleared and can be reused.
    pub fn apply(&mut self, world: &mut World) -> anyhow::Result<()> {
        for cmd in self.commands.drain(..) {
            match cmd {
                Command::Spawn(mut entity) => {
                    entity.spawn(world);
                }
                Command::SpawnAt(mut entity, id) => {
                    entity
                        .spawn_at(world, id)
                        .map_err(|v| v.into_anyhow())
                        .context("Failed to spawn entity")?;
                }
                Command::AppendTo(mut entity, id) => {
                    entity
                        .append_to(world, id)
                        .map_err(|v| v.into_anyhow())
                        .context("Failed to append to entity")?;
                }
                Command::SpawnBatch(mut batch) => {
                    batch.spawn(world);
                }
                Command::SpawnBatchAt(mut batch, ids) => {
                    batch
                        .spawn_at(world, &ids)
                        .map_err(|v| v.into_anyhow())
                        .context("Failed to spawn entity")?;
                }
                Command::Set { id, desc, offset } => unsafe {
                    let value = self.inserts.take_dyn(offset);
                    world
                        .set_dyn(id, desc, value)
                        .map_err(|v| v.into_anyhow())
                        .with_context(|| format!("Failed to set component {}", desc.name()))?;
                },
                Command::SetDedup {
                    id,
                    desc,
                    offset,
                    cmp,
                } => unsafe {
                    let value = self.inserts.take_dyn(offset);
                    world
                        .set_with_writer(
                            id,
                            SingleComponentWriter::new(desc, WriteDedupDyn { value, cmp }),
                        )
                        .map_err(|v| v.into_anyhow())
                        .with_context(|| format!("Failed to set component {}", desc.name()))?;
                },
                Command::SetMissing { id, desc, offset } => unsafe {
                    let value = self.inserts.take_dyn(offset);
                    world
                        .set_with_writer(id, SingleComponentWriter::new(desc, MissingDyn { value }))
                        .map_err(|v| v.into_anyhow())
                        .with_context(|| format!("Failed to set component {}", desc.name()))?;
                },
                Command::Despawn(id) => world
                    .despawn(id)
                    .map_err(|v| v.into_anyhow())
                    .context("Failed to despawn entity")?,
                Command::Remove { id, desc } => world
                    .remove_dyn(id, desc)
                    .map_err(|v| v.into_anyhow())
                    .with_context(|| format!("Failed to remove component {}", desc.name()))?,
                Command::Defer(func) => {
                    func(world).context("Failed to execute deferred function")?
                }
            }
        }

        Ok(())
    }

    /// Clears all values in the component buffer but keeps allocations around.
    /// Is automatically called for [`Self::apply`].
    pub fn clear(&mut self) {
        self.inserts.clear();
        self.commands.clear()
    }
}

#[cfg(test)]
mod tests {
    use crate::{component, FetchExt, Query};

    use super::*;

    #[test]
    fn set_missing() {
        use alloc::string::String;
        use alloc::string::ToString;

        component! {
            a: String,
        }

        let mut world = World::new();
        let mut cmd = CommandBuffer::new();

        let mut query = Query::new((a().modified().satisfied(), a().cloned()));

        let id = EntityBuilder::new().spawn(&mut world);

        assert!(query.collect_vec(&world).is_empty());

        cmd.set_missing(id, a(), "Foo".into())
            .set_missing(id, a(), "Bar".into());

        cmd.apply(&mut world).unwrap();

        assert_eq!(query.collect_vec(&world), [(true, "Foo".to_string())]);
        assert_eq!(query.collect_vec(&world), [(false, "Foo".to_string())]);

        cmd.set_missing(id, a(), "Baz".into());
        cmd.apply(&mut world).unwrap();

        assert_eq!(query.collect_vec(&world), [(false, "Foo".to_string())]);
    }

    #[test]
    fn set_dedup() {
        use alloc::string::String;
        use alloc::string::ToString;

        component! {
            a: String,
        }

        let mut world = World::new();
        let mut cmd = CommandBuffer::new();

        let mut query = Query::new((a().modified().satisfied(), a().cloned()));

        let id = EntityBuilder::new().spawn(&mut world);

        assert!(query.collect_vec(&world).is_empty());

        cmd.set_dedup(id, a(), "Foo".into())
            .set_dedup(id, a(), "Bar".into());

        cmd.apply(&mut world).unwrap();

        assert_eq!(query.collect_vec(&world), [(true, "Bar".to_string())]);
        assert_eq!(query.collect_vec(&world), [(false, "Bar".to_string())]);

        cmd.set_dedup(id, a(), "Baz".into());
        cmd.apply(&mut world).unwrap();

        assert_eq!(query.collect_vec(&world), [(true, "Baz".to_string())]);

        cmd.set_dedup(id, a(), "Baz".into());
        cmd.apply(&mut world).unwrap();
        assert_eq!(query.collect_vec(&world), [(false, "Baz".to_string())]);
    }
}