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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
//! Elements related to saving world state.
//!
//! # Example
//! ```
//! use bevy::prelude::*;
//! use moonshine_save::prelude::*;
//!
//! #[derive(Component, Default, Reflect)]
//! #[reflect(Component)]
//! struct Data(u32);
//!
//! let mut app = App::new();
//! app.add_plugins((MinimalPlugins, SavePlugin))
//!     .register_type::<Data>()
//!     .add_systems(PreUpdate, save_default().into_file("example.ron"));
//!
//! app.world.spawn((Data(12), Save));
//! app.update();
//!
//! let data = std::fs::read_to_string("example.ron").unwrap();
//! # assert!(data.contains("(12)"));
//! # std::fs::remove_file("example.ron");
//! ```

use std::{
    any::TypeId,
    io,
    marker::PhantomData,
    path::{Path, PathBuf},
};

use bevy_app::{App, Plugin, PreUpdate};
use bevy_ecs::{prelude::*, query::QueryFilter, schedule::SystemConfigs};
use bevy_scene::{DynamicScene, DynamicSceneBuilder, SceneFilter};
use bevy_utils::{
    tracing::{error, info, warn},
    HashSet,
};
use moonshine_util::system::*;

/// A [`Plugin`] which configures [`SaveSystem`] in [`PreUpdate`] schedule.
pub struct SavePlugin;

impl Plugin for SavePlugin {
    fn build(&self, app: &mut App) {
        app.configure_sets(
            PreUpdate,
            (
                SaveSystem::Save,
                SaveSystem::PostSave.run_if(has_resource::<Saved>),
            )
                .chain(),
        )
        .add_systems(
            PreUpdate,
            remove_resource::<Saved>.in_set(SaveSystem::PostSave),
        );
    }
}

/// A [`SystemSet`] for systems that process saving.
#[derive(Clone, Debug, Hash, PartialEq, Eq, SystemSet)]
pub enum SaveSystem {
    /// Reserved for systems which serialize the world and process the output.
    Save,
    /// Runs after [`SaveSystem::Save`].
    PostSave,
}

/// A [`Resource`] which contains the saved [`World`] data during [`SaveSystem::PostSave`].
#[derive(Resource)]
pub struct Saved {
    pub scene: DynamicScene,
}

/// A [`Component`] which marks its [`Entity`] to be saved.
#[derive(Component, Default, Clone)]
pub struct Save;

#[derive(Debug)]
pub enum SaveError {
    Ron(ron::Error),
    Io(io::Error),
}

impl From<ron::Error> for SaveError {
    fn from(e: ron::Error) -> Self {
        Self::Ron(e)
    }
}

impl From<io::Error> for SaveError {
    fn from(e: io::Error) -> Self {
        Self::Io(e)
    }
}

#[derive(Default, Clone)]
pub enum EntityFilter {
    #[default]
    Any,
    Allow(HashSet<Entity>),
    Block(HashSet<Entity>),
}

impl EntityFilter {
    pub fn any() -> Self {
        Self::Any
    }

    pub fn allow(entities: impl IntoIterator<Item = Entity>) -> Self {
        Self::Allow(entities.into_iter().collect())
    }

    pub fn block(entities: impl IntoIterator<Item = Entity>) -> Self {
        Self::Block(entities.into_iter().collect())
    }
}

#[derive(Clone)]
pub struct SaveFilter {
    pub entities: EntityFilter,
    pub resources: SceneFilter,
    pub components: SceneFilter,
}

impl Default for SaveFilter {
    fn default() -> Self {
        SaveFilter {
            entities: EntityFilter::default(),
            // By default, save all components on all saved entities.
            components: SceneFilter::allow_all(),
            // By default, do not save any resources. Most Bevy resources are not safely serializable.
            resources: SceneFilter::deny_all(),
        }
    }
}

