bevy_ecs 0.19.0

Bevy Engine's entity component system
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
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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
#[cfg(feature = "hotpatching")]
use crate::{change_detection::DetectChanges, HotPatchChanges};
use crate::{
    change_detection::Mut,
    entity::Entity,
    error::BevyError,
    prelude::{FromTemplate, Template},
    system::{
        input::SystemInput, BoxedSystem, Commands, If, IntoSystem, Res, RunSystemError,
        SystemParamValidationError,
    },
    template::TemplateContext,
    world::World,
};
use alloc::boxed::Box;
use bevy_ecs_macros::{Component, Resource};
use bevy_platform::sync::{Arc, Mutex};
use bevy_utils::prelude::DebugName;
use concurrent_queue::ConcurrentQueue;
use core::{any::TypeId, marker::PhantomData};
use thiserror::Error;

/// A small wrapper for [`BoxedSystem`] that also keeps track whether or not the system has been initialized.
#[derive(Component)]
#[require(SystemIdMarker = SystemIdMarker::typed_system_id_marker::<I, O>())]
pub(crate) struct RegisteredSystem<I, O> {
    initialized: bool,
    system: Option<BoxedSystem<I, O>>,
}

impl<I, O> RegisteredSystem<I, O> {
    pub fn new(system: BoxedSystem<I, O>) -> Self {
        RegisteredSystem {
            initialized: false,
            system: Some(system),
        }
    }
}

#[derive(Debug, Clone)]
struct TypeIdAndName {
    type_id: TypeId,
    name: DebugName,
}

impl TypeIdAndName {
    fn new<T: 'static>() -> Self {
        Self {
            type_id: TypeId::of::<T>(),
            name: DebugName::type_name::<T>(),
        }
    }
}

impl Default for TypeIdAndName {
    fn default() -> Self {
        Self {
            type_id: TypeId::of::<()>(),
            name: DebugName::type_name::<()>(),
        }
    }
}

/// Marker [`Component`](bevy_ecs::component::Component) for identifying [`SystemId`] [`Entity`]s.
#[derive(Debug, Default, Clone, Component)]
pub struct SystemIdMarker {
    input_type_id: TypeIdAndName,
    output_type_id: TypeIdAndName,
}

impl SystemIdMarker {
    fn typed_system_id_marker<I: 'static, O: 'static>() -> Self {
        Self {
            input_type_id: TypeIdAndName::new::<I>(),
            output_type_id: TypeIdAndName::new::<O>(),
        }
    }
}

/// A system that has been removed from the registry.
/// It contains the system and whether or not it has been initialized.
///
/// This struct is returned by [`World::unregister_system`].
pub struct RemovedSystem<I = (), O = ()> {
    initialized: bool,
    system: BoxedSystem<I, O>,
}

impl<I, O> RemovedSystem<I, O> {
    /// Is the system initialized?
    /// A system is initialized the first time it's ran.
    pub fn initialized(&self) -> bool {
        self.initialized
    }

    /// The system removed from the storage.
    pub fn system(self) -> BoxedSystem<I, O> {
        self.system
    }
}

/// A system that despawns any registered system entities whose [`SystemHandle`]
/// reference count has reached zero.
pub fn despawn_unused_registered_systems(
    // `RegisteredSystemDespawner` is initialized lazily the first time a system
    // is registered, so it's possible that it doesn't exist yet when this system runs.
    despawner: If<Res<RegisteredSystemDespawner>>,
    mut commands: Commands,
) {
    for entity in despawner.queue.try_iter() {
        // In case the entity was already despawned manually, we ignore the error here.
        commands.entity(entity).try_despawn();
    }
}

/// A resource that stores the channel for despawning unused registered system
/// entities.
#[derive(Resource)]
pub struct RegisteredSystemDespawner {
    queue: Arc<ConcurrentQueue<Entity>>,
}

impl Default for RegisteredSystemDespawner {
    fn default() -> Self {
        Self {
            queue: Arc::new(ConcurrentQueue::unbounded()),
        }
    }
}

/// A maybe-strong handle to an entity acting as a registered system. Strong
/// handles are created by [`World::register_tracked_system`] or
/// [`World::register_tracked_boxed_system`].
///
/// Strong handles provide automatic cleanup of registered systems once all clones
/// of the handle are dropped, while weak handles do not. However, the **existence
/// of a strong handle does not prevent the registered system entity from being
/// despawned manually**, like with [`World::unregister_system`] or
/// [`World::unregister_system_cached`].
///
/// # Cleanup
///
/// Registered system entities are cleaned up by the [`despawn_unused_registered_systems`]
/// system, which is automatically added to the default app by the `bevy_app`
/// crate when the "std" feature is enabled. If not using the default app, the
/// "std" feature, or `bevy_app` in general, consider running this system
/// yourself to ensure proper cleanup of registered systems.
pub enum SystemHandle<I: SystemInput = (), O = ()> {
    /// A strong handle keeps the system entity alive as long as the handle
    /// (and any clones of it) exist, as long as the system entity isn't
    /// manually despawned.
    Strong(Arc<StrongSystemHandle>),
    /// A weak handle does not keep the system entity alive.
    Weak(SystemId<I, O>),
}

impl<I: SystemInput, O> SystemHandle<I, O> {
    /// Returns the [`Entity`] of the registered system associated with this handle.
    pub fn entity(&self) -> Entity {
        match self {
            SystemHandle::Strong(strong) => strong.entity,
            SystemHandle::Weak(weak) => weak.entity,
        }
    }
}

impl<I: SystemInput, O> Eq for SystemHandle<I, O> {}

// A manual impl is used because the trait bounds should ignore the `I` and `O` phantom parameters.
impl<I: SystemInput, O> Clone for SystemHandle<I, O> {
    fn clone(&self) -> Self {
        match self {
            SystemHandle::Strong(strong) => SystemHandle::Strong(Arc::clone(strong)),
            SystemHandle::Weak(weak) => SystemHandle::Weak(*weak),
        }
    }
}

// A manual impl is used because the trait bounds should ignore the `I` and `O` phantom parameters,
// and so that strong and weak handles can be compared for equality based on their entities.
impl<I: SystemInput, O> PartialEq for SystemHandle<I, O> {
    fn eq(&self, other: &Self) -> bool {
        self.entity() == other.entity()
    }
}

