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
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
mod component_fetch;
mod entity_mut;
mod entity_ref;
mod entry;
mod except;
mod filtered;
mod world_mut;

pub use component_fetch::*;
pub use entity_mut::*;
pub use entity_ref::*;
pub use entry::*;
pub use except::*;
pub use filtered::*;
pub use world_mut::*;

#[cfg(test)]
mod tests {
    use alloc::{vec, vec::Vec};
    use bevy_ptr::{OwningPtr, Ptr};
    use core::panic::AssertUnwindSafe;
    use std::sync::OnceLock;

    use crate::change_detection::Tick;
    use crate::lifecycle::HookContext;
    use crate::query::QueryAccessError;
    use crate::{
        change_detection::{MaybeLocation, MutUntyped},
        component::ComponentId,
        prelude::*,
        resource::IsResource,
        system::{assert_is_system, RunSystemOnce as _},
        world::{error::EntityComponentError, DeferredWorld, FilteredEntityMut, FilteredEntityRef},
    };

    use super::{EntityMutExcept, EntityRefExcept};

    #[derive(Component, Clone, Copy, Debug, PartialEq)]
    struct TestComponent(u32);

    #[derive(Component, Clone, Copy, Debug, PartialEq)]
    #[component(storage = "SparseSet")]
    struct TestComponent2(u32);

    #[derive(Component)]
    struct Marker;

    #[derive(Component)]
    #[component(on_add = despawn_on_add)]
    struct DespawnOnAdd;

    fn despawn_on_add(mut world: DeferredWorld, HookContext { entity, .. }: HookContext) {
        world.commands().entity(entity).despawn();
    }

    #[test]
    fn entity_ref_get_by_id() {
        let mut world = World::new();
        let entity = world.spawn(TestComponent(42)).id();
        let component_id = world
            .components()
            .get_valid_id(core::any::TypeId::of::<TestComponent>())
            .unwrap();

        let entity = world.entity(entity);
        let test_component = entity.get_by_id(component_id).unwrap();
        // SAFETY: points to a valid `TestComponent`
        let test_component = unsafe { test_component.deref::<TestComponent>() };

        assert_eq!(test_component.0, 42);
    }

    #[test]
    fn entity_mut_get_by_id() {
        let mut world = World::new();
        let entity = world.spawn(TestComponent(42)).id();
        let component_id = world
            .components()
            .get_valid_id(core::any::TypeId::of::<TestComponent>())
            .unwrap();

        let mut entity_mut = world.entity_mut(entity);
        let mut test_component = entity_mut.get_mut_by_id(component_id).unwrap();
        {
            test_component.set_changed();
            let test_component =
                // SAFETY: `test_component` has unique access of the `EntityWorldMut` and is not used afterwards
                unsafe { test_component.into_inner().deref_mut::<TestComponent>() };
            test_component.0 = 43;
        }

        let entity = world.entity(entity);
        let test_component = entity.get_by_id(component_id).unwrap();
        // SAFETY: `TestComponent` is the correct component type
        let test_component = unsafe { test_component.deref::<TestComponent>() };

        assert_eq!(test_component.0, 43);
    }

    #[test]
    fn entity_ref_get_by_id_invalid_component_id() {
        let invalid_component_id = ComponentId::new(usize::MAX);

        let mut world = World::new();
        let entity = world.spawn_empty().id();
        let entity = world.entity(entity);
        assert!(entity.get_by_id(invalid_component_id).is_err());
    }

    #[test]
    fn entity_mut_get_by_id_invalid_component_id() {
        let invalid_component_id = ComponentId::new(usize::MAX);

        let mut world = World::new();
        let mut entity = world.spawn_empty();
        assert!(entity.get_by_id(invalid_component_id).is_err());
        assert!(entity.get_mut_by_id(invalid_component_id).is_err());
    }

    #[derive(Resource)]
    struct R(usize);

    #[test]
    fn entity_mut_resource_scope() {
        // Keep in sync with the `resource_scope` test in lib.rs
        let mut world = World::new();
        let mut entity = world.spawn_empty();

        assert!(entity.try_resource_scope::<R, _>(|_, _| {}).is_none());
        entity.world_scope(|world| world.insert_resource(R(0)));
        entity.resource_scope(|entity: &mut EntityWorldMut, mut value: Mut<R>| {
            value.0 += 1;
            assert!(!entity.world().contains_resource::<R>());
        });
        assert_eq!(entity.resource::<R>().0, 1);
    }

