iyes_scene_tools 0.2.0

Extra helpers for working with Bevy Scenes
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
use std::path::Path;

use bevy::prelude::*;
use bevy::ecs::all_tuples;
use bevy::ecs::system::SystemState;
use bevy::ecs::component::ComponentId;
use bevy::ecs::query::ReadOnlyWorldQuery;
use bevy::scene::DynamicEntity;
use bevy::utils::{HashMap, HashSet};

use thiserror::Error;

/// Error when exporting scene to a file
#[derive(Error, Debug)]
pub enum SceneExportError {
    #[error("Bevy Scene serialization to RON format failed")]
    Ron(#[from] ron::Error),
    #[error("Error writing to output file")]
    Io(#[from] std::io::Error),
}

/// Create a Bevy Dynamic Scene with specific entities and components.
///
/// The two generic parameters are treated the same way as with Bevy `Query`.
///
/// The created scene will include only the entities that match the query,
/// and only the set of components that are included in the query and impl `Reflect`.
///
/// If you want to include all components, try:
///  - [`scene_from_query`]
///
/// If what you need cannot be expressed with just a query,
/// try [`SceneBuilder`].
pub fn scene_from_query_components<Q, F>(
    world: &mut World,
) -> DynamicScene
where
    Q: ComponentList,
    F: ReadOnlyWorldQuery + 'static,
{
    let mut ss = SystemState::<Query<Entity, (Q::QueryFilter, F)>>::new(world);

    let type_registry = world.get_resource::<AppTypeRegistry>()
        .expect("The World provided for scene generation does not contain a TypeRegistry")
        .read();

    let q = ss.get(world);

    let entities = q.iter().map(|entity| {
        let get_reflect_by_id = |id|
            world.components()
                .get_info(id)
                .and_then(|info| type_registry.get(info.type_id().unwrap()))
                .and_then(|reg| reg.data::<ReflectComponent>())
                .and_then(|rc| rc.reflect(world, entity))
                .map(|c| c.clone_value());

        // TODO: avoid this allocation somehow?
        let mut ids = HashSet::new();
        Q::do_component_ids(world, &mut |id| {ids.insert(id);});

        let components = ids.into_iter()
            .filter_map(get_reflect_by_id)
            .collect();

        DynamicEntity {
            entity: entity.index(),
            components,
        }
    }).collect();

    DynamicScene {
        entities,
    }
}

/// Convenience wrapper for [`scene_from_query_components`] to output to file
///
/// Creates a file in the Bevy Scene RON format. Path should end in `.scn.ron`.
///
/// On success (if both scene generation and file output succeed), will return
/// the generated [`DynamicScene`], just in case you need it.
pub fn scene_file_from_query_components<Q, F>(
    world: &mut World,
    path: impl AsRef<Path>,
) -> Result<DynamicScene, SceneExportError>
where
    Q: ComponentList,
    F: ReadOnlyWorldQuery + 'static,
{
    let scene = scene_from_query_components::<Q, F>(world);
    let type_registry = world.get_resource::<AppTypeRegistry>()
        .expect("The World provided for scene generation does not contain a TypeRegistry");
    let data = scene.serialize_ron(type_registry)?;
    std::fs::write(path, &data)?;
    Ok(scene)
}

/// Convenience wrapper for [`scene_from_query_components`] to add the scene to the app's assets collection
///
/// Returns an asset handle that can be used for spawning the scene, (with [`DynamicSceneBundle`]).
pub fn add_scene_from_query_components<Q, F>(
    world: &mut World,
) -> Handle<DynamicScene>
where
    Q: ComponentList,
    F: ReadOnlyWorldQuery + 'static,
{
    let scene = scene_from_query_components::<Q, F>(world);
    let mut assets = world.get_resource_mut::<Assets<DynamicScene>>()
        .expect("World does not have an Assets<DynamicScene> to add the new scene to");
    assets.add(scene)
}

/// Create a Bevy Dynamic Scene with specific entities.
///
/// The generic parameter is used as a `Query` filter.
///
/// The created scene will include only the entities that match the query
/// filter provided. All components that impl `Reflect` will be included.
///
/// If you only want specific components, try:
///  - [`scene_from_query_components`]
///
/// If what you need cannot be expressed with just a query filter,
/// try [`SceneBuilder`].
pub fn scene_from_query_filter<F>(
    world: &mut World,
) -> DynamicScene
where
    F: ReadOnlyWorldQuery + 'static,
{
    let mut ss = SystemState::<Query<Entity, F>>::new(world);

    let type_registry = world.get_resource::<AppTypeRegistry>()
        .expect("The World provided for scene generation does not contain a TypeRegistry")
        .read();

    let q = ss.get(world);

    let entities = q.iter().map(|entity| {
        let get_reflect_by_id = |id|
            world.components()
                .get_info(id)
                .and_then(|info| type_registry.get(info.type_id().unwrap()))
                .and_then(|reg| reg.data::<ReflectComponent>())
                .and_then(|rc| rc.reflect(world, entity))
                .map(|c| c.clone_value());

        let components = world.entities()
            .get(entity)
            .and_then(|eloc| world.archetypes().get(eloc.archetype_id))
            .into_iter()
            .flat_map(|a| a.components())
            .filter_map(get_reflect_by_id)
            .collect();

        DynamicEntity {
            entity: entity.index(),
            components,
        }
    }).collect();

    DynamicScene {
        entities,
    }
}

/// Convenience wrapper for [`scene_from_query_filter`] to output to file
///
/// Creates a file in the Bevy Scene RON format. Path should end in `.scn.ron`.
///
/// On success (if both scene generation and file output succeed), will return
/// the generated [`DynamicScene`], just in case you need it.
pub fn scene_file_from_query_filter<F>(
    world: &mut World,
    path: impl AsRef<Path>,
) -> Result<DynamicScene, SceneExportError>
where
    F: ReadOnlyWorldQuery + 'static,
{
    let scene = scene_from_query_filter::<F>(world);
    let type_registry = world.get_resource::<AppTypeRegistry>()
        .expect("The World provided for scene generation does not contain a TypeRegistry");
    let data = scene.serialize_ron(type_registry)?;
    std::fs::write(path, &data)?;
    Ok(scene)
}

/// Convenience wrapper for [`scene_from_query_filter`] to add the scene to the app's assets collection
///
/// Returns an asset handle that can be used for spawning the scene, (with [`DynamicSceneBundle`]).
pub fn add_scene_from_query_filter<F>(
    world: &mut World,
) -> Handle<DynamicScene>
where
    F: ReadOnlyWorldQuery + 'static,
{
    let scene = scene_from_query_filter::<F>(world);
    let mut assets = world.get_resource_mut::<Assets<DynamicScene>>()
        .expect("World does not have an Assets<DynamicScene> to add the new scene to");
    assets.add(scene)
}

enum ComponentSelection {
    All,
    ByIds(HashSet<ComponentId>),
}

/// Flexible tool for creating Bevy scenes
///
/// You can select what entities from your `World` you would like
/// to include in the scene, by adding them using the various methods.
///
/// For each entity, you can choose whether you would like to include
/// all components (that impl `Reflect`) or just a specific set.
///
/// See the documentation of the various methods for more info.
///
/// After you are done adding entities and components, you can call
/// `.build_scene(...)` to create a [`DynamicScene`] with everything
/// that was selected.
pub struct SceneBuilder<'w> {
    world: &'w mut World,
    ec: HashMap<Entity, ComponentSelection>,
    ignored: HashSet<ComponentId>,
}

impl<'w> SceneBuilder<'w> {
    /// Create a new scene builder
    ///
    /// The entities and components of the created scene will come from
    /// the provided `world`.
    pub fn new(world: &'w mut World) -> SceneBuilder<'w> {
        SceneBuilder {
            world,
            ec: Default::default(),
            ignored: Default::default(),
        }
    }

    /// Add components to the set of components to be ignored
    ///
    /// This applies only to entities without explicit component selections.
    ///
    /// If you have explicitly added any of them to specific entities, they
    /// will still be exported to the scene.
    ///
    /// If an entity was added in "all components" mode, then `.build_scene()`
    /// will skip any of these components that it encounters.
    pub fn ignore_components<Q>(&mut self) -> &mut Self
    where
        Q: ComponentList,
    {
        Q::do_component_ids(self.world, &mut |id| {self.ignored.insert(id);});
        self
    }

    /// Add all entities that match the given query filter
    ///
    /// This method allows you to select entities in a way similar to
    /// using Bevy query filters.
    ///
    /// All components of each entity will be included.
    ///
    /// If you want to only include specific components, try:
    ///  - [`add_with_components`]
    pub fn add_from_query_filter<F>(&mut self) -> &mut Self
    where
        F: ReadOnlyWorldQuery + 'static,
    {
        let mut ss = SystemState::<Query<Entity, F>>::new(self.world);
        let q = ss.get(self.world);
        for e in q.iter() {
            self.ec.insert(e, ComponentSelection::All);
        }
        self
    }

    /// Add a specific entity
    ///
    /// The entity ID provided will be added, if it has not been already.
    ///
    /// All components of the entity will be included.
    ///
    /// If you want to only include specific components, try:
    ///  - [`add_components_to_entity`]
    pub fn add_entity(&mut self, e: Entity) -> &mut Self {
        self.ec.insert(e, ComponentSelection::All);
        self
    }

    /// Include the specified components on a given entity ID
    ///
    /// The entity ID provided will be added, if it has not been already.
    ///
    /// The components listed in `Q` will be added its component selection.
    ///
    /// If you want to select all components, try:
    ///  - [`add_entity`]
    pub fn add_components_to_entity<Q>(&mut self, e: Entity) -> &mut Self
    where
        Q: ComponentList,
    {
        if let Some(item) = self.ec.get_mut(&e) {
            if let ComponentSelection::ByIds(c) = item {
                Q::do_component_ids(self.world, &mut |id| {c.insert(id);});
            }
        } else {
            let mut c = HashSet::default();
            Q::do_component_ids(self.world, &mut |id| {c.insert(id);});
            self.ec.insert(e, ComponentSelection::ByIds(c));
        }
        self
    }

    /// Add entities by ID
    ///
    /// The entity IDs provided will be added, if they have not been already.
    ///
    /// All components of each entity will be included.
    ///
    /// If you want to only include specific components, try:
    ///  - [`add_components_to_entities`]
    pub fn add_entities<I>(&mut self, entities: I) -> &mut Self
    where
        I: IntoIterator<Item = Entity>,
    {
        for e in entities {
            self.ec.insert(e, ComponentSelection::All);
        }
        self
    }

    /// Include the specified components to entities with ID
    ///
    /// The entity IDs provided will be added, if they have not been already.
    ///
    /// The components listed in `Q` will be added their component selections.
    ///
    /// If you want to select all components, try:
    ///  - [`add_entities`]
    pub fn add_components_to_entities<I, Q>(&mut self, entities: I) -> &mut Self
    where
        I: IntoIterator<Item = Entity>,
        Q: ComponentList,
    {
        for e in entities {
            if let Some(item) = self.ec.get_mut(&e) {
                if let ComponentSelection::ByIds(c) = item {
                    Q::do_component_ids(self.world, &mut |id| {c.insert(id);});
                }
            } else {
                let mut c = HashSet::default();
                Q::do_component_ids(self.world, &mut |id| {c.insert(id);});
                self.ec.insert(e, ComponentSelection::ByIds(c));
            }
        }
        self
    }

    /// Add specific components to entities that match a query filter
    ///
    /// This method allows you to select entities in a way similar to
    /// using Bevy query filters.
    ///
    /// The components listed in `Q` will be added to each of the entities.
    ///
    /// If you want to select all components, try:
    ///  - [`add_from_query_filter`]
    pub fn add_with_components<Q, F>(&mut self) -> &mut Self
    where
        Q: ComponentList,
        F: ReadOnlyWorldQuery + 'static,
    {
        let mut ss = SystemState::<Query<Entity, (Q::QueryFilter, F)>>::new(self.world);
        let q = ss.get(self.world);
        for e in q.iter() {
            if let Some(item) = self.ec.get_mut(&e) {
                if let ComponentSelection::ByIds(c) = item {
                    Q::do_component_ids(self.world, &mut |id| {c.insert(id);});
                }
            } else {
                let mut c = HashSet::default();
                Q::do_component_ids(self.world, &mut |id| {c.insert(id);});
                self.ec.insert(e, ComponentSelection::ByIds(c));
            }
        }
        self
    }

    /// Build a [`DynamicScene`] with the selected entities and components
    ///
    /// Everything that was added to the builder (using the various `add_*`
    /// methods) will be included in the scene.
    ///
    /// All the relevant data will be copied from the `World` that was provided
    /// when the [`SceneBuilder`] was created.
    pub fn build_scene(&self) -> DynamicScene {
        let type_registry = self.world.get_resource::<AppTypeRegistry>()
            .expect("The World provided to the SceneBuilder does not contain a TypeRegistry")
            .read();

        let entities = self.ec.iter().map(|(entity, csel)| {
            let get_reflect_by_id = |id|
                self.world.components()
                    .get_info(id)
                    .and_then(|info| type_registry.get(info.type_id().unwrap()))
                    .and_then(|reg| reg.data::<ReflectComponent>())
                    .and_then(|rc| rc.reflect(self.world, *entity))
                    .map(|c| c.clone_value());

            let components = match csel {
                ComponentSelection::All => {
                    self.world.entities()
                        .get(*entity)
                        .and_then(|eloc| self.world.archetypes().get(eloc.archetype_id))
                        .into_iter()
                        .flat_map(|a| a.components())
                        .filter(|id| !self.ignored.contains(&id))
                        .filter_map(get_reflect_by_id)
                        .collect()
                },
                ComponentSelection::ByIds(ids) => {
                    ids.iter()
                        .cloned()
                        .filter_map(get_reflect_by_id)
                        .collect()
                },
            };

            DynamicEntity {
                entity: entity.index(),
                components,
            }
        }).collect();

        DynamicScene {
            entities,
        }
    }

    /// Convenience method: build the scene and serialize to file
    ///
    /// Creates a file in the Bevy Scene RON format. Path should end in `.scn.ron`.
    ///
    /// On success (if both scene generation and file output succeed), will return
    /// the generated [`DynamicScene`], just in case you need it.
    pub fn export_to_file(&self, path: impl AsRef<Path>) -> Result<DynamicScene, SceneExportError> {
        let scene = self.build_scene();
        let type_registry = self.world.get_resource::<AppTypeRegistry>()
            .expect("The World provided to the SceneBuilder does not contain a TypeRegistry");
        let data = scene.serialize_ron(type_registry)?;
        std::fs::write(path, &data)?;
        Ok(scene)
    }

    /// Convenience method: build the scene and add to the app's asset collection
    ///
    /// Returns an asset handle that can be used for spawning the scene, (with [`DynamicSceneBundle`]).
    pub fn build_scene_and_add(&mut self) -> Handle<DynamicScene> {
        let scene = self.build_scene();
        let mut assets = self.world.get_resource_mut::<Assets<DynamicScene>>()
            .expect("World does not have an Assets<DynamicScene> to add the new scene to");
        assets.add(scene)
    }
}

/// Represents a selection of components to export into a scene.
///
/// Works similar to Bevy's queries, but only immutable access
/// (`&T`), optional access (`Option<&T>`), and tuples to combine
/// multiple types, are supported.
pub trait ComponentList {
    type QueryFilter: ReadOnlyWorldQuery + 'static;
    fn do_component_ids<F: FnMut(ComponentId)>(world: &World, f: &mut F);
}

impl<T: Component + Reflect> ComponentList for &T {
    type QueryFilter = With<T>;
    #[inline]
    fn do_component_ids<F: FnMut(ComponentId)>(world: &World, f: &mut F) {
        if let Some(id) = world.component_id::<T>() {
            f(id);
        }
    }
}

impl<T: Component + Reflect> ComponentList for Option<&T> {
    type QueryFilter = ();
    #[inline]
    fn do_component_ids<F: FnMut(ComponentId)>(world: &World, f: &mut F) {
        if let Some(id) = world.component_id::<T>() {
            f(id);
        }
    }
}

macro_rules! componentlist_impl {
    ($($x:ident),*) => {
        impl<$($x: ComponentList),*> ComponentList for ($($x,)*) {
            type QueryFilter = ($($x::QueryFilter,)*);
            #[inline]
            fn do_component_ids<F: FnMut(ComponentId)>(_world: &World, _f: &mut F) {
                $($x::do_component_ids(_world, _f);)*
            }
        }
    };
}

all_tuples!(componentlist_impl, 0, 15, T);

#[cfg(test)]
mod test {
}