alice-physics 1.1.0

Deterministic 128-bit Fixed-Point Physics Engine
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
//! C Foreign Function Interface for ALICE-Physics
//!
//! Provides a C-compatible API for Unity, Unreal Engine, and other
//! game engines to use the deterministic physics simulation.
//!
//! # Safety
//!
//! All functions that take raw pointers require valid, non-null pointers.
//! The caller is responsible for proper lifecycle management (create/destroy pairs).
//!
//! Author: Moroya Sakamoto

use crate::math::{Fix128, QuatFix, Vec3Fix};
use crate::solver::{PhysicsWorld, RigidBody, SolverConfig};

// ============================================================================
// C-compatible types
// ============================================================================

/// C-compatible 3D vector (f64 for FFI boundary, converted to Fix128 internally)
#[repr(C)]
pub struct AliceVec3 {
    /// X component
    pub x: f64,
    /// Y component
    pub y: f64,
    /// Z component
    pub z: f64,
}

/// C-compatible quaternion
#[repr(C)]
pub struct AliceQuat {
    /// X component (imaginary i)
    pub x: f64,
    /// Y component (imaginary j)
    pub y: f64,
    /// Z component (imaginary k)
    pub z: f64,
    /// W component (scalar/real part)
    pub w: f64,
}

/// C-compatible physics config
#[repr(C)]
pub struct AlicePhysicsConfig {
    /// Number of substeps per step
    pub substeps: u32,
    /// Number of solver iterations per substep
    pub iterations: u32,
    /// Gravity X component (m/s^2)
    pub gravity_x: f64,
    /// Gravity Y component (m/s^2)
    pub gravity_y: f64,
    /// Gravity Z component (m/s^2)
    pub gravity_z: f64,
    /// Velocity damping factor (0..1)
    pub damping: f64,
}

/// C-compatible body info (read-only snapshot)
#[repr(C)]
pub struct AliceBodyInfo {
    /// Body position in world space
    pub position: AliceVec3,
    /// Linear velocity (m/s)
    pub velocity: AliceVec3,
    /// Angular velocity (rad/s)
    pub angular_velocity: AliceVec3,
    /// Orientation quaternion
    pub rotation: AliceQuat,
    /// Inverse mass (0 for static bodies)
    pub inv_mass: f64,
    /// 1 if static body, 0 otherwise
    pub is_static: u8,
    /// 1 if sensor/trigger body, 0 otherwise
    pub is_sensor: u8,
}

// ============================================================================
// Helper conversions
// ============================================================================

impl AliceVec3 {
    fn to_vec3fix(&self) -> Vec3Fix {
        Vec3Fix::new(
            Fix128::from_f64(self.x),
            Fix128::from_f64(self.y),
            Fix128::from_f64(self.z),
        )
    }

    fn from_vec3fix(v: Vec3Fix) -> Self {
        Self {
            x: v.x.to_f64(),
            y: v.y.to_f64(),
            z: v.z.to_f64(),
        }
    }
}

impl AliceQuat {
    fn from_quatfix(q: QuatFix) -> Self {
        Self {
            x: q.x.to_f64(),
            y: q.y.to_f64(),
            z: q.z.to_f64(),
            w: q.w.to_f64(),
        }
    }
}

// ============================================================================
// World lifecycle
// ============================================================================

/// Create a new physics world with default config.
/// Returns an opaque pointer. Must be freed with `alice_physics_world_destroy`.
#[no_mangle]
pub extern "C" fn alice_physics_world_create() -> *mut PhysicsWorld {
    let world = PhysicsWorld::new(SolverConfig::default());
    Box::into_raw(Box::new(world))
}

/// Create a physics world with custom config.
#[no_mangle]
pub extern "C" fn alice_physics_world_create_with_config(
    config: AlicePhysicsConfig,
) -> *mut PhysicsWorld {
    let solver_config = SolverConfig {
        substeps: config.substeps as usize,
        iterations: config.iterations as usize,
        gravity: Vec3Fix::new(
            Fix128::from_f64(config.gravity_x),
            Fix128::from_f64(config.gravity_y),
            Fix128::from_f64(config.gravity_z),
        ),
        damping: Fix128::from_f64(config.damping),
        ..Default::default()
    };
    let world = PhysicsWorld::new(solver_config);
    Box::into_raw(Box::new(world))
}

/// Destroy a physics world.
///
/// # Safety
/// `world` must be a valid pointer from `alice_physics_world_create*`.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_world_destroy(world: *mut PhysicsWorld) {
    if !world.is_null() {
        drop(Box::from_raw(world));
    }
}