pub fn filter<F: QueryFilter>(entities: Query<Entity, F>) -> SaveFilter {
    SaveFilter {
        entities: EntityFilter::allow(&entities),
        // TODO: We do not want to save any Bevy resources by default. They may not be serializable.
        resources: SceneFilter::deny_all(),
        ..Default::default()
    }
}

pub fn filter_entities<F: QueryFilter>(
    In(mut filter): In<SaveFilter>,
    entities: Query<Entity, F>,
) -> SaveFilter
where
    F: 'static,
{
    filter.entities = EntityFilter::allow(&entities);
    filter
}

/// A collection of systems ([`SystemConfigs`]) which perform the save process.
pub type SavePipeline = SystemConfigs;

/// A [`System`] which creates [`Saved`] data from all entities with given `Filter`.
///
/// # Usage
///
/// All save pipelines should start with this system.
pub fn save_scene(In(filter): In<SaveFilter>, world: &World) -> Saved {
    let mut builder = DynamicSceneBuilder::from_world(world)
        .with_filter(filter.components)
        .with_resource_filter(filter.resources)
        .extract_resources();
    match filter.entities {
        EntityFilter::Any => {}
        EntityFilter::Allow(entities) => {
            builder = builder.extract_entities(entities.into_iter());
        }
        EntityFilter::Block(entities) => {
            builder =
                builder.extract_entities(world.iter_entities().filter_map(|entity| {
                    (!entities.contains(&entity.id())).then_some(entity.id())
                }));
        }
    }
    let scene = builder.build();
    Saved { scene }
}

/// A [`System`] which writes [`Saved`] data into a file at given `path`.
pub fn into_file(
    path: PathBuf,
) -> impl Fn(In<Saved>, Res<AppTypeRegistry>) -> Result<Saved, SaveError> {
    move |In(saved), type_registry| {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let data = saved.scene.serialize_ron(&type_registry)?;
        std::fs::write(&path, data.as_bytes())?;
        info!("saved into file: {path:?}");
        Ok(saved)
    }
}

/// A [`System`] which writes [`Saved`] data into a file with its path defined at runtime.
pub fn into_file_dyn(
    In((path, saved)): In<(PathBuf, Saved)>,
    type_registry: Res<AppTypeRegistry>,
) -> Result<Saved, SaveError> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let data = saved.scene.serialize_ron(&type_registry)?;
    std::fs::write(&path, data.as_bytes())?;
    info!("saved into file: {path:?}");
    Ok(saved)
}

/// A [`System`] which finishes the save process.
///
/// # Usage
/// All save pipelines should end with this system.
pub fn finish(In(result): In<Result<Saved, SaveError>>, world: &mut World) {
    match result {
        Ok(saved) => world.insert_resource(saved),
        Err(why) => error!("save failed: {why:?}"),
    }
}

/// A [`System`] which extracts the path from a [`SaveIntoFileRequest`] [`Resource`].
pub fn file_from_request<R>(In(saved): In<Saved>, request: Res<R>) -> (PathBuf, Saved)
where
    R: SaveIntoFileRequest + Resource,
{
    let path = request.path().to_owned();
    (path, saved)
}

/// A [`System`] which extracts the path from a [`SaveIntoFileRequest`] [`Event`].
///
/// # Warning
///
/// If multiple events are sent in a single update cycle, only the first one is processed.
///
/// This system assumes that at least one event has been sent. It must be used in conjunction with [`has_event`].
pub fn file_from_event<R>(In(saved): In<Saved>, mut events: EventReader<R>) -> (PathBuf, Saved)
where
    R: SaveIntoFileRequest + Event,
{
    let mut iter = events.read();
    let event = iter.next().unwrap();
    if iter.next().is_some() {
        warn!("multiple save request events received; only the first one is processed.");
    }
    let path = event.path().to_owned();
    (path, saved)
}

/// Any type which may be used to trigger [`save_into_file_on_request`] or [`save_into_file_on_event`].
pub trait SaveIntoFileRequest {
    /// Path of the file to save into.
    fn path(&self) -> &Path;
}

