wasserxr 0.2.1

A **dynamic XR Engine** to help you stay in the **flow**
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
use std::{
    ffi::{c_char, c_void},
    ptr, slice,
};

use uuid::Uuid;

use crate::{
    bindings::{
        WXRSceneError, clear_error, result_code, set_error, set_scene_error, str_from_ptr,
        string_to_ptr,
    },
    scene::Scene,
};

/// C callback that destroys a raw resource pointer.
pub type WXRResourceDestroyer = unsafe extern "C" fn(*mut c_void);

/// Opaque C handle for `wasserxr::scene::Scene`.
pub struct WXRScene {
    _private: [u8; 0],
}

#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
/// 16-byte entity UUID used by the C ABI.
pub struct WXREntity {
    /// UUID bytes.
    pub bytes: [u8; 16],
}

#[repr(C)]
/// Owned byte buffer returned by WasserXR bindings.
pub struct WXRBytes {
    /// Pointer to the first byte.
    pub ptr: *mut u8,
    /// Number of initialized bytes.
    pub len: usize,
    /// Allocation capacity.
    pub cap: usize,
}

#[repr(C)]
/// Owned array of entity ids returned by WasserXR bindings.
pub struct WXREntityArray {
    /// Pointer to the first entity id.
    pub ptr: *mut WXREntity,
    /// Number of entity ids.
    pub len: usize,
}

#[repr(C)]
/// Owned array of C strings returned by WasserXR bindings.
pub struct WXRStringArray {
    /// Pointer to the first C string pointer.
    pub ptr: *mut *mut c_char,
    /// Number of strings.
    pub len: usize,
}

impl WXREntity {
    pub(crate) fn from_uuid(id: Uuid) -> Self {
        Self {
            bytes: *id.as_bytes(),
        }
    }

    pub(crate) fn into_uuid(self) -> Uuid {
        Uuid::from_bytes(self.bytes)
    }
}

impl WXRBytes {
    fn empty() -> Self {
        Self {
            ptr: ptr::null_mut(),
            len: 0,
            cap: 0,
        }
    }

    fn from_vec(mut data: Vec<u8>) -> Self {
        let bytes = Self {
            ptr: data.as_mut_ptr(),
            len: data.len(),
            cap: data.capacity(),
        };
        std::mem::forget(data);
        bytes
    }
}

fn scene_ref<'a>(scene: *const WXRScene) -> Result<&'a Scene, WXRSceneError> {
    if scene.is_null() {
        return Err(WXRSceneError::NullPointer);
    }

    Ok(unsafe { &*(scene as *const Scene) })
}

fn scene_mut<'a>(scene: *mut WXRScene) -> Result<&'a mut Scene, WXRSceneError> {
    if scene.is_null() {
        return Err(WXRSceneError::NullPointer);
    }

    Ok(unsafe { &mut *(scene as *mut Scene) })
}

fn string_array(values: Vec<String>) -> WXRStringArray {
    let mut values: Vec<*mut c_char> = values.into_iter().map(string_to_ptr).collect();
    let array = WXRStringArray {
        ptr: values.as_mut_ptr(),
        len: values.len(),
    };
    std::mem::forget(values);
    array
}

fn entity_array(values: Vec<Uuid>) -> WXREntityArray {
    let mut values: Vec<WXREntity> = values.into_iter().map(WXREntity::from_uuid).collect();
    let array = WXREntityArray {
        ptr: values.as_mut_ptr(),
        len: values.len(),
    };
    std::mem::forget(values);
    array
}

/// Creates a new scene.
#[unsafe(no_mangle)]
pub extern "C" fn wxr_create_scene() -> *mut WXRScene {
    clear_error();
    Box::into_raw(Box::new(Scene::new())).cast()
}

/// Destroys a scene created by `wxr_create_scene`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_destroy_scene(scene: *mut WXRScene) {
    if !scene.is_null() {
        unsafe {
            drop(Box::from_raw(scene as *mut Scene));
        }
    }
}