/// Step the simulation by dt seconds (as f64, converted to Fix128).
///
/// Returns 1 on success, 0 on failure (null pointer or internal panic).
///
/// # Safety
/// `world` must be a valid pointer.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_world_step(world: *mut PhysicsWorld, dt: f64) -> u8 {
    let w = match world.as_mut() {
        Some(w) => w as *mut PhysicsWorld,
        None => return 0,
    };
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        (*w).step(Fix128::from_f64(dt));
    }));
    result.is_ok() as u8
}

/// Step the simulation N times with fixed dt (batch stepping).
///
/// Amortizes FFI overhead — ideal for training loops and rollback re-simulation.
/// Returns 1 on success, 0 on failure.
///
/// # Safety
/// `world` must be a valid pointer.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_world_step_n(
    world: *mut PhysicsWorld,
    dt: f64,
    steps: u32,
) -> u8 {
    let w = match world.as_mut() {
        Some(w) => w as *mut PhysicsWorld,
        None => return 0,
    };
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let dt_fix = Fix128::from_f64(dt);
        for _ in 0..steps {
            (*w).step(dt_fix);
        }
    }));
    result.is_ok() as u8
}

/// Get the number of bodies.
///
/// # Safety
/// `world` must be a valid pointer from `alice_physics_world_create*`, or null.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_world_body_count(world: *const PhysicsWorld) -> u32 {
    match world.as_ref() {
        Some(w) => w.bodies.len() as u32,
        None => 0,
    }
}

/// Get all body positions as a flat [x,y,z, x,y,z, ...] f64 array (zero-copy write).
///
/// Caller provides a buffer of `body_count * 3` f64 values.
/// Returns 1 on success, 0 on failure.
///
/// # Safety
/// `out` must point to at least `body_count * 3` f64 values.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_world_get_positions_batch(
    world: *const PhysicsWorld,
    out: *mut f64,
    out_capacity: u32,
) -> u8 {
    let w = match world.as_ref() {
        Some(w) => w,
        None => return 0,
    };
    if out.is_null() {
        return 0;
    }
    let n = w.bodies.len();
    if (out_capacity as usize) < n * 3 {
        return 0;
    }
    let buf = std::slice::from_raw_parts_mut(out, n * 3);
    for (i, body) in w.bodies.iter().enumerate() {
        buf[i * 3] = body.position.x.to_f64();
        buf[i * 3 + 1] = body.position.y.to_f64();
        buf[i * 3 + 2] = body.position.z.to_f64();
    }
    1
}

/// Get all body velocities as a flat [vx,vy,vz, ...] f64 array (zero-copy write).
///
/// # Safety
/// `out` must point to at least `body_count * 3` f64 values.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_world_get_velocities_batch(
    world: *const PhysicsWorld,
    out: *mut f64,
    out_capacity: u32,
) -> u8 {
    let w = match world.as_ref() {
        Some(w) => w,
        None => return 0,
    };
    if out.is_null() {
        return 0;
    }
    let n = w.bodies.len();
    if (out_capacity as usize) < n * 3 {
        return 0;
    }
    let buf = std::slice::from_raw_parts_mut(out, n * 3);
    for (i, body) in w.bodies.iter().enumerate() {
        buf[i * 3] = body.velocity.x.to_f64();
        buf[i * 3 + 1] = body.velocity.y.to_f64();
        buf[i * 3 + 2] = body.velocity.z.to_f64();
    }
    1
}

/// Set all body velocities from a flat [vx,vy,vz, ...] f64 array (batch update).
///
/// # Safety
/// `data` must point to at least `body_count * 3` f64 values.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_world_set_velocities_batch(
    world: *mut PhysicsWorld,
    data: *const f64,
    count: u32,
) -> u8 {
    let w = match world.as_mut() {
        Some(w) => w,
        None => return 0,
    };
    if data.is_null() {
        return 0;
    }
    let n = w.bodies.len();
    if (count as usize) < n * 3 {
        return 0;
    }
    let buf = std::slice::from_raw_parts(data, n * 3);
    for (i, body) in w.bodies.iter_mut().enumerate() {
        body.velocity = Vec3Fix::new(
            Fix128::from_f64(buf[i * 3]),
            Fix128::from_f64(buf[i * 3 + 1]),
            Fix128::from_f64(buf[i * 3 + 2]),
        );
    }
    1
}