/// A convenient builder for defining a [`SavePipeline`].
///
/// See [`save`], [`save_default`], [`save_all`] on how to create an instance of this type.
pub struct SavePipelineBuilder<F: QueryFilter> {
    query: PhantomData<F>,
    filter: SaveFilter,
}

/// Creates a [`SavePipelineBuilder`] which saves all entities with given entity filter `F`.
///
/// During the save process, all entities that match the given query `F` will be selected for saving.
///
/// # Example
/// ```
/// use bevy::prelude::*;
/// use moonshine_save::prelude::*;
///
/// let mut app = App::new();
/// app.add_plugins((MinimalPlugins, SavePlugin))
///     .add_systems(PreUpdate, save::<With<Save>>().into_file("example.ron"));
/// ```
pub fn save<F: QueryFilter>() -> SavePipelineBuilder<F> {
    SavePipelineBuilder {
        query: PhantomData,
        filter: Default::default(),
    }
}

/// Creates a [`SavePipelineBuilder`] which saves all entities with a [`Save`] component.
///
/// # Example
/// ```
/// use bevy::prelude::*;
/// use moonshine_save::prelude::*;
///
/// let mut app = App::new();
/// app.add_plugins((MinimalPlugins, SavePlugin))
///     .add_systems(PreUpdate, save_default().into_file("example.ron"));
/// ```
pub fn save_default() -> SavePipelineBuilder<With<Save>> {
    save()
}

/// Creates a [`SavePipelineBuilder`] which saves all entities unconditionally.
///
/// # Warning
/// Be careful about using this builder as some entities and/or components may not be safely serializable.
///
/// # Example
/// ```
/// use bevy::prelude::*;
/// use moonshine_save::prelude::*;
///
/// let mut app = App::new();
/// app.add_plugins((MinimalPlugins, SavePlugin))
///     .add_systems(PreUpdate, save_all().into_file("example.ron"));
/// ```
pub fn save_all() -> SavePipelineBuilder<()> {
    save()
}