/// Resets a scene.
#[unsafe(no_mangle)]
pub extern "C" fn wxr_reset(scene: *mut WXRScene) -> i32 {
    match scene_mut(scene) {
        Ok(scene) => result_code(scene.reset()),
        Err(error) => {
            set_error(error);
            -1
        }
    }
}

/// Serializes a scene into an owned byte buffer.
#[unsafe(no_mangle)]
pub extern "C" fn wxr_serialize(scene: *const WXRScene) -> WXRBytes {
    match scene_ref(scene).and_then(|scene| scene.serialize().map_err(Into::into)) {
        Ok(data) => {
            clear_error();
            WXRBytes::from_vec(data)
        }
        Err(error) => {
            set_error(error);
            WXRBytes::empty()
        }
    }
}

/// Frees a byte buffer returned by WasserXR bindings.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_free_bytes(bytes: WXRBytes) {
    if !bytes.ptr.is_null() && bytes.cap != 0 && bytes.len <= bytes.cap {
        unsafe {
            drop(Vec::from_raw_parts(bytes.ptr, bytes.len, bytes.cap));
        }
    }
}

/// Replaces a scene with serialized bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_deserialize(scene: *mut WXRScene, data: *const u8, len: usize) -> i32 {
    if data.is_null() && len != 0 {
        set_error(WXRSceneError::NullPointer);
        return -1;
    }

    match scene_mut(scene) {
        Ok(scene) => {
            let data = unsafe { slice::from_raw_parts(data, len) };
            result_code(scene.deserialize(data))
        }
        Err(error) => {
            set_error(error);
            -1
        }
    }
}

/// Saves a scene to a filesystem path.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_save(scene: *const WXRScene, path: *const c_char) -> i32 {
    match (scene_ref(scene), unsafe { str_from_ptr(path) }) {
        (Ok(scene), Ok(path)) => result_code(scene.save(path)),
        (Err(error), _) | (_, Err(error)) => {
            set_error(error);
            -1
        }
    }
}

/// Loads a scene from a filesystem path.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_load(scene: *mut WXRScene, path: *const c_char) -> i32 {
    match (scene_mut(scene), unsafe { str_from_ptr(path) }) {
        (Ok(scene), Ok(path)) => result_code(scene.load(path)),
        (Err(error), _) | (_, Err(error)) => {
            set_error(error);
            -1
        }
    }
}

/// Loads a dynamic plugin by path.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_load_plugin(scene: *mut WXRScene, path: *const c_char) -> i32 {
    match (scene_mut(scene), unsafe { str_from_ptr(path) }) {
        (Ok(scene), Ok(path)) => result_code(scene.load_plugin(path.to_owned())),
        (Err(error), _) | (_, Err(error)) => {
            set_error(error);
            -1
        }
    }
}

/// Returns the sorted paths of dynamically loaded plugins.
#[unsafe(no_mangle)]
pub extern "C" fn wxr_get_plugins(scene: *const WXRScene) -> WXRStringArray {
    match scene_ref(scene) {
        Ok(scene) => {
            clear_error();
            string_array(scene.get_plugins())
        }
        Err(error) => {
            set_error(error);
            WXRStringArray {
                ptr: ptr::null_mut(),
                len: 0,
            }
        }
    }
}

/// Unloads a dynamic plugin by path.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_unload_plugin(scene: *mut WXRScene, path: *const c_char) -> i32 {
    match (scene_mut(scene), unsafe { str_from_ptr(path) }) {
        (Ok(scene), Ok(path)) => result_code(scene.unload_plugin(path)),
        (Err(error), _) | (_, Err(error)) => {
            set_error(error);
            -1
        }
    }
}

/// Adds a new entity and returns its 16-byte id.
#[unsafe(no_mangle)]
pub extern "C" fn wxr_add_entity(scene: *mut WXRScene) -> WXREntity {
    match scene_mut(scene) {
        Ok(scene) => {
            clear_error();
            WXREntity::from_uuid(scene.add_entity())
        }
        Err(error) => {
            set_error(error);
            WXREntity { bytes: [0; 16] }
        }
    }
}