/// Apply impulses to multiple bodies in batch.
///
/// `data` is a flat array of [body_id_as_f64, ix, iy, iz, ...] with `count/4` impulses.
///
/// # Safety
/// `data` must point to at least `count` f64 values, with `count` divisible by 4.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_body_apply_impulses_batch(
    world: *mut PhysicsWorld,
    data: *const f64,
    count: u32,
) -> u8 {
    let w = match world.as_mut() {
        Some(w) => w,
        None => return 0,
    };
    if data.is_null() || count % 4 != 0 {
        return 0;
    }
    let buf = std::slice::from_raw_parts(data, count as usize);
    let n_bodies = w.bodies.len();

    for chunk in buf.chunks_exact(4) {
        let body_id = chunk[0] as usize;
        if body_id >= n_bodies {
            continue;
        }
        let impulse = Vec3Fix::new(
            Fix128::from_f64(chunk[1]),
            Fix128::from_f64(chunk[2]),
            Fix128::from_f64(chunk[3]),
        );
        w.bodies[body_id].apply_impulse(impulse);
    }
    1
}

// ============================================================================
// Body management
// ============================================================================

/// Add a dynamic body. Returns body index.
///
/// # Safety
/// `world` must be a valid pointer from `alice_physics_world_create*`.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_body_add_dynamic(
    world: *mut PhysicsWorld,
    position: AliceVec3,
    mass: f64,
) -> u32 {
    match world.as_mut() {
        Some(w) => {
            let body = RigidBody::new_dynamic(position.to_vec3fix(), Fix128::from_f64(mass));
            w.add_body(body) as u32
        }
        None => u32::MAX,
    }
}

/// Add a static body. Returns body index.
///
/// # Safety
/// `world` must be a valid pointer from `alice_physics_world_create*`.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_body_add_static(
    world: *mut PhysicsWorld,
    position: AliceVec3,
) -> u32 {
    match world.as_mut() {
        Some(w) => {
            let body = RigidBody::new_static(position.to_vec3fix());
            w.add_body(body) as u32
        }
        None => u32::MAX,
    }
}

/// Add a sensor (trigger) body. Returns body index.
///
/// # Safety
/// `world` must be a valid pointer from `alice_physics_world_create*`.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_body_add_sensor(
    world: *mut PhysicsWorld,
    position: AliceVec3,
) -> u32 {
    match world.as_mut() {
        Some(w) => {
            let body = RigidBody::new_sensor(position.to_vec3fix());
            w.add_body(body) as u32
        }
        None => u32::MAX,
    }
}

/// Get body info (read-only snapshot).
///
/// # Safety
/// `world` must be a valid pointer. `out` must point to a valid `AliceBodyInfo`.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_body_get_info(
    world: *const PhysicsWorld,
    body_id: u32,
    out: *mut AliceBodyInfo,
) -> u8 {
    let (w, o) = match (world.as_ref(), out.as_mut()) {
        (Some(w), Some(o)) => (w, o),
        _ => return 0,
    };
    match w.bodies.get(body_id as usize) {
        Some(b) => {
            o.position = AliceVec3::from_vec3fix(b.position);
            o.velocity = AliceVec3::from_vec3fix(b.velocity);
            o.angular_velocity = AliceVec3::from_vec3fix(b.angular_velocity);
            o.rotation = AliceQuat::from_quatfix(b.rotation);
            o.inv_mass = b.inv_mass.to_f64();
            o.is_static = b.is_static() as u8;
            o.is_sensor = b.is_sensor as u8;
            1
        }
        None => 0,
    }
}

/// Get body position.
///
/// # Safety
/// `world` must be a valid pointer. `out` must point to a valid `AliceVec3`.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_body_get_position(
    world: *const PhysicsWorld,
    body_id: u32,
    out: *mut AliceVec3,
) -> u8 {
    let (w, o) = match (world.as_ref(), out.as_mut()) {
        (Some(w), Some(o)) => (w, o),
        _ => return 0,
    };
    match w.bodies.get(body_id as usize) {
        Some(b) => {
            *o = AliceVec3::from_vec3fix(b.position);
            1
        }
        None => 0,
    }
}

/// Raw Fix128 pair (hi:i64, lo:u64) exposed across the C ABI so
/// Unity/UE5 hosts can pin down determinism to the exact bit-pattern
/// used by the Rust solver (Phase F 11.3 byte-for-byte contract).
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AliceFix128Raw {
    /// High 64 bits (integer part).
    pub hi: i64,
    /// Low 64 bits (fractional part).
    pub lo: u64,
}

/// Raw Fix128 3-tuple exposed for byte-for-byte determinism contracts.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AliceVec3Fix128Raw {
    /// X component (raw Fix128 hi/lo pair).
    pub x: AliceFix128Raw,
    /// Y component (raw Fix128 hi/lo pair).
    pub y: AliceFix128Raw,
    /// Z component (raw Fix128 hi/lo pair).
    pub z: AliceFix128Raw,
}

