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
use crate::{
    app::AppLifeCycle,
    ecs::{life_cycle::EntityChanges, Universe},
    prefab::PrefabManager,
};
pub use hecs::*;
use std::{any::TypeId, collections::HashMap, marker::PhantomData};

pub trait UniverseCommand: Send + Sync {
    fn run(&mut self, universe: &mut Universe);
}

struct ClosureUniverseCommand(Box<dyn FnMut(&mut Universe) + Send + Sync>);

impl UniverseCommand for ClosureUniverseCommand {
    fn run(&mut self, universe: &mut Universe) {
        (self.0)(universe);
    }
}

pub struct SpawnEntity {
    pub entity_builder: EntityBuilder,
    #[allow(clippy::type_complexity)]
    on_complete: Option<Box<dyn FnOnce(&mut Universe, Entity) + Send + Sync>>,
}

impl SpawnEntity {
    pub fn new(entity_builder: EntityBuilder) -> Self {
        Self {
            entity_builder,
            on_complete: None,
        }
    }

    pub fn from_bundle<B>(bundle: B) -> Self
    where
        B: DynamicBundle,
    {
        let mut entity_builder = EntityBuilder::new();
        entity_builder.add_bundle(bundle);
        Self::new(entity_builder)
    }

    pub fn on_complete<F>(mut self, f: F) -> Self
    where
        F: FnOnce(&mut Universe, Entity) + Send + Sync + 'static,
    {
        self.on_complete = Some(Box::new(f));
        self
    }

    pub fn execute(&mut self, universe: &mut Universe) -> Entity {
        let entity = universe.world_mut().spawn(self.entity_builder.build());
        let mut changes = universe.expect_resource_mut::<EntityChanges>();
        changes.spawned.insert(entity);
        let components = changes.added_components.entry(entity).or_default();
        components.extend(self.entity_builder.component_types());
        if let Some(on_complete) = self.on_complete.take() {
            (on_complete)(universe, entity);
        }
        entity
    }
}

impl UniverseCommand for SpawnEntity {
    fn run(&mut self, universe: &mut Universe) {
        self.execute(universe);
    }
}

pub struct DespawnEntity(pub Entity);

impl UniverseCommand for DespawnEntity {
    fn run(&mut self, universe: &mut Universe) {
        if universe.world_mut().despawn(self.0).is_ok() {
            universe
                .expect_resource_mut::<EntityChanges>()
                .despawned
                .insert(self.0);
        }
    }
}

pub struct EntityAddComponent<C>
where
    C: Component + Send + Sync,
{
    pub entity: Entity,
    component: Option<C>,
    #[allow(clippy::type_complexity)]
    on_complete: Option<Box<dyn FnMut(&mut Universe, Entity) + Send + Sync>>,
}

impl<C> EntityAddComponent<C>
where
    C: Component + Send + Sync,
{
    pub fn new(entity: Entity, component: C) -> Self {
        Self {
            entity,
            component: Some(component),
            on_complete: None,
        }
    }

    pub fn on_complete<F>(mut self, f: F) -> Self
    where
        F: FnMut(&mut Universe, Entity) + Send + Sync + 'static,
    {
        self.on_complete = Some(Box::new(f));
        self
    }
}

impl<C> UniverseCommand for EntityAddComponent<C>
where
    C: Component + Send + Sync + 'static,
{
    fn run(&mut self, universe: &mut Universe) {
        if let Some(component) = self.component.take() {
            if universe
                .world_mut()
                .insert_one(self.entity, component)
                .is_ok()
            {
                let mut changes = universe.expect_resource_mut::<EntityChanges>();
                let components = changes.added_components.entry(self.entity).or_default();
                components.insert(TypeId::of::<C>());
                if let Some(mut on_complete) = self.on_complete.take() {
                    (on_complete)(universe, self.entity);
                }
            }
        }
    }
}

pub struct EntityRemoveComponent<C>
where
    C: Component,
{
    pub entity: Entity,
    #[allow(clippy::type_complexity)]
    on_complete: Option<Box<dyn FnMut(&mut Universe, Entity) + Send + Sync>>,
    _phantom: PhantomData<fn() -> C>,
}

impl<C> EntityRemoveComponent<C>
where
    C: Component,
{
    pub fn new(entity: Entity) -> Self {
        Self {
            entity,
            on_complete: None,
            _phantom: Default::default(),
        }
    }

    pub fn on_complete<F>(mut self, f: F) -> Self
    where
        F: FnMut(&mut Universe, Entity) + Send + Sync + 'static,
    {
        self.on_complete = Some(Box::new(f));
        self
    }
}