/// Returns all entity ids in sorted order.
#[unsafe(no_mangle)]
pub extern "C" fn wxr_get_entities(scene: *const WXRScene) -> WXREntityArray {
    match scene_ref(scene) {
        Ok(scene) => {
            clear_error();
            entity_array(scene.get_entities())
        }
        Err(error) => {
            set_error(error);
            WXREntityArray {
                ptr: ptr::null_mut(),
                len: 0,
            }
        }
    }
}

/// Frees an entity array returned by WasserXR bindings.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_free_entities(array: WXREntityArray) {
    if !array.ptr.is_null() {
        unsafe {
            drop(Vec::from_raw_parts(array.ptr, array.len, array.len));
        }
    }
}

/// Frees a string array returned by WasserXR bindings.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_free_strings(array: WXRStringArray) {
    if array.ptr.is_null() {
        return;
    }

    let values = unsafe { Vec::from_raw_parts(array.ptr, array.len, array.len) };
    for value in values {
        unsafe {
            crate::bindings::wxr_free_string(value);
        }
    }
}

/// Removes an entity and all components attached to it.
#[unsafe(no_mangle)]
pub extern "C" fn wxr_remove_entity(scene: *mut WXRScene, entity: WXREntity) -> i32 {
    match scene_mut(scene) {
        Ok(scene) => result_code(scene.remove_entity(entity.into_uuid())),
        Err(error) => {
            set_error(error);
            -1
        }
    }
}

/// Returns an entity display name as an owned C string.
#[unsafe(no_mangle)]
pub extern "C" fn wxr_get_entity_name(scene: *const WXRScene, entity: WXREntity) -> *mut c_char {
    match scene_ref(scene).and_then(|scene| {
        scene
            .get_entity_name(entity.into_uuid())
            .map(|name| name.to_owned())
            .map_err(Into::into)
    }) {
        Ok(name) => {
            clear_error();
            string_to_ptr(name)
        }
        Err(error) => {
            set_error(error);
            ptr::null_mut()
        }
    }
}

/// Sets an entity display name.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_set_entity_name(
    scene: *mut WXRScene,
    entity: WXREntity,
    name: *const c_char,
) -> i32 {
    match (scene_mut(scene), unsafe { str_from_ptr(name) }) {
        (Ok(scene), Ok(name)) => {
            result_code(scene.set_entity_name(entity.into_uuid(), name.to_owned()))
        }
        (Err(error), _) | (_, Err(error)) => {
            set_error(error);
            -1
        }
    }
}

/// Adds a system by id and priority.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_add_system(
    scene: *mut WXRScene,
    id: *const c_char,
    priority: usize,
) -> i32 {
    match (scene_mut(scene), unsafe { str_from_ptr(id) }) {
        (Ok(scene), Ok(id)) => result_code(scene.add_system(id.to_owned(), priority)),
        (Err(error), _) | (_, Err(error)) => {
            set_error(error);
            -1
        }
    }
}

/// Removes a system by id.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_remove_system(scene: *mut WXRScene, id: *const c_char) -> i32 {
    match (scene_mut(scene), unsafe { str_from_ptr(id) }) {
        (Ok(scene), Ok(id)) => result_code(scene.remove_system(id)),
        (Err(error), _) | (_, Err(error)) => {
            set_error(error);
            -1
        }
    }
}

/// Returns all system ids in sorted order.
#[unsafe(no_mangle)]
pub extern "C" fn wxr_get_systems(scene: *const WXRScene) -> WXRStringArray {
    match scene_ref(scene) {
        Ok(scene) => {
            clear_error();
            string_array(scene.get_systems())
        }
        Err(error) => {
            set_error(error);
            WXRStringArray {
                ptr: ptr::null_mut(),
                len: 0,
            }
        }
    }
}

/// Returns a system priority, or zero on failure.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_get_system_priority(
    scene: *const WXRScene,
    id: *const c_char,
) -> usize {
    match (scene_ref(scene), unsafe { str_from_ptr(id) }) {
        (Ok(scene), Ok(id)) => match scene.get_system_priority(id) {
            Ok(priority) => {
                clear_error();
                priority
            }
            Err(error) => {
                set_scene_error(error);
                0
            }
        },
        (Err(error), _) | (_, Err(error)) => {
            set_error(error);
            0
        }
    }
}