/// Get body position as the raw Fix128 hi/lo pair (Phase F 11.3
/// byte-for-byte determinism contract). Unity/UE5 hosts assert on
/// the exact `(hi, lo)` pair to guarantee that every solver step
/// produces identical state on every platform (see
/// `deterministic-physics-lockstep-discipline` skill §11.3).
///
/// Returns 1 on success, 0 on invalid pointer or body index.
///
/// # Safety
/// `world` must be a valid pointer from `alice_physics_world_create*`.
/// `out` must be a valid pointer to writable `AliceVec3Fix128Raw`.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_body_get_position_fix128_raw(
    world: *const PhysicsWorld,
    body_id: u32,
    out: *mut AliceVec3Fix128Raw,
) -> u8 {
    let (w, o) = match (world.as_ref(), out.as_mut()) {
        (Some(w), Some(o)) => (w, o),
        _ => return 0,
    };
    match w.bodies.get(body_id as usize) {
        Some(b) => {
            *o = AliceVec3Fix128Raw {
                x: AliceFix128Raw {
                    hi: b.position.x.hi,
                    lo: b.position.x.lo,
                },
                y: AliceFix128Raw {
                    hi: b.position.y.hi,
                    lo: b.position.y.lo,
                },
                z: AliceFix128Raw {
                    hi: b.position.z.hi,
                    lo: b.position.z.lo,
                },
            };
            1
        }
        None => 0,
    }
}

/// Set body position.
///
/// # Safety
/// `world` must be a valid pointer from `alice_physics_world_create*`.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_body_set_position(
    world: *mut PhysicsWorld,
    body_id: u32,
    position: AliceVec3,
) -> u8 {
    match world.as_mut() {
        Some(w) => match w.bodies.get_mut(body_id as usize) {
            Some(b) => {
                b.position = position.to_vec3fix();
                1
            }
            None => 0,
        },
        None => 0,
    }
}

/// Get body velocity.
///
/// # Safety
/// `world` must be a valid pointer. `out` must point to a valid `AliceVec3`.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_body_get_velocity(
    world: *const PhysicsWorld,
    body_id: u32,
    out: *mut AliceVec3,
) -> u8 {
    let (w, o) = match (world.as_ref(), out.as_mut()) {
        (Some(w), Some(o)) => (w, o),
        _ => return 0,
    };
    match w.bodies.get(body_id as usize) {
        Some(b) => {
            *o = AliceVec3::from_vec3fix(b.velocity);
            1
        }
        None => 0,
    }
}

/// Set body velocity.
///
/// # Safety
/// `world` must be a valid pointer from `alice_physics_world_create*`.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_body_set_velocity(
    world: *mut PhysicsWorld,
    body_id: u32,
    velocity: AliceVec3,
) -> u8 {
    match world.as_mut() {
        Some(w) => match w.bodies.get_mut(body_id as usize) {
            Some(b) => {
                b.velocity = velocity.to_vec3fix();
                1
            }
            None => 0,
        },
        None => 0,
    }
}

/// Get body rotation as quaternion.
///
/// # Safety
/// `world` must be a valid pointer. `out` must point to a valid `AliceQuat`.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_body_get_rotation(
    world: *const PhysicsWorld,
    body_id: u32,
    out: *mut AliceQuat,
) -> u8 {
    let (w, o) = match (world.as_ref(), out.as_mut()) {
        (Some(w), Some(o)) => (w, o),
        _ => return 0,
    };
    match w.bodies.get(body_id as usize) {
        Some(b) => {
            *o = AliceQuat::from_quatfix(b.rotation);
            1
        }
        None => 0,
    }
}

/// Set body restitution (bounciness, 0.0-1.0).
///
/// # Safety
/// `world` must be a valid pointer from `alice_physics_world_create*`.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_body_set_restitution(
    world: *mut PhysicsWorld,
    body_id: u32,
    restitution: f64,
) -> u8 {
    match world.as_mut() {
        Some(w) => match w.bodies.get_mut(body_id as usize) {
            Some(b) => {
                b.restitution = Fix128::from_f64(restitution);
                1
            }
            None => 0,
        },
        None => 0,
    }
}

/// Set body friction coefficient.
///
/// # Safety
/// `world` must be a valid pointer from `alice_physics_world_create*`.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_body_set_friction(
    world: *mut PhysicsWorld,
    body_id: u32,
    friction: f64,
) -> u8 {
    match world.as_mut() {
        Some(w) => match w.bodies.get_mut(body_id as usize) {
            Some(b) => {
                b.friction = Fix128::from_f64(friction);
                1
            }
            None => 0,
        },
        None => 0,
    }
}