impl<I: SystemInput, O> PartialEq<SystemId<I, O>> for SystemHandle<I, O> {
    fn eq(&self, other: &SystemId<I, O>) -> bool {
        self.entity() == other.entity
    }
}

// A manual impl is used because the trait bounds should ignore the `I` and `O` phantom parameters,
// and so that the handle can be hashed based on its entity instead of its handle type.
impl<I: SystemInput, O> core::hash::Hash for SystemHandle<I, O> {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.entity().hash(state);
    }
}

impl<I: SystemInput, O> core::fmt::Debug for SystemHandle<I, O> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let name = if matches!(self, SystemHandle::Strong(_)) {
            "StrongSystemHandle"
        } else {
            "WeakSystemHandle"
        };
        f.debug_tuple(name).field(&self.entity()).finish()
    }
}

impl<I: SystemInput, O> From<SystemId<I, O>> for SystemHandle<I, O> {
    fn from(id: SystemId<I, O>) -> Self {
        SystemHandle::Weak(id)
    }
}

/// A strong handle for a registered system that despawns the entity when dropped.
pub struct StrongSystemHandle {
    entity: Entity,
    drop_queue: Arc<ConcurrentQueue<Entity>>,
}

impl Drop for StrongSystemHandle {
    fn drop(&mut self) {
        // Send the entity to be despawned by the world when the last strong handle is dropped.
        let _ = self.drop_queue.push(self.entity);
    }
}

/// An identifier for a registered system.
///
/// These are opaque identifiers, keyed to a specific [`World`],
/// and are created via [`World::register_system`].
pub struct SystemId<I: SystemInput = (), O = ()> {
    pub(crate) entity: Entity,
    pub(crate) marker: PhantomData<fn(I) -> O>,
}

impl<I: SystemInput, O> SystemId<I, O> {
    /// Transforms a [`SystemId`] into the [`Entity`] that holds the one-shot system's state.
    ///
    /// It's trivial to convert [`SystemId`] into an [`Entity`] since a one-shot system
    /// is really an entity with associated handler function.
    ///
    /// For example, this is useful if you want to assign a name label to a system.
    pub fn entity(self) -> Entity {
        self.entity
    }

    /// Create [`SystemId`] from an [`Entity`]. Useful when you only have entity handles to avoid
    /// adding extra components that have a [`SystemId`] everywhere. To run a system with this ID
    ///  - The entity must be a system
    ///  - The `I` + `O` types must be correct
    pub fn from_entity(entity: Entity) -> Self {
        Self {
            entity,
            marker: PhantomData,
        }
    }
}

impl<I: SystemInput, O> Eq for SystemId<I, O> {}

// A manual impl is used because the trait bounds should ignore the `I` and `O` phantom parameters.
impl<I: SystemInput, O> Copy for SystemId<I, O> {}

// A manual impl is used because the trait bounds should ignore the `I` and `O` phantom parameters.
impl<I: SystemInput, O> Clone for SystemId<I, O> {
    fn clone(&self) -> Self {
        *self
    }
}

// A manual impl is used because the trait bounds should ignore the `I` and `O` phantom parameters.
impl<I: SystemInput, O> PartialEq for SystemId<I, O> {
    fn eq(&self, other: &Self) -> bool {
        self.entity == other.entity && self.marker == other.marker
    }
}

// A manual impl is used because the trait bounds should ignore the `I` and `O` phantom parameters.
impl<I: SystemInput, O> core::hash::Hash for SystemId<I, O> {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.entity.hash(state);
    }
}

impl<I: SystemInput, O> core::fmt::Debug for SystemId<I, O> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_tuple("SystemId").field(&self.entity).finish()
    }
}

impl<I: SystemInput, O> From<&SystemHandle<I, O>> for SystemId<I, O> {
    fn from(handle: &SystemHandle<I, O>) -> Self {
        Self::from_entity(handle.entity())
    }
}

impl<I: SystemInput, O> From<SystemHandle<I, O>> for SystemId<I, O> {
    fn from(handle: SystemHandle<I, O>) -> Self {
        (&handle).into()
    }
}

impl<I: SystemInput + 'static, O: 'static> FromTemplate for SystemHandle<I, O> {
    type Template = SystemHandleTemplate<I, O>;
}

/// A [`Template`] that produces a [`SystemHandle`].
pub enum SystemHandleTemplate<I: SystemInput + 'static = (), O: 'static = ()> {
    /// Creates a [`SystemHandle`] by cloning the given [`SystemHandle`] value.
    Handle(SystemHandle<I, O>),
    /// Creates a [`SystemHandle`] by registering the given system value using
    /// [`World::register_tracked_boxed_system`]. This will cache the resulting
    /// [`SystemHandle`]
    /// on the template and reuse it for future template builds.
    ///
    /// This should generally be constructed using [`SystemHandleTemplate::value`]
    /// or [`system_value`].
    Value(SystemHandleValue<I, O>),
}

/// Stores an [`Arc<Mutex<SystemHandleOrValue<I, O>>>`].
pub struct SystemHandleValue<I: SystemInput + 'static = (), O: 'static = ()>(
    Arc<Mutex<SystemHandleOrValue<I, O>>>,
);

impl<I: SystemInput + 'static, O: 'static> Clone for SystemHandleValue<I, O> {
    fn clone(&self) -> Self {
        Self(Arc::clone(&self.0))
    }
}

enum SystemHandleOrValue<I: SystemInput + 'static = (), O: 'static = ()> {
    Handle(SystemHandle<I, O>),
    Value(Option<BoxedSystem<I, O>>),
}

impl<I: SystemInput + 'static, O: 'static> SystemHandleTemplate<I, O> {
    /// This will create a new [`SystemHandleTemplate`] for the given `system` value.
    /// This makes it possible to define systems "inline" in templates / scenes
    /// that produce a [`SystemId`].
    pub fn value<M>(system: impl IntoSystem<I, O, M>) -> Self {
        Self::Value(SystemHandleValue(Arc::new(Mutex::new(
            SystemHandleOrValue::Value(Some(Box::new(IntoSystem::into_system(system)))),
        ))))
    }
}