/// Returns the plugin id that provided a system.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_get_system_plugin_id(
    scene: *const WXRScene,
    id: *const c_char,
) -> *mut c_char {
    match (scene_ref(scene), unsafe { str_from_ptr(id) }) {
        (Ok(scene), Ok(id)) => match scene.get_system_plugin_id(id) {
            Ok(plugin) => {
                clear_error();
                string_to_ptr(plugin.to_owned())
            }
            Err(error) => {
                set_scene_error(error);
                ptr::null_mut()
            }
        },
        (Err(error), _) | (_, Err(error)) => {
            set_error(error);
            ptr::null_mut()
        }
    }
}

/// Adds a component to an entity by component id.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_add_component(
    scene: *mut WXRScene,
    entity: WXREntity,
    id: *const c_char,
) -> i32 {
    match (scene_mut(scene), unsafe { str_from_ptr(id) }) {
        (Ok(scene), Ok(id)) => result_code(scene.add_component(entity.into_uuid(), id.to_owned())),
        (Err(error), _) | (_, Err(error)) => {
            set_error(error);
            -1
        }
    }
}

/// Removes a component from an entity.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_remove_component(
    scene: *mut WXRScene,
    entity: WXREntity,
    id: *const c_char,
) -> i32 {
    match (scene_mut(scene), unsafe { str_from_ptr(id) }) {
        (Ok(scene), Ok(id)) => result_code(scene.remove_component(entity.into_uuid(), id)),
        (Err(error), _) | (_, Err(error)) => {
            set_error(error);
            -1
        }
    }
}

/// Returns component ids attached to an entity.
#[unsafe(no_mangle)]
pub extern "C" fn wxr_get_entity_components(
    scene: *const WXRScene,
    entity: WXREntity,
) -> WXRStringArray {
    match scene_ref(scene).and_then(|scene| {
        scene
            .get_entity_components(entity.into_uuid())
            .map_err(Into::into)
    }) {
        Ok(components) => {
            clear_error();
            string_array(components)
        }
        Err(error) => {
            set_error(error);
            WXRStringArray {
                ptr: ptr::null_mut(),
                len: 0,
            }
        }
    }
}

/// Returns the first entity with the component id, or a zero UUID if none exists.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_get_entity_with_component(
    scene: *const WXRScene,
    component_id: *const c_char,
) -> WXREntity {
    match (scene_ref(scene), unsafe { str_from_ptr(component_id) }) {
        (Ok(scene), Ok(component_id)) => {
            clear_error();
            scene
                .get_entity_with_component(component_id)
                .map(WXREntity::from_uuid)
                .unwrap_or(WXREntity { bytes: [0; 16] })
        }
        (Err(error), _) | (_, Err(error)) => {
            set_error(error);
            WXREntity { bytes: [0; 16] }
        }
    }
}

/// Returns 1 when an entity has the component id, otherwise 0.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_has_component(
    scene: *const WXRScene,
    entity: WXREntity,
    component_id: *const c_char,
) -> i32 {
    match (scene_ref(scene), unsafe { str_from_ptr(component_id) }) {
        (Ok(scene), Ok(component_id)) => {
            clear_error();
            i32::from(scene.has_component(entity.into_uuid(), component_id))
        }
        (Err(error), _) | (_, Err(error)) => {
            set_error(error);
            0
        }
    }
}

/// Hot-reloads all dynamic plugins while preserving serializable scene state.
#[unsafe(no_mangle)]
pub extern "C" fn wxr_reload(scene: *mut WXRScene) -> i32 {
    match scene_mut(scene) {
        Ok(scene) => result_code(scene.reload()),
        Err(error) => {
            set_error(error);
            -1
        }
    }
}

/// Runs all systems once. Returns 1 to continue and 0 to stop.
#[unsafe(no_mangle)]
pub extern "C" fn wxr_tick(scene: *mut WXRScene) -> i32 {
    match scene_mut(scene) {
        Ok(scene) => {
            clear_error();
            i32::from(scene.tick())
        }
        Err(error) => {
            set_error(error);
            0
        }
    }
}