impl<F: QueryFilter> SavePipelineBuilder<F>
where
    F: 'static,
{
    /// Includes a given [`Resource`] type into the save pipeline.
    ///
    /// By default, all resources are *excluded* from the save pipeline.
    ///
    /// # Example
    /// ```
    /// use bevy::prelude::*;
    /// use moonshine_save::prelude::*;
    ///
    /// #[derive(Resource, Default, Reflect)]
    /// #[reflect(Resource)]
    /// struct R;
    ///
    /// let mut app = App::new();
    /// app.register_type::<R>()
    ///     .insert_resource(R)
    ///     .add_plugins((MinimalPlugins, SavePlugin))
    ///     .add_systems(
    ///         PreUpdate,
    ///         save_default()
    ///             .include_resource::<R>()
    ///             .into_file("example.ron"));
    /// ```
    pub fn include_resource<R: Resource>(mut self) -> Self {
        self.filter.resources = self.filter.resources.allow::<R>();
        self
    }

    /// Includes a given [`Resource`] type into the save pipeline by its [`TypeId`].
    pub fn include_resource_by_id(mut self, type_id: TypeId) -> Self {
        self.filter.resources = self.filter.resources.allow_by_id(type_id);
        self
    }

    /// Excludes a given [`Component`] type from the save pipeline.
    ///
    /// By default, all components which derive `Reflect` are *included* in the save pipeline.
    ///
    /// # Example
    /// ```
    /// use bevy::prelude::*;
    /// use moonshine_save::prelude::*;
    ///
    /// #[derive(Resource, Default, Reflect)]
    /// #[reflect(Resource)]
    /// struct R;
    ///
    /// let mut app = App::new();
    /// app.register_type::<R>()
    ///     .insert_resource(R)
    ///     .add_plugins((MinimalPlugins, SavePlugin))
    ///     .add_systems(
    ///         PreUpdate,
    ///         save_default()
    ///             .exclude_component::<Transform>()
    ///             .into_file("example.ron"));
    /// ```
    pub fn exclude_component<T: Component>(mut self) -> Self {
        self.filter.components = self.filter.components.deny::<T>();
        self
    }

    /// Excludes a given [`Component`] type from the save pipeline by its [`TypeId`].
    pub fn exclude_component_by_id(mut self, type_id: TypeId) -> Self {
        self.filter.components = self.filter.components.deny_by_id(type_id);
        self
    }

    /// Finishes the save pipeline by writing the saved data into a file at given `path`.
    pub fn into_file(self, path: impl Into<PathBuf>) -> SavePipeline {
        let Self { filter, .. } = self;
        (move || filter.clone())
            .pipe(filter_entities::<F>)
            .pipe(save_scene)
            .pipe(into_file(path.into()))
            .pipe(finish)
            .in_set(SaveSystem::Save)
    }

    /// Finishes the save pipeline by writing the saved data into a file with its path derived from a resource of type `R`.
    ///
    /// The save pipeline will only be triggered if a resource of type `R` is present.
    pub fn into_file_on_request<R: SaveIntoFileRequest + Resource>(self) -> SavePipeline {
        let Self { filter, .. } = self;
        (move || filter.clone())
            .pipe(filter_entities::<F>)
            .pipe(save_scene)
            .pipe(file_from_request::<R>)
            .pipe(into_file_dyn)
            .pipe(finish)
            .pipe(remove_resource::<R>)
            .run_if(has_resource::<R>)
            .in_set(SaveSystem::Save)
    }

    /// Finishes the save pipeline by writing the saved data into a file with its path derived from an event of type `R`.
    ///
    /// The save pipeline will only be triggered if an event of type `R` is sent.
    ///
    /// # Warning
    /// If multiple events are sent in a single update cycle, only the first one is processed.
    pub fn into_file_on_event<R: SaveIntoFileRequest + Event>(self) -> SavePipeline {
        let Self { filter, .. } = self;
        (move || filter.clone())
            .pipe(filter_entities::<F>)
            .pipe(save_scene)
            .pipe(file_from_event::<R>)
            .pipe(into_file_dyn)
            .pipe(finish)
            .run_if(has_event::<R>)
            .in_set(SaveSystem::Save)
    }
}

/// A convenient builder for defining a [`SavePipeline`] with a dynamic [`SaveFilter`] which can be provided from any [`System`].
///
/// See [`save_with`], [`save_default_with`], and [`save_all_with`] on how to create an instance of this type.
pub struct DynamicSavePipelineBuilder<F: QueryFilter, S: System<In = (), Out = SaveFilter>> {
    query: PhantomData<F>,
    filter_source: S,
}

impl<F: QueryFilter, S: System<In = (), Out = SaveFilter>> DynamicSavePipelineBuilder<F, S>
where
    F: 'static,
{
    /// Finishes the save pipeline by writing the saved data into a file at given `path`.
    pub fn into_file(self, path: impl Into<PathBuf>) -> SavePipeline {
        let Self { filter_source, .. } = self;
        filter_source
            .pipe(filter_entities::<F>)
            .pipe(save_scene)
            .pipe(into_file(path.into()))
            .pipe(finish)
            .in_set(SaveSystem::Save)
    }

    /// Finishes the save pipeline by writing the saved data into a file with its path derived from a resource of type `R`.
    ///
    /// The save pipeline will only be triggered if a resource of type `R` is present.
    pub fn into_file_on_request<R: SaveIntoFileRequest + Resource>(self) -> SavePipeline {
        let Self { filter_source, .. } = self;
        filter_source
            .pipe(filter_entities::<F>)
            .pipe(save_scene)
            .pipe(file_from_request::<R>)
            .pipe(into_file_dyn)
            .pipe(finish)
            .pipe(remove_resource::<R>)
            .run_if(has_resource::<R>)
            .in_set(SaveSystem::Save)
    }

    /// Finishes the save pipeline by writing the saved data into a file with its path derived from an event of type `R`.
    ///
    /// The save pipeline will only be triggered if an event of type `R` is sent.
    ///
    /// # Warning
    /// If multiple events are sent in a single update cycle, only the first one is processed.
    pub fn into_file_on_event<R: SaveIntoFileRequest + Event>(self) -> SavePipeline {
        let Self { filter_source, .. } = self;
        filter_source
            .pipe(filter_entities::<F>)
            .pipe(save_scene)
            .pipe(file_from_event::<R>)
            .pipe(into_file_dyn)
            .pipe(finish)
            .run_if(has_event::<R>)
            .in_set(SaveSystem::Save)
    }
}