impl<I: SystemInput + 'static, O: 'static> Template for SystemHandleTemplate<I, O> {
    type Output = SystemHandle<I, O>;

    fn build_template(
        &self,
        context: &mut TemplateContext,
    ) -> crate::prelude::Result<Self::Output> {
        match self {
            Self::Handle(handle) => Ok(handle.clone()),
            Self::Value(value) => {
                let mut value_or_id = value.0.lock().unwrap();
                match &mut *value_or_id {
                    SystemHandleOrValue::Handle(handle) => Ok(handle.clone()),
                    SystemHandleOrValue::Value(system) => {
                        let system = system.take().unwrap();
                        let id = context
                            .entity
                            .world_scope(|world| world.register_tracked_boxed_system(system));
                        *value_or_id = SystemHandleOrValue::Handle(id.clone());
                        Ok(id)
                    }
                }
            }
        }
    }

    fn clone_template(&self) -> Self {
        match self {
            Self::Handle(handle) => Self::Handle(handle.clone()),
            Self::Value(value) => Self::Value(value.clone()),
        }
    }
}

impl<I: SystemInput + 'static, O: 'static> Default for SystemHandleTemplate<I, O> {
    fn default() -> Self {
        Self::Handle(SystemHandle::Weak(SystemId::from_entity(
            Entity::PLACEHOLDER,
        )))
    }
}

impl<I: SystemInput + 'static, O: 'static> From<SystemHandle<I, O>> for SystemHandleTemplate<I, O> {
    fn from(handle: SystemHandle<I, O>) -> Self {
        Self::Handle(handle)
    }
}

impl<I: SystemInput + 'static, O: 'static> From<BoxedSystem<I, O>> for SystemHandleTemplate<I, O> {
    fn from(system: BoxedSystem<I, O>) -> Self {
        Self::Value(SystemHandleValue(Arc::new(Mutex::new(
            SystemHandleOrValue::Value(Some(system)),
        ))))
    }
}

impl<I: SystemInput + 'static, O: 'static> From<SystemId<I, O>> for SystemHandleTemplate<I, O> {
    fn from(id: SystemId<I, O>) -> Self {
        Self::Handle(SystemHandle::Weak(id))
    }
}

/// This will create a new [`SystemHandleTemplate`] for the given `system` value.
/// This makes it possible to define systems "inline" in templates / scenes that
/// produce a [`SystemHandle`].
pub fn system_value<I: SystemInput + 'static, O: 'static, M>(
    system: impl IntoSystem<I, O, M>,
) -> SystemHandleTemplate<I, O> {
    SystemHandleTemplate::value(system)
}

/// A cached [`SystemId`] distinguished by the unique function type of its system.
///
/// This resource is inserted by [`World::register_system_cached`].
#[derive(Resource)]
pub struct CachedSystemId<S> {
    /// The cached `SystemId` as an `Entity`.
    pub entity: Entity,
    _marker: PhantomData<fn() -> S>,
}

impl<S> CachedSystemId<S> {
    /// Creates a new `CachedSystemId` struct given a `SystemId`.
    pub fn new<I: SystemInput, O>(id: SystemId<I, O>) -> Self {
        Self {
            entity: id.entity(),
            _marker: PhantomData,
        }
    }
}

impl World {
    /// Registers a system and returns a [`SystemId`] so it can later be called by [`World::run_system`].
    ///
    /// It's possible to register multiple copies of the same system by calling this function
    /// multiple times. If that's not what you want, consider using [`World::register_system_cached`]
    /// instead.
    ///
    /// This is different from adding systems to a [`Schedule`](crate::schedule::Schedule),
    /// because the [`SystemId`] that is returned can be used anywhere in the [`World`] to run the associated system.
    /// This allows for running systems in a pushed-based fashion.
    /// Using a [`Schedule`](crate::schedule::Schedule) is still preferred for most cases
    /// due to its better performance and ability to run non-conflicting systems simultaneously.
    pub fn register_system<I, O, M>(
        &mut self,
        system: impl IntoSystem<I, O, M> + 'static,
    ) -> SystemId<I, O>
    where
        I: SystemInput + 'static,
        O: 'static,
    {
        self.register_boxed_system(Box::new(IntoSystem::into_system(system)))
    }

    /// Similar to [`Self::register_system`], but allows passing in a [`BoxedSystem`].
    ///
    ///  This is useful if the [`IntoSystem`] implementor has already been turned into a
    /// [`System`](crate::system::System) trait object and put in a [`Box`].
    pub fn register_boxed_system<I, O>(&mut self, system: BoxedSystem<I, O>) -> SystemId<I, O>
    where
        I: SystemInput + 'static,
        O: 'static,
    {
        let entity = self.spawn(RegisteredSystem::new(system)).id();
        SystemId::from_entity(entity)
    }

    /// Registers a system and returns a tracked [`SystemHandle`] so it can later
    /// be called by [`World::run_system`]. The system entity will be automatically
    /// queued for despawn when the last clone of the returned handle is dropped.
    ///
    /// By default, unused tracked system entities are despawned by the
    /// [`despawn_unused_registered_systems`] system in the `Last` schedule of
    /// the default app. Otherwise, it needs to be run manually to ensure proper
    /// cleanup of registered systems.
    ///
    /// It's possible to register multiple copies of the same system by calling
    /// this function multiple times. If that's not what you want, consider using
    /// [`World::register_system_cached`] instead.
    pub fn register_tracked_system<I, O, M>(
        &mut self,
        system: impl IntoSystem<I, O, M> + 'static,
    ) -> SystemHandle<I, O>
    where
        I: SystemInput + 'static,
        O: 'static,
    {
        self.register_tracked_boxed_system(Box::new(IntoSystem::into_system(system)))
    }