/// Apply impulse at center of mass.
///
/// # Safety
/// `world` must be a valid pointer from `alice_physics_world_create*`.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_body_apply_impulse(
    world: *mut PhysicsWorld,
    body_id: u32,
    impulse: AliceVec3,
) -> u8 {
    match world.as_mut() {
        Some(w) => match w.bodies.get_mut(body_id as usize) {
            Some(b) => {
                b.apply_impulse(impulse.to_vec3fix());
                1
            }
            None => 0,
        },
        None => 0,
    }
}

/// Apply impulse at a world-space point.
///
/// # Safety
/// `world` must be a valid pointer from `alice_physics_world_create*`.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_body_apply_impulse_at(
    world: *mut PhysicsWorld,
    body_id: u32,
    impulse: AliceVec3,
    point: AliceVec3,
) -> u8 {
    match world.as_mut() {
        Some(w) => match w.bodies.get_mut(body_id as usize) {
            Some(b) => {
                b.apply_impulse_at(impulse.to_vec3fix(), point.to_vec3fix());
                1
            }
            None => 0,
        },
        None => 0,
    }
}

// ============================================================================
// Config
// ============================================================================

/// Get default physics config.
#[no_mangle]
pub extern "C" fn alice_physics_config_default() -> AlicePhysicsConfig {
    let cfg = SolverConfig::default();
    AlicePhysicsConfig {
        substeps: cfg.substeps as u32,
        iterations: cfg.iterations as u32,
        gravity_x: cfg.gravity.x.to_f64(),
        gravity_y: cfg.gravity.y.to_f64(),
        gravity_z: cfg.gravity.z.to_f64(),
        damping: cfg.damping.to_f64(),
    }
}

/// Set gravity on an existing world.
///
/// # Safety
/// `world` must be a valid pointer from `alice_physics_world_create*`.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_world_set_gravity(
    world: *mut PhysicsWorld,
    x: f64,
    y: f64,
    z: f64,
) {
    if let Some(w) = world.as_mut() {
        w.config.gravity = Vec3Fix::new(
            Fix128::from_f64(x),
            Fix128::from_f64(y),
            Fix128::from_f64(z),
        );
    }
}

/// Set substeps on an existing world.
///
/// # Safety
/// `world` must be a valid pointer from `alice_physics_world_create*`.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_world_set_substeps(world: *mut PhysicsWorld, substeps: u32) {
    if let Some(w) = world.as_mut() {
        w.config.substeps = substeps as usize;
    }
}

// ============================================================================
// State serialization (for rollback netcode)
// ============================================================================

/// Serialize world state. Caller must free with `alice_physics_state_free`.
/// Returns data pointer and writes length to `out_len`.
///
/// # Safety
/// `world` must be a valid pointer. `out_len` must point to a valid `u32`.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_state_serialize(
    world: *const PhysicsWorld,
    out_len: *mut u32,
) -> *mut u8 {
    let w = match world.as_ref() {
        Some(w) => w,
        None => {
            if let Some(len) = out_len.as_mut() {
                *len = 0;
            }
            return std::ptr::null_mut();
        }
    };
    let state = w.serialize_state();
    let len = state.len();
    if let Some(out) = out_len.as_mut() {
        *out = len as u32;
    }
    let boxed = state.into_boxed_slice();
    Box::into_raw(boxed) as *mut u8
}

/// Deserialize world state (restores from serialized snapshot).
/// Returns 1 on success, 0 on failure.
///
/// # Safety
/// `world` must be a valid pointer. `data` must point to `len` valid bytes.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_state_deserialize(
    world: *mut PhysicsWorld,
    data: *const u8,
    len: u32,
) -> u8 {
    let w = match world.as_mut() {
        Some(w) => w,
        None => return 0,
    };
    if data.is_null() || len == 0 {
        return 0;
    }
    let slice = std::slice::from_raw_parts(data, len as usize);
    w.deserialize_state(slice) as u8
}

/// Free a serialized state buffer.
///
/// # Safety
/// `data` must be a pointer returned by `alice_physics_state_serialize` with matching `len`.
#[no_mangle]
pub unsafe extern "C" fn alice_physics_state_free(data: *mut u8, len: u32) {
    if !data.is_null() && len > 0 {
        let slice = std::slice::from_raw_parts_mut(data, len as usize);
        drop(Box::from_raw(slice as *mut [u8]));
    }
}

// ============================================================================
// Version
// ============================================================================