/// Creates a [`DynamicSavePipelineBuilder`] which saves all entities with given entity filter `F` and a filter source `S`.
///
/// During the save process, all entities that match the given query `F` will be selected for saving.
/// Additionally, any valid system which returns a [`SaveFilter`] may be used as a filter source `S`.
///
/// # Example
/// ```
/// use bevy::prelude::*;
/// use moonshine_save::prelude::*;
///
/// fn save_filter(/* ... */) -> SaveFilter {
///     todo!()
/// }
///
/// let mut app = App::new();
/// app.add_plugins((MinimalPlugins, SavePlugin))
///     .add_systems(PreUpdate, save_with::<With<Save>, _, _>(save_filter).into_file("example.ron"));
/// ```
pub fn save_with<F: QueryFilter, S: IntoSystem<(), SaveFilter, M>, M>(
    filter_source: S,
) -> DynamicSavePipelineBuilder<F, S::System> {
    DynamicSavePipelineBuilder {
        query: PhantomData,
        filter_source: IntoSystem::into_system(filter_source),
    }
}

/// Creates a [`DynamicSavePipelineBuilder`] which saves all entities with a [`Save`] component and a filter source `S`.
///
/// Additionally, any valid system which returns a [`SaveFilter`] may be used as a filter source `S`.
///
/// # Example
/// ```
/// use bevy::prelude::*;
/// use moonshine_save::prelude::*;
///
/// fn save_filter(/* ... */) -> SaveFilter {
///     todo!()
/// }
///
/// let mut app = App::new();
/// app.add_plugins((MinimalPlugins, SavePlugin))
///     .add_systems(PreUpdate, save_default_with(save_filter).into_file("example.ron"));
/// ```
pub fn save_default_with<S: IntoSystem<(), SaveFilter, M>, M>(
    filter_source: S,
) -> DynamicSavePipelineBuilder<With<Save>, S::System> {
    DynamicSavePipelineBuilder {
        query: PhantomData,
        filter_source: IntoSystem::into_system(filter_source),
    }
}

/// Creates a [`DynamicSavePipelineBuilder`] which saves all entities unconditionally and a filter source `S`.
///
/// Additionally, any valid system which returns a [`SaveFilter`] may be used as a filter source `S`.
///
/// # Warning
/// Be careful about using this builder as some entities and/or components may not be safely serializable.
///
/// # Example
/// ```
/// use bevy::prelude::*;
/// use moonshine_save::prelude::*;
///
/// fn save_filter(/* ... */) -> SaveFilter {
///     todo!()
/// }
///
/// let mut app = App::new();
/// app.add_plugins((MinimalPlugins, SavePlugin))
///     .add_systems(PreUpdate, save_all_with(save_filter).into_file("example.ron"));
/// ```
pub fn save_all_with<S: IntoSystem<(), SaveFilter, M>, M>(
    filter_source: S,
) -> DynamicSavePipelineBuilder<(), S::System> {
    DynamicSavePipelineBuilder {
        query: PhantomData,
        filter_source: IntoSystem::into_system(filter_source),
    }
}

#[cfg(test)]
mod tests {
    use std::fs::*;

    use bevy::prelude::*;

    use super::*;

    #[derive(Component, Default, Reflect)]
    #[reflect(Component)]
    struct Dummy;