/// Ensures an asset is loaded.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_ensure_asset_loaded(
    scene: *mut WXRScene,
    asset_type: *const c_char,
    data_string: *const c_char,
) -> i32 {
    match (
        scene_mut(scene),
        unsafe { str_from_ptr(asset_type) },
        unsafe { str_from_ptr(data_string) },
    ) {
        (Ok(scene), Ok(asset_type), Ok(data_string)) => {
            result_code(scene.ensure_asset_loaded(asset_type, data_string))
        }
        (Err(error), _, _) | (_, Err(error), _) | (_, _, Err(error)) => {
            set_error(error);
            -1
        }
    }
}

/// Returns loaded data strings for an asset type.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_get_loaded_asset_data_strings(
    scene: *const WXRScene,
    asset_type: *const c_char,
) -> WXRStringArray {
    match (scene_ref(scene), unsafe { str_from_ptr(asset_type) }) {
        (Ok(scene), Ok(asset_type)) => {
            clear_error();
            string_array(scene.get_loaded_asset_data_strings(asset_type))
        }
        (Err(error), _) | (_, Err(error)) => {
            set_error(error);
            WXRStringArray {
                ptr: ptr::null_mut(),
                len: 0,
            }
        }
    }
}

/// Returns a raw pointer to one component field.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_query(
    scene: *const WXRScene,
    entity: WXREntity,
    component_id: *const c_char,
    field_id: *const c_char,
) -> *mut c_void {
    match (
        scene_ref(scene),
        unsafe { str_from_ptr(component_id) },
        unsafe { str_from_ptr(field_id) },
    ) {
        (Ok(scene), Ok(component_id), Ok(field_id)) => {
            let fields = [field_id];
            match unsafe { scene.get_field_ptrs(entity.into_uuid(), component_id, &fields) } {
                Ok(mut fields) => {
                    clear_error();
                    fields.pop().unwrap_or(ptr::null_mut())
                }
                Err(error) => {
                    set_scene_error(error);
                    ptr::null_mut()
                }
            }
        }
        (Err(error), _, _) | (_, Err(error), _) | (_, _, Err(error)) => {
            set_error(error);
            ptr::null_mut()
        }
    }
}

/// Loads an asset if needed and returns a raw pointer to one asset field.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_asset_query(
    scene: *mut WXRScene,
    asset_type: *const c_char,
    data_string: *const c_char,
    field_id: *const c_char,
) -> *mut c_void {
    match (
        scene_mut(scene),
        unsafe { str_from_ptr(asset_type) },
        unsafe { str_from_ptr(data_string) },
        unsafe { str_from_ptr(field_id) },
    ) {
        (Ok(scene), Ok(asset_type), Ok(data_string), Ok(field_id)) => {
            if let Err(error) = scene.ensure_asset_loaded(asset_type, data_string) {
                set_scene_error(error);
                return ptr::null_mut();
            }
            let fields = [field_id];
            match unsafe { scene.get_asset_field_ptrs(asset_type, data_string, &fields) } {
                Ok(mut fields) => {
                    clear_error();
                    fields.pop().unwrap_or(ptr::null_mut())
                }
                Err(error) => {
                    set_scene_error(error);
                    ptr::null_mut()
                }
            }
        }
        (Err(error), _, _, _)
        | (_, Err(error), _, _)
        | (_, _, Err(error), _)
        | (_, _, _, Err(error)) => {
            set_error(error);
            ptr::null_mut()
        }
    }
}

/// Returns component field ids for a component on an entity.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_get_component_fields(
    scene: *const WXRScene,
    entity: WXREntity,
    component_id: *const c_char,
) -> WXRStringArray {
    match (scene_ref(scene), unsafe { str_from_ptr(component_id) }) {
        (Ok(scene), Ok(component_id)) => {
            match scene.get_component_fields(entity.into_uuid(), component_id) {
                Ok(fields) => {
                    clear_error();
                    string_array(fields)
                }
                Err(error) => {
                    set_scene_error(error);
                    WXRStringArray {
                        ptr: ptr::null_mut(),
                        len: 0,
                    }
                }
            }
        }
        (Err(error), _) | (_, Err(error)) => {
            set_error(error);
            WXRStringArray {
                ptr: ptr::null_mut(),
                len: 0,
            }
        }
    }
}

