bevy_mod_scripting_bindings 0.19.0

Core traits and structures required for smoothly interfacing with other languages in a generic way
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
//! # Motivation
//!
//! Traits and structs needed to support the creation of bindings for scripting languages.
//! reflection gives us access to `dyn PartialReflect` objects via their type name,
//! Scripting languages only really support `Clone` objects so if we want to support references,
//! we need wrapper types which have owned and ref variants.

use super::{
    AppReflectAllocator, AppScriptComponentRegistry, ReflectBase, ReflectBaseType,
    ReflectReference, ScriptComponentRegistration, ScriptResourceRegistration,
    ScriptTypeRegistration, Union,
    access_map::{
        AccessCount, AccessMapKey, AnyAccessMap, DynamicSystemMeta, ReflectAccessId,
        ReflectAccessKind, SubsetAccessMap,
    },
    function::{
        namespace::Namespace,
        script_function::{AppScriptFunctionRegistry, DynamicScriptFunction, FunctionCallContext},
    },
    schedule::AppScheduleRegistry,
    script_value::ScriptValue,
    with_global_access,
};
use crate::{
    error::InteropError,
    function::{from::FromScript, from_ref::FromScriptRef},
    reflection_extensions::PartialReflectExt,
    with_access_read, with_access_write,
};
use ::{
    bevy_app::AppExit,
    bevy_asset::{AssetServer, Handle, LoadState},
    bevy_ecs::{
        component::{Component, ComponentId},
        entity::Entity,
        prelude::Resource,
        reflect::{AppTypeRegistry, ReflectFromWorld, ReflectResource},
        system::Commands,
        world::{CommandQueue, Mut, World, unsafe_world_cell::UnsafeWorldCell},
    },
    bevy_reflect::{
        DynamicEnum, DynamicStruct, DynamicTuple, DynamicTupleStruct, DynamicVariant,
        PartialReflect, TypeRegistryArc, std_traits::ReflectDefault,
    },
};
use bevy_asset::AssetPath;
use bevy_ecs::{
    component::Mutable,
    hierarchy::{ChildOf, Children},
    system::Command,
    world::WorldId,
};
use bevy_mod_scripting_asset::ScriptAsset;
use bevy_mod_scripting_display::GetTypeInfo;
use bevy_mod_scripting_script::ScriptAttachment;
use bevy_platform::collections::HashMap;
use bevy_reflect::{TypeInfo, VariantInfo};
use bevy_system_reflection::ReflectSchedule;
use std::{
    any::{Any, TypeId},
    borrow::Cow,
    cell::RefCell,
    fmt::Debug,
    rc::Rc,
    sync::{Arc, atomic::AtomicBool},
};

/// Prefer to directly using [`WorldAccessGuard`]. If the underlying type changes, this alias will be updated.
pub type WorldGuard<'w> = WorldAccessGuard<'w>;
/// Similar to [`WorldGuard`], but without the arc, use for when you don't need the outer Arc.
pub type WorldGuardRef<'w> = &'w WorldAccessGuard<'w>;

/// Provides safe access to the world via [`AnyAccessMap`] permissions, which enforce aliasing rules at runtime in multi-thread environments
#[derive(Clone, Debug)]
pub struct WorldAccessGuard<'w> {
    /// The guard this guard pointer represents
    pub(crate) inner: Rc<WorldAccessGuardInner<'w>>,
    /// if true the guard is invalid and cannot be used, stored as a second pointer so that this validity can be
    /// stored separate from the contents of the guard
    invalid: Rc<AtomicBool>,
}
impl WorldAccessGuard<'_> {
    /// Returns the id of the world this guard provides access to
    pub fn id(&self) -> WorldId {
        self.inner.cell.id()
    }
}

/// Used to decrease the stack size of [`WorldAccessGuard`]
pub(crate) struct WorldAccessGuardInner<'w> {
    /// Safety: cannot be used unless the scope depth is less than the max valid scope
    cell: UnsafeWorldCell<'w>,
    // TODO: this is fairly hefty, explore sparse sets, bit fields etc
    pub(crate) accesses: AnyAccessMap,
    /// Cached for convenience, since we need it for most operations, means we don't need to lock the type registry every time
    type_registry: TypeRegistryArc,
    /// The script allocator for the world
    allocator: AppReflectAllocator,
    /// The function registry for the world
    function_registry: AppScriptFunctionRegistry,
    /// The schedule registry for the world
    schedule_registry: AppScheduleRegistry,
    /// The registry of script registered components
    script_component_registry: AppScriptComponentRegistry,
}

impl std::fmt::Debug for WorldAccessGuardInner<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WorldAccessGuardInner").finish()
    }
}

#[profiling::all_functions]
impl WorldAccessGuard<'static> {
    /// Shortens the lifetime of the guard to the given lifetime.
    pub(crate) fn shorten_lifetime<'w>(self) -> WorldGuard<'w> {
        // Safety: todo
        unsafe { std::mem::transmute(self) }
    }
}
#[profiling::all_functions]
impl<'w> WorldAccessGuard<'w> {
    /// creates a new guard derived from this one, which if invalidated, will not invalidate the original
    fn scope(&self) -> Self {
        let mut new_guard = self.clone();
        new_guard.invalid = Rc::new(
            new_guard
                .invalid
                .load(std::sync::atomic::Ordering::Relaxed)
                .into(),
        );
        new_guard
    }

    /// Returns true if the guard is valid, false if it is invalid
    fn is_valid(&self) -> bool {
        !self.invalid.load(std::sync::atomic::Ordering::Relaxed)
    }

    /// Invalidates the world access guard, making it and any guards derived from this one unusable.
    pub fn invalidate(&self) {
        self.invalid
            .store(true, std::sync::atomic::Ordering::Relaxed);
    }