/// Get library version string. Returns a static null-terminated string.
///
/// Always equals `CARGO_PKG_VERSION` of the built crate (v1.0.1 fix: the
/// string was a hardcoded `"0.6.0"` before).
#[no_mangle]
pub extern "C" fn alice_physics_version() -> *const std::os::raw::c_char {
    // `concat!` + `env!` keeps this a `&'static str` with an explicit NUL;
    // no C-string literal so the `ffi` feature stays within the 1.70 MSRV.
    const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), "\0");
    VERSION.as_ptr().cast()
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn version_string_matches_cargo_pkg_version() {
        // SAFETY: `alice_physics_version` returns a NUL-terminated static
        // string owned by the binary.
        let s = unsafe { std::ffi::CStr::from_ptr(alice_physics_version()) };
        assert_eq!(s.to_str().unwrap(), env!("CARGO_PKG_VERSION"));
    }

    #[test]
    fn test_vec3_conversion_roundtrip() {
        let original = Vec3Fix::new(
            Fix128::from_f64(1.5),
            Fix128::from_f64(-2.25),
            Fix128::from_f64(3.75),
        );
        let c = AliceVec3::from_vec3fix(original);
        let back = c.to_vec3fix();
        assert_eq!(original.x.hi, back.x.hi);
        assert_eq!(original.y.hi, back.y.hi);
        assert_eq!(original.z.hi, back.z.hi);
    }

    #[test]
    fn test_world_create_destroy() {
        // SAFETY: All pointers are created/destroyed within this test scope.
        unsafe {
            let world = alice_physics_world_create();
            assert!(!world.is_null());
            assert_eq!(alice_physics_world_body_count(world), 0);
            alice_physics_world_destroy(world);
        }
    }

    #[test]
    fn test_world_destroy_null() {
        // SAFETY: Null pointer is explicitly handled by the C API.
        unsafe {
            alice_physics_world_destroy(std::ptr::null_mut());
        }
    }

    #[test]
    fn test_world_create_with_config() {
        // SAFETY: All pointers are created/destroyed within this test scope.
        unsafe {
            let config = alice_physics_config_default();
            let world = alice_physics_world_create_with_config(config);
            assert!(!world.is_null());
            alice_physics_world_destroy(world);
        }
    }

    #[test]
    fn test_body_add_and_get() {
        // SAFETY: All pointers are created/destroyed within this test scope.
        unsafe {
            let world = alice_physics_world_create();
            let pos = AliceVec3 {
                x: 1.0,
                y: 2.0,
                z: 3.0,
            };
            let id = alice_physics_body_add_dynamic(world, pos, 1.0);
            assert_eq!(id, 0);
            assert_eq!(alice_physics_world_body_count(world), 1);

            let mut out = AliceVec3 {
                x: 0.0,
                y: 0.0,
                z: 0.0,
            };
            let ok = alice_physics_body_get_position(world, id, &mut out);
            assert_eq!(ok, 1);
            assert!((out.x - 1.0).abs() < 1e-10);
            assert!((out.y - 2.0).abs() < 1e-10);
            assert!((out.z - 3.0).abs() < 1e-10);

            alice_physics_world_destroy(world);
        }
    }

    #[test]
    fn test_body_get_invalid_id() {
        // SAFETY: All pointers are created/destroyed within this test scope.
        unsafe {
            let world = alice_physics_world_create();
            let mut out = AliceVec3 {
                x: 0.0,
                y: 0.0,
                z: 0.0,
            };
            let ok = alice_physics_body_get_position(world, 999, &mut out);
            assert_eq!(ok, 0);
            alice_physics_world_destroy(world);
        }
    }

    #[test]
    fn test_null_world_safety() {
        // SAFETY: Null pointers are explicitly handled by the C API.
        unsafe {
            let null: *mut PhysicsWorld = std::ptr::null_mut();
            assert_eq!(alice_physics_world_body_count(null), 0);
            assert_eq!(alice_physics_world_step(null, 0.016), 0);
            assert_eq!(alice_physics_world_step_n(null, 0.016, 10), 0);

            let pos = AliceVec3 {
                x: 0.0,
                y: 0.0,
                z: 0.0,
            };
            assert_eq!(alice_physics_body_add_dynamic(null, pos, 1.0), u32::MAX);
        }
    }

    #[test]
    fn test_step_and_gravity() {
        // SAFETY: All pointers are created/destroyed within this test scope.
        unsafe {
            let world = alice_physics_world_create();
            let pos = AliceVec3 {
                x: 0.0,
                y: 10.0,
                z: 0.0,
            };
            let id = alice_physics_body_add_dynamic(world, pos, 1.0);

            for _ in 0..60 {
                alice_physics_world_step(world, 1.0 / 60.0);
            }

            let mut out = AliceVec3 {
                x: 0.0,
                y: 0.0,
                z: 0.0,
            };
            alice_physics_body_get_position(world, id, &mut out);
            assert!(out.y < 10.0, "Body should fall under gravity, y={}", out.y);

            alice_physics_world_destroy(world);
        }
    }

    #[test]
    fn test_batch_positions() {
        // SAFETY: All pointers are created/destroyed within this test scope.
        unsafe {
            let world = alice_physics_world_create();
            let p1 = AliceVec3 {
                x: 1.0,
                y: 2.0,
                z: 3.0,
            };
            let p2 = AliceVec3 {
                x: 4.0,
                y: 5.0,
                z: 6.0,
            };
            alice_physics_body_add_static(world, p1);
            alice_physics_body_add_static(world, p2);

            let mut buf = [0.0f64; 6];
            let ok = alice_physics_world_get_positions_batch(world, buf.as_mut_ptr(), 6);
            assert_eq!(ok, 1);
            assert!((buf[0] - 1.0).abs() < 1e-10);
            assert!((buf[1] - 2.0).abs() < 1e-10);
            assert!((buf[2] - 3.0).abs() < 1e-10);
            assert!((buf[3] - 4.0).abs() < 1e-10);
            assert!((buf[4] - 5.0).abs() < 1e-10);
            assert!((buf[5] - 6.0).abs() < 1e-10);

            // Insufficient capacity
            let fail = alice_physics_world_get_positions_batch(world, buf.as_mut_ptr(), 3);
            assert_eq!(fail, 0);

            alice_physics_world_destroy(world);
        }
    }

    #[test]
    fn test_state_serialization_ffi() {
        // SAFETY: All pointers are created/destroyed within this test scope.
        unsafe {
            let world = alice_physics_world_create();
            let pos = AliceVec3 {
                x: 0.0,
                y: 10.0,
                z: 0.0,
            };
            alice_physics_body_add_dynamic(world, pos, 1.0);

            // Serialize
            let mut len: u32 = 0;
            let data = alice_physics_state_serialize(world, &mut len);
            assert!(!data.is_null());
            assert!(len > 0);

            // Deserialize into same world
            let ok = alice_physics_state_deserialize(world, data, len);
            assert_eq!(ok, 1);

            // Free
            alice_physics_state_free(data, len);
            alice_physics_world_destroy(world);
        }
    }

    #[test]
    fn test_impulse_application() {
        // SAFETY: All pointers are created/destroyed within this test scope.
        unsafe {
            let world = alice_physics_world_create();
            alice_physics_world_set_gravity(world, 0.0, 0.0, 0.0);
            let pos = AliceVec3 {
                x: 0.0,
                y: 0.0,
                z: 0.0,
            };
            let id = alice_physics_body_add_dynamic(world, pos, 1.0);

            let impulse = AliceVec3 {
                x: 10.0,
                y: 0.0,
                z: 0.0,
            };
            alice_physics_body_apply_impulse(world, id, impulse);
            alice_physics_world_step(world, 1.0 / 60.0);

            let mut out = AliceVec3 {
                x: 0.0,
                y: 0.0,
                z: 0.0,
            };
            alice_physics_body_get_position(world, id, &mut out);
            assert!(out.x > 0.0, "Impulse should move body right, x={}", out.x);

            alice_physics_world_destroy(world);
        }
    }

    #[test]
    fn test_body_info() {
        // SAFETY: All pointers are created/destroyed within this test scope.
        unsafe {
            let world = alice_physics_world_create();
            let pos = AliceVec3 {
                x: 1.0,
                y: 2.0,
                z: 3.0,
            };
            let id = alice_physics_body_add_sensor(world, pos);

            let mut info = std::mem::zeroed::<AliceBodyInfo>();
            let ok = alice_physics_body_get_info(world, id, &mut info);
            assert_eq!(ok, 1);
            assert_eq!(info.is_sensor, 1);
            assert!((info.position.x - 1.0).abs() < 1e-10);

            alice_physics_world_destroy(world);
        }
    }

    /// FFI contract test (Phase F 11.3): verifies deterministic
    /// gravity fall through the C ABI so Unity/UE5 host integrations
    /// can be checked against a Rust-side reference.
    ///
    /// The Rust side runs the reference invocation and asserts on
    /// bracketing tolerances that describe the current behaviour;
    /// Unity/UE5 binding tests must reproduce the same
    /// `(x, y, z)` final position to within these brackets. Once
    /// the Fix128 output is pinned in a follow-up, the tolerances
    /// will be replaced with byte-for-byte assertions (see
    /// `deterministic-physics-lockstep-discipline` skill §11.3 FFI
    /// contract test).
    #[test]
    fn ffi_contract_gravity_fall_deterministic() {
        // SAFETY: All FFI pointers are created and destroyed within
        // this test scope; no aliasing occurs because no other test
        // touches the returned world pointer.
        unsafe {
            let world = alice_physics_world_create();
            let pos = AliceVec3 {
                x: 0.0,
                y: 10.0,
                z: 0.0,
            };
            let mass = 1.0_f64;
            let id = alice_physics_body_add_dynamic(world, pos, mass);

            // 60 steps at 60 Hz = 1 s under default gravity.
            for _ in 0..60 {
                let _ = alice_physics_world_step(world, 1.0 / 60.0);
            }

            let mut info = std::mem::zeroed::<AliceBodyInfo>();
            let ok = alice_physics_body_get_info(world, id, &mut info);
            assert_eq!(ok, 1);

            // Reference contract:
            // - Body must fall (y strictly less than starting height).
            // - No horizontal drift under vertical gravity.
            // - Final y is bounded below by a conservative lower limit
            //   (well within the physically plausible range for 1 s of
            //   uniform gravity ≈ -9.81 m/s² over one-second flight).
            assert!(
                info.position.y < 10.0,
                "body must fall under gravity, got y={}",
                info.position.y
            );
            assert!(
                info.position.y > -20.0,
                "final y out of expected range, got y={}",
                info.position.y
            );
            assert!(
                info.position.x.abs() < 1e-9,
                "no horizontal drift expected, got x={}",
                info.position.x
            );
            assert!(
                info.position.z.abs() < 1e-9,
                "no horizontal drift expected, got z={}",
                info.position.z
            );

            // Phase F 11.3 body: byte-for-byte determinism gate.
            // Read the Fix128 hi/lo raw pair via the dedicated FFI
            // getter and verify that a second identical simulation
            // produces the exact same hi/lo pair — this is the runtime
            // contract that Unity/UE5 host bindings must satisfy.
            let mut raw = std::mem::zeroed::<AliceVec3Fix128Raw>();
            let ok_raw = alice_physics_body_get_position_fix128_raw(world, id, &mut raw);
            assert_eq!(ok_raw, 1, "raw fix128 getter must succeed");

            let world2 = alice_physics_world_create();
            let pos2 = AliceVec3 {
                x: 0.0,
                y: 10.0,
                z: 0.0,
            };
            let id2 = alice_physics_body_add_dynamic(world2, pos2, mass);
            for _ in 0..60 {
                let _ = alice_physics_world_step(world2, 1.0 / 60.0);
            }
            let mut raw2 = std::mem::zeroed::<AliceVec3Fix128Raw>();
            let ok_raw2 = alice_physics_body_get_position_fix128_raw(world2, id2, &mut raw2);
            assert_eq!(
                ok_raw2, 1,
                "raw fix128 getter must succeed on the replay world"
            );
            alice_physics_world_destroy(world2);

            assert_eq!(raw.x.hi, raw2.x.hi, "byte-for-byte determinism (x.hi)");
            assert_eq!(raw.x.lo, raw2.x.lo, "byte-for-byte determinism (x.lo)");
            assert_eq!(raw.y.hi, raw2.y.hi, "byte-for-byte determinism (y.hi)");
            assert_eq!(raw.y.lo, raw2.y.lo, "byte-for-byte determinism (y.lo)");
            assert_eq!(raw.z.hi, raw2.z.hi, "byte-for-byte determinism (z.hi)");
            assert_eq!(raw.z.lo, raw2.z.lo, "byte-for-byte determinism (z.lo)");

            // Golden pin (v1.0.1): the exact raw pair produced by this
            // scenario (dynamic body at y=10, mass 1, 60 steps of 1/60 s
            // under default gravity). Unity / UE5 host bindings replay the
            // same scenario and must read back these six values; any
            // solver-side change that moves them is a determinism break
            // and must bump the golden together with a CHANGELOG entry.
            const GOLDEN: [(i64, u64); 3] = [(0, 0), (8, 6_631_112_686_738_674_129), (0, 0)];
            assert_eq!(
                [
                    (raw.x.hi, raw.x.lo),
                    (raw.y.hi, raw.y.lo),
                    (raw.z.hi, raw.z.lo)
                ],
                GOLDEN,
                "FFI free-fall golden raw Fix128 pair drifted"
            );

            alice_physics_world_destroy(world);
        }
    }
}