/// Returns the plugin id that provided a component on an entity.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_get_entity_component_plugin_id(
    scene: *const WXRScene,
    entity: WXREntity,
    component_id: *const c_char,
) -> *mut c_char {
    match (scene_ref(scene), unsafe { str_from_ptr(component_id) }) {
        (Ok(scene), Ok(component_id)) => {
            match scene.get_entity_component_plugin_id(entity.into_uuid(), component_id) {
                Ok(plugin) => {
                    clear_error();
                    string_to_ptr(plugin.to_owned())
                }
                Err(error) => {
                    set_scene_error(error);
                    ptr::null_mut()
                }
            }
        }
        (Err(error), _) | (_, Err(error)) => {
            set_error(error);
            ptr::null_mut()
        }
    }
}

/// Returns a component field type hint.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_get_component_field_type(
    scene: *const WXRScene,
    entity: WXREntity,
    component_id: *const c_char,
    field_id: *const c_char,
) -> i32 {
    match (
        scene_ref(scene),
        unsafe { str_from_ptr(component_id) },
        unsafe { str_from_ptr(field_id) },
    ) {
        (Ok(scene), Ok(component_id), Ok(field_id)) => {
            match scene.get_component_field_type(entity.into_uuid(), component_id, field_id) {
                Ok(field_type) => {
                    clear_error();
                    field_type as i32
                }
                Err(error) => {
                    set_scene_error(error);
                    -1
                }
            }
        }
        (Err(error), _, _) | (_, Err(error), _) | (_, _, Err(error)) => {
            set_error(error);
            -1
        }
    }
}

/// Returns 1 when a component field is mutable, otherwise 0.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_is_component_field_mutable(
    scene: *const WXRScene,
    entity: WXREntity,
    component_id: *const c_char,
    field_id: *const c_char,
) -> i32 {
    match (
        scene_ref(scene),
        unsafe { str_from_ptr(component_id) },
        unsafe { str_from_ptr(field_id) },
    ) {
        (Ok(scene), Ok(component_id), Ok(field_id)) => {
            match scene.is_component_field_mutable(entity.into_uuid(), component_id, field_id) {
                Ok(value) => {
                    clear_error();
                    i32::from(value)
                }
                Err(error) => {
                    set_scene_error(error);
                    0
                }
            }
        }
        (Err(error), _, _) | (_, Err(error), _) | (_, _, Err(error)) => {
            set_error(error);
            0
        }
    }
}

/// Returns 1 when a component field can be parsed from a string, otherwise 0.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_is_component_field_string_parsable(
    scene: *const WXRScene,
    entity: WXREntity,
    component_id: *const c_char,
    field_id: *const c_char,
) -> i32 {
    match (
        scene_ref(scene),
        unsafe { str_from_ptr(component_id) },
        unsafe { str_from_ptr(field_id) },
    ) {
        (Ok(scene), Ok(component_id), Ok(field_id)) => {
            match scene.is_component_field_string_parsable(
                entity.into_uuid(),
                component_id,
                field_id,
            ) {
                Ok(value) => {
                    clear_error();
                    i32::from(value)
                }
                Err(error) => {
                    set_scene_error(error);
                    0
                }
            }
        }
        (Err(error), _, _) | (_, Err(error), _) | (_, _, Err(error)) => {
            set_error(error);
            0
        }
    }
}