    /// Safely allows access to the world for the duration of the closure via a static [`WorldAccessGuard`].
    ///
    /// The guard is invalidated at the end of the closure, meaning the world cannot be accessed at all after the closure ends.
    pub fn with_static_guard<O>(
        world: &'w mut World,
        f: impl FnOnce(WorldGuard<'static>) -> O,
    ) -> O {
        let guard = WorldAccessGuard::new_exclusive(world);
        // safety: we invalidate the guard after the closure is called, meaning the world cannot be accessed at all after the 'w lifetime ends
        let static_guard: WorldAccessGuard<'static> = unsafe { std::mem::transmute(guard) };
        let o = f(static_guard.clone());

        static_guard.invalidate();
        o
    }

    /// Safely allows access to the world for the duration of the closure via a static [`WorldAccessGuard`] using a previously lifetimed world guard.
    /// Will invalidate the static guard at the end but not the original.
    pub fn with_existing_static_guard<O>(
        guard: WorldAccessGuard<'w>,
        f: impl FnOnce(WorldGuard<'static>) -> O,
    ) -> O {
        // safety: we invalidate the guard after the closure is called, meaning the world cannot be accessed at all after the 'w lifetime ends, from the static guard
        // i.e. even if somebody squirells it away, it will be useless.
        let static_guard: WorldAccessGuard<'static> = unsafe { std::mem::transmute(guard.scope()) };
        let o = f(static_guard.clone());
        static_guard.invalidate();
        o
    }

    /// Creates a new [`WorldAccessGuard`] from a possibly non-exclusive access to the world.
    ///
    /// It requires specyfing the exact accesses that are allowed to be given out by the guard.
    /// Those accesses need to be safe to be given out to the script, as the guard will assume that it is safe to give them out in any way.
    ///
    /// # Safety
    /// - The caller must ensure that the accesses in subset are not aliased by any other access
    /// - If an access is allowed in this subset, but alised by someone else,
    /// either by being converted to mutable or non mutable reference, this guard will be unsafe.
    pub unsafe fn new_non_exclusive(
        world: UnsafeWorldCell<'w>,
        subset: impl IntoIterator<Item = ReflectAccessId>,
        type_registry: AppTypeRegistry,
        allocator: AppReflectAllocator,
        function_registry: AppScriptFunctionRegistry,
        schedule_registry: AppScheduleRegistry,
        script_component_registry: AppScriptComponentRegistry,
    ) -> Self {
        Self {
            inner: Rc::new(WorldAccessGuardInner {
                cell: world,
                accesses: AnyAccessMap::SubsetAccessMap(SubsetAccessMap::new(
                    subset,
                    // allocations live beyond the world, and can be safely accessed
                    |id| ReflectAccessId::from_index(id).kind == ReflectAccessKind::Allocation,
                )),
                type_registry: type_registry.0,
                allocator,
                function_registry,
                schedule_registry,
                script_component_registry,
            }),
            invalid: Rc::new(false.into()),
        }
    }

    /// Creates a new [`WorldAccessGuard`] for the given mutable borrow of the world.
    ///
    /// Creating a guard requires that some resources exist in the world, namely:
    /// - [`AppTypeRegistry`]
    /// - [`AppReflectAllocator`]
    /// - [`AppScriptFunctionRegistry`]
    ///
    /// If these resources do not exist, they will be initialized.
    pub fn new_exclusive(world: &'w mut World) -> Self {
        let type_registry = world.get_resource_or_init::<AppTypeRegistry>().0.clone();

        let allocator = world.get_resource_or_init::<AppReflectAllocator>().clone();

        let function_registry = world
            .get_resource_or_init::<AppScriptFunctionRegistry>()
            .clone();

        let script_component_registry = world
            .get_resource_or_init::<AppScriptComponentRegistry>()
            .clone();

        let schedule_registry = world.get_resource_or_init::<AppScheduleRegistry>().clone();
        Self {
            inner: Rc::new(WorldAccessGuardInner {
                cell: world.as_unsafe_world_cell(),
                accesses: AnyAccessMap::UnlimitedAccessMap(Default::default()),
                allocator,
                type_registry,
                function_registry,
                schedule_registry,
                script_component_registry,
            }),
            invalid: Rc::new(false.into()),
        }
    }

    /// Queues a command to the world, which will be executed later.
    pub(crate) fn queue(&self, command: impl Command) -> Result<(), InteropError> {
        self.with_global_access(|w| {
            w.commands().queue(command);
        })
    }

    /// Runs a closure within an isolated access scope, releasing leftover accesses, should only be used in a single-threaded context.
    ///
    /// Safety:
    /// - The caller must ensure it's safe to release any potentially locked accesses.
    pub(crate) unsafe fn with_access_scope<O, F: FnOnce() -> O>(
        &self,
        f: F,
    ) -> Result<O, InteropError> {
        Ok(self.inner.accesses.with_scope(f))
    }

    /// Purely debugging utility to list all accesses currently held.
    pub fn list_accesses(&self) -> Vec<(ReflectAccessId, AccessCount)> {
        self.inner.accesses.list_accesses()
    }

    /// Should only really be used for testing purposes
    pub unsafe fn release_all_accesses(&self) {
        self.inner.accesses.release_all_accesses();
    }

    /// Returns the number of accesses currently held.
    pub fn access_len(&self) -> usize {
        self.inner.accesses.count_accesses()
    }

    /// Retrieves the underlying unsafe world cell, with no additional guarantees of safety
    /// proceed with caution and only use this if you understand what you're doing
    pub fn as_unsafe_world_cell(&self) -> Result<UnsafeWorldCell<'w>, InteropError> {
        if !self.is_valid() {
            return Err(InteropError::missing_world());
        }

        Ok(self.inner.cell)
    }

    /// Retrieves the underlying read only unsafe world cell, with no additional guarantees of safety
    /// proceed with caution and only use this if you understand what you're doing
    pub fn as_unsafe_world_cell_readonly(&self) -> Result<UnsafeWorldCell<'w>, InteropError> {
        if !self.is_valid() {
            return Err(InteropError::missing_world());
        }

        Ok(self.inner.cell)
    }

    /// Gets the component id of the given component or resource
    pub fn get_component_id(&self, id: TypeId) -> Result<Option<ComponentId>, InteropError> {
        Ok(self
            .as_unsafe_world_cell_readonly()?
            .components()
            .get_id(id))
    }

    /// Gets the resource id of the given component or resource
    pub fn get_resource_id(&self, id: TypeId) -> Result<Option<ComponentId>, InteropError> {
        Ok(self
            .as_unsafe_world_cell_readonly()?
            .components()
            .get_resource_id(id))
    }

    /// A utility for running a closure with scoped read access to the given id
    pub fn with_read_access<T: Into<ReflectAccessId>, O, F: FnOnce(&Self) -> O>(
        &self,
        id: T,
        closure: F,
    ) -> Result<O, ()> {
        let id = id.into();
        if self.claim_read_access(id) {
            let out = Ok(closure(self));
            // Safety: just claimed this access
            unsafe { self.release_access(id) };
            out
        } else {
            Err(())
        }
    }

    /// A utility for running a closure with scoped write access to the given id
    pub fn with_write_access<T: Into<ReflectAccessId>, O, F: FnOnce(&Self) -> O>(
        &self,
        id: T,
        closure: F,
    ) -> Result<O, ()> {
        let id = id.into();
        if self.claim_write_access(id) {
            let out = Ok(closure(self));
            // Safety: just claimed this access
            unsafe { self.release_access(id) };
            out
        } else {
            Err(())
        }
    }