    fn app() -> App {
        let mut app = App::new();
        app.add_plugins((MinimalPlugins, SavePlugin))
            .register_type::<Dummy>();
        app
    }

    #[test]
    fn test_save_into_file() {
        pub const PATH: &str = "test_save.ron";
        let mut app = app();
        app.add_systems(PreUpdate, save_default().into_file(PATH));

        app.world.spawn((Dummy, Save));
        app.update();

        let data = read_to_string(PATH).unwrap();
        assert!(data.contains("Dummy"));
        assert!(!app.world.contains_resource::<Saved>());

        remove_file(PATH).unwrap();
    }

    #[test]
    fn test_save_into_file_on_request() {
        pub const PATH: &str = "test_save_dyn.ron";

        #[derive(Resource)]
        struct SaveRequest;

        impl SaveIntoFileRequest for SaveRequest {
            fn path(&self) -> &Path {
                PATH.as_ref()
            }
        }

        let mut app = app();
        app.add_systems(
            PreUpdate,
            save_default().into_file_on_request::<SaveRequest>(),
        );

        app.world.insert_resource(SaveRequest);
        app.world.spawn((Dummy, Save));
        app.update();

        let data = read_to_string(PATH).unwrap();
        assert!(data.contains("Dummy"));

        remove_file(PATH).unwrap();
    }

    #[test]
    fn test_save_into_file_on_event() {
        pub const PATH: &str = "test_save_event.ron";

        #[derive(Event)]
        struct SaveRequest;

        impl SaveIntoFileRequest for SaveRequest {
            fn path(&self) -> &Path {
                PATH.as_ref()
            }
        }

        let mut app = app();
        app.add_event::<SaveRequest>().add_systems(
            PreUpdate,
            save_default().into_file_on_event::<SaveRequest>(),
        );

        app.world.send_event(SaveRequest);
        app.world.spawn((Dummy, Save));
        app.update();

        let data = read_to_string(PATH).unwrap();
        assert!(data.contains("Dummy"));

        remove_file(PATH).unwrap();
    }

    #[test]
    fn test_save_resource() {
        pub const PATH: &str = "test_save_resource.ron";

        #[derive(Resource, Default, Reflect)]
        #[reflect(Resource)]
        struct Dummy;

        let mut app = app();
        app.register_type::<Dummy>()
            .insert_resource(Dummy)
            .add_systems(
                Update,
                save_default().include_resource::<Dummy>().into_file(PATH),
            );

        app.update();

        let data = read_to_string(PATH).unwrap();
        assert!(data.contains("Dummy"));

        remove_file(PATH).unwrap();
    }

    #[test]
    fn test_save_without_component() {
        pub const PATH: &str = "test_save_without_component.ron";

        #[derive(Component, Default, Reflect)]
        #[reflect(Component)]
        struct Foo;

        let mut app = app();
        app.add_systems(
            PreUpdate,
            save_default().exclude_component::<Foo>().into_file(PATH),
        );

        app.world.spawn((Dummy, Foo, Save));
        app.update();

        let data = read_to_string(PATH).unwrap();
        assert!(data.contains("Dummy"));
        assert!(!data.contains("Foo"));

        remove_file(PATH).unwrap();
    }

    #[test]
    fn test_dynamic_save_without_component() {
        pub const PATH: &str = "test_dynamic_save_without_component.ron";

        #[derive(Component, Default, Reflect)]
        #[reflect(Component)]
        struct Foo;

        fn deny_foo() -> SaveFilter {
            SaveFilter {
                components: SceneFilter::default().deny::<Foo>(),
                ..Default::default()
            }
        }

        let mut app = app();
        app.add_systems(PreUpdate, save_default_with(deny_foo).into_file(PATH));

        app.world.spawn((Dummy, Foo, Save));
        app.update();

        let data = read_to_string(PATH).unwrap();
        assert!(data.contains("Dummy"));
        assert!(!data.contains("Foo"));

        remove_file(PATH).unwrap();
    }
}