/// Renders a component field as an owned C string.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_render_field(
    scene: *const WXRScene,
    entity: WXREntity,
    component_id: *const c_char,
    field_id: *const c_char,
) -> *mut c_char {
    match (
        scene_ref(scene),
        unsafe { str_from_ptr(component_id) },
        unsafe { str_from_ptr(field_id) },
    ) {
        (Ok(scene), Ok(component_id), Ok(field_id)) => {
            match scene.render_field(entity.into_uuid(), component_id, field_id) {
                Ok(value) => {
                    clear_error();
                    string_to_ptr(value)
                }
                Err(error) => {
                    set_scene_error(error);
                    ptr::null_mut()
                }
            }
        }
        (Err(error), _, _) | (_, Err(error), _) | (_, _, Err(error)) => {
            set_error(error);
            ptr::null_mut()
        }
    }
}

/// Parses a string into a component field.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_parse_field(
    scene: *mut WXRScene,
    entity: WXREntity,
    component_id: *const c_char,
    field_id: *const c_char,
    input: *const c_char,
) -> i32 {
    match (
        scene_mut(scene),
        unsafe { str_from_ptr(component_id) },
        unsafe { str_from_ptr(field_id) },
        unsafe { str_from_ptr(input) },
    ) {
        (Ok(scene), Ok(component_id), Ok(field_id), Ok(input)) => {
            result_code(scene.parse_field(entity.into_uuid(), component_id, field_id, input))
        }
        (Err(error), _, _, _)
        | (_, Err(error), _, _)
        | (_, _, Err(error), _)
        | (_, _, _, Err(error)) => {
            set_error(error);
            -1
        }
    }
}

/// Adds a raw C resource to the scene.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_add_resource(
    scene: *mut WXRScene,
    name: *const c_char,
    data: *mut c_void,
    destroyer: WXRResourceDestroyer,
) -> i32 {
    if data.is_null() {
        set_error(WXRSceneError::NullPointer);
        return -1;
    }

    match (scene_mut(scene), unsafe { str_from_ptr(name) }) {
        (Ok(scene), Ok(name)) => {
            result_code(scene.add_raw_resource(name.to_owned(), data, destroyer))
        }
        (Err(error), _) | (_, Err(error)) => {
            set_error(error);
            -1
        }
    }
}

/// Returns a raw C resource pointer by name.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wxr_get_resource(
    scene: *mut WXRScene,
    name: *const c_char,
) -> *mut c_void {
    match (scene_mut(scene), unsafe { str_from_ptr(name) }) {
        (Ok(scene), Ok(name)) => match scene.get_raw_resource(name) {
            Ok(data) => {
                clear_error();
                data
            }
            Err(error) => {
                set_scene_error(error);
                ptr::null_mut()
            }
        },
        (Err(error), _) | (_, Err(error)) => {
            set_error(error);
            ptr::null_mut()
        }
    }
}