impl<C> UniverseCommand for EntityRemoveComponent<C>
where
    C: Component,
{
    fn run(&mut self, universe: &mut Universe) {
        if universe.world_mut().remove_one::<C>(self.entity).is_ok() {
            let mut changes = universe.expect_resource_mut::<EntityChanges>();
            let components = changes.removed_components.entry(self.entity).or_default();
            components.insert(TypeId::of::<C>());
            if let Some(mut on_complete) = self.on_complete.take() {
                (on_complete)(universe, self.entity);
            }
        }
    }
}

/// (template name, add/override components)
pub struct InstantiatePrefab {
    pub name: String,
    pub components: HashMap<usize, EntityBuilder>,
    #[allow(clippy::type_complexity)]
    on_complete: Option<Box<dyn FnMut(&mut Universe, &[Entity]) + Send + Sync>>,
}

impl InstantiatePrefab {
    pub fn new(name: impl ToString) -> Self {
        Self {
            name: name.to_string(),
            components: Default::default(),
            on_complete: None,
        }
    }

    pub fn components(mut self, index: usize, entity_builder: EntityBuilder) -> Self {
        self.components.insert(index, entity_builder);
        self
    }

    pub fn components_from_bundle<B>(mut self, index: usize, bundle: B) -> Self
    where
        B: DynamicBundle,
    {
        let mut entity_builder = EntityBuilder::new();
        entity_builder.add_bundle(bundle);
        self.components.insert(index, entity_builder);
        self
    }

    pub fn on_complete<F>(mut self, f: F) -> Self
    where
        F: FnMut(&mut Universe, &[Entity]) + Send + Sync + 'static,
    {
        self.on_complete = Some(Box::new(f));
        self
    }

    pub fn execute(&mut self, universe: &mut Universe) -> Option<Vec<Entity>> {
        if let Some(mut prefabs) = universe.resource_mut::<PrefabManager>() {
            let mut world = universe.world_mut();
            let mut changes = universe.expect_resource_mut::<EntityChanges>();
            let state_token = universe
                .expect_resource::<AppLifeCycle>()
                .current_state_token();
            let entities = if let Ok(entities) =
                prefabs.instantiate_direct(&self.name, &mut world, &mut changes, state_token)
            {
                for (index, entity_builder) in &mut self.components {
                    if let Some(entity) = entities.get(*index) {
                        let _ = world.insert(*entity, entity_builder.build());
                    }
                }
                entities
            } else {
                return None;
            };
            drop(world);
            if let Some(mut on_complete) = self.on_complete.take() {
                (on_complete)(universe, &entities);
            }
            Some(entities)
        } else {
            None
        }
    }
}

impl UniverseCommand for InstantiatePrefab {
    fn run(&mut self, universe: &mut Universe) {
        self.execute(universe);
    }
}

pub struct UniverseCommands {
    queue: Vec<Box<dyn UniverseCommand>>,
    resize: usize,
}

impl Default for UniverseCommands {
    fn default() -> Self {
        Self {
            queue: Default::default(),
            resize: 1024,
        }
    }
}

impl UniverseCommands {
    pub fn schedule<T>(&mut self, command: T)
    where
        T: UniverseCommand + 'static,
    {
        self.schedule_raw(Box::new(command));
    }

    pub fn schedule_raw(&mut self, command: Box<dyn UniverseCommand>) {
        if self.resize > 0 && self.queue.len() == self.queue.capacity() {
            self.queue.reserve(self.resize);
        }
        self.queue.push(command);
    }

    pub fn schedule_fn<F>(&mut self, f: F)
    where
        F: FnMut(&mut Universe) + Send + Sync + 'static,
    {
        self.schedule(ClosureUniverseCommand(Box::new(f)));
    }

    pub fn execute(&mut self) -> UniverseCommandsExecutor {
        let commands = Vec::with_capacity(self.queue.len());
        UniverseCommandsExecutor(std::mem::replace(&mut self.queue, commands))
    }
}

pub struct UniverseCommandsExecutor(Vec<Box<dyn UniverseCommand>>);

impl UniverseCommandsExecutor {
    pub fn execute(self, universe: &mut Universe) {
        for mut command in self.0 {
            command.run(universe);
        }
    }
}