    /// Similar to [`Self::register_tracked_system`], but allows passing in a
    /// [`BoxedSystem`].
    ///
    /// This is useful if the [`IntoSystem`] implementor has already been turned
    /// into a [`System`](crate::system::System) trait object and put in a [`Box`].
    pub fn register_tracked_boxed_system<I, O>(
        &mut self,
        system: BoxedSystem<I, O>,
    ) -> SystemHandle<I, O>
    where
        I: SystemInput + 'static,
        O: 'static,
    {
        let entity = self.spawn(RegisteredSystem::new(system)).id();
        let despawner = self.get_resource_or_init::<RegisteredSystemDespawner>();

        SystemHandle::Strong(Arc::new(StrongSystemHandle {
            entity,
            drop_queue: despawner.queue.clone(),
        }))
    }

    /// Removes a registered system and returns the system, if it exists.
    /// After removing a system, the [`SystemId`] becomes invalid and attempting to use it afterwards will result in errors.
    /// Re-adding the removed system will register it on a new [`SystemId`].
    ///
    /// If no system corresponds to the given [`SystemId`], this method returns an error.
    /// Systems are also not allowed to remove themselves, this returns an error too.
    pub fn unregister_system<I, O>(
        &mut self,
        id: SystemId<I, O>,
    ) -> Result<RemovedSystem<I, O>, RegisteredSystemError<I, O>>
    where
        I: SystemInput + 'static,
        O: 'static,
    {
        match self.get_entity_mut(id.entity) {
            Ok(mut entity) => {
                let registered_system = entity
                    .take::<RegisteredSystem<I, O>>()
                    .ok_or(RegisteredSystemError::SelfRemove(id))?;
                entity.despawn();
                Ok(RemovedSystem {
                    initialized: registered_system.initialized,
                    system: registered_system
                        .system
                        .ok_or(RegisteredSystemError::SystemMissing(id))?,
                })
            }
            Err(_) => Err(RegisteredSystemError::SystemIdNotRegistered(id)),
        }
    }