/// Requests that the next `wxr_tick` return 0.
#[unsafe(no_mangle)]
pub extern "C" fn wxr_should_exit(scene: *mut WXRScene) -> i32 {
    match scene_mut(scene) {
        Ok(scene) => {
            scene.should_exit();
            clear_error();
            0
        }
        Err(error) => {
            set_error(error);
            -1
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        bindings::wxr_error,
        scene::component::{FieldType, Schema, SerializedBytes},
    };
    use std::{
        ffi::{CStr, CString},
        sync::atomic::{AtomicUsize, Ordering},
    };

    #[repr(C)]
    struct FfiCounter {
        value: i64,
    }

    unsafe extern "C" fn ffi_counter_getter(data: *mut c_void) -> *mut c_void {
        unsafe { &mut (*(data as *mut FfiCounter)).value as *mut i64 as *mut c_void }
    }

    unsafe extern "C" fn ffi_counter_serializer(data: *const c_void) -> SerializedBytes {
        unsafe {
            SerializedBytes::from_vec((*(data as *const FfiCounter)).value.to_le_bytes().to_vec())
        }
    }

    unsafe extern "C" fn ffi_counter_deserializer(data: *mut c_void, value: SerializedBytes) {
        unsafe {
            let bytes = value.into_vec();
            if let Ok(bytes) = <[u8; 8]>::try_from(bytes.as_slice()) {
                (*(data as *mut FfiCounter)).value = i64::from_le_bytes(bytes);
            }
        }
    }

    #[unsafe(no_mangle)]
    unsafe extern "C" fn wxr_create_ffi_counter(_scene: *mut Scene) -> *mut c_void {
        Box::into_raw(Box::new(FfiCounter { value: 5 })) as *mut c_void
    }

    #[unsafe(no_mangle)]
    unsafe extern "C" fn wxr_destroy_ffi_counter(data: *mut c_void) {
        unsafe {
            drop(Box::from_raw(data as *mut FfiCounter));
        }
    }

    #[unsafe(no_mangle)]
    unsafe extern "C" fn wxr_schema_ffi_counter(schema: *mut Schema) {
        unsafe {
            (*schema).add_field(
                "value".to_owned(),
                FieldType::I64,
                Some(ffi_counter_getter),
                true,
                Some(ffi_counter_serializer),
                Some(ffi_counter_deserializer),
            );
        }
    }

    static RESOURCE_DROPS: AtomicUsize = AtomicUsize::new(0);

    unsafe extern "C" fn drop_usize(data: *mut c_void) {
        unsafe {
            drop(Box::from_raw(data as *mut usize));
        }
        RESOURCE_DROPS.fetch_add(1, Ordering::SeqCst);
    }

    #[test]
    fn scene_entity_name_round_trip() {
        let scene = wxr_create_scene();
        let entity = wxr_add_entity(scene);
        let name = CString::new("Player").unwrap();

        assert_eq!(
            unsafe { wxr_set_entity_name(scene, entity, name.as_ptr()) },
            0
        );

        let actual = wxr_get_entity_name(scene, entity);
        assert_eq!(
            unsafe { CStr::from_ptr(actual) }.to_str().unwrap(),
            "Player"
        );
        unsafe {
            crate::bindings::wxr_free_string(actual);
        }

        let entities = wxr_get_entities(scene);
        assert_eq!(entities.len, 1);
        unsafe {
            wxr_free_entities(entities);
            wxr_destroy_scene(scene);
        }
    }

    #[test]
    fn scene_error_tracks_failure() {
        let scene = wxr_create_scene();
        let missing = WXREntity { bytes: [7; 16] };

        assert_eq!(wxr_remove_entity(scene, missing), -1);
        assert_eq!(wxr_error(), WXRSceneError::EntityNotFound);

        unsafe {
            wxr_destroy_scene(scene);
        }
    }

    #[test]
    fn scene_query_returns_field_pointer() {
        let scene = wxr_create_scene();
        let entity = wxr_add_entity(scene);
        let component = CString::new("ffi_counter").unwrap();
        let field = CString::new("value").unwrap();

        assert_eq!(
            unsafe { wxr_add_component(scene, entity, component.as_ptr()) },
            0
        );
        let value = unsafe { wxr_query(scene, entity, component.as_ptr(), field.as_ptr()) };
        assert!(!value.is_null());
        assert_eq!(unsafe { *(value as *const i64) }, 5);

        unsafe {
            *(value as *mut i64) = 9;
        }
        let rendered =
            unsafe { wxr_render_field(scene, entity, component.as_ptr(), field.as_ptr()) };
        assert_eq!(unsafe { CStr::from_ptr(rendered) }.to_str().unwrap(), "9");
        unsafe {
            crate::bindings::wxr_free_string(rendered);
            wxr_destroy_scene(scene);
        }
    }

    #[test]
    fn raw_resource_round_trip_and_drop() {
        RESOURCE_DROPS.store(0, Ordering::SeqCst);
        let scene = wxr_create_scene();
        let name = CString::new("answer").unwrap();
        let data = Box::into_raw(Box::new(42usize)) as *mut c_void;

        assert_eq!(
            unsafe { wxr_add_resource(scene, name.as_ptr(), data, drop_usize) },
            0
        );
        let value = unsafe { wxr_get_resource(scene, name.as_ptr()) };
        assert_eq!(unsafe { *(value as *const usize) }, 42);

        unsafe {
            wxr_destroy_scene(scene);
        }
        assert_eq!(RESOURCE_DROPS.load(Ordering::SeqCst), 1);
    }
}