    /// Get the location of the given access
    pub fn get_access_location(
        &self,
        raid: ReflectAccessId,
    ) -> Option<std::panic::Location<'static>> {
        self.inner.accesses.access_location(raid)
    }

    #[track_caller]
    /// Claims read access to the given type.
    pub fn claim_read_access(&self, raid: ReflectAccessId) -> bool {
        self.inner.accesses.claim_read_access(raid)
    }

    #[track_caller]
    /// Claims write access to the given type.
    pub fn claim_write_access(&self, raid: ReflectAccessId) -> bool {
        self.inner.accesses.claim_write_access(raid)
    }

    /// Releases read or write access to the given type.
    ///
    /// # Safety
    /// - This can only be called safely after all references to the type created using the access have been dropped
    /// - You can only call this if you previously called one of: [`WorldAccessGuard::claim_read_access`] or [`WorldAccessGuard::claim_write_access`]
    /// - The number of claim and release calls for the same id must always match
    pub unsafe fn release_access(&self, raid: ReflectAccessId) {
        self.inner.accesses.release_access(raid)
    }

    /// Claims global access to the world
    pub fn claim_global_access(&self) -> bool {
        self.inner.accesses.claim_global_access()
    }

    /// Releases global access to the world
    ///
    /// # Safety
    /// - This can only be called safely after all references created using the access have been dropped
    pub unsafe fn release_global_access(&self) {
        self.inner.accesses.release_global_access()
    }

    /// Returns the type registry for the world
    pub fn type_registry(&self) -> TypeRegistryArc {
        self.inner.type_registry.clone()
    }

    /// Returns the schedule registry for the world
    pub fn schedule_registry(&self) -> AppScheduleRegistry {
        self.inner.schedule_registry.clone()
    }

    /// Returns the component registry for the world
    pub fn component_registry(&self) -> AppScriptComponentRegistry {
        self.inner.script_component_registry.clone()
    }

    /// Returns the script allocator for the world
    pub fn allocator(&self) -> AppReflectAllocator {
        self.inner.allocator.clone()
    }

    /// Returns the function registry for the world
    pub fn script_function_registry(&self) -> AppScriptFunctionRegistry {
        self.inner.function_registry.clone()
    }

    /// Claims access to the world for the duration of the closure, allowing for global access to the world.
    #[track_caller]
    pub fn with_global_access<F: FnOnce(&mut World) -> O, O>(
        &self,
        f: F,
    ) -> Result<O, InteropError> {
        with_global_access!(
            &self.inner.accesses,
            "Could not claim exclusive world access",
            {
                // safety: we have global access for the duration of the closure
                let world = unsafe { self.as_unsafe_world_cell()?.world_mut() };
                Ok(f(world))
            }
        )?
    }

    /// Safely accesses the resource by claiming and releasing access to it.
    ///
    /// # Panics
    /// - if the resource does not exist
    pub fn with_resource<F, R, O>(&self, f: F) -> Result<O, InteropError>
    where
        R: Resource,
        F: FnOnce(&R) -> O,
    {
        let cell = self.as_unsafe_world_cell()?;
        let access_id = ReflectAccessId::for_resource::<R>(&cell)?;

        with_access_read!(
            &self.inner.accesses,
            access_id,
            format!("Could not access resource: {}", std::any::type_name::<R>()),
            {
                // Safety: we have acquired access for the duration of the closure
                f(unsafe {
                    cell.get_resource::<R>().ok_or_else(|| {
                        InteropError::unregistered_component_or_resource_type(
                            std::any::type_name::<R>(),
                        )
                    })?
                })
            }
        )
    }

    /// Safely accesses the resource by claiming and releasing access to it.
    ///
    /// # Panics
    /// - if the resource does not exist
    pub fn with_resource_mut<F, R, O>(&self, f: F) -> Result<O, InteropError>
    where
        R: Resource,
        F: FnOnce(Mut<R>) -> O,
    {
        let cell = self.as_unsafe_world_cell()?;
        let access_id = ReflectAccessId::for_resource::<R>(&cell)?;
        with_access_write!(
            &self.inner.accesses,
            access_id,
            format!("Could not access resource: {}", std::any::type_name::<R>()),
            {
                // Safety: we have acquired access for the duration of the closure
                f(unsafe {
                    cell.get_resource_mut::<R>().ok_or_else(|| {
                        InteropError::unregistered_component_or_resource_type(
                            std::any::type_name::<R>(),
                        )
                    })?
                })
            }
        )
    }

    /// Safely accesses the component by claiming and releasing access to it.
    pub fn with_component<F, T, O>(&self, entity: Entity, f: F) -> Result<O, InteropError>
    where
        T: Component,
        F: FnOnce(Option<&T>) -> O,
    {
        let cell = self.as_unsafe_world_cell()?;
        let access_id = ReflectAccessId::for_component::<T>(&cell)?;
        with_access_read!(
            &self.inner.accesses,
            access_id,
            format!("Could not access component: {}", std::any::type_name::<T>()),
            {
                // Safety: we have acquired access for the duration of the closure
                f(unsafe { cell.get_entity(entity).map(|e| e.get::<T>()) }
                    .ok()
                    .unwrap_or(None))
            }
        )
    }

    /// Safely accesses the component by claiming and releasing access to it.
    pub fn with_component_mut<F, T, O>(&self, entity: Entity, f: F) -> Result<O, InteropError>
    where
        T: Component<Mutability = Mutable>,
        F: FnOnce(Option<Mut<T>>) -> O,
    {
        let cell = self.as_unsafe_world_cell()?;
        let access_id = ReflectAccessId::for_component::<T>(&cell)?;

        with_access_write!(
            &self.inner.accesses,
            access_id,
            format!("Could not access component: {}", std::any::type_name::<T>()),
            {
                // Safety: we have acquired access for the duration of the closure
                f(unsafe { cell.get_entity(entity).map(|e| e.get_mut::<T>()) }
                    .ok()
                    .unwrap_or(None))
            }
        )
    }

    /// Safey modify or insert a component by claiming and releasing global access.
    pub fn with_or_insert_component_mut<F, T, O>(
        &self,
        entity: Entity,
        f: F,
    ) -> Result<O, InteropError>
    where
        T: Component<Mutability = Mutable> + Default,
        F: FnOnce(&mut T) -> O,
    {
        self.with_global_access(|world| match world.get_mut::<T>(entity) {
            Some(mut component) => f(&mut component),
            None => {
                let mut component = T::default();
                let mut commands = world.commands();
                let result = f(&mut component);
                commands.entity(entity).insert(component);
                result
            }
        })
    }

    /// Try to lookup a function with the given name on the given type id's namespaces.
    ///
    /// Returns the function if found, otherwise returns the name of the function that was not found.
    pub fn lookup_function(
        &self,
        type_ids: impl IntoIterator<Item = TypeId>,
        name: impl Into<Cow<'static, str>>,
    ) -> Result<DynamicScriptFunction, Cow<'static, str>> {
        let registry = self.script_function_registry();
        let registry = registry.read();

        let mut name = name.into();
        for type_id in type_ids {
            name = match registry.get_function(Namespace::OnType(type_id), name) {
                Ok(func) => return Ok(func.clone()),
                Err(name) => name,
            };
        }

        Err(name)
    }

    /// Iterates over all available functions on the type id's namespace + those available on any reference if any exist.
    pub fn get_functions_on_type(
        &self,
        type_id: TypeId,
    ) -> Vec<(Cow<'static, str>, DynamicScriptFunction)> {
        let registry = self.script_function_registry();
        let registry = registry.read();

        registry
            .iter_namespace(Namespace::OnType(type_id))
            .chain(
                registry
                    .iter_namespace(Namespace::OnType(std::any::TypeId::of::<ReflectReference>())),
            )
            .map(|(key, func)| (key.name.clone(), func.clone()))
            .collect()
    }

    /// checks if a given entity exists and is valid
    pub fn is_valid_entity(&self, entity: Entity) -> Result<bool, InteropError> {
        let cell = self.as_unsafe_world_cell()?;
        Ok(cell.get_entity(entity).is_ok() && entity.index().index() != 0)
    }

    /// Tries to call a fitting overload of the function with the given name and in the type id's namespace based on the arguments provided.
    /// Currently does this by repeatedly trying each overload until one succeeds or all fail.
    pub fn try_call_overloads(
        &self,
        type_id: TypeId,
        name: impl Into<Cow<'static, str>>,
        args: Vec<ScriptValue>,
        context: FunctionCallContext,
    ) -> Result<ScriptValue, InteropError> {
        let registry = self.script_function_registry();
        let registry = registry.read();

        let name = name.into();
        let overload_iter = match registry.iter_overloads(Namespace::OnType(type_id), name) {
            Ok(iter) => iter,
            Err(name) => {
                return Err(InteropError::missing_function(
                    name.to_string(),
                    Namespace::OnType(type_id),
                    Some(context.clone()),
                ));
            }
        };

        let mut last_error = None;
        for overload in overload_iter {
            match overload.call(args.clone(), context.clone()) {
                Ok(out) => return Ok(out),
                Err(e) => last_error = Some(e),
            }
        }

        Err(last_error.ok_or_else(|| InteropError::invariant("invariant, iterator should always return at least one item, and if the call fails it should return an error"))?)
    }
}