    /// Run stored systems by their [`SystemId`].
    /// Before running a system, it must first be registered.
    /// The method [`World::register_system`] stores a given system and returns a [`SystemId`].
    /// This is different from [`RunSystemOnce::run_system_once`](crate::system::RunSystemOnce::run_system_once),
    /// because it keeps local state between calls and change detection works correctly.
    ///
    /// Also runs any queued-up commands.
    ///
    /// In order to run a chained system with an input, use [`World::run_system_with`] instead.
    ///
    /// # Examples
    ///
    /// ## Running a system
    ///
    /// ```
    /// # use bevy_ecs::prelude::*;
    /// fn increment(mut counter: Local<u8>) {
    ///    *counter += 1;
    ///    println!("{}", *counter);
    /// }
    ///
    /// let mut world = World::default();
    /// let counter_one = world.register_system(increment);
    /// let counter_two = world.register_system(increment);
    /// world.run_system(counter_one); // -> 1
    /// world.run_system(counter_one); // -> 2
    /// world.run_system(counter_two); // -> 1
    /// ```
    ///
    /// ## Change detection
    ///
    /// ```
    /// # use bevy_ecs::prelude::*;
    /// #[derive(Resource, Default)]
    /// struct ChangeDetector;
    ///
    /// let mut world = World::default();
    /// world.init_resource::<ChangeDetector>();
    /// let detector = world.register_system(|change_detector: ResMut<ChangeDetector>| {
    ///     if change_detector.is_changed() {
    ///         println!("Something happened!");
    ///     } else {
    ///         println!("Nothing happened.");
    ///     }
    /// });
    ///
    /// // Resources are changed when they are first added
    /// let _ = world.run_system(detector); // -> Something happened!
    /// let _ = world.run_system(detector); // -> Nothing happened.
    /// world.resource_mut::<ChangeDetector>().set_changed();
    /// let _ = world.run_system(detector); // -> Something happened!
    /// ```
    ///
    /// ## Getting system output
    ///
    /// ```
    /// # use bevy_ecs::prelude::*;
    ///
    /// #[derive(Resource)]
    /// struct PlayerScore(i32);
    ///
    /// #[derive(Resource)]
    /// struct OpponentScore(i32);
    ///
    /// fn get_player_score(player_score: Res<PlayerScore>) -> i32 {
    ///   player_score.0
    /// }
    ///
    /// fn get_opponent_score(opponent_score: Res<OpponentScore>) -> i32 {
    ///   opponent_score.0
    /// }
    ///
    /// let mut world = World::default();
    /// world.insert_resource(PlayerScore(3));
    /// world.insert_resource(OpponentScore(2));
    ///
    /// let scoring_systems = [
    ///   ("player", world.register_system(get_player_score)),
    ///   ("opponent", world.register_system(get_opponent_score)),
    /// ];
    ///
    /// for (label, scoring_system) in scoring_systems {
    ///   println!("{label} has score {}", world.run_system(scoring_system).expect("system succeeded"));
    /// }
    /// ```
    pub fn run_system<O: 'static>(
        &mut self,
        id: impl Into<SystemId<(), O>>,
    ) -> Result<O, RegisteredSystemError<(), O>> {
        self.run_system_with(id, ())
    }

    /// Run a stored chained system by its [`SystemId`], providing an input value.
    /// Before running a system, it must first be registered.
    /// The method [`World::register_system`] stores a given system and returns a [`SystemId`].
    ///
    /// To use the supplied input, the system should have a [`SystemInput`] as the first parameter.
    /// Also runs any queued-up commands.
    ///
    /// # Examples
    ///
    /// ```
    /// # use bevy_ecs::prelude::*;
    /// fn increment(In(increment_by): In<u8>, mut counter: Local<u8>) -> u8 {
    ///   *counter += increment_by;
    ///   *counter
    /// }
    ///
    /// let mut world = World::default();
    /// let counter_one = world.register_system(increment);
    /// let counter_two = world.register_system(increment);
    /// assert_eq!(world.run_system_with(counter_one, 1).unwrap(), 1);
    /// assert_eq!(world.run_system_with(counter_one, 20).unwrap(), 21);
    /// assert_eq!(world.run_system_with(counter_two, 30).unwrap(), 30);
    /// ```
    ///
    /// See [`World::run_system`] for more examples.
    pub fn run_system_with<I, O>(
        &mut self,
        id: impl Into<SystemId<I, O>>,
        input: I::Inner<'_>,
    ) -> Result<O, RegisteredSystemError<I, O>>
    where
        I: SystemInput + 'static,
        O: 'static,
    {
        let id = id.into();
        // Lookup
        let mut entity = self
            .get_entity_mut(id.entity)
            .map_err(|_| RegisteredSystemError::SystemIdNotRegistered(id))?;

        // Take ownership of system trait object
        let Some(mut registered_system) = entity.get_mut::<RegisteredSystem<I, O>>() else {
            let Some(system_id_marker) = entity.get::<SystemIdMarker>() else {
                return Err(RegisteredSystemError::SystemIdNotRegistered(id));
            };
            if system_id_marker.input_type_id.type_id != TypeId::of::<I>()
                || system_id_marker.output_type_id.type_id != TypeId::of::<O>()
            {
                return Err(RegisteredSystemError::IncorrectType(
                    id,
                    system_id_marker.clone(),
                ));
            }
            return Err(RegisteredSystemError::MissingRegisteredSystemComponent(id));
        };

        let mut system = registered_system
            .system
            .take()
            .ok_or(RegisteredSystemError::SystemMissing(id))?;

        // Initialize the system
        if !registered_system.initialized {
            system.initialize(self);
        }

        // refresh hotpatches for stored systems
        #[cfg(feature = "hotpatching")]
        if self
            .get_resource_ref::<HotPatchChanges>()
            .is_none_or(|r| r.is_changed_after(system.get_last_run()))
        {
            system.refresh_hotpatch();
        }

        // Wait to run the commands until the system is available again.
        // This is needed so the systems can recursively run themselves.
        let result = system.run_without_applying_deferred(input, self);
        system.queue_deferred(self.into());

        // Return ownership of system trait object (if entity still exists)
        if let Ok(mut entity) = self.get_entity_mut(id.entity)
            && let Some(mut registered_system) = entity.get_mut::<RegisteredSystem<I, O>>()
        {
            registered_system.system = Some(system);
            registered_system.initialized = true;
        }

        // Run any commands enqueued by the system
        self.flush();
        Ok(result?)
    }

    /// Registers a system or returns its cached [`SystemId`].
    ///
    /// If you want to run the system immediately and you don't need its `SystemId`, see
    /// [`World::run_system_cached`].
    ///
    /// The first time this function is called for a particular system, it will register it and
    /// store its [`SystemId`] in a [`CachedSystemId`] resource for later. If you would rather
    /// manage the `SystemId` yourself, or register multiple copies of the same system, use
    /// [`World::register_system`] instead.
    ///
    /// # Limitations
    ///
    /// This function only accepts ZST (zero-sized) systems to guarantee that any two systems of
    /// the same type must be equal. This means that closures that capture the environment, and
    /// function pointers, are not accepted.
    ///
    /// If you want to access values from the environment within a system, consider passing them in
    /// as inputs via [`World::run_system_cached_with`]. If that's not an option, consider
    /// [`World::register_system`] instead.
    pub fn register_system_cached<I, O, M, S>(&mut self, system: S) -> SystemId<I, O>
    where
        I: SystemInput + 'static,
        O: 'static,
        S: IntoSystem<I, O, M> + 'static,
    {
        const {
            assert!(
                size_of::<S>() == 0,
                "Non-ZST systems (e.g. capturing closures, function pointers) cannot be cached.",
            );
        }

        if !self.contains_resource::<CachedSystemId<S>>() {
            let id = self.register_system(system);
            self.insert_resource(CachedSystemId::<S>::new(id));
            return id;
        }

        self.resource_scope(|world, mut id: Mut<CachedSystemId<S>>| {
            if let Ok(mut entity) = world.get_entity_mut(id.entity) {
                if !entity.contains::<RegisteredSystem<I, O>>() {
                    entity.insert(RegisteredSystem::new(Box::new(IntoSystem::into_system(
                        system,
                    ))));
                }
            } else {
                id.entity = world.register_system(system).entity();
            }
            SystemId::from_entity(id.entity)
        })
    }

    /// Removes a cached system and its [`CachedSystemId`] resource.
    ///
    /// See [`World::register_system_cached`] for more information.
    pub fn unregister_system_cached<I, O, M, S>(
        &mut self,
        _system: S,
    ) -> Result<RemovedSystem<I, O>, RegisteredSystemError<I, O>>
    where
        I: SystemInput + 'static,
        O: 'static,
        S: IntoSystem<I, O, M> + 'static,
    {
        let id = self
            .remove_resource::<CachedSystemId<S>>()
            .ok_or(RegisteredSystemError::SystemNotCached)?;
        self.unregister_system(SystemId::<I, O>::from_entity(id.entity))
    }

    /// Runs a cached system, registering it if necessary.
    ///
    /// See [`World::register_system_cached`] for more information.
    pub fn run_system_cached<O: 'static, M, S: IntoSystem<(), O, M> + 'static>(
        &mut self,
        system: S,
    ) -> Result<O, RegisteredSystemError<(), O>> {
        self.run_system_cached_with(system, ())
    }

    /// Runs a cached system with an input, registering it if necessary.
    ///
    /// To use the supplied input, the system should have a [`SystemInput`] as the first parameter.
    /// See [`World::register_system_cached`] for more information.
    pub fn run_system_cached_with<I, O, M, S>(
        &mut self,
        system: S,
        input: I::Inner<'_>,
    ) -> Result<O, RegisteredSystemError<I, O>>
    where
        I: SystemInput + 'static,
        O: 'static,
        S: IntoSystem<I, O, M> + 'static,
    {
        let id = self.register_system_cached(system);
        self.run_system_with(id, input)
    }
}