    #[test]
    fn entity_mut_resource_scope_panic() {
        let mut world = World::new();
        world.insert_resource(R(0));

        let mut entity = world.spawn_empty();
        let old_location = entity.location();
        let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
            entity.resource_scope(|entity: &mut EntityWorldMut, _: Mut<R>| {
                // Change the entity's `EntityLocation`.
                entity.insert(TestComponent(0));

                // Ensure that the entity location still gets updated even in case of a panic.
                panic!("this should get caught by the outer scope")
            });
        }));
        assert!(result.is_err());

        // Ensure that the location has been properly updated.
        assert_ne!(entity.location(), old_location);
    }

    // regression test for https://github.com/bevyengine/bevy/pull/7387
    #[test]
    fn entity_mut_world_scope_panic() {
        let mut world = World::new();

        let mut entity = world.spawn_empty();
        let old_location = entity.location();
        let id = entity.id();
        let res = std::panic::catch_unwind(AssertUnwindSafe(|| {
            entity.world_scope(|w| {
                // Change the entity's `EntityLocation`, which invalidates the original `EntityWorldMut`.
                // This will get updated at the end of the scope.
                w.entity_mut(id).insert(TestComponent(0));

                // Ensure that the entity location still gets updated even in case of a panic.
                panic!("this should get caught by the outer scope")
            });
        }));
        assert!(res.is_err());

        // Ensure that the location has been properly updated.
        assert_ne!(entity.location(), old_location);
    }

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

        let mut entity = world.spawn_empty();
        let old_location = entity.location();
        let res = std::panic::catch_unwind(AssertUnwindSafe(|| {
            entity.reborrow_scope(|mut entity| {
                // Change the entity's `EntityLocation`, which invalidates the original `EntityWorldMut`.
                // This will get updated at the end of the scope.
                entity.insert(TestComponent(0));

                // Ensure that the entity location still gets updated even in case of a panic.
                panic!("this should get caught by the outer scope")
            });
        }));
        assert!(res.is_err());

        // Ensure that the location has been properly updated.
        assert_ne!(entity.location(), old_location);
    }

    // regression test for https://github.com/bevyengine/bevy/pull/7805
    #[test]
    fn removing_sparse_updates_archetype_row() {
        #[derive(Component, PartialEq, Debug)]
        struct Dense(u8);

        #[derive(Component)]
        #[component(storage = "SparseSet")]
        struct Sparse;

        let mut world = World::new();
        let e1 = world.spawn((Dense(0), Sparse)).id();
        let e2 = world.spawn((Dense(1), Sparse)).id();

        world.entity_mut(e1).remove::<Sparse>();
        assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
    }

    // regression test for https://github.com/bevyengine/bevy/pull/7805
    #[test]
    fn removing_dense_updates_table_row() {
        #[derive(Component, PartialEq, Debug)]
        struct Dense(u8);

        #[derive(Component)]
        #[component(storage = "SparseSet")]
        struct Sparse;

        let mut world = World::new();
        let e1 = world.spawn((Dense(0), Sparse)).id();
        let e2 = world.spawn((Dense(1), Sparse)).id();

        world.entity_mut(e1).remove::<Dense>();
        assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
    }

    // Test that calling retain with `()` removes all components.
    #[test]
    fn retain_nothing() {
        #[derive(Component)]
        struct Marker<const N: usize>;

        let mut world = World::new();
        let ent = world.spawn((Marker::<1>, Marker::<2>, Marker::<3>)).id();

        world.entity_mut(ent).retain::<()>();
        assert_eq!(world.entity(ent).archetype().components().len(), 0);
    }

    // Test removing some components with `retain`, including components not on the entity.
    #[test]
    fn retain_some_components() {
        #[derive(Component)]
        struct Marker<const N: usize>;

        let mut world = World::new();
        let ent = world.spawn((Marker::<1>, Marker::<2>, Marker::<3>)).id();

        world.entity_mut(ent).retain::<(Marker<2>, Marker<4>)>();
        // Check that marker 2 was retained.
        assert!(world.entity(ent).get::<Marker<2>>().is_some());
        // Check that only marker 2 was retained.
        assert_eq!(world.entity(ent).archetype().components().len(), 1);
    }

    // regression test for https://github.com/bevyengine/bevy/pull/7805
    #[test]
    fn inserting_sparse_updates_archetype_row() {
        #[derive(Component, PartialEq, Debug)]
        struct Dense(u8);

        #[derive(Component)]
        #[component(storage = "SparseSet")]
        struct Sparse;

        let mut world = World::new();
        let e1 = world.spawn(Dense(0)).id();
        let e2 = world.spawn(Dense(1)).id();

        world.entity_mut(e1).insert(Sparse);
        assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
    }

    // regression test for https://github.com/bevyengine/bevy/pull/7805
    #[test]
    fn inserting_dense_updates_archetype_row() {
        #[derive(Component, PartialEq, Debug)]
        struct Dense(u8);

        #[derive(Component)]
        struct Dense2;

        #[derive(Component)]
        #[component(storage = "SparseSet")]
        struct Sparse;

        let mut world = World::new();
        let e1 = world.spawn(Dense(0)).id();
        let e2 = world.spawn(Dense(1)).id();

        world.entity_mut(e1).insert(Sparse).remove::<Sparse>();

        // archetype with [e2, e1]
        // table with [e1, e2]

        world.entity_mut(e2).insert(Dense2);

        assert_eq!(world.entity(e1).get::<Dense>().unwrap(), &Dense(0));
    }

    #[test]
    fn inserting_dense_updates_table_row() {
        #[derive(Component, PartialEq, Debug)]
        struct Dense(u8);

        #[derive(Component)]
        struct Dense2;

        #[derive(Component)]
        #[component(storage = "SparseSet")]
        struct Sparse;

        let mut world = World::new();
        let e1 = world.spawn(Dense(0)).id();
        let e2 = world.spawn(Dense(1)).id();

        world.entity_mut(e1).insert(Sparse).remove::<Sparse>();

        // archetype with [e2, e1]
        // table with [e1, e2]

        world.entity_mut(e1).insert(Dense2);

        assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
    }

    // regression test for https://github.com/bevyengine/bevy/pull/7805
    #[test]
    fn despawning_entity_updates_archetype_row() {
        #[derive(Component, PartialEq, Debug)]
        struct Dense(u8);

        #[derive(Component)]
        #[component(storage = "SparseSet")]
        struct Sparse;

        let mut world = World::new();
        let e1 = world.spawn(Dense(0)).id();
        let e2 = world.spawn(Dense(1)).id();

        world.entity_mut(e1).insert(Sparse).remove::<Sparse>();

        // archetype with [e2, e1]
        // table with [e1, e2]

        world.entity_mut(e2).despawn();

        assert_eq!(world.entity(e1).get::<Dense>().unwrap(), &Dense(0));
    }

    // regression test for https://github.com/bevyengine/bevy/pull/7805
    #[test]
    fn despawning_entity_updates_table_row() {
        #[derive(Component, PartialEq, Debug)]
        struct Dense(u8);

        #[derive(Component)]
        #[component(storage = "SparseSet")]
        struct Sparse;

        let mut world = World::new();
        let e1 = world.spawn(Dense(0)).id();
        let e2 = world.spawn(Dense(1)).id();

        world.entity_mut(e1).insert(Sparse).remove::<Sparse>();

        // archetype with [e2, e1]
        // table with [e1, e2]

        world.entity_mut(e1).despawn();

        assert_eq!(world.entity(e2).get::<Dense>().unwrap(), &Dense(1));
    }

    #[test]
    fn entity_mut_insert_by_id() {
        let mut world = World::new();
        let test_component_id = world.register_component::<TestComponent>();

        let mut entity = world.spawn_empty();
        OwningPtr::make(TestComponent(42), |ptr| {
            // SAFETY: `ptr` matches the component id
            unsafe { entity.insert_by_id(test_component_id, ptr) };
        });

        let components: Vec<_> = world.query::<&TestComponent>().iter(&world).collect();

        assert_eq!(components, vec![&TestComponent(42)]);

        // Compare with `insert_bundle_by_id`

        let mut entity = world.spawn_empty();
        OwningPtr::make(TestComponent(84), |ptr| {
            // SAFETY: `ptr` matches the component id
            unsafe { entity.insert_by_ids(&[test_component_id], vec![ptr].into_iter()) };
        });

        let components: Vec<_> = world.query::<&TestComponent>().iter(&world).collect();

        assert_eq!(components, vec![&TestComponent(42), &TestComponent(84)]);
    }

    #[test]
    fn entity_mut_insert_bundle_by_id() {
        let mut world = World::new();
        let test_component_id = world.register_component::<TestComponent>();
        let test_component_2_id = world.register_component::<TestComponent2>();

        let component_ids = [test_component_id, test_component_2_id];
        let test_component_value = TestComponent(42);
        let test_component_2_value = TestComponent2(84);

        let mut entity = world.spawn_empty();
        OwningPtr::make(test_component_value, |ptr1| {
            OwningPtr::make(test_component_2_value, |ptr2| {
                // SAFETY: `ptr1` and `ptr2` match the component ids
                unsafe { entity.insert_by_ids(&component_ids, vec![ptr1, ptr2].into_iter()) };
            });
        });

        let dynamic_components: Vec<_> = world
            .query::<(&TestComponent, &TestComponent2)>()
            .iter(&world)
            .collect();

        assert_eq!(
            dynamic_components,
            vec![(&TestComponent(42), &TestComponent2(84))]
        );

        // Compare with `World` generated using static type equivalents
        let mut static_world = World::new();

        static_world.spawn((test_component_value, test_component_2_value));
        let static_components: Vec<_> = static_world
            .query::<(&TestComponent, &TestComponent2)>()
            .iter(&static_world)
            .collect();

        assert_eq!(dynamic_components, static_components);
    }

    #[test]
    fn entity_mut_remove_by_id() {
        let mut world = World::new();
        let test_component_id = world.register_component::<TestComponent>();

        let mut entity = world.spawn(TestComponent(42));
        entity.remove_by_id(test_component_id);

        let components: Vec<_> = world.query::<&TestComponent>().iter(&world).collect();

        assert_eq!(components, vec![] as Vec<&TestComponent>);

        // remove non-existent component does not panic
        world.spawn_empty().remove_by_id(test_component_id);
    }

    /// Tests that components can be accessed through an `EntityRefExcept`.
    #[test]
    fn entity_ref_except() {
        let mut world = World::new();
        world.register_component::<TestComponent>();
        world.register_component::<TestComponent2>();

        world.spawn((TestComponent(0), TestComponent2(0), Marker));

        let mut query = world.query_filtered::<EntityRefExcept<TestComponent>, With<Marker>>();

        let mut found = false;
        for entity_ref in query.iter_mut(&mut world) {
            found = true;
            assert!(entity_ref.get::<TestComponent>().is_none());
            assert!(entity_ref.get_ref::<TestComponent>().is_none());
            assert!(matches!(
                entity_ref.get::<TestComponent2>(),
                Some(TestComponent2(0))
            ));
        }

        assert!(found);
    }

    // Test that a single query can't both contain a mutable reference to a
    // component C and an `EntityRefExcept` that doesn't include C among its
    // exclusions.
    #[test]
    #[should_panic]
    fn entity_ref_except_conflicts_with_self() {
        let mut world = World::new();
        world.spawn(TestComponent(0)).insert(TestComponent2(0));

        // This should panic, because we have a mutable borrow on
        // `TestComponent` but have a simultaneous indirect immutable borrow on
        // that component via `EntityRefExcept`.
        world.run_system_once(system).unwrap();

        fn system(_: Query<(&mut TestComponent, EntityRefExcept<TestComponent2>)>) {}
    }

    // Test that an `EntityRefExcept` that doesn't include a component C among
    // its exclusions can't coexist with a mutable query for that component.
    #[test]
    #[should_panic]
    fn entity_ref_except_conflicts_with_other() {
        let mut world = World::new();
        world.spawn(TestComponent(0)).insert(TestComponent2(0));

        // This should panic, because we have a mutable borrow on
        // `TestComponent` but have a simultaneous indirect immutable borrow on
        // that component via `EntityRefExcept`.
        world.run_system_once(system).unwrap();

        fn system(_: Query<&mut TestComponent>, _: Query<EntityRefExcept<TestComponent2>>) {}
    }

    // Test that an `EntityRefExcept` with an exception for some component C can
    // coexist with a query for that component C.
    #[test]
    fn entity_ref_except_doesnt_conflict() {
        let mut world = World::new();
        world.spawn((TestComponent(0), TestComponent2(0), Marker));

        world.run_system_once(system).unwrap();

        fn system(
            _: Query<&mut TestComponent, With<Marker>>,
            query: Query<EntityRefExcept<TestComponent>, With<Marker>>,
        ) {
            for entity_ref in query.iter() {
                assert!(matches!(
                    entity_ref.get::<TestComponent2>(),
                    Some(TestComponent2(0))
                ));
            }
        }
    }

    /// Tests that components can be mutably accessed through an
    /// `EntityMutExcept`.
    #[test]
    fn entity_mut_except() {
        let mut world = World::new();
        world.spawn((TestComponent(0), TestComponent2(0), Marker));

        let mut query = world.query_filtered::<EntityMutExcept<TestComponent>, With<Marker>>();

        let mut found = false;
        for mut entity_mut in query.iter_mut(&mut world) {
            found = true;
            assert!(entity_mut.get::<TestComponent>().is_none());
            assert!(entity_mut.get_ref::<TestComponent>().is_none());
            assert!(entity_mut.get_mut::<TestComponent>().is_none());
            assert!(matches!(
                entity_mut.get::<TestComponent2>(),
                Some(TestComponent2(0))
            ));
        }

        assert!(found);
    }

    // Test that a single query can't both contain a mutable reference to a
    // component C and an `EntityMutExcept` that doesn't include C among its
    // exclusions.
    #[test]
    #[should_panic]
    fn entity_mut_except_conflicts_with_self() {
        let mut world = World::new();
        world.spawn(TestComponent(0)).insert(TestComponent2(0));

        // This should panic, because we have a mutable borrow on
        // `TestComponent` but have a simultaneous indirect immutable borrow on
        // that component via `EntityRefExcept`.
        world.run_system_once(system).unwrap();

        fn system(_: Query<(&mut TestComponent, EntityMutExcept<TestComponent2>)>) {}
    }

    // Test that an `EntityMutExcept` that doesn't include a component C among
    // its exclusions can't coexist with a query for that component.
    #[test]
    #[should_panic]
    fn entity_mut_except_conflicts_with_other() {
        let mut world = World::new();
        world.spawn(TestComponent(0)).insert(TestComponent2(0));

        // This should panic, because we have a mutable borrow on
        // `TestComponent` but have a simultaneous indirect immutable borrow on
        // that component via `EntityRefExcept`.
        world.run_system_once(system).unwrap();

        fn system(_: Query<&mut TestComponent>, mut query: Query<EntityMutExcept<TestComponent2>>) {
            for mut entity_mut in query.iter_mut() {
                assert!(entity_mut
                    .get_mut::<TestComponent2>()
                    .is_some_and(|component| component.0 == 0));
            }
        }
    }

    // Test that an `EntityMutExcept` with an exception for some component C can
    // coexist with a query for that component C.
    #[test]
    fn entity_mut_except_doesnt_conflict() {
        let mut world = World::new();
        world.spawn((TestComponent(0), TestComponent2(0), Marker));

        world.run_system_once(system).unwrap();

        fn system(
            _: Query<&mut TestComponent, With<Marker>>,
            mut query: Query<EntityMutExcept<TestComponent>, With<Marker>>,
        ) {
            for mut entity_mut in query.iter_mut() {
                assert!(entity_mut
                    .get_mut::<TestComponent2>()
                    .is_some_and(|component| component.0 == 0));
            }
        }
    }

    #[test]
    fn entity_mut_except_registers_components() {
        // Checks for a bug where `EntityMutExcept` would not register the component and
        // would therefore not include an exception, causing it to conflict with the later query.
        fn system1(_query: Query<EntityMutExcept<TestComponent>>, _: Query<&mut TestComponent>) {}
        let mut world = World::new();
        world.run_system_once(system1).unwrap();

        fn system2(_: Query<&mut TestComponent>, _query: Query<EntityMutExcept<TestComponent>>) {}
        let mut world = World::new();
        world.run_system_once(system2).unwrap();
    }

    #[derive(Component)]
    struct A;

    #[test]
    fn disjoint_access() {
        fn disjoint_readonly(_: Query<EntityMut, With<A>>, _: Query<EntityRef, Without<A>>) {}

        fn disjoint_mutable(_: Query<EntityMut, With<A>>, _: Query<EntityMut, Without<A>>) {}

        assert_is_system(disjoint_readonly);
        assert_is_system(disjoint_mutable);
    }

    #[test]
    fn ref_compatible() {
        fn borrow_system(_: Query<(EntityRef, &A)>, _: Query<&A>) {}

        assert_is_system(borrow_system);
    }

    #[test]
    fn ref_compatible_with_resource() {
        fn borrow_system(_: Query<EntityRef>, _: Res<R>) {}

        assert_is_system(borrow_system);
    }

    #[test]
    #[should_panic]
    fn ref_incompatible_with_resource_mut() {
        fn borrow_system(_: Query<EntityRef>, _: ResMut<R>) {}

        assert_is_system(borrow_system);
    }

    #[test]
    fn ref_compatible_with_resource_mut() {
        fn borrow_system(_: Query<EntityRef, Without<IsResource>>, _: ResMut<R>) {}

        assert_is_system(borrow_system);
    }

    #[test]
    #[should_panic]
    fn ref_incompatible_with_mutable_component() {
        fn incompatible_system(_: Query<(EntityRef, &mut A)>) {}

        assert_is_system(incompatible_system);
    }

    #[test]
    #[should_panic]
    fn ref_incompatible_with_mutable_query() {
        fn incompatible_system(_: Query<EntityRef>, _: Query<&mut A>) {}

        assert_is_system(incompatible_system);
    }

    #[test]
    fn mut_compatible_with_entity() {
        fn borrow_mut_system(_: Query<(Entity, EntityMut)>) {}

        assert_is_system(borrow_mut_system);
    }

    #[test]
    #[should_panic]
    fn mut_incompatible_with_resource() {
        fn borrow_mut_system(_: Res<R>, _: Query<EntityMut>) {}

        assert_is_system(borrow_mut_system);
    }

    #[test]
    #[should_panic]
    fn mut_incompatible_with_resource_mut() {
        fn borrow_mut_system(_: ResMut<R>, _: Query<EntityMut>) {}

        assert_is_system(borrow_mut_system);
    }

    #[test]
    fn mut_compatible_with_resource() {
        fn borrow_mut_system(_: Res<R>, _: Query<EntityMut, Without<IsResource>>) {}

        assert_is_system(borrow_mut_system);
    }

    #[test]
    fn mut_compatible_with_resource_mut() {
        fn borrow_mut_system(_: ResMut<R>, _: Query<EntityMut, Without<IsResource>>) {}

        assert_is_system(borrow_mut_system);
    }

    #[test]
    #[should_panic]
    fn mut_incompatible_with_read_only_component() {
        fn incompatible_system(_: Query<(EntityMut, &A)>) {}

        assert_is_system(incompatible_system);
    }

    #[test]
    #[should_panic]
    fn mut_incompatible_with_mutable_component() {
        fn incompatible_system(_: Query<(EntityMut, &mut A)>) {}

        assert_is_system(incompatible_system);
    }

    #[test]
    #[should_panic]
    fn mut_incompatible_with_read_only_query() {
        fn incompatible_system(_: Query<EntityMut>, _: Query<&A>) {}

        assert_is_system(incompatible_system);
    }

    #[test]
    #[should_panic]
    fn mut_incompatible_with_mutable_query() {
        fn incompatible_system(_: Query<EntityMut>, _: Query<&mut A>) {}

        assert_is_system(incompatible_system);
    }

    #[test]
    fn filtered_entity_ref_normal() {
        let mut world = World::new();
        let a_id = world.register_component::<A>();

        let e: FilteredEntityRef = world.spawn(A).into();

        assert!(e.get::<A>().is_some());
        assert!(e.get_ref::<A>().is_some());
        assert!(e.get_change_ticks::<A>().is_some());
        assert!(e.get_by_id(a_id).is_some());
        assert!(e.get_change_ticks_by_id(a_id).is_some());
    }

    #[test]
    fn filtered_entity_ref_missing() {
        let mut world = World::new();
        let a_id = world.register_component::<A>();

        let e: FilteredEntityRef = world.spawn(()).into();

        assert!(e.get::<A>().is_none());
        assert!(e.get_ref::<A>().is_none());
        assert!(e.get_change_ticks::<A>().is_none());
        assert!(e.get_by_id(a_id).is_none());
        assert!(e.get_change_ticks_by_id(a_id).is_none());
    }

    #[test]
    fn filtered_entity_mut_normal() {
        let mut world = World::new();
        let a_id = world.register_component::<A>();

        let mut e: FilteredEntityMut = world.spawn(A).into();

        assert!(e.get::<A>().is_some());
        assert!(e.get_ref::<A>().is_some());
        assert!(e.get_mut::<A>().is_some());
        assert!(e.get_change_ticks::<A>().is_some());
        assert!(e.get_by_id(a_id).is_some());
        assert!(e.get_mut_by_id(a_id).is_some());
        assert!(e.get_change_ticks_by_id(a_id).is_some());
    }

    #[test]
    fn filtered_entity_mut_missing() {
        let mut world = World::new();
        let a_id = world.register_component::<A>();

        let mut e: FilteredEntityMut = world.spawn(()).into();

        assert!(e.get::<A>().is_none());
        assert!(e.get_ref::<A>().is_none());
        assert!(e.get_mut::<A>().is_none());
        assert!(e.get_change_ticks::<A>().is_none());
        assert!(e.get_by_id(a_id).is_none());
        assert!(e.get_mut_by_id(a_id).is_none());
        assert!(e.get_change_ticks_by_id(a_id).is_none());
    }

    #[derive(Component, PartialEq, Eq, Debug)]
    struct X(usize);

    #[derive(Component, PartialEq, Eq, Debug)]
    struct Y(usize);

    #[test]
    fn get_components() {
        let mut world = World::default();
        let e1 = world.spawn((X(7), Y(10))).id();
        let e2 = world.spawn(X(8)).id();
        let e3 = world.spawn_empty().id();

        assert_eq!(
            Ok((&X(7), &Y(10))),
            world.entity(e1).get_components::<(&X, &Y)>()
        );
        assert_eq!(
            Err(QueryAccessError::EntityDoesNotMatch),
            world.entity(e2).get_components::<(&X, &Y)>()
        );
        assert_eq!(
            Err(QueryAccessError::EntityDoesNotMatch),
            world.entity(e3).get_components::<(&X, &Y)>()
        );
    }

    #[test]
    fn get_components_mut() {
        let mut world = World::default();
        let e1 = world.spawn((X(7), Y(10))).id();

        let mut entity_mut_1 = world.entity_mut(e1);
        let Ok((mut x, mut y)) = entity_mut_1.get_components_mut::<(&mut X, &mut Y)>() else {
            panic!("could not get components");
        };
        x.0 += 1;
        y.0 += 1;

        assert_eq!(
            Ok((&X(8), &Y(11))),
            world.entity(e1).get_components::<(&X, &Y)>()
        );
    }

    #[test]
    fn get_by_id_array() {
        let mut world = World::default();
        let e1 = world.spawn((X(7), Y(10))).id();
        let e2 = world.spawn(X(8)).id();
        let e3 = world.spawn_empty().id();

        let x_id = world.register_component::<X>();
        let y_id = world.register_component::<Y>();

        assert_eq!(
            Ok((&X(7), &Y(10))),
            world
                .entity(e1)
                .get_by_id([x_id, y_id])
                .map(|[x_ptr, y_ptr]| {
                    // SAFETY: components match the id they were fetched with
                    (unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
                })
        );
        assert_eq!(
            Err(EntityComponentError::MissingComponent(y_id)),
            world
                .entity(e2)
                .get_by_id([x_id, y_id])
                .map(|[x_ptr, y_ptr]| {
                    // SAFETY: components match the id they were fetched with
                    (unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
                })
        );
        assert_eq!(
            Err(EntityComponentError::MissingComponent(x_id)),
            world
                .entity(e3)
                .get_by_id([x_id, y_id])
                .map(|[x_ptr, y_ptr]| {
                    // SAFETY: components match the id they were fetched with
                    (unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
                })
        );
    }

    #[test]
    fn get_by_id_vec() {
        let mut world = World::default();
        let e1 = world.spawn((X(7), Y(10))).id();
        let e2 = world.spawn(X(8)).id();
        let e3 = world.spawn_empty().id();

        let x_id = world.register_component::<X>();
        let y_id = world.register_component::<Y>();

        assert_eq!(
            Ok((&X(7), &Y(10))),
            world
                .entity(e1)
                .get_by_id(&[x_id, y_id] as &[ComponentId])
                .map(|ptrs| {
                    let Ok([x_ptr, y_ptr]): Result<[Ptr; 2], _> = ptrs.try_into() else {
                        panic!("get_by_id(slice) didn't return 2 elements")
                    };

                    // SAFETY: components match the id they were fetched with
                    (unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
                })
        );
        assert_eq!(
            Err(EntityComponentError::MissingComponent(y_id)),
            world
                .entity(e2)
                .get_by_id(&[x_id, y_id] as &[ComponentId])
                .map(|ptrs| {
                    let Ok([x_ptr, y_ptr]): Result<[Ptr; 2], _> = ptrs.try_into() else {
                        panic!("get_by_id(slice) didn't return 2 elements")
                    };

                    // SAFETY: components match the id they were fetched with
                    (unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
                })
        );
        assert_eq!(
            Err(EntityComponentError::MissingComponent(x_id)),
            world
                .entity(e3)
                .get_by_id(&[x_id, y_id] as &[ComponentId])
                .map(|ptrs| {
                    let Ok([x_ptr, y_ptr]): Result<[Ptr; 2], _> = ptrs.try_into() else {
                        panic!("get_by_id(slice) didn't return 2 elements")
                    };

                    // SAFETY: components match the id they were fetched with
                    (unsafe { x_ptr.deref::<X>() }, unsafe { y_ptr.deref::<Y>() })
                })
        );
    }

    #[test]
    fn get_mut_by_id_array() {
        let mut world = World::default();
        let e1 = world.spawn((X(7), Y(10))).id();
        let e2 = world.spawn(X(8)).id();
        let e3 = world.spawn_empty().id();

        let x_id = world.register_component::<X>();
        let y_id = world.register_component::<Y>();

        assert_eq!(
            Ok((&mut X(7), &mut Y(10))),
            world
                .entity_mut(e1)
                .get_mut_by_id([x_id, y_id])
                .map(|[x_ptr, y_ptr]| {
                    // SAFETY: components match the id they were fetched with
                    (unsafe { x_ptr.into_inner().deref_mut::<X>() }, unsafe {
                        y_ptr.into_inner().deref_mut::<Y>()
                    })
                })
        );
        assert_eq!(
            Err(EntityComponentError::MissingComponent(y_id)),
            world
                .entity_mut(e2)
                .get_mut_by_id([x_id, y_id])
                .map(|[x_ptr, y_ptr]| {
                    // SAFETY: components match the id they were fetched with
                    (unsafe { x_ptr.into_inner().deref_mut::<X>() }, unsafe {
                        y_ptr.into_inner().deref_mut::<Y>()
                    })
                })
        );
        assert_eq!(
            Err(EntityComponentError::MissingComponent(x_id)),
            world
                .entity_mut(e3)
                .get_mut_by_id([x_id, y_id])
                .map(|[x_ptr, y_ptr]| {
                    // SAFETY: components match the id they were fetched with
                    (unsafe { x_ptr.into_inner().deref_mut::<X>() }, unsafe {
                        y_ptr.into_inner().deref_mut::<Y>()
                    })
                })
        );

        assert_eq!(
            Err(EntityComponentError::AliasedMutability(x_id)),
            world
                .entity_mut(e1)
                .get_mut_by_id([x_id, x_id])
                .map(|_| { unreachable!() })
        );
        assert_eq!(
            Err(EntityComponentError::AliasedMutability(x_id)),
            world
                .entity_mut(e3)
                .get_mut_by_id([x_id, x_id])
                .map(|_| { unreachable!() })
        );
    }

    #[test]
    fn get_mut_by_id_vec() {
        let mut world = World::default();
        let e1 = world.spawn((X(7), Y(10))).id();
        let e2 = world.spawn(X(8)).id();
        let e3 = world.spawn_empty().id();

        let x_id = world.register_component::<X>();
        let y_id = world.register_component::<Y>();

        assert_eq!(
            Ok((&mut X(7), &mut Y(10))),
            world
                .entity_mut(e1)
                .get_mut_by_id(&[x_id, y_id] as &[ComponentId])
                .map(|ptrs| {
                    let Ok([x_ptr, y_ptr]): Result<[MutUntyped; 2], _> = ptrs.try_into() else {
                        panic!("get_mut_by_id(slice) didn't return 2 elements")
                    };

                    // SAFETY: components match the id they were fetched with
                    (unsafe { x_ptr.into_inner().deref_mut::<X>() }, unsafe {
                        y_ptr.into_inner().deref_mut::<Y>()
                    })
                })
        );
        assert_eq!(
            Err(EntityComponentError::MissingComponent(y_id)),
            world
                .entity_mut(e2)
                .get_mut_by_id(&[x_id, y_id] as &[ComponentId])
                .map(|ptrs| {
                    let Ok([x_ptr, y_ptr]): Result<[MutUntyped; 2], _> = ptrs.try_into() else {
                        panic!("get_mut_by_id(slice) didn't return 2 elements")
                    };

                    // SAFETY: components match the id they were fetched with
                    (unsafe { x_ptr.into_inner().deref_mut::<X>() }, unsafe {
                        y_ptr.into_inner().deref_mut::<Y>()
                    })
                })
        );
        assert_eq!(
            Err(EntityComponentError::MissingComponent(x_id)),
            world
                .entity_mut(e3)
                .get_mut_by_id(&[x_id, y_id] as &[ComponentId])
                .map(|ptrs| {
                    let Ok([x_ptr, y_ptr]): Result<[MutUntyped; 2], _> = ptrs.try_into() else {
                        panic!("get_mut_by_id(slice) didn't return 2 elements")
                    };

                    // SAFETY: components match the id they were fetched with
                    (unsafe { x_ptr.into_inner().deref_mut::<X>() }, unsafe {
                        y_ptr.into_inner().deref_mut::<Y>()
                    })
                })
        );

        assert_eq!(
            Err(EntityComponentError::AliasedMutability(x_id)),
            world
                .entity_mut(e1)
                .get_mut_by_id(&[x_id, x_id])
                .map(|_| { unreachable!() })
        );
        assert_eq!(
            Err(EntityComponentError::AliasedMutability(x_id)),
            world
                .entity_mut(e3)
                .get_mut_by_id(&[x_id, x_id])
                .map(|_| { unreachable!() })
        );
    }

    #[test]
    fn get_mut_by_id_unchecked() {
        let mut world = World::default();
        let e1 = world.spawn((X(7), Y(10))).id();
        let x_id = world.register_component::<X>();
        let y_id = world.register_component::<Y>();

        let e1_mut = &world.get_entity_mut([e1]).unwrap()[0];
        // SAFETY: The entity e1 contains component X.
        let x_ptr = unsafe { e1_mut.get_mut_by_id_unchecked(x_id) }.unwrap();
        // SAFETY: The entity e1 contains component Y, with components X and Y being mutually independent.
        let y_ptr = unsafe { e1_mut.get_mut_by_id_unchecked(y_id) }.unwrap();

        // SAFETY: components match the id they were fetched with
        let x_component = unsafe { x_ptr.into_inner().deref_mut::<X>() };
        x_component.0 += 1;
        // SAFETY: components match the id they were fetched with
        let y_component = unsafe { y_ptr.into_inner().deref_mut::<Y>() };
        y_component.0 -= 1;

        assert_eq!((&mut X(8), &mut Y(9)), (x_component, y_component));
    }

    #[derive(EntityEvent)]
    struct TestEvent(Entity);

    #[test]
    fn adding_observer_updates_location() {
        let mut world = World::new();
        let entity = world
            .spawn_empty()
            .observe(|event: On<TestEvent>, mut commands: Commands| {
                commands
                    .entity(event.event_target())
                    .insert(TestComponent(0));
            })
            .id();

        // this should not be needed, but is currently required to tease out the bug
        world.flush();

        let mut a = world.entity_mut(entity);
        // SAFETY: this _intentionally_ doesn't update the location, to ensure that we're actually testing
        // that observe() updates location
        unsafe { a.world_mut().trigger(TestEvent(entity)) }
        a.observe(|_: On<TestEvent>| {}); // this flushes commands implicitly by spawning
        let location = a.location();
        assert_eq!(world.entities().get(entity).unwrap(), Some(location));
    }

    #[test]
    #[should_panic]
    fn location_on_despawned_entity_panics() {
        let mut world = World::new();
        world.add_observer(|add: On<Add, TestComponent>, mut commands: Commands| {
            commands.entity(add.entity).despawn();
        });
        let entity = world.spawn_empty().id();
        let mut a = world.entity_mut(entity);
        a.insert(TestComponent(0));
        a.location();
    }

    #[derive(Resource)]
    struct TestFlush(usize);

    fn count_flush(world: &mut World) {
        world.resource_mut::<TestFlush>().0 += 1;
    }

    #[test]
    fn archetype_modifications_trigger_flush() {
        let mut world = World::new();
        world.insert_resource(TestFlush(0));
        world.add_observer(|_: On<Add, TestComponent>, mut commands: Commands| {
            commands.queue(count_flush);
        });
        world.add_observer(|_: On<Remove, TestComponent>, mut commands: Commands| {
            commands.queue(count_flush);
        });

        // Spawning an empty should not flush.
        world.commands().queue(count_flush);
        let entity = world.spawn_empty().id();
        assert_eq!(world.resource::<TestFlush>().0, 0);

        world.commands().queue(count_flush);
        world.flush_commands();

        let mut a = world.entity_mut(entity);
        assert_eq!(a.world().resource::<TestFlush>().0, 2);
        a.insert(TestComponent(0));
        assert_eq!(a.world().resource::<TestFlush>().0, 3);
        a.remove::<TestComponent>();
        assert_eq!(a.world().resource::<TestFlush>().0, 4);
        a.insert(TestComponent(0));
        assert_eq!(a.world().resource::<TestFlush>().0, 5);
        let _ = a.take::<TestComponent>();
        assert_eq!(a.world().resource::<TestFlush>().0, 6);
        a.insert(TestComponent(0));
        assert_eq!(a.world().resource::<TestFlush>().0, 7);
        a.retain::<()>();
        assert_eq!(a.world().resource::<TestFlush>().0, 8);
        a.insert(TestComponent(0));
        assert_eq!(a.world().resource::<TestFlush>().0, 9);
        a.clear();
        assert_eq!(a.world().resource::<TestFlush>().0, 10);
        a.insert(TestComponent(0));
        assert_eq!(a.world().resource::<TestFlush>().0, 11);
        a.despawn();
        assert_eq!(world.resource::<TestFlush>().0, 12);
    }

    #[derive(Resource)]
    struct TestVec(Vec<&'static str>);

    #[derive(Component)]
    #[component(on_add = ord_a_hook_on_add, on_insert = ord_a_hook_on_insert, on_discard = ord_a_hook_on_discard, on_remove = ord_a_hook_on_remove)]
    struct OrdA;

    fn ord_a_hook_on_add(mut world: DeferredWorld, HookContext { entity, .. }: HookContext) {
        world.resource_mut::<TestVec>().0.push("OrdA hook on_add");
        world.commands().entity(entity).insert(OrdB);
    }

    fn ord_a_hook_on_insert(mut world: DeferredWorld, HookContext { entity, .. }: HookContext) {
        world
            .resource_mut::<TestVec>()
            .0
            .push("OrdA hook on_insert");
        world.commands().entity(entity).remove::<OrdA>();
        world.commands().entity(entity).remove::<OrdB>();
    }

    fn ord_a_hook_on_discard(mut world: DeferredWorld, _: HookContext) {
        world
            .resource_mut::<TestVec>()
            .0
            .push("OrdA hook on_discard");
    }

    fn ord_a_hook_on_remove(mut world: DeferredWorld, _: HookContext) {
        world
            .resource_mut::<TestVec>()
            .0
            .push("OrdA hook on_remove");
    }

    fn ord_a_observer_on_add(_event: On<Add, OrdA>, mut res: ResMut<TestVec>) {
        res.0.push("OrdA observer on_add");
    }

    fn ord_a_observer_on_insert(_event: On<Insert, OrdA>, mut res: ResMut<TestVec>) {
        res.0.push("OrdA observer on_insert");
    }

    fn ord_a_observer_on_discard(_event: On<Discard, OrdA>, mut res: ResMut<TestVec>) {
        res.0.push("OrdA observer on_discard");
    }

    fn ord_a_observer_on_remove(_event: On<Remove, OrdA>, mut res: ResMut<TestVec>) {
        res.0.push("OrdA observer on_remove");
    }

    #[derive(Component)]
    #[component(on_add = ord_b_hook_on_add, on_insert = ord_b_hook_on_insert, on_discard = ord_b_hook_on_discard, on_remove = ord_b_hook_on_remove)]
    struct OrdB;

    fn ord_b_hook_on_add(mut world: DeferredWorld, _: HookContext) {
        world.resource_mut::<TestVec>().0.push("OrdB hook on_add");
        world.commands().queue(|world: &mut World| {
            world
                .resource_mut::<TestVec>()
                .0
                .push("OrdB command on_add");
        });
    }

    fn ord_b_hook_on_insert(mut world: DeferredWorld, _: HookContext) {
        world
            .resource_mut::<TestVec>()
            .0
            .push("OrdB hook on_insert");
    }

    fn ord_b_hook_on_discard(mut world: DeferredWorld, _: HookContext) {
        world
            .resource_mut::<TestVec>()
            .0
            .push("OrdB hook on_discard");
    }

    fn ord_b_hook_on_remove(mut world: DeferredWorld, _: HookContext) {
        world
            .resource_mut::<TestVec>()
            .0
            .push("OrdB hook on_remove");
    }

    fn ord_b_observer_on_add(_event: On<Add, OrdB>, mut res: ResMut<TestVec>) {
        res.0.push("OrdB observer on_add");
    }

    fn ord_b_observer_on_insert(_event: On<Insert, OrdB>, mut res: ResMut<TestVec>) {
        res.0.push("OrdB observer on_insert");
    }

    fn ord_b_observer_on_discard(_event: On<Discard, OrdB>, mut res: ResMut<TestVec>) {
        res.0.push("OrdB observer on_discard");
    }

    fn ord_b_observer_on_remove(_event: On<Remove, OrdB>, mut res: ResMut<TestVec>) {
        res.0.push("OrdB observer on_remove");
    }

    #[test]
    fn command_ordering_is_correct() {
        let mut world = World::new();
        world.insert_resource(TestVec(Vec::new()));
        world.add_observer(ord_a_observer_on_add);
        world.add_observer(ord_a_observer_on_insert);
        world.add_observer(ord_a_observer_on_discard);
        world.add_observer(ord_a_observer_on_remove);
        world.add_observer(ord_b_observer_on_add);
        world.add_observer(ord_b_observer_on_insert);
        world.add_observer(ord_b_observer_on_discard);
        world.add_observer(ord_b_observer_on_remove);
        let _entity = world.spawn(OrdA).id();
        let expected = [
            "OrdA hook on_add", // adds command to insert OrdB
            "OrdA observer on_add",
            "OrdA hook on_insert", // adds command to despawn entity
            "OrdA observer on_insert",
            "OrdB hook on_add", // adds command to just add to this log
            "OrdB observer on_add",
            "OrdB hook on_insert",
            "OrdB observer on_insert",
            "OrdB command on_add", // command added by OrdB hook on_add, needs to run before despawn command
            "OrdA observer on_discard", // start of despawn
            "OrdA hook on_discard",
            "OrdA observer on_remove",
            "OrdA hook on_remove",
            "OrdB observer on_discard",
            "OrdB hook on_discard",
            "OrdB observer on_remove",
            "OrdB hook on_remove",
        ];
        world.flush();
        assert_eq!(world.resource_mut::<TestVec>().0.as_slice(), &expected[..]);
    }

    #[test]
    fn entity_world_mut_clone_and_move_components() {
        #[derive(Component, Clone, PartialEq, Debug)]
        struct A;

        #[derive(Component, Clone, PartialEq, Debug)]
        struct B;

        #[derive(Component, Clone, PartialEq, Debug)]
        struct C(u32);

        let mut world = World::new();
        let entity_a = world.spawn((A, B, C(5))).id();
        let entity_b = world.spawn((A, C(4))).id();

        world.entity_mut(entity_a).clone_components::<B>(entity_b);
        assert_eq!(world.entity(entity_a).get::<B>(), Some(&B));
        assert_eq!(world.entity(entity_b).get::<B>(), Some(&B));

        world.entity_mut(entity_a).move_components::<C>(entity_b);
        assert_eq!(world.entity(entity_a).get::<C>(), None);
        assert_eq!(world.entity(entity_b).get::<C>(), Some(&C(5)));

        assert_eq!(world.entity(entity_a).get::<A>(), Some(&A));
        assert_eq!(world.entity(entity_b).get::<A>(), Some(&A));
    }

    #[test]
    fn entity_world_mut_clone_with_move_and_require() {
        #[derive(Component, Clone, PartialEq, Debug)]
        #[require(B(3))]
        struct A;

        #[derive(Component, Clone, PartialEq, Debug, Default)]
        #[require(C(3))]
        struct B(u32);

        #[derive(Component, Clone, PartialEq, Debug, Default)]
        #[require(D)]
        struct C(u32);

        #[derive(Component, Clone, PartialEq, Debug, Default)]
        struct D;

        let mut world = World::new();
        let entity_a = world.spawn((A, B(5))).id();
        let entity_b = world.spawn_empty().id();

        world
            .entity_mut(entity_a)
            .clone_with_opt_in(entity_b, |builder| {
                builder
                    .move_components(true)
                    .allow::<C>()
                    .without_required_components(|builder| {
                        builder.allow::<A>();
                    });
            });

        assert_eq!(world.entity(entity_a).get::<A>(), None);
        assert_eq!(world.entity(entity_b).get::<A>(), Some(&A));

        assert_eq!(world.entity(entity_a).get::<B>(), Some(&B(5)));
        assert_eq!(world.entity(entity_b).get::<B>(), Some(&B(3)));

        assert_eq!(world.entity(entity_a).get::<C>(), None);
        assert_eq!(world.entity(entity_b).get::<C>(), Some(&C(3)));

        assert_eq!(world.entity(entity_a).get::<D>(), None);
        assert_eq!(world.entity(entity_b).get::<D>(), Some(&D));
    }

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

        let mut entity = world.spawn(TestComponent(1));
        entity.insert(DespawnOnAdd);
        assert!(entity.is_despawned());
    }

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

        let mut entity = world.spawn(TestComponent(1));
        entity.insert(DespawnOnAdd);
        assert!(entity.is_despawned());
        entity.insert(TestComponent2(2));
    }

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

        #[derive(Component)]
        #[component(on_remove = get_tracked)]
        struct C;

        static TRACKED: OnceLock<(MaybeLocation, Tick)> = OnceLock::new();
        fn get_tracked(world: DeferredWorld, HookContext { entity, .. }: HookContext) {
            TRACKED.get_or_init(|| {
                let by = world
                    .entities
                    .entity_get_spawned_or_despawned_by(entity)
                    .map(|l| l.unwrap());
                let at = world
                    .entities
                    .entity_get_spawn_or_despawn_tick(entity)
                    .unwrap();
                (by, at)
            });
        }

        #[track_caller]
        fn caller_spawn(world: &mut World) -> (Entity, MaybeLocation, Tick) {
            let caller = MaybeLocation::caller();
            (world.spawn(C).id(), caller, world.change_tick())
        }
        let (entity, spawner, spawn_tick) = caller_spawn(&mut world);

        assert_eq!(
            spawner,
            world
                .entities()
                .entity_get_spawned_or_despawned_by(entity)
                .map(|l| l.unwrap())
        );

        #[track_caller]
        fn caller_despawn(world: &mut World, entity: Entity) -> (MaybeLocation, Tick) {
            world.despawn(entity);
            (MaybeLocation::caller(), world.change_tick())
        }
        let (despawner, despawn_tick) = caller_despawn(&mut world, entity);

        assert_eq!((spawner, spawn_tick), *TRACKED.get().unwrap());
        assert_eq!(
            despawner,
            world
                .entities()
                .entity_get_spawned_or_despawned_by(entity)
                .map(|l| l.unwrap())
        );
        assert_eq!(
            despawn_tick,
            world
                .entities()
                .entity_get_spawn_or_despawn_tick(entity)
                .unwrap()
        );
    }

    #[test]
    fn with_component_activates_hooks() {
        use core::sync::atomic::{AtomicBool, AtomicU8, Ordering};

        #[derive(Component, PartialEq, Eq, Debug)]
        #[component(immutable)]
        struct Foo(bool);

        static EXPECTED_VALUE: AtomicBool = AtomicBool::new(false);

        static ADD_COUNT: AtomicU8 = AtomicU8::new(0);
        static REMOVE_COUNT: AtomicU8 = AtomicU8::new(0);
        static DISCARD_COUNT: AtomicU8 = AtomicU8::new(0);
        static INSERT_COUNT: AtomicU8 = AtomicU8::new(0);

        let mut world = World::default();

        world.register_component::<Foo>();
        world
            .register_component_hooks::<Foo>()
            .on_add(|world, context| {
                ADD_COUNT.fetch_add(1, Ordering::Relaxed);

                assert_eq!(
                    world.get(context.entity),
                    Some(&Foo(EXPECTED_VALUE.load(Ordering::Relaxed)))
                );
            })
            .on_remove(|world, context| {
                REMOVE_COUNT.fetch_add(1, Ordering::Relaxed);

                assert_eq!(
                    world.get(context.entity),
                    Some(&Foo(EXPECTED_VALUE.load(Ordering::Relaxed)))
                );
            })
            .on_discard(|world, context| {
                DISCARD_COUNT.fetch_add(1, Ordering::Relaxed);

                assert_eq!(
                    world.get(context.entity),
                    Some(&Foo(EXPECTED_VALUE.load(Ordering::Relaxed)))
                );
            })
            .on_insert(|world, context| {
                INSERT_COUNT.fetch_add(1, Ordering::Relaxed);

                assert_eq!(
                    world.get(context.entity),
                    Some(&Foo(EXPECTED_VALUE.load(Ordering::Relaxed)))
                );
            });

        let entity = world.spawn(Foo(false)).id();

        assert_eq!(ADD_COUNT.load(Ordering::Relaxed), 1);
        assert_eq!(REMOVE_COUNT.load(Ordering::Relaxed), 0);
        assert_eq!(DISCARD_COUNT.load(Ordering::Relaxed), 0);
        assert_eq!(INSERT_COUNT.load(Ordering::Relaxed), 1);

        let mut entity = world.entity_mut(entity);

        let archetype_pointer_before = &raw const *entity.archetype();

        assert_eq!(entity.get::<Foo>(), Some(&Foo(false)));

        entity.modify_component(|foo: &mut Foo| {
            foo.0 = true;
            EXPECTED_VALUE.store(foo.0, Ordering::Relaxed);
        });

        let archetype_pointer_after = &raw const *entity.archetype();

        assert_eq!(entity.get::<Foo>(), Some(&Foo(true)));

        assert_eq!(ADD_COUNT.load(Ordering::Relaxed), 1);
        assert_eq!(REMOVE_COUNT.load(Ordering::Relaxed), 0);
        assert_eq!(DISCARD_COUNT.load(Ordering::Relaxed), 1);
        assert_eq!(INSERT_COUNT.load(Ordering::Relaxed), 2);

        assert_eq!(archetype_pointer_before, archetype_pointer_after);
    }

    #[test]
    fn bundle_remove_only_triggers_for_present_components() {
        let mut world = World::default();

        #[derive(Component)]
        struct A;

        #[derive(Component)]
        struct B;

        #[derive(Resource, PartialEq, Eq, Debug)]
        struct Tracker {
            a: bool,
            b: bool,
        }

        world.insert_resource(Tracker { a: false, b: false });
        let entity = world.spawn(A).id();

        world.add_observer(|_: On<Remove, A>, mut tracker: ResMut<Tracker>| {
            tracker.a = true;
        });
        world.add_observer(|_: On<Remove, B>, mut tracker: ResMut<Tracker>| {
            tracker.b = true;
        });

        world.entity_mut(entity).remove::<(A, B)>();

        assert_eq!(
            world.resource::<Tracker>(),
            &Tracker {
                a: true,
                // The entity didn't have a B component, so it should not have been triggered.
                b: false,
            }
        );
    }

    #[test]
    fn spawned_after_swap_remove() {
        #[derive(Component)]
        struct Marker;

        let mut world = World::new();
        let id1 = world.spawn(Marker).id();
        let _id2 = world.spawn(Marker).id();
        let id3 = world.spawn(Marker).id();

        let e1_spawned = world.entity(id1).spawned_by();

        let spawn = world.entity(id3).spawned_by();
        world.entity_mut(id1).despawn();
        let e1_despawned = world.entities().entity_get_spawned_or_despawned_by(id1);

        // These assertions are only possible if the `track_location` feature is enabled
        if let (Some(e1_spawned), Some(e1_despawned)) =
            (e1_spawned.into_option(), e1_despawned.into_option())
        {
            assert!(e1_despawned.is_some());
            assert_ne!(Some(e1_spawned), e1_despawned);
        }

        let spawn_after = world.entity(id3).spawned_by();
        assert_eq!(spawn, spawn_after);
    }

    #[test]
    fn spawned_by_set_before_flush() {
        #[derive(Component)]
        #[component(on_despawn = on_despawn)]
        struct C;

        fn on_despawn(mut world: DeferredWorld, context: HookContext) {
            let spawned = world.entity(context.entity).spawned_by();
            world.commands().queue(move |world: &mut World| {
                // The entity has finished despawning...
                assert!(world.get_entity(context.entity).is_err());
                let despawned = world
                    .entities()
                    .entity_get_spawned_or_despawned_by(context.entity);
                // These assertions are only possible if the `track_location` feature is enabled
                if let (Some(spawned), Some(despawned)) =
                    (spawned.into_option(), despawned.into_option())
                {
                    // ... so ensure that `despawned_by` has been written
                    assert!(despawned.is_some());
                    assert_ne!(Some(spawned), despawned);
                }
            });
        }

        let mut world = World::new();
        let original = world.spawn(C).id();
        world.despawn(original);
    }
}