/// Impl block for higher level world methods
#[profiling::all_functions]
impl WorldAccessGuard<'_> {
    fn construct_from_script_value(
        &self,
        descriptor: impl Into<Cow<'static, str>>,
        type_id: TypeId,
        value: Option<ScriptValue>,
    ) -> Result<Box<dyn PartialReflect>, InteropError> {
        // if the value is missing, try to construct a default and return it
        let value = match value {
            Some(value) => value,
            None => {
                let type_registry = self.type_registry();
                let type_registry = type_registry.read();
                let default_data = type_registry
                    .get_type_data::<ReflectDefault>(type_id)
                    .ok_or_else(|| {
                        InteropError::function_interop_error(
                            "construct",
                            Namespace::OnType(TypeId::of::<World>()),
                            InteropError::string(format!(
                                "field missing and no default provided: '{}'",
                                descriptor.into()
                            )),
                            None,
                        )
                    })?;
                return Ok(default_data.default().into_partial_reflect());
            }
        };

        // otherwise we need to use from_script_ref
        <Box<dyn PartialReflect>>::from_script_ref(type_id, value, self.clone())
    }

    fn construct_dynamic_struct(
        &self,
        payload: &mut HashMap<String, ScriptValue>,
        fields: Vec<(&'static str, TypeId)>,
    ) -> Result<DynamicStruct, InteropError> {
        let mut dynamic = DynamicStruct::default();
        for (field_name, field_type_id) in fields {
            let constructed = self.construct_from_script_value(
                field_name,
                field_type_id,
                payload.remove(field_name),
            )?;

            dynamic.insert_boxed(field_name, constructed);
        }
        Ok(dynamic)
    }

    fn construct_dynamic_tuple_struct(
        &self,
        payload: &mut HashMap<String, ScriptValue>,
        fields: Vec<TypeId>,
        one_indexed: bool,
    ) -> Result<DynamicTupleStruct, InteropError> {
        let mut dynamic = DynamicTupleStruct::default();
        for (field_idx, field_type_id) in fields.into_iter().enumerate() {
            // correct for indexing
            let script_idx = if one_indexed {
                field_idx + 1
            } else {
                field_idx
            };
            let field_string = script_idx.to_string();
            dynamic.insert_boxed(self.construct_from_script_value(
                field_string.clone(),
                field_type_id,
                payload.remove(&field_string),
            )?);
        }
        Ok(dynamic)
    }

    fn construct_dynamic_tuple(
        &self,
        payload: &mut HashMap<String, ScriptValue>,
        fields: Vec<TypeId>,
        one_indexed: bool,
    ) -> Result<DynamicTuple, InteropError> {
        let mut dynamic = DynamicTuple::default();
        for (field_idx, field_type_id) in fields.into_iter().enumerate() {
            // correct for indexing
            let script_idx = if one_indexed {
                field_idx + 1
            } else {
                field_idx
            };

            let field_string = script_idx.to_string();

            dynamic.insert_boxed(self.construct_from_script_value(
                field_string.clone(),
                field_type_id,
                payload.remove(&field_string),
            )?);
        }
        Ok(dynamic)
    }

    /// An arbitrary type constructor utility.
    ///
    /// Allows the construction of arbitrary types (within limits dictated by the API) from the script directly
    pub fn construct(
        &self,
        type_: ScriptTypeRegistration,
        mut payload: HashMap<String, ScriptValue>,
        one_indexed: bool,
    ) -> Result<Box<dyn PartialReflect>, InteropError> {
        // figure out the kind of type we're building
        let type_info = type_.registration.type_info();
        // we just need to a) extract fields, if enum we need a "variant" field specifying the variant
        // then build the corresponding dynamic structure, whatever it may be

        let dynamic: Box<dyn PartialReflect> = match type_info {
            TypeInfo::Struct(struct_info) => {
                let fields_iter = struct_info
                    .field_names()
                    .iter()
                    .map(|f| {
                        Ok((
                            *f,
                            struct_info
                                .field(f)
                                .ok_or_else(|| {
                                    InteropError::invariant(
                                        "field in field_names should have reflection information",
                                    )
                                })?
                                .type_id(),
                        ))
                    })
                    .collect::<Result<Vec<_>, InteropError>>()?;
                let mut dynamic = self.construct_dynamic_struct(&mut payload, fields_iter)?;
                dynamic.set_represented_type(Some(type_info));
                Box::new(dynamic)
            }
            TypeInfo::TupleStruct(tuple_struct_info) => {
                let fields_iter = (0..tuple_struct_info.field_len())
                    .map(|f| {
                        Ok(tuple_struct_info
                            .field_at(f)
                            .ok_or_else(|| {
                                InteropError::invariant(
                                    "field in field_names should have reflection information",
                                )
                            })?
                            .type_id())
                    })
                    .collect::<Result<Vec<_>, InteropError>>()?;

                let mut dynamic =
                    self.construct_dynamic_tuple_struct(&mut payload, fields_iter, one_indexed)?;
                dynamic.set_represented_type(Some(type_info));
                Box::new(dynamic)
            }
            TypeInfo::Tuple(tuple_info) => {
                let fields_iter = (0..tuple_info.field_len())
                    .map(|f| {
                        Ok(tuple_info
                            .field_at(f)
                            .ok_or_else(|| {
                                InteropError::invariant(
                                    "field in field_names should have reflection information",
                                )
                            })?
                            .type_id())
                    })
                    .collect::<Result<Vec<_>, InteropError>>()?;

                let mut dynamic =
                    self.construct_dynamic_tuple(&mut payload, fields_iter, one_indexed)?;
                dynamic.set_represented_type(Some(type_info));
                Box::new(dynamic)
            }
            TypeInfo::Enum(enum_info) => {
                // extract variant from "variant"
                let variant = payload.remove("variant").ok_or_else(|| {
                    InteropError::function_interop_error(
                        "construct",
                        Namespace::OnType(TypeId::of::<World>()),
                        InteropError::str("missing 'variant' field in enum constructor payload"),
                        None,
                    )
                })?;

                let variant_name = String::from_script(variant, self.clone())?;

                let variant = enum_info.variant(&variant_name).ok_or_else(|| {
                    InteropError::function_interop_error(
                        "construct",
                        Namespace::OnType(TypeId::of::<World>()),
                        InteropError::string(format!(
                            "invalid variant name '{}' for enum '{}'",
                            variant_name,
                            enum_info.type_path()
                        )),
                        None,
                    )
                })?;

                let variant = match variant {
                    VariantInfo::Struct(struct_variant_info) => {
                        // same as above struct variant
                        let fields_iter = struct_variant_info
                            .field_names()
                            .iter()
                            .map(|f| {
                                Ok((
                                    *f,
                                    struct_variant_info
                                        .field(f)
                                        .ok_or_else(|| {
                                            InteropError::invariant(
                                                "field in field_names should have reflection information",
                                            )
                                        })?
                                        .type_id(),
                                ))
                            })
                            .collect::<Result<Vec<_>, InteropError>>()?;

                        let dynamic = self.construct_dynamic_struct(&mut payload, fields_iter)?;
                        DynamicVariant::Struct(dynamic)
                    }
                    VariantInfo::Tuple(tuple_variant_info) => {
                        // same as tuple variant
                        let fields_iter = (0..tuple_variant_info.field_len())
                            .map(|f| {
                                Ok(tuple_variant_info
                                    .field_at(f)
                                    .ok_or_else(|| {
                                        InteropError::invariant(
                                            "field in field_names should have reflection information",
                                        )
                                    })?
                                    .type_id())
                            })
                            .collect::<Result<Vec<_>, InteropError>>()?;

                        let dynamic =
                            self.construct_dynamic_tuple(&mut payload, fields_iter, one_indexed)?;
                        DynamicVariant::Tuple(dynamic)
                    }
                    VariantInfo::Unit(_) => DynamicVariant::Unit,
                };
                let mut dynamic = DynamicEnum::new(variant_name, variant);
                dynamic.set_represented_type(Some(type_info));
                Box::new(dynamic)
            }
            _ => {
                return Err(InteropError::unsupported_operation(
                    Some(type_info.type_id()),
                    Some(Box::new(payload)),
                    "Type constructor not supported",
                ));
            }
        };

        // try to construct type from reflect
        // TODO: it would be nice to have a <dyn PartialReflect>::from_reflect_with_fallback equivalent, that does exactly that
        // only using this as it's already there and convenient, the clone variant hitting will be confusing to end users
        <dyn PartialReflect>::from_reflect_or_clone(dynamic.as_ref(), self.clone())
    }

    /// Loads a script from the given asset path with default settings.
    pub fn load_script_asset<'a>(
        &self,
        asset_path: impl Into<AssetPath<'a>>,
    ) -> Result<Handle<ScriptAsset>, InteropError> {
        self.with_resource(|r: &AssetServer| r.load(asset_path))
    }

    /// Checks the load state of a script asset.
    pub fn get_script_asset_load_state(
        &self,
        script: Handle<ScriptAsset>,
    ) -> Result<LoadState, InteropError> {
        self.with_resource(|r: &AssetServer| r.load_state(script.id()))
    }

    // /// Attaches a script
    // pub fn attach_script(&self, attachment: ScriptAttachment) -> Result<(), InteropError> {
    //     match attachment {
    //         ScriptAttachment::EntityScript(entity, handle) => {
    //             // find existing script components on the entity
    //             self.with_or_insert_component_mut(entity, |c: &mut ScriptComponent| {
    //                 c.0.push(handle.clone())
    //             })?;
    //         }
    //         ScriptAttachment::StaticScript(handle) => {
    //             self.queue(AddStaticScript::new(handle))?;
    //         }
    //     };

    //     Ok(())
    // }

    /// Spawns a new entity in the world
    pub fn spawn(&self) -> Result<Entity, InteropError> {
        self.with_global_access(|world| {
            let mut command_queue = CommandQueue::default();
            let mut commands = Commands::new(&mut command_queue, world);
            let id = commands.spawn_empty().id();
            command_queue.apply(world);
            id
        })
    }

    /// get a type registration for the type, without checking if it's a component or resource
    pub fn get_type_by_name(&self, type_name: &str) -> Option<ScriptTypeRegistration> {
        let type_registry = self.type_registry();
        let type_registry = type_registry.read();
        type_registry
            .get_with_short_type_path(type_name)
            .or_else(|| type_registry.get_with_type_path(type_name))
            .map(|registration| ScriptTypeRegistration::new(Arc::new(registration.clone())))
    }

    /// get a type erased type registration for the type including information about whether it's a component or resource
    pub(crate) fn get_type_registration(
        &self,
        registration: ScriptTypeRegistration,
    ) -> Result<
        Union<
            ScriptTypeRegistration,
            Union<ScriptComponentRegistration, ScriptResourceRegistration>,
        >,
        InteropError,
    > {
        let registration = match self.get_resource_type(registration)? {
            Ok(res) => {
                return Ok(Union::new_right(Union::new_right(res)));
            }
            Err(registration) => registration,
        };

        let registration = match self.get_component_type(registration)? {
            Ok(comp) => {
                return Ok(Union::new_right(Union::new_left(comp)));
            }
            Err(registration) => registration,
        };

        Ok(Union::new_left(registration))
    }

    /// Similar to [`Self::get_type_by_name`] but returns a type erased [`ScriptTypeRegistration`], [`ScriptComponentRegistration`] or [`ScriptResourceRegistration`]
    /// depending on the underlying type and state of the world.
    pub fn get_type_registration_by_name(
        &self,
        type_name: String,
    ) -> Result<
        Option<
            Union<
                ScriptTypeRegistration,
                Union<ScriptComponentRegistration, ScriptResourceRegistration>,
            >,
        >,
        InteropError,
    > {
        let val = self.get_type_by_name(&type_name);
        Ok(match val {
            Some(registration) => Some(self.get_type_registration(registration)?),
            None => {
                // try the component registry
                let components = self.component_registry();
                let components = components.read();
                components
                    .get(&type_name)
                    .map(|c| Union::new_right(Union::new_left(c.registration.clone())))
            }
        })
    }

    /// get a schedule by name
    pub fn get_schedule_by_name(&self, schedule_name: String) -> Option<ReflectSchedule> {
        let schedule_registry = self.schedule_registry();
        let schedule_registry = schedule_registry.read();

        schedule_registry
            .get_schedule_by_name(&schedule_name)
            .cloned()
    }

    /// get a component type registration for the type
    pub fn get_component_type(
        &self,
        registration: ScriptTypeRegistration,
    ) -> Result<Result<ScriptComponentRegistration, ScriptTypeRegistration>, InteropError> {
        Ok(match self.get_component_id(registration.type_id())? {
            Some(comp_id) => Ok(ScriptComponentRegistration::new(registration, comp_id)),
            None => Err(registration),
        })
    }

    /// get a resource type registration for the type
    pub fn get_resource_type(
        &self,
        registration: ScriptTypeRegistration,
    ) -> Result<Result<ScriptResourceRegistration, ScriptTypeRegistration>, InteropError> {
        Ok(match self.get_resource_id(registration.type_id())? {
            Some(resource_id) => Ok(ScriptResourceRegistration::new(registration, resource_id)),
            None => Err(registration),
        })
    }

    /// add a default component to an entity
    pub fn add_default_component(
        &self,
        entity: Entity,
        registration: ScriptComponentRegistration,
    ) -> Result<(), InteropError> {
        // we look for ReflectDefault or ReflectFromWorld data then a ReflectComponent data
        let instance = if let Some(default_td) = registration
            .type_registration()
            .type_registration()
            .data::<ReflectDefault>()
        {
            default_td.default()
        } else if let Some(from_world_td) = registration
            .type_registration()
            .type_registration()
            .data::<ReflectFromWorld>()
        {
            self.with_global_access(|world| from_world_td.from_world(world))?
        } else {
            return Err(InteropError::missing_type_data(
                registration.registration.type_id(),
                "ReflectDefault or ReflectFromWorld".to_owned(),
            ));
        };

        registration.insert_into_entity(self.clone(), entity, instance)
    }

    /// insert the component into the entity
    pub fn insert_component(
        &self,
        entity: Entity,
        registration: ScriptComponentRegistration,
        value: ReflectReference,
    ) -> Result<(), InteropError> {
        let instance = <Box<dyn PartialReflect>>::from_script_ref(
            registration.type_registration().type_id(),
            ScriptValue::Reference(value),
            self.clone(),
        )?;

        let reflect = instance.try_into_reflect().map_err(|v| {
            InteropError::failed_from_reflect(
                Some(registration.type_registration().type_id()),
                format!("instance produced by conversion to target type when inserting component is not a full reflect type: {v:?}"),
            )
        })?;

        registration.insert_into_entity(self.clone(), entity, reflect)
    }

    /// get the component from the entity
    pub fn get_component(
        &self,
        entity: Entity,
        component_registration: ScriptComponentRegistration,
    ) -> Result<Option<ReflectReference>, InteropError> {
        let cell = self.as_unsafe_world_cell()?;
        let entity = cell
            .get_entity(entity)
            .map_err(|_| InteropError::missing_entity(entity))?;

        if entity.contains_id(component_registration.component_id) {
            Ok(Some(ReflectReference {
                base: ReflectBaseType {
                    type_id: component_registration.type_registration().type_id(),
                    base_id: ReflectBase::Component(
                        entity.id(),
                        component_registration.component_id,
                    ),
                },
                reflect_path: Default::default(),
            }))
        } else {
            Ok(None)
        }
    }

    /// check if the entity has the component
    pub fn has_component(
        &self,
        entity: Entity,
        component_id: ComponentId,
    ) -> Result<bool, InteropError> {
        let cell = self.as_unsafe_world_cell()?;
        let entity = cell
            .get_entity(entity)
            .map_err(|_| InteropError::missing_entity(entity))?;

        Ok(entity.contains_id(component_id))
    }

    /// remove the component from the entity
    pub fn remove_component(
        &self,
        entity: Entity,
        registration: ScriptComponentRegistration,
    ) -> Result<(), InteropError> {
        registration.remove_from_entity(self.clone(), entity)
    }

    /// get the given resource
    pub fn get_resource(
        &self,
        resource_id: ComponentId,
    ) -> Result<Option<ReflectReference>, InteropError> {
        let cell = self.as_unsafe_world_cell()?;
        let component_info = match cell.components().get_info(resource_id) {
            Some(info) => info,
            None => return Ok(None),
        };

        Ok(Some(ReflectReference {
            base: ReflectBaseType {
                type_id: component_info
                    .type_id()
                    .ok_or_else(|| {
                        InteropError::unsupported_operation(
                            None,
                            None,
                            format!(
                                "Resource {} does not have a type id. Such resources are not supported by BMS.",
                                component_info.name()
                            ),
                        )
                    })?,
                base_id: ReflectBase::Resource(resource_id),
            },
            reflect_path: Default::default(),
        }))
    }

    /// remove the given resource
    pub fn remove_resource(
        &self,
        registration: ScriptResourceRegistration,
    ) -> Result<(), InteropError> {
        let component_data = registration
            .type_registration()
            .type_registration()
            .data::<ReflectResource>()
            .ok_or_else(|| {
                InteropError::missing_type_data(
                    registration.registration.type_id(),
                    "ReflectResource".to_owned(),
                )
            })?;

        //  TODO: this shouldn't need entire world access it feels
        self.with_global_access(|world| component_data.remove(world))
    }

    /// check if the entity has the resource
    pub fn has_resource(&self, resource_id: ComponentId) -> Result<bool, InteropError> {
        let cell = self.as_unsafe_world_cell()?;
        // Safety: we are not reading the value at all
        let res_ptr = unsafe { cell.get_resource_by_id(resource_id) };
        Ok(res_ptr.is_some())
    }

    /// check the given entity exists
    pub fn has_entity(&self, entity: Entity) -> Result<bool, InteropError> {
        self.is_valid_entity(entity)
    }

    /// get the children of the given entity
    pub fn get_children(&self, entity: Entity) -> Result<Vec<Entity>, InteropError> {
        if !self.is_valid_entity(entity)? {
            return Err(InteropError::missing_entity(entity));
        }

        self.with_component(entity, |c: Option<&Children>| {
            c.map(|c| c.to_vec()).unwrap_or_default()
        })
    }

    /// get the parent of the given entity
    pub fn get_parent(&self, entity: Entity) -> Result<Option<Entity>, InteropError> {
        if !self.is_valid_entity(entity)? {
            return Err(InteropError::missing_entity(entity));
        }

        self.with_component(entity, |c: Option<&ChildOf>| c.map(|c| c.parent()))
    }

    /// insert children into the given entity
    pub fn push_children(&self, parent: Entity, children: &[Entity]) -> Result<(), InteropError> {
        // verify entities exist
        if !self.is_valid_entity(parent)? {
            return Err(InteropError::missing_entity(parent));
        }
        for c in children {
            if !self.is_valid_entity(*c)? {
                return Err(InteropError::missing_entity(*c));
            }
        }
        self.with_global_access(|world| {
            let mut queue = CommandQueue::default();
            let mut commands = Commands::new(&mut queue, world);
            commands.entity(parent).add_children(children);
            queue.apply(world);
        })
    }

    /// remove children from the given entity
    pub fn remove_children(&self, parent: Entity, children: &[Entity]) -> Result<(), InteropError> {
        if !self.is_valid_entity(parent)? {
            return Err(InteropError::missing_entity(parent));
        }

        for c in children {
            if !self.is_valid_entity(*c)? {
                return Err(InteropError::missing_entity(*c));
            }
        }
        self.with_global_access(|world| {
            let mut queue = CommandQueue::default();
            let mut commands = Commands::new(&mut queue, world);
            commands.entity(parent).detach_children(children);
            queue.apply(world);
        })
    }

    /// insert children into the given entity at the given index
    pub fn insert_children(
        &self,
        parent: Entity,
        index: usize,
        children: &[Entity],
    ) -> Result<(), InteropError> {
        if !self.is_valid_entity(parent)? {
            return Err(InteropError::missing_entity(parent));
        }

        for c in children {
            if !self.is_valid_entity(*c)? {
                return Err(InteropError::missing_entity(*c));
            }
        }

        self.with_global_access(|world| {
            let mut queue = CommandQueue::default();
            let mut commands = Commands::new(&mut queue, world);
            commands.entity(parent).insert_children(index, children);
            queue.apply(world);
        })
    }

    /// despawn this and all children of the given entity recursively
    pub fn despawn_recursive(&self, parent: Entity) -> Result<(), InteropError> {
        if !self.is_valid_entity(parent)? {
            return Err(InteropError::missing_entity(parent));
        }
        self.with_global_access(|world| {
            let mut queue = CommandQueue::default();
            let mut commands = Commands::new(&mut queue, world);
            commands.entity(parent).despawn();
            queue.apply(world);
        })
    }

    /// despawn the given entity
    pub fn despawn(&self, entity: Entity) -> Result<(), InteropError> {
        if !self.is_valid_entity(entity)? {
            return Err(InteropError::missing_entity(entity));
        }

        self.with_global_access(|world| {
            let mut queue = CommandQueue::default();
            let mut commands = Commands::new(&mut queue, world);
            commands.entity(entity).remove::<Children>().despawn();
            queue.apply(world);
        })
    }

    /// despawn all children of the given entity recursively
    pub fn despawn_descendants(&self, parent: Entity) -> Result<(), InteropError> {
        if !self.is_valid_entity(parent)? {
            return Err(InteropError::missing_entity(parent));
        }

        self.with_global_access(|world| {
            let mut queue = CommandQueue::default();
            let mut commands = Commands::new(&mut queue, world);
            commands.entity(parent).despawn_related::<Children>();
            queue.apply(world);
        })
    }

    /// Sends AppExit event to the world with success status
    pub fn exit(&self) -> Result<(), InteropError> {
        self.with_global_access(|world| {
            world.write_message(AppExit::Success);
        })
    }
}