/// An operation with stored systems failed.
#[derive(Error)]
pub enum RegisteredSystemError<I: SystemInput = (), O = ()> {
    /// A system was run by id, but no system with that id was found.
    ///
    /// Did you forget to register it?
    #[error("System {0:?} was not registered")]
    SystemIdNotRegistered(SystemId<I, O>),
    /// A cached system was removed by value, but no system with its type was found.
    ///
    /// Did you forget to register it?
    #[error("Cached system was not found")]
    SystemNotCached,
    /// The `RegisteredSystem` component is missing.
    #[error("System {0:?} does not have a RegisteredSystem component. This only happens if app code removed the component.")]
    MissingRegisteredSystemComponent(SystemId<I, O>),
    /// A system tried to remove itself.
    #[error("System {0:?} tried to remove itself")]
    SelfRemove(SystemId<I, O>),
    /// System could not be run due to parameters that failed validation.
    /// This is not considered an error.
    #[error("System did not run due to failed parameter validation: {0}")]
    Skipped(SystemParamValidationError),
    /// System returned an error or failed required parameter validation.
    #[error("System returned error: {0}")]
    Failed(BevyError),
    /// [`SystemId`] had different input and/or output types than [`SystemIdMarker`]
    #[error("Could not get system from `{}`, entity was `SystemId<{}, {}>`", DebugName::type_name::<SystemId<I, O>>(), .1.input_type_id.name, .1.output_type_id.name)]
    IncorrectType(SystemId<I, O>, SystemIdMarker),
    /// System is not present in the `RegisteredSystem` component.
    // TODO: We should consider using catch_unwind to protect against the panic case.
    #[error("The system is not present in the RegisteredSystem component. This can happen if the system was called recursively or if the system panicked on the last run.")]
    SystemMissing(SystemId<I, O>),
}

impl<I: SystemInput, O> From<RunSystemError> for RegisteredSystemError<I, O> {
    fn from(value: RunSystemError) -> Self {
        match value {
            RunSystemError::Skipped(err) => Self::Skipped(err),
            RunSystemError::Failed(err) => Self::Failed(err),
        }
    }
}

impl<I: SystemInput, O> core::fmt::Debug for RegisteredSystemError<I, O> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::SystemIdNotRegistered(arg0) => {
                f.debug_tuple("SystemIdNotRegistered").field(arg0).finish()
            }
            Self::SystemNotCached => write!(f, "SystemNotCached"),
            Self::MissingRegisteredSystemComponent(arg0) => f
                .debug_tuple("MissingRegisteredSystemComponent")
                .field(arg0)
                .finish(),
            Self::SelfRemove(arg0) => f.debug_tuple("SelfRemove").field(arg0).finish(),
            Self::Skipped(arg0) => f.debug_tuple("Skipped").field(arg0).finish(),
            Self::Failed(arg0) => f.debug_tuple("Failed").field(arg0).finish(),
            Self::IncorrectType(arg0, arg1) => f
                .debug_tuple("IncorrectType")
                .field(arg0)
                .field(arg1)
                .finish(),
            Self::SystemMissing(arg0) => f.debug_tuple("SystemMissing").field(arg0).finish(),
        }
    }
}

#[cfg(test)]
mod tests {
    use core::cell::Cell;

    use bevy_utils::default;

    use crate::{
        prelude::*,
        system::{
            despawn_unused_registered_systems, system_value, RegisteredSystemError, SystemHandle,
            SystemHandleTemplate, SystemId,
        },
    };

    #[derive(Resource, Default, PartialEq, Debug)]
    struct Counter(u8);

    #[test]
    fn change_detection() {
        #[derive(Resource, Default)]
        struct ChangeDetector;

        fn count_up_iff_changed(
            mut counter: ResMut<Counter>,
            change_detector: ResMut<ChangeDetector>,
        ) {
            if change_detector.is_changed() {
                counter.0 += 1;
            }
        }

        let mut world = World::new();
        world.init_resource::<ChangeDetector>();
        world.init_resource::<Counter>();
        assert_eq!(*world.resource::<Counter>(), Counter(0));
        // Resources are changed when they are first added.
        let id = world.register_system(count_up_iff_changed);
        world.run_system(id).expect("system runs successfully");
        assert_eq!(*world.resource::<Counter>(), Counter(1));
        // Nothing changed
        world.run_system(id).expect("system runs successfully");
        assert_eq!(*world.resource::<Counter>(), Counter(1));
        // Making a change
        world.resource_mut::<ChangeDetector>().set_changed();
        world.run_system(id).expect("system runs successfully");
        assert_eq!(*world.resource::<Counter>(), Counter(2));
    }

    #[test]
    fn local_variables() {
        // The `Local` begins at the default value of 0
        fn doubling(last_counter: Local<Counter>, mut counter: ResMut<Counter>) {
            counter.0 += last_counter.0 .0;
            last_counter.0 .0 = counter.0;
        }

        let mut world = World::new();
        world.insert_resource(Counter(1));
        assert_eq!(*world.resource::<Counter>(), Counter(1));
        let id = world.register_system(doubling);
        world.run_system(id).expect("system runs successfully");
        assert_eq!(*world.resource::<Counter>(), Counter(1));
        world.run_system(id).expect("system runs successfully");
        assert_eq!(*world.resource::<Counter>(), Counter(2));
        world.run_system(id).expect("system runs successfully");
        assert_eq!(*world.resource::<Counter>(), Counter(4));
        world.run_system(id).expect("system runs successfully");
        assert_eq!(*world.resource::<Counter>(), Counter(8));
    }

    #[test]
    fn input_values() {
        // Verify that a non-Copy, non-Clone type can be passed in.
        struct NonCopy(u8);

        fn increment_sys(In(NonCopy(increment_by)): In<NonCopy>, mut counter: ResMut<Counter>) {
            counter.0 += increment_by;
        }

        let mut world = World::new();

        let id = world.register_system(increment_sys);

        // Insert the resource after registering the system.
        world.insert_resource(Counter(1));
        assert_eq!(*world.resource::<Counter>(), Counter(1));

        world
            .run_system_with(id, NonCopy(1))
            .expect("system runs successfully");
        assert_eq!(*world.resource::<Counter>(), Counter(2));

        world
            .run_system_with(id, NonCopy(1))
            .expect("system runs successfully");
        assert_eq!(*world.resource::<Counter>(), Counter(3));

        world
            .run_system_with(id, NonCopy(20))
            .expect("system runs successfully");
        assert_eq!(*world.resource::<Counter>(), Counter(23));

        world
            .run_system_with(id, NonCopy(1))
            .expect("system runs successfully");
        assert_eq!(*world.resource::<Counter>(), Counter(24));
    }