/// A world container that stores the world in a thread local
pub struct ThreadWorldContainer;

#[derive(Clone)]
/// Context passed down indirectly to script related functions, used to avoid prop drilling problems.
pub struct ThreadScriptContext<'l> {
    /// The world pointer
    pub world: WorldGuard<'l>,
    /// The currently active script attachment
    pub attachment: ScriptAttachment,
}

thread_local! {
    static WORLD_CALLBACK_ACCESS: RefCell<Option<ThreadScriptContext<'static>>> = const { RefCell::new(None) };
}
#[profiling::all_functions]
impl ThreadWorldContainer {
    /// Tries to set the thread context to the given value
    pub fn set_context(&mut self, world: ThreadScriptContext<'static>) -> Result<(), InteropError> {
        WORLD_CALLBACK_ACCESS.with(|w| {
            w.replace(Some(world));
        });
        Ok(())
    }

    /// Tries to get the world from the container
    pub fn try_get_context<'l>(&self) -> Result<ThreadScriptContext<'l>, InteropError> {
        WORLD_CALLBACK_ACCESS
            .with(|w| w.borrow().clone().ok_or_else(InteropError::missing_world))
            .map(|v| ThreadScriptContext {
                world: v.world.shorten_lifetime(),
                attachment: v.attachment,
            })
    }
}