    #[test]
    fn output_values() {
        // Verify that a non-Copy, non-Clone type can be returned.
        #[derive(Eq, PartialEq, Debug)]
        struct NonCopy(u8);

        fn increment_sys(mut counter: ResMut<Counter>) -> NonCopy {
            counter.0 += 1;
            NonCopy(counter.0)
        }

        let mut world = World::new();

        let id = world.register_system(increment_sys);

        // Insert the resource after registering the system.
        world.insert_resource(Counter(1));
        assert_eq!(*world.resource::<Counter>(), Counter(1));

        let output = world.run_system(id).expect("system runs successfully");
        assert_eq!(*world.resource::<Counter>(), Counter(2));
        assert_eq!(output, NonCopy(2));

        let output = world.run_system(id).expect("system runs successfully");
        assert_eq!(*world.resource::<Counter>(), Counter(3));
        assert_eq!(output, NonCopy(3));
    }

    #[test]
    fn fallible_system() {
        fn sys() -> Result<()> {
            Err("error")?;
            Ok(())
        }

        let mut world = World::new();
        let fallible_system_id = world.register_system(sys);
        let output = world.run_system(fallible_system_id);
        assert!(matches!(output, Ok(Err(_))));
    }

    #[test]
    fn exclusive_system() {
        let mut world = World::new();
        let exclusive_system_id = world.register_system(|world: &mut World| {
            world.spawn_empty();
        });
        let entity_count = world.entities.count_spawned();
        let _ = world.run_system(exclusive_system_id);
        assert_eq!(world.entities.count_spawned(), entity_count + 1);
    }

    #[test]
    fn nested_systems() {
        use crate::system::SystemId;

        #[derive(Component)]
        struct Callback(SystemId);

        fn nested(query: Query<&Callback>, mut commands: Commands) {
            for callback in query.iter() {
                commands.run_system(callback.0);
            }
        }

        let mut world = World::new();
        world.insert_resource(Counter(0));

        let increment_two = world.register_system(|mut counter: ResMut<Counter>| {
            counter.0 += 2;
        });
        let increment_three = world.register_system(|mut counter: ResMut<Counter>| {
            counter.0 += 3;
        });
        let nested_id = world.register_system(nested);

        world.spawn(Callback(increment_two));
        world.spawn(Callback(increment_three));
        let _ = world.run_system(nested_id);
        assert_eq!(*world.resource::<Counter>(), Counter(5));
    }

    #[test]
    fn nested_systems_with_inputs() {
        use crate::system::SystemId;

        #[derive(Component)]
        struct Callback(SystemId<In<u8>>, u8);

        fn nested(query: Query<&Callback>, mut commands: Commands) {
            for callback in query.iter() {
                commands.run_system_with(callback.0, callback.1);
            }
        }

        let mut world = World::new();
        world.insert_resource(Counter(0));

        let increment_by =
            world.register_system(|In(amt): In<u8>, mut counter: ResMut<Counter>| {
                counter.0 += amt;
            });
        let nested_id = world.register_system(nested);

        world.spawn(Callback(increment_by, 2));
        world.spawn(Callback(increment_by, 3));
        let _ = world.run_system(nested_id);
        assert_eq!(*world.resource::<Counter>(), Counter(5));
    }

    #[test]
    fn cached_system() {
        use crate::system::RegisteredSystemError;

        fn four() -> i32 {
            4
        }

        let mut world = World::new();
        let old = world.register_system_cached(four);
        let new = world.register_system_cached(four);
        assert_eq!(old, new);

        let result = world.unregister_system_cached(four);
        assert!(result.is_ok());
        let new = world.register_system_cached(four);
        assert_ne!(old, new);

        let output = world.run_system(old);
        assert!(matches!(
            output,
            Err(RegisteredSystemError::SystemIdNotRegistered(x)) if x == old,
        ));
        let output = world.run_system(new);
        assert!(matches!(output, Ok(x) if x == four()));
        let output = world.run_system_cached(four);
        assert!(matches!(output, Ok(x) if x == four()));
        let output = world.run_system_cached_with(four, ());
        assert!(matches!(output, Ok(x) if x == four()));
    }

    #[test]
    fn cached_fallible_system() {
        fn sys() -> Result<()> {
            Err("error")?;
            Ok(())
        }

        let mut world = World::new();
        let fallible_system_id = world.register_system_cached(sys);
        let output = world.run_system(fallible_system_id);
        assert!(matches!(output, Ok(Err(_))));
        let output = world.run_system_cached(sys);
        assert!(matches!(output, Ok(Err(_))));
        let output = world.run_system_cached_with(sys, ());
        assert!(matches!(output, Ok(Err(_))));
    }

    #[test]
    fn cached_system_commands() {
        fn sys(mut counter: ResMut<Counter>) {
            counter.0 += 1;
        }

        let mut world = World::new();
        world.insert_resource(Counter(0));
        world.commands().run_system_cached(sys);
        world.flush_commands();
        assert_eq!(world.resource::<Counter>().0, 1);
        world.commands().run_system_cached_with(sys, ());
        world.flush_commands();
        assert_eq!(world.resource::<Counter>().0, 2);
    }

    #[test]
    fn cached_fallible_system_commands() {
        fn sys(mut counter: ResMut<Counter>) -> Result {
            counter.0 += 1;
            Ok(())
        }

        let mut world = World::new();
        world.insert_resource(Counter(0));
        world.commands().run_system_cached(sys);
        world.flush_commands();
        assert_eq!(world.resource::<Counter>().0, 1);
        world.commands().run_system_cached_with(sys, ());
        world.flush_commands();
        assert_eq!(world.resource::<Counter>().0, 2);
    }

    #[test]
    #[should_panic(expected = "This system always fails")]
    fn cached_fallible_system_commands_can_fail() {
        use crate::system::command;
        fn sys() -> Result {
            Err("This system always fails".into())
        }

        let mut world = World::new();
        world.commands().queue(command::run_system_cached(sys));
        world.flush_commands();
    }

    #[test]
    fn cached_system_adapters() {
        fn four() -> i32 {
            4
        }

        fn double(In(i): In<i32>) -> i32 {
            i * 2
        }

        let mut world = World::new();

        let output = world.run_system_cached(four.pipe(double));
        assert!(matches!(output, Ok(8)));

        let output = world.run_system_cached(four.map(|i| i * 2));
        assert!(matches!(output, Ok(8)));
    }

    #[test]
    fn cached_system_into_same_system_type() {
        struct Foo;
        impl IntoSystem<(), (), ()> for Foo {
            type System = ApplyDeferred;
            fn into_system(_: Self) -> Self::System {
                ApplyDeferred
            }
        }

        struct Bar;
        impl IntoSystem<(), (), ()> for Bar {
            type System = ApplyDeferred;
            fn into_system(_: Self) -> Self::System {
                ApplyDeferred
            }
        }

        let mut world = World::new();
        let foo1 = world.register_system_cached(Foo);
        let foo2 = world.register_system_cached(Foo);
        let bar1 = world.register_system_cached(Bar);
        let bar2 = world.register_system_cached(Bar);

        // The `S: IntoSystem` types are different, so they should be cached
        // as separate systems, even though the `<S as IntoSystem>::System`
        // types / values are the same (`ApplyDeferred`).
        assert_ne!(foo1, bar1);

        // But if the `S: IntoSystem` types are the same, they'll be cached
        // as the same system.
        assert_eq!(foo1, foo2);
        assert_eq!(bar1, bar2);
    }

    #[test]
    fn system_with_input_ref() {
        fn with_ref(InRef(input): InRef<u8>, mut counter: ResMut<Counter>) {
            counter.0 += *input;
        }

        let mut world = World::new();
        world.insert_resource(Counter(0));

        let id = world.register_system(with_ref);
        world.run_system_with(id, &2).unwrap();
        assert_eq!(*world.resource::<Counter>(), Counter(2));
    }

    #[test]
    fn system_with_input_mut() {
        #[derive(Event)]
        struct MyEvent {
            cancelled: bool,
        }

        fn post(InMut(event): InMut<MyEvent>, counter: ResMut<Counter>) {
            if counter.0 > 0 {
                event.cancelled = true;
            }
        }

        let mut world = World::new();
        world.insert_resource(Counter(0));
        let post_system = world.register_system(post);

        let mut event = MyEvent { cancelled: false };
        world.run_system_with(post_system, &mut event).unwrap();
        assert!(!event.cancelled);

        world.resource_mut::<Counter>().0 = 1;
        world.run_system_with(post_system, &mut event).unwrap();
        assert!(event.cancelled);
    }

    #[test]
    fn run_system_invalid_params() {
        use crate::system::RegisteredSystemError;
        use alloc::string::ToString;

        #[derive(Resource)]
        struct T;

        fn system(_: Res<T>) {}

        let mut world = World::new();
        let id = world.register_system(system);
        // This fails because `T` has not been added to the world yet.
        let result = world.run_system(id);

        assert!(matches!(result, Err(RegisteredSystemError::Failed { .. })));
        let expected = "does not exist";
        let actual = result.unwrap_err().to_string();

        assert!(
            actual.contains(expected),
            "Expected error message to contain `{}` but got `{}`",
            expected,
            actual
        );
    }

    #[test]
    fn run_system_recursive() {
        std::thread_local! {
            static INVOCATIONS_LEFT: Cell<i32> = const { Cell::new(3) };
            static SYSTEM_ID: Cell<Option<SystemId>> = default();
        }

        fn system(mut commands: Commands) {
            let count = INVOCATIONS_LEFT.get() - 1;
            INVOCATIONS_LEFT.set(count);
            if count > 0 {
                commands.run_system(SYSTEM_ID.get().unwrap());
            }
        }

        let mut world = World::new();
        let id = world.register_system(system);
        SYSTEM_ID.set(Some(id));
        world.run_system(id).unwrap();

        assert_eq!(INVOCATIONS_LEFT.get(), 0);
    }

    #[test]
    fn run_system_exclusive_adapters() {
        let mut world = World::new();
        fn system(_: &mut World) {}
        world.run_system_cached(system).unwrap();
        world.run_system_cached(system.pipe(system)).unwrap();
        world.run_system_cached(system.map(|()| {})).unwrap();
    }

    #[test]
    fn wrong_system_type() {
        fn test() -> Result<(), u8> {
            Ok(())
        }

        let mut world = World::new();

        let entity = world.register_system_cached(test).entity();

        match world.run_system::<u8>(SystemId::from_entity(entity)) {
            Ok(_) => panic!("Should fail since called `run_system` with wrong SystemId type."),
            Err(RegisteredSystemError::IncorrectType(_, _)) => (),
            Err(err) => panic!("Failed with wrong error. `{:?}`", err),
        }
    }

    #[test]
    fn despawn_unused() {
        let mut world = World::new();

        fn system() {}

        let handle = world.register_tracked_system(system);
        let entity = handle.entity();
        drop(handle);

        assert!(world.get_entity(entity).is_ok());

        world
            .run_system_cached(despawn_unused_registered_systems)
            .unwrap();

        assert!(world.get_entity(entity).is_err());
    }

    #[test]
    fn system_handle_template() {
        fn my_system() {}

        let mut world = World::new();

        {
            let my_system_handle = world.register_tracked_system(my_system);
            let system_handle = world
                .spawn_empty()
                .build_template(&SystemHandleTemplate::Handle(my_system_handle.clone()))
                .unwrap();
            assert_eq!(system_handle, my_system_handle);
        }

        {
            let template = system_value(my_system);

            let a = world.spawn_empty().build_template(&template).unwrap();
            let b = world.spawn_empty().build_template(&template).unwrap();

            assert!(matches!(a, SystemHandle::Strong(_)));
            assert!(matches!(b, SystemHandle::Strong(_)));

            assert_eq!(a, b);
        }
    }

    #[test]
    fn run_system_with_owned_system_handle() {
        fn increment(mut counter: ResMut<Counter>) {
            counter.0 += 1;
        }

        let mut world = World::new();
        world.insert_resource(Counter(0));

        let handle = world.register_tracked_system(increment);
        world.run_system(handle).expect("system runs successfully");

        assert_eq!(*world.resource::<Counter>(), Counter(1));
    }
}