impl GetTypeInfo for ThreadWorldContainer {
    fn get_type_info(&self, type_id: TypeId) -> Option<&TypeInfo> {
        let world = self.try_get_context().ok()?.world;
        let registry = world.type_registry();
        let registry = registry.read();
        registry.get(type_id).map(|r| r.type_info())
    }

    fn query_type_registration(
        &self,
        type_id: TypeId,
        type_data_id: TypeId,
    ) -> Option<Box<dyn bevy_reflect::TypeData>> {
        let world = self.try_get_context().ok()?.world;
        let registry = world.type_registry();
        let registry = registry.read();
        registry
            .get(type_id)
            .and_then(|r| r.data_by_id(type_data_id).map(|t| t.clone_type_data()))
    }

    fn get_component_info(
        &self,
        component_id: ComponentId,
    ) -> Option<&bevy_ecs::component::ComponentInfo> {
        let world = self.try_get_context().ok()?.world;
        let cell = world.as_unsafe_world_cell().ok()?;
        cell.components().get_info(component_id)
    }

    unsafe fn as_any_static(&self) -> &dyn Any {
        self
    }
}

impl GetTypeInfo for WorldGuard<'_> {
    fn get_type_info(&self, type_id: TypeId) -> Option<&TypeInfo> {
        let registry = self.type_registry();
        let registry = registry.read();
        registry.get(type_id).map(|r| r.type_info())
    }

    fn query_type_registration(
        &self,
        type_id: TypeId,
        type_data_id: TypeId,
    ) -> Option<Box<dyn bevy_reflect::TypeData>> {
        let registry = self.type_registry();
        let registry = registry.read();
        registry
            .get(type_id)
            .and_then(|r| r.data_by_id(type_data_id).map(|t| t.clone_type_data()))
    }

    fn get_component_info(
        &self,
        component_id: ComponentId,
    ) -> Option<&bevy_ecs::component::ComponentInfo> {
        let cell = self.as_unsafe_world_cell().ok()?;
        cell.components().get_info(component_id)
    }

    /// # Safety
    /// - TODO: should generaly be safe as the guard is invalidated once the world is out of scope
    unsafe fn as_any_static(&self) -> &dyn Any {
        let static_self: &WorldGuard<'static> = unsafe { std::mem::transmute(self) };
        static_self as &dyn Any
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use bevy_reflect::{GetTypeRegistration, ReflectFromReflect};
    use test_utils::test_data::{SimpleEnum, SimpleStruct, SimpleTupleStruct, setup_world};

    #[test]
    fn test_construct_struct() {
        let mut world = setup_world(|_, _| {});
        let world = WorldAccessGuard::new_exclusive(&mut world);

        let registry = world.type_registry();
        let registry = registry.read();

        let registration = registry.get(TypeId::of::<SimpleStruct>()).unwrap().clone();
        let type_registration = ScriptTypeRegistration::new(Arc::new(registration));

        let payload = HashMap::from_iter(vec![("foo".to_owned(), ScriptValue::Integer(1))]);

        let result = world.construct(type_registration, payload, false);
        let expected =
            Ok::<_, InteropError>(Box::new(SimpleStruct { foo: 1 }) as Box<dyn PartialReflect>);
        pretty_assertions::assert_str_eq!(format!("{result:#?}"), format!("{expected:#?}"));
    }

    #[test]
    fn test_construct_tuple_struct() {
        let mut world = setup_world(|_, _| {});
        let world = WorldAccessGuard::new_exclusive(&mut world);

        let registry = world.type_registry();
        let registry = registry.read();

        let registration = registry
            .get(TypeId::of::<SimpleTupleStruct>())
            .unwrap()
            .clone();
        let type_registration = ScriptTypeRegistration::new(Arc::new(registration));

        // zero indexed
        let payload = HashMap::from_iter(vec![("0".to_owned(), ScriptValue::Integer(1))]);

        let result = world.construct(type_registration.clone(), payload, false);
        let expected =
            Ok::<_, InteropError>(Box::new(SimpleTupleStruct(1)) as Box<dyn PartialReflect>);
        pretty_assertions::assert_str_eq!(format!("{result:#?}"), format!("{expected:#?}"));

        // one indexed
        let payload = HashMap::from_iter(vec![("1".to_owned(), ScriptValue::Integer(1))]);

        let result = world.construct(type_registration, payload, true);
        let expected =
            Ok::<_, InteropError>(Box::new(SimpleTupleStruct(1)) as Box<dyn PartialReflect>);

        pretty_assertions::assert_str_eq!(format!("{result:#?}"), format!("{expected:#?}"));
    }

    #[test]
    fn test_construct_tuple() {
        let mut world = setup_world(|_, registry| {
            registry.register::<(usize, usize)>();
            // TODO: does this ever get registered on normal types? I don't think so: https://github.com/bevyengine/bevy/issues/17981
            registry.register_type_data::<(usize, usize), ReflectFromReflect>();
        });

        <usize as GetTypeRegistration>::get_type_registration();
        let world = WorldAccessGuard::new_exclusive(&mut world);

        let registry = world.type_registry();
        let registry = registry.read();

        let registration = registry
            .get(TypeId::of::<(usize, usize)>())
            .unwrap()
            .clone();
        let type_registration = ScriptTypeRegistration::new(Arc::new(registration));

        // zero indexed
        let payload = HashMap::from_iter(vec![
            ("0".to_owned(), ScriptValue::Integer(1)),
            ("1".to_owned(), ScriptValue::Integer(2)),
        ]);

        let result = world.construct(type_registration.clone(), payload, false);
        let expected = Ok::<_, InteropError>(Box::new((1, 2)) as Box<dyn PartialReflect>);
        pretty_assertions::assert_str_eq!(format!("{result:#?}"), format!("{expected:#?}"));

        // one indexed
        let payload = HashMap::from_iter(vec![
            ("1".to_owned(), ScriptValue::Integer(1)),
            ("2".to_owned(), ScriptValue::Integer(2)),
        ]);

        let result = world.construct(type_registration.clone(), payload, true);
        let expected = Ok::<_, InteropError>(Box::new((1, 2)) as Box<dyn PartialReflect>);
        pretty_assertions::assert_str_eq!(format!("{result:#?}"), format!("{expected:#?}"));
    }

    #[test]
    fn test_construct_enum() {
        let mut world = setup_world(|_, _| {});
        let world = WorldAccessGuard::new_exclusive(&mut world);

        let registry = world.type_registry();
        let registry = registry.read();

        let registration = registry.get(TypeId::of::<SimpleEnum>()).unwrap().clone();
        let type_registration = ScriptTypeRegistration::new(Arc::new(registration));

        // struct version
        let payload = HashMap::from_iter(vec![
            ("foo".to_owned(), ScriptValue::Integer(1)),
            ("variant".to_owned(), ScriptValue::String("Struct".into())),
        ]);

        let result = world.construct(type_registration.clone(), payload, false);
        let expected = Ok::<_, InteropError>(
            Box::new(SimpleEnum::Struct { foo: 1 }) as Box<dyn PartialReflect>
        );
        pretty_assertions::assert_str_eq!(format!("{result:#?}"), format!("{expected:#?}"));

        // tuple struct version
        let payload = HashMap::from_iter(vec![
            ("0".to_owned(), ScriptValue::Integer(1)),
            (
                "variant".to_owned(),
                ScriptValue::String("TupleStruct".into()),
            ),
        ]);

        let result = world.construct(type_registration.clone(), payload, false);
        let expected =
            Ok::<_, InteropError>(Box::new(SimpleEnum::TupleStruct(1)) as Box<dyn PartialReflect>);

        pretty_assertions::assert_str_eq!(format!("{result:#?}"), format!("{expected:#?}"));

        // unit version
        let payload = HashMap::from_iter(vec![(
            "variant".to_owned(),
            ScriptValue::String("Unit".into()),
        )]);

        let result = world.construct(type_registration, payload, false);
        let expected = Ok::<_, InteropError>(Box::new(SimpleEnum::Unit) as Box<dyn PartialReflect>);
        pretty_assertions::assert_str_eq!(format!("{result:#?}"), format!("{expected:#?}"));
    }

    #[test]
    fn test_scoped_handle_invalidate_doesnt_invalidate_parent() {
        let mut world = setup_world(|_, _| {});
        let world = WorldAccessGuard::new_exclusive(&mut world);
        let scoped_world = world.scope();

        // can use scoped & normal worlds
        scoped_world.spawn().unwrap();
        world.spawn().unwrap();
        pretty_assertions::assert_eq!(scoped_world.is_valid(), true);
        pretty_assertions::assert_eq!(world.is_valid(), true);

        scoped_world.invalidate();

        // can only use normal world
        pretty_assertions::assert_eq!(scoped_world.is_valid(), false);
        pretty_assertions::assert_eq!(world.is_valid(), true);
        world.spawn().unwrap();
    }

    #[test]
    fn with_existing_static_guard_does_not_invalidate_original() {
        let mut world = setup_world(|_, _| {});
        let world = WorldAccessGuard::new_exclusive(&mut world);

        let mut sneaky_clone = None;
        WorldAccessGuard::with_existing_static_guard(world.clone(), |g| {
            pretty_assertions::assert_eq!(g.is_valid(), true);
            sneaky_clone = Some(g.clone());
        });
        pretty_assertions::assert_eq!(world.is_valid(), true, "original world was invalidated");
        pretty_assertions::assert_eq!(
            sneaky_clone.map(|c| c.is_valid()),
            Some(false),
            "scoped world was not invalidated"
        );
    }

    #[test]
    fn test_with_access_scope_success() {
        let mut world = setup_world(|_, _| {});
        let guard = WorldAccessGuard::new_exclusive(&mut world);

        // within the access scope, no extra accesses are claimed
        let result = unsafe { guard.with_access_scope(|| 100) };
        assert_eq!(result.unwrap(), 100);
    }
}