alice-physics 3.0.1

Deterministic physics engine: 128-bit fixed-point rigid bodies with bit-exact, replayable results, typed observation and rollback for search and planning, plus FEM, CFD and 3D-print analysis modules
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
//! ALICE-Physics: Deterministic 128-bit Fixed-Point Physics Engine
//!
//! A high-precision physics engine designed for deterministic simulation
//! across different platforms and hardware. Uses 128-bit fixed-point arithmetic
//! to ensure bit-exact results regardless of CPU or compiler.
//!
//! # Features
//!
//! - **Deterministic**: the Fix128 core (rigid bodies, constraints, joints,
//!   BVH, CCD) is bit-exact across all platforms — pure integer arithmetic.
//!   <!-- claim-test: test_multi_step_bit_exact -->
//!   Grid / engineering modules on `f32` / `f64` are bit-exact via `det_math`
//!   (correctly-rounded software transcendental functions); see README
//!   "Determinism" for the per-module table.
//!   <!-- claim-test: determinism_freefall -->
//! - **128-bit Fixed-Point**: I64F64 format with CORDIC trigonometry
//! - **XPBD Solver**: Extended Position Based Dynamics for stable constraints
//! - **GJK/EPA**: Robust collision detection for convex shapes
//! - **Linear BVH**: Morton code-based spatial acceleration (used for broad-phase and raycast)
//! - **Rollback Support**: State serialization for netcode
//!
//! # Feature Flags
//!
//! <!-- readme-sync: features -->
//! | Feature | Description |
//! |---------|-------------|
//! | `std` (default) | Standard library support. Disable for `no_std` (requires `alloc`). |
//! | `simd` | SSE2 acceleration for `Vec3Fix` math ops (`dot`, `add`, `sub`). Results remain bit-exact. Solver hot paths use scalar arithmetic to guarantee cross-platform determinism. |
//! | `parallel` | Parallel constraint solving via Rayon with graph-colored batches. |
//! | `neural` | Deterministic neural controller integration (ALICE-ML). |
//! | `python` | `PyO3` + `NumPy` zero-copy Python bindings. |
//! | `replay` | Replay recording/playback via ALICE-DB. |
//! | `ffi` | C FFI for Unity/UE5/game engine integration. |
//! | `wasm` | WebAssembly bindings via wasm-bindgen. |
//! | `analytics` | ALICE-Analytics simulation profiling (`DDSketch`, `HyperLogLog`). |
//! | `gpu-solver-bridge` | `GpuSolverBridge` trait for external GPU solver backends. No cost when off. |
//! | `privacy-crypto` | `privacy` re-exports `alice-crypto`'s differential-privacy primitives and adds `KeyedRappor`. Off by default; `alice-crypto` becomes a public dependency. |
//!
//! # Example
//!
//! ```rust
//! use alice_physics::{PhysicsWorld, PhysicsConfig, RigidBody, Fix128, Vec3Fix};
//!
//! // Create physics world
//! let config = PhysicsConfig::default();
//! let mut world = PhysicsWorld::new(config);
//!
//! // Add a dynamic body
//! let body = RigidBody::new_dynamic(
//!     Vec3Fix::from_int(0, 10, 0),  // position
//!     Fix128::ONE,                   // mass = 1
//! );
//! let body_id = world.add_body(body);
//!
//! // Step simulation (60 frames at 1/60 second)
//! let dt = Fix128::from_ratio(1, 60);
//! for _ in 0..60 {
//!     world.step(dt);
//! }
//!
//! // Body should have fallen under gravity
//! let pos = world.bodies[body_id].position;
//! assert!(pos.y < Fix128::from_int(10), "Body fell under gravity");
//! ```
//!
//! # Modules
//!
//! ## Core
//! - [`math`]: Fixed-point math primitives (Fix128, `Vec3Fix`, `QuatFix`, `Mat3Fix`, CORDIC)
//! - [`collider`]: Collision shapes (Sphere, Capsule, `ConvexHull`, AABB) and GJK/EPA detection
//! - [`solver`]: XPBD physics solver, rigid body dynamics, constraint batching
//! - [`bvh`]: Linear BVH for broad-phase collision detection (Morton codes, stackless traversal)
//! - [`error`]: Unified physics error type (`PhysicsError`)
//!
//! ## Collision Shapes
//! - [`box_collider`]: Oriented Bounding Box (OBB) with GJK support
//! - [`compound`]: Multi-shape compound collider with local transforms
//! - [`cone`]: Cone collider with GJK support (apex +Y, base -Y)
//! - [`convex_mesh_builder`]: Incremental convex hull builder from point sets
//! - [`cylinder`]: Cylinder collider with GJK support
//! - [`ellipsoid`]: Ellipsoid collider with three independent semi-axes
//! - [`plane_collider`]: Infinite plane collider (sphere/AABB intersection)
//! - [`sdf_collider`]: SDF-based collision shapes (distance field surfaces)
//! - [`spherical_terrain`]: Sphere-world ground as a radial height field, and central gravity
//! - [`torus`]: Torus collider with major/minor radii
//! - [`wedge`]: Wedge (triangular prism) collider with 6 vertices
//!
//! ## Spatial Acceleration
//! - [`dynamic_bvh`]: Incremental AABB tree with O(log n) insert/remove/update
//! - [`spatial`]: Hash grid for neighbor queries (shared across fluid, cloth)
//! - [`contact_cache`]: Persistent contact manifold cache with `HashMap` O(1) lookup
//!
//! ## Constraints & Dynamics
//! - [`joint`]: Joint constraints (Ball, Hinge, Fixed, Slider, Spring, D6, `ConeTwist`)
//! - [`joint_extra`]: Advanced joints (Pulley, Gear, Weld, Rack-and-Pinion, Mouse)
//! - [`motor`]: PD controllers and joint motors
//! - [`articulation`]: Articulated bodies (ragdolls, robotic arms, Featherstone)
//! - [`force`]: Custom force fields (wind, gravity, buoyancy, vortex, explosion, magnetic)
//! - [`sleeping`]: Sleep/wake and island management (Union-Find)
//! - [`filter`]: Collision filtering with layer/mask bitmasks (see [`filter::layers`])
//! - [`material`]: Material pair table (friction, restitution, combine rules)
//!
//! ## Queries
//! - [`raycast`]: Ray casting against spheres, AABBs, capsules, planes
//! - [`shape_raycast`]: World ray queries against the geometry bodies collide as (shapes, compounds, static colliders, SDF)
//! - [`sensors`]: Simulated lidar, contact sensor and IMU with deterministic Gaussian noise
//! - [`query`]: Shape cast (sphere, capsule) and overlap queries (sphere, AABB)
//! - [`ccd`]: Continuous collision detection (TOI, conservative advancement, speculative)
//!
//! ## Soft Body & Simulation
//! - [`rope`]: XPBD distance chain rope and cable simulation
//! - [`cloth`]: XPBD triangle mesh cloth with self-collision
//! - [`fluid`]: Position-Based Fluids (PBF) with spatial hash grid
//! - [`deformable`]: FEM-XPBD deformable body simulation
//! - [`vehicle`]: Vehicle physics (wheel, suspension, engine, steering)
//! - [`vehicle_dynamics`]: Per-wheel vehicle dynamics (tyre models, wheel spin, brakes / ABS, road surfaces and weather, powertrain, scenario metrics and lossless replay)
//! - [`character`]: Kinematic capsule-based character controller (move-and-slide)
//! - [`world_character`]: `PhysicsWorld::move_character`, move-and-slide of a character against the world's collided geometry
//! - [`trimesh`]: Triangle mesh collision with BVH acceleration (Moller-Trumbore)
//! - [`heightfield`]: Height field terrain collision (bilinear interpolation)
//! - [`cloth_fluid`]: Cloth-fluid coupling (drag, buoyancy, boundary repulsion)
//! - [`rope_attach`]: Rope attachment to rigid bodies with compliance and break force
//! - [`soft_body_cut`]: Plane-based cutting of deformable bodies and cloth
//! - [`particle`]: General-purpose particle system with emitters and force fields
//!
//! ## 2D Physics
//! - [`physics2d`]: Complete 2D engine (SAT collision, XPBD solver, joints)
//!
//! ## Mesh & I/O Utilities
//! - [`mass_properties`]: Mass and inertia tensor computation for standard shapes
//! - [`collision_mesh_gen`]: Marching cubes SDF-to-mesh with simplification
//! - [`scene_io`]: Binary (.aphys) and JSON scene serialization (`std`)
//! - [`multi_world`]: Multiple independent physics worlds with body transfer
//!
//! ## Visualization
//! - [`heatmap`]: Stress/temperature heatmap with viridis colormap
//! - [`flow_viz`]: Fluid flow arrows and streamline generation
//! - [`contact_viz`]: Contact force arrows and friction cone visualization
//!
//! ## SDF Integration
//! - [`sdf_manifold`]: Multi-point contact manifold from SDF surfaces
//! - [`sdf_ccd`]: Sphere tracing continuous collision detection for SDF
//! - [`sdf_force`]: SDF-driven force fields (attract, repel, contain, flow)
//! - [`sdf_destruction`]: Real-time CSG boolean destruction (`std`)
//! - [`sdf_adaptive`]: Adaptive SDF evaluation with distance-based LOD (`std`)
//! - [`convex_decompose`]: Convex decomposition from SDF voxel grid (`std`)
//! - [`gpu_sdf`]: GPU compute shader interface for batch SDF evaluation (`std`)
//!
//! ## SDF Simulation Modifiers (`std`)
//! - [`sim_field`]: 3D scalar/vector fields with trilinear interpolation and diffusion
//! - [`sim_modifier`]: Physics modifier chain for SDF surfaces
//! - [`thermal`]: Heat diffusion, melt, thermal expansion, freeze
//! - [`pressure`]: Contact-force deformation (crush, bulge, dent)
//! - [`erosion`]: Wind, water, chemical, ablation erosion
//! - [`fracture`]: Stress-driven crack propagation with CSG subtraction
//! - [`phase_change`]: Solid/liquid/gas transitions driven by temperature
//! - [`coupled_field`]: Deterministic `Fix128` channel for sharing one field between physics
//!
//! ## Game Systems
//! - [`animation_blend`]: Ragdoll animation blending with SLERP
//! - [`audio_physics`]: Physics-based audio parameter generation
//! - [`netcode`]: Deterministic simulation with frame input, checksum, rollback
//! - [`fluid_netcode`]: Deterministic fluid netcode with delta compression (`std`)
//! - [`interpolation`]: Substep interpolation with SLERP quaternion blending
//! - [`debug_render`]: Wireframe visualization API (bodies, contacts, joints, BVH)
//! - [`profiling`]: Per-stage timer and per-frame statistics
//!
//! ## Analytics & Privacy (`std`)
//! - [`sketch`]: Probabilistic sketches (`HyperLogLog`, `DDSketch`, Count-Min)
//! - [`anomaly`]: Streaming anomaly detection (MAD, EWMA, Z-score)
//! - [`privacy`]: Local differential privacy (Laplace, RAPPOR)
//! - [`pipeline`]: Lock-free metric aggregation pipeline
//!
//! ## Utility
//! - [`rng`]: Deterministic pseudo-random number generator (PCG-XSH-RR)
//! - [`event`]: Contact and trigger event tracking
//!
//! ## Feature-Gated
//! - `neural`: Deterministic neural controller (ALICE-ML, `--features neural`)
//! - `ffi`: C FFI for Unity/UE5 game engines (`--features ffi`)
//! - `replay`: Replay recording/playback (`--features replay`)
//! - `db_bridge`: Physics state persistence bridge (`--features replay`)
//! - `analytics_bridge`: Simulation profiling bridge (`--features analytics`)
//!
//! # Determinism
//!
//! This engine guarantees bit-exact results by:
//!
//! 1. Using 128-bit fixed-point instead of IEEE 754 floating-point
//! 2. CORDIC algorithm for trigonometry (no FPU instructions)
//! 3. Fixed iteration counts in all algorithms
//! 4. Deterministic sorting (stable sort with explicit comparators)
//!
//! This makes it suitable for:
//! - Lockstep multiplayer games
//! - Rollback netcode
//! - Replay systems
//! - Distributed physics simulation

// TGS solver family (`solver_tgs*`) modules opt out of missing_docs
// locally with `#![allow(missing_docs)]` while their per-item `///`
// docs are being backfilled (Turn E follow-up). The rest of the crate
// is now under `deny` — verified 0 warnings via
// `cargo doc --no-deps --all-features` at v0.14.0-preview.3 landing,
// escalated from `warn` on 2026-09-13 (v1.0 roadmap Item D).
#![deny(missing_docs)]
// Pedantic: suppress lints inherent to physics/math code.
// - Cast lints: Fixed-point ↔ float conversions and index casts are pervasive.
// - Naming: coordinate variables (px, py, pz), vertex indices (v0, v1, v2).
// - must_use: pure functions returning computed values are the norm; annotating
//   every constructor and accessor adds noise without improving safety.
// - doc_markdown: technical identifiers in docs are context-obvious.
// - unreadable_literal: hash constants and bit patterns are more readable without separators.
// - large_stack_arrays: physics lookup tables and inline data are intentional.
#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_precision_loss,
    clippy::cast_sign_loss,
    clippy::cast_lossless,
    clippy::cast_possible_wrap,
    clippy::similar_names,
    clippy::many_single_char_names,
    clippy::module_name_repetitions,
    clippy::unreadable_literal,
    clippy::large_stack_arrays,
    clippy::doc_markdown
)]
#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(all(feature = "wasm", feature = "ffi"))]
compile_error!("Features `wasm` and `ffi` are mutually exclusive. Enable only one.");

#[cfg(all(feature = "wasm", not(feature = "std")))]
compile_error!("Feature `wasm` requires `std`.");

#[cfg(not(feature = "std"))]
extern crate alloc;

// Test builds only: lets a module compile an integration test file (which
// names the crate `alice_physics`) as part of the lib tests, so its lines count
// in the `--lib` coverage.
#[cfg(test)]
extern crate self as alice_physics;

pub mod acoustic_wave;
pub mod aeroelasticity;
#[cfg(feature = "analytics")]
pub mod analytics_bridge;
pub mod animation_blend;
pub mod anisotropic;
pub mod anisotropic_friction;
#[cfg(feature = "std")]
pub mod anomaly;
pub mod articulation;
pub mod atmosphere;
pub mod audio_physics;
pub mod beam_stress;
pub mod bimaterial;
pub mod box_collider;
#[cfg(feature = "std")]
pub mod bridging;
pub mod buckling;
pub mod buoyancy_zone;
pub mod bvh;
pub mod ccd;
#[cfg(feature = "std")]
pub mod cfd_solver;
pub mod character;
pub mod character_state;
pub mod cloth;
pub mod cloth_fluid;
pub mod collider;
pub mod collision_mesh_gen;
pub mod compound;
pub mod compressible;
pub mod cone;
pub mod contact_cache;
pub mod contact_viz;
#[cfg(feature = "std")]
pub mod convex_decompose;
pub mod convex_mesh_builder;
pub mod coupled_field;
pub mod coupled_iteration;
pub mod coupling_medium;
pub mod creep_longterm;
pub mod crowd_force;
pub mod cubic_elastic_fem;
pub mod cylinder;
pub mod damping_rayleigh;
#[cfg(feature = "replay")]
pub mod db_bridge;
pub mod debug_render;
pub mod deformable;
/// Deterministic `f32` / `f64` transcendentals (cross-platform bit-exact).
///
/// Since 1.3.0 the implementation lives in the [`alice_det_math`] crate;
/// every function here is an `#[inline]` delegation to it, so
/// `alice_physics::det_math::sin` and `alice_det_math::sin` are the same law
/// — ALICE-SDF's evaluator uses the same crate, which is what makes the
/// `SdfField` boundary bit-exact across the two. Available without `std`
/// (software `sqrt`; same bits).
///
/// The functions are delegations rather than a `pub use` because
/// `cargo-semver-checks` cannot see items re-exported from another crate and
/// would report the 1.2.0 API as removed.
pub mod det_math {
    pub use alice_det_math::{acos64, asin64, round, round64, sin_cos, sqrt, sqrt64};

    macro_rules! delegate {
        ($(fn $name:ident($($arg:ident: $ty:ty),*) -> $ret:ty;)*) => {
            $(
                #[doc = concat!("Delegates to [`alice_det_math::", stringify!($name), "`].")]
                #[inline]
                #[must_use]
                pub fn $name($($arg: $ty),*) -> $ret {
                    alice_det_math::$name($($arg),*)
                }
            )*
        };
    }

    delegate! {
        fn sin(x: f32) -> f32;
        fn cos(x: f32) -> f32;
        fn exp(x: f32) -> f32;
        fn ln(x: f32) -> f32;
        fn powf(x: f32, y: f32) -> f32;
        fn powi(x: f32, n: i32) -> f32;
        fn cbrt(x: f32) -> f32;
        fn hypot(x: f32, y: f32) -> f32;
        fn atan(x: f32) -> f32;
        fn atan2(y: f32, x: f32) -> f32;
        fn asin(x: f32) -> f32;
        fn acos(x: f32) -> f32;
        fn tan(x: f32) -> f32;
        fn tanh(x: f32) -> f32;
        fn atan64(x: f64) -> f64;
        fn atan2_64(y: f64, x: f64) -> f64;
        fn exp64(x: f64) -> f64;
        fn ln64(x: f64) -> f64;
        fn powf64(x: f64, y: f64) -> f64;
    }

    // max / min with a defined result on every target and profile
    //
    // `f32::max` / `f32::min` (and `f64`) leave the sign of an equal pair of
    // zeros unspecified, and the targets differ: aarch64 returns +0 from max and
    // -0 from min, x86_64 returns the argument (`0.0f32.max(-0.0)` is -0 there),
    // and x86_64's `f64::min(0.0, -0.0)` is -0 unoptimized and +0 optimized The
    // functions below fix that case: a NaN operand yields the other operand (as
    // std does), an equal pair of zeros yields +0 from max and -0 from min (IEEE
    // 754-2019 maximumNumber / minimumNumber, which is what aarch64 already
    // returns), and every other pair is ordered by value Production code uses
    // these; the lib clippy pass forbids `f32::max` / `f32::min` / `f64::max` /
    // `f64::min` (`.github/clippy-lib/clippy.toml`)

    /// `max` with a defined zero sign: NaN yields the other operand, `max(-0.0,
    /// 0.0)` and `max(0.0, -0.0)` are `+0.0`
    #[inline]
    #[must_use]
    pub(crate) fn max(a: f32, b: f32) -> f32 {
        if a.is_nan() || b > a {
            b
        } else if b.is_nan() || a > b || !a.is_sign_negative() {
            a
        } else {
            b
        }
    }

    /// `min` with a defined zero sign: NaN yields the other operand, `min(-0.0,
    /// 0.0)` and `min(0.0, -0.0)` are `-0.0`
    #[inline]
    #[must_use]
    pub(crate) fn min(a: f32, b: f32) -> f32 {
        if a.is_nan() || b < a {
            b
        } else if b.is_nan() || a < b || a.is_sign_negative() {
            a
        } else {
            b
        }
    }

    /// [`max`] for `f64`
    #[inline]
    #[must_use]
    pub(crate) fn max64(a: f64, b: f64) -> f64 {
        if a.is_nan() || b > a {
            b
        } else if b.is_nan() || a > b || !a.is_sign_negative() {
            a
        } else {
            b
        }
    }

    /// [`min`] for `f64`
    #[inline]
    #[must_use]
    pub(crate) fn min64(a: f64, b: f64) -> f64 {
        if a.is_nan() || b < a {
            b
        } else if b.is_nan() || a < b || a.is_sign_negative() {
            a
        } else {
            b
        }
    }

    #[cfg(test)]
    mod max_min_tests {
        use super::{max, max64, min, min64};

        // the expected value on {-inf, -1, -0, +0, +1, +inf, NaN}^2, written out
        // by rule rather than computed with the std functions under test
        fn expected_max(a: f64, b: f64) -> f64 {
            match (a.is_nan(), b.is_nan()) {
                (true, _) => b,
                (_, true) => a,
                _ if a > b => a,
                _ if b > a => b,
                // equal: only the zero pair can differ in bits
                _ => {
                    if a != 0.0 {
                        a
                    } else if a.is_sign_negative() && b.is_sign_negative() {
                        -0.0
                    } else {
                        0.0
                    }
                }
            }
        }

        fn expected_min(a: f64, b: f64) -> f64 {
            match (a.is_nan(), b.is_nan()) {
                (true, _) => b,
                (_, true) => a,
                _ if a < b => a,
                _ if b < a => b,
                _ => {
                    if a == 0.0 && (a.is_sign_negative() || b.is_sign_negative()) {
                        -0.0
                    } else {
                        a
                    }
                }
            }
        }

        const LATTICE: [f64; 7] = [
            f64::NEG_INFINITY,
            -1.0,
            -0.0,
            0.0,
            1.0,
            f64::INFINITY,
            f64::NAN,
        ];

        fn same(x: f64, y: f64) -> bool {
            (x.is_nan() && y.is_nan()) || x.to_bits() == y.to_bits()
        }

        #[test]
        fn max_and_min_follow_the_rule_on_the_signed_zero_lattice() {
            let mut compared = 0;
            for &a in &LATTICE {
                for &b in &LATTICE {
                    // black_box keeps the comparisons at run time, so the
                    // profile under test compiles the branches itself
                    let (x, y) = (core::hint::black_box(a), core::hint::black_box(b));
                    let (xf, yf) = (x as f32, y as f32);
                    assert!(
                        same(max64(x, y), expected_max(a, b)),
                        "max64({a:?}, {b:?}) = {:?}",
                        max64(x, y)
                    );
                    assert!(
                        same(min64(x, y), expected_min(a, b)),
                        "min64({a:?}, {b:?}) = {:?}",
                        min64(x, y)
                    );
                    assert!(
                        same(f64::from(max(xf, yf)), expected_max(a, b)),
                        "max({a:?}, {b:?}) = {:?}",
                        max(xf, yf)
                    );
                    assert!(
                        same(f64::from(min(xf, yf)), expected_min(a, b)),
                        "min({a:?}, {b:?}) = {:?}",
                        min(xf, yf)
                    );
                    compared += 4;
                }
            }
            assert_eq!(compared, 4 * 49);
        }

        #[test]
        fn the_zero_pair_has_the_documented_sign_in_both_orders() {
            let (p, n) = (
                core::hint::black_box(0.0f32),
                core::hint::black_box(-0.0f32),
            );
            assert_eq!(max(p, n).to_bits(), 0x0000_0000);
            assert_eq!(max(n, p).to_bits(), 0x0000_0000);
            assert_eq!(min(p, n).to_bits(), 0x8000_0000);
            assert_eq!(min(n, p).to_bits(), 0x8000_0000);
            let (p, n) = (
                core::hint::black_box(0.0f64),
                core::hint::black_box(-0.0f64),
            );
            assert_eq!(max64(p, n).to_bits(), 0);
            assert_eq!(max64(n, p).to_bits(), 0);
            assert_eq!(min64(p, n).to_bits(), 0x8000_0000_0000_0000);
            assert_eq!(min64(n, p).to_bits(), 0x8000_0000_0000_0000);
        }
    }
}
#[cfg(any(feature = "ffi", feature = "wasm", feature = "python"))]
mod binding_api;
pub mod dynamic_bvh;
#[cfg(feature = "std")]
pub mod dynamic_fem;
pub mod electromagnetic;
pub mod ellipsoid;
#[cfg(feature = "std")]
pub mod erosion;
pub mod error;
pub mod euler_fv;
pub mod eulerian_grid;
pub mod event;
pub mod fatigue;
#[cfg(feature = "ffi")]
pub mod ffi;
pub mod filament_db;

pub(crate) mod body_collider;
pub mod fillet_stress;
pub mod filter;
#[cfg(feature = "std")]
pub mod flow_viz;
pub mod fluid;
#[cfg(feature = "std")]
pub mod fluid_netcode;
pub mod force;
#[cfg(feature = "std")]
pub mod fracture;
#[cfg(feature = "std")]
pub mod fsi_advanced;
#[cfg(feature = "std")]
pub mod gpu_sdf;
pub mod heatmap;
pub mod heightfield;
pub mod hyperelastic;
#[cfg(feature = "std")]
pub mod ik_physics_bridge;
pub mod interface_capture;
pub mod interpolation;
pub mod joint;
pub mod joint_extra;
pub mod kepler;
pub mod kinematic_loop;
#[cfg(feature = "std")]
pub mod laminate;
pub mod laminate_failure;
// Content identifier of the rules a world is configured with.
pub mod law_id;
pub mod layer_adhesion;
pub mod lift_drag;
/// Small-strain linear elastic FEM on tetrahedra (P1), producing a Cauchy
/// stress tensor per element from an [`sdf_fem_mesh::SdfTetMesh`].
///
/// `std` only, because its input is: [`sdf_fem_mesh`] deduplicates vertices
/// through a `HashMap`, which `alloc` does not provide, so it carries the same
/// gate. Adding `alloc` imports here would not help — the module cannot be
/// built at all without the type it consumes.
#[cfg(feature = "std")]
pub mod linear_elastic_fem;
pub mod linear_solver;
pub mod mass_properties;
pub mod material;
pub mod math;
pub mod math_util;
pub mod maxwell_fdtd;
pub mod metric;
pub mod modal;
pub mod molecular_dynamics;
pub mod motor;
pub mod multi_world;
pub mod multiphase;
pub mod nbody;
pub mod netcode;
#[cfg(feature = "std")]
pub mod netcode_prediction;
#[cfg(feature = "neural")]
pub mod neural;
pub mod non_newtonian;
pub mod pair_potential;
pub mod particle;
#[cfg(feature = "std")]
pub mod phase_change;
#[cfg(feature = "std")]
pub mod piezoelectric;
#[cfg(feature = "std")]
pub mod pipeline;
pub mod plane_collider;
pub mod plastic;
#[cfg(feature = "std")]
pub mod pressure;
pub mod prestressed;
pub mod print_orientation;
#[cfg(feature = "std")]
pub mod print_pipeline_solver;
#[cfg(feature = "std")]
pub mod privacy;
pub mod profiling;
#[cfg(feature = "python")]
mod python;
pub mod quadratic_elastic_fem;
pub mod query;
pub mod ragdoll;
pub mod raycast;
#[cfg(feature = "replay")]
pub mod replay;
pub mod rng;
#[cfg(feature = "std")]
pub mod rolling_contact;
pub mod rope;
pub mod rope_attach;
pub mod rotor;
#[cfg(feature = "std")]
pub mod scene_io;
#[cfg(feature = "std")]
pub mod sdf_adaptive;
pub mod sdf_ccd;
pub mod sdf_character;
pub mod sdf_collider;
#[cfg(feature = "std")]
pub mod sdf_destruction;
#[cfg(feature = "std")]
pub mod sdf_fem_mesh;
pub mod sdf_force;
pub mod sdf_manifold;
#[cfg(feature = "std")]
pub mod sdf_sph;
pub mod sdf_wind_field;
// Content hash of the stepping semantics; no `cfg`: the same value in every build.
pub mod semantics;
pub mod sensors;
pub mod shape;
pub mod shape_raycast;
#[cfg(feature = "std")]
pub mod sim_field;
#[cfg(feature = "std")]
pub mod sim_modifier;
pub mod static_collider;
pub mod structural_solver;
#[cfg(feature = "std")]
pub mod support_volume;
pub mod surface_tension_csf;
#[cfg(feature = "std")]
pub mod thin_wall;
pub mod vibration_wall;
pub mod warp_risk;
pub mod wave_ship;
pub mod wind_zone;
pub mod world_character;
pub mod world_participant;
pub mod world_shape_query;

pub mod physics2d;

#[cfg(feature = "gpu-solver-bridge")]
pub mod gpu_bridge;
#[cfg(feature = "std")]
pub mod sketch;
pub mod sleeping;
pub mod smoke_fire;
pub mod soft_body_cut;
pub mod solver;
// Gyroscopic term `ω × Iω` by symplectic splitting, shared by XPBD and TGS.
pub(crate) mod gyroscopic;
// solver_tgs* family: pub(crate) since v0.14.0-preview.8 (v1.0 Item B
// Option C — TGS extension mechanism with zero downstream adoption is
// hidden from the public surface; re-expose via semver-minor bump if
// concrete demand emerges).
#[cfg(feature = "std")]
pub(crate) mod det_hash;
#[cfg(feature = "std")]
pub(crate) mod solver_tgs;
#[cfg(feature = "std")]
pub(crate) mod solver_tgs_hooks_6dof_oriented;
#[cfg(feature = "std")]
pub(crate) mod solver_tgs_hooks_6dof_oriented_scoped;
// Adapter from `solver::RigidBody` / `ContactConstraint` to the solver_tgs*
// family's oriented body/contact types — the production entry point for
// `SolverBackend::Tgs` (`PhysicsWorld::step_tgs`). std-gated for the same
// reason as the rest of `solver_tgs*` (the family uses `std::collections::HashMap`).
#[cfg(feature = "std")]
pub(crate) mod solver_tgs_backend;
pub mod spatial;
pub mod spherical_terrain;
#[cfg(feature = "std")]
pub mod thermal;
pub mod thermal_stress;
pub mod torus;
#[cfg(feature = "std")]
pub mod transient_thermal;
pub mod trimesh;
pub mod turbulence;
pub mod vehicle;
pub mod vehicle_dynamics;
#[cfg(feature = "wasm")]
mod wasm;
pub mod wedge;

// Re-export commonly used types
pub use animation_blend::{AnimationBlender, AnimationClip, BlendMode, SkeletonPose};
#[cfg(feature = "std")]
pub use anomaly::{
    AnomalyCallback, AnomalyEvent, CompositeDetector, EwmaDetector, MadDetector, StreamingMedian,
    ZScoreDetector,
};
pub use articulation::{ArticulatedBody, FeatherstoneSolver};
pub use audio_physics::{AudioConfig, AudioEvent, AudioGenerator, AudioMaterial};
pub use box_collider::OrientedBox;
pub use bvh::{BvhNode, BvhPrimitive, LinearBvh};
pub use ccd::{
    aabb_plane_toi, capsule_plane_toi, speculative_contact, sphere_capsule_toi, CcdConfig,
};
pub use character::{CharacterConfig, CharacterController, MoveResult, PushImpulse};
pub use cloth::{Cloth, ClothConfig};
pub use cloth_fluid::{
    apply_cloth_boundary_to_fluid, apply_fluid_forces_to_cloth, ClothFluidCoupling,
};
pub use collider::{Capsule, CollisionResult, ConvexHull, ScaledShape, Sphere, Support, AABB};
pub use collision_mesh_gen::{
    compute_mesh_aabb, generate_collision_mesh, simplify_collision_mesh, CollisionMesh,
    CollisionMeshConfig,
};
#[cfg(feature = "std")]
pub use compound::{CompoundShape, ShapeRef};
pub use cone::Cone;
pub use contact_cache::{BodyPairKey, ContactCache, ContactManifold};
pub use contact_viz::{
    generate_contact_arrows, generate_friction_cones, ContactArrow, FrictionCone,
};
#[cfg(feature = "std")]
pub use convex_decompose::{DecomposeConfig, DecompositionResult};
pub use convex_mesh_builder::{build_convex_hull, compute_centroid};
pub use cylinder::Cylinder;
pub use debug_render::{debug_draw_world, DebugColor, DebugDrawData, DebugDrawFlags};
pub use deformable::{DeformableBody, DeformableConfig};
pub use dynamic_bvh::DynamicAabbTree;
pub use ellipsoid::Ellipsoid;
#[cfg(feature = "std")]
pub use erosion::{ErosionConfig, ErosionModifier, ErosionType};
pub use error::PhysicsError;
pub use event::{ContactEvent, ContactEventType, EventCollector, JointBreakEvent, TriggerEvent};
/// Re-export predefined collision layer constants for convenience.
pub use filter::layers;
pub use filter::CollisionFilter;
#[cfg(feature = "std")]
pub use flow_viz::{
    generate_flow_arrows, generate_streamlines, FlowArrow, FlowVizConfig, Streamlines,
};
pub use fluid::{Fluid, FluidConfig};
#[cfg(feature = "std")]
pub use fluid_netcode::{FluidDelta, FluidSnapshot};
pub use force::{apply_force_fields, ForceField, ForceFieldInstance};
#[cfg(feature = "std")]
pub use fracture::{Crack, FractureConfig, FractureModifier};
#[cfg(feature = "std")]
pub use gpu_sdf::{
    batch_size, GpuDispatchConfig, GpuSdfBatch, GpuSdfInstancedBatch, GpuSdfMultiDispatch,
    GpuSdfQuery, GpuSdfResult,
};
pub use heatmap::{
    generate_stress_heatmap, generate_temperature_heatmap, heatmap_to_rgba, Heatmap, HeatmapConfig,
    SliceAxis,
};
pub use heightfield::HeightField;
pub use interpolation::{BodySnapshot, InterpolationState, WorldSnapshot};
#[allow(deprecated)] // re-exported for compatibility until 3.0
pub use joint::{
    solve_joints, solve_joints_breakable, solve_joints_breaking_on_force,
    solve_joints_with_reaction_forces,
};
pub use joint::{
    BallJoint, ConeTwistJoint, D6Joint, D6Motion, FixedJoint, HingeJoint, Joint, JointType,
    SliderJoint, SpringJoint,
};
pub use joint_extra::{
    solve_extra_joints, ExtraJoint, GearJoint, MouseJoint, PulleyJoint, RackAndPinionJoint,
    WeldJoint,
};
pub use mass_properties::{
    box_mass_properties, capsule_mass_properties, convex_hull_mass_properties,
    cylinder_mass_properties, sphere_mass_properties, translate_inertia, MassProperties,
};
pub use material::{CombineRule, CombinedMaterial, MaterialId, MaterialTable, PhysicsMaterial};
pub use math::{simd_width, Fix128, Mat3Fix, QuatFix, Vec3Fix, SIMD_WIDTH};
pub use motor::{JointMotor, MotorMode, PdController};
pub use multi_world::{MultiWorld, Portal};
pub use netcode::{
    DeterministicSimulation, FrameInput, InputApplicator, NetcodeConfig, SimulationChecksum,
    SimulationSnapshot,
};
pub use particle::{LandingEvent, LandingTarget, Particle, ParticleEmitter, ParticleSystem};
#[cfg(feature = "std")]
pub use phase_change::{Phase, PhaseChangeConfig, PhaseChangeModifier};
pub use physics2d::{
    BodyType2D, Contact2D, Joint2D, PhysicsConfig2D, PhysicsWorld2D, RigidBody2D, Shape2D, Vec2Fix,
};
#[cfg(feature = "std")]
pub use pipeline::{
    MetricEvent, MetricPipeline, MetricRegistry, MetricSnapshot, MetricType, RingBuffer,
};
pub use plane_collider::PlaneCollider;
#[cfg(feature = "std")]
pub use pressure::{PressureConfig, PressureModifier};
#[cfg(feature = "privacy-crypto")]
pub use privacy::KeyedRappor;
#[cfg(feature = "std")]
#[allow(deprecated)] // kept for existing callers, who see the deprecation at their use
pub use privacy::{
    LaplaceNoise, PrivacyBudget, PrivateAggregator, RandomizedResponse, Rappor, XorShift64,
};
pub use profiling::{PhysicsProfiler, ProfileEntry, StepStats};
pub use query::{
    batch_raycast, batch_sphere_cast, capsule_cast, overlap_aabb, overlap_aabb_bvh, overlap_sphere,
    overlap_sphere_bvh, sphere_cast, BatchRayQuery, OverlapResult, ShapeCastHit,
};
pub use raycast::{
    raycast_all_aabbs, raycast_all_spheres, raycast_any_aabbs, raycast_any_spheres, Ray, RayHit,
};
pub use rng::DeterministicRng;
pub use rope::{Rope, RopeConfig};
pub use rope_attach::{solve_rope_attachments, RopeAttachment};
#[cfg(feature = "std")]
pub use scene_io::{
    load_scene, load_scene_json, save_scene, save_scene_json, PhysicsScene, SerializedBody,
    SerializedJoint,
};
#[cfg(feature = "std")]
pub use sdf_adaptive::{AdaptiveConfig, AdaptiveSdfEvaluator};
pub use sdf_ccd::SdfCcdConfig;
pub use sdf_collider::{ClosureSdf, SdfCollider, SdfContact, SdfField};
#[cfg(feature = "std")]
pub use sdf_destruction::{DestructibleSdf, DestructionShape};
pub use sdf_force::{SdfForceField, SdfForceType};
pub use sdf_manifold::ManifoldConfig;
#[cfg(feature = "std")]
pub use sdf_manifold::SdfManifold;
pub use semantics::{PHYSICS_SEMANTICS_ID, PHYSICS_SEMANTICS_PINS};
pub use shape::{Shape, ShapeError};
#[cfg(feature = "std")]
pub use sim_field::{ScalarField3D, VectorField3D};
#[cfg(feature = "std")]
pub use sim_modifier::{ModifiedSdf, PhysicsModifier, SingleModifiedSdf};
#[cfg(feature = "std")]
pub use sketch::{CountMinSketch, DDSketch, FnvHasher, HeavyHitters, HyperLogLog, Mergeable};
pub use sleeping::{Island, IslandManager, SleepConfig, SleepData, SleepState};
pub use soft_body_cut::{cut_cloth, cut_deformable, CutPlane, CutResult};
#[cfg(feature = "std")]
pub use solver::ContactModifier;
#[cfg(feature = "std")]
pub use solver::TgsCacheStats;
pub use solver::{
    BodyType, ContactConstraint, DistanceConstraint, LawCheck, PhysicsConfig, PhysicsWorld,
    RigidBody, SolverBackend, StageWork, WorldCcdConfig, WorldSnapshotError,
};
pub use spatial::SpatialGrid;
#[cfg(feature = "std")]
pub use thermal::{HeatSource, ThermalConfig, ThermalModifier};
pub use torus::Torus;
pub use trimesh::{TriMesh, Triangle};
pub use vehicle::{Vehicle, VehicleConfig};
pub use wedge::Wedge;

/// Prelude module for convenient imports
pub mod prelude {
    pub use crate::animation_blend::{AnimationBlender, AnimationClip, BlendMode, SkeletonPose};
    #[cfg(feature = "std")]
    pub use crate::anomaly::{
        AnomalyCallback, AnomalyEvent, CompositeDetector, EwmaDetector, MadDetector,
        StreamingMedian, ZScoreDetector,
    };
    pub use crate::articulation::{ArticulatedBody, FeatherstoneSolver};
    pub use crate::audio_physics::{AudioConfig, AudioEvent, AudioGenerator, AudioMaterial};
    pub use crate::box_collider::OrientedBox;
    pub use crate::bvh::{BvhNode, BvhPrimitive, LinearBvh};
    pub use crate::ccd::{speculative_contact, CcdConfig};
    pub use crate::character::{CharacterConfig, CharacterController, MoveResult, PushImpulse};
    pub use crate::cloth::{Cloth, ClothConfig};
    pub use crate::cloth_fluid::{
        apply_cloth_boundary_to_fluid, apply_fluid_forces_to_cloth, ClothFluidCoupling,
    };
    pub use crate::collider::{
        Capsule, CollisionResult, ConvexHull, ScaledShape, Sphere, Support, AABB,
    };
    pub use crate::collision_mesh_gen::{
        compute_mesh_aabb, generate_collision_mesh, simplify_collision_mesh, CollisionMesh,
        CollisionMeshConfig,
    };
    #[cfg(feature = "std")]
    pub use crate::compound::{CompoundShape, ShapeRef};
    pub use crate::cone::Cone;
    pub use crate::contact_cache::{BodyPairKey, ContactCache, ContactManifold};
    pub use crate::contact_viz::{
        generate_contact_arrows, generate_friction_cones, ContactArrow, FrictionCone,
    };
    #[cfg(feature = "std")]
    pub use crate::convex_decompose::{DecomposeConfig, DecompositionResult};
    pub use crate::convex_mesh_builder::{build_convex_hull, compute_centroid};
    pub use crate::cylinder::Cylinder;
    pub use crate::debug_render::{debug_draw_world, DebugColor, DebugDrawData, DebugDrawFlags};
    pub use crate::deformable::{DeformableBody, DeformableConfig};
    pub use crate::dynamic_bvh::DynamicAabbTree;
    pub use crate::ellipsoid::Ellipsoid;
    #[cfg(feature = "std")]
    pub use crate::erosion::{ErosionConfig, ErosionModifier, ErosionType};
    pub use crate::error::PhysicsError;
    pub use crate::event::{
        ContactEvent, ContactEventType, EventCollector, JointBreakEvent, TriggerEvent,
    };
    pub use crate::filter::layers;
    pub use crate::filter::CollisionFilter;
    #[cfg(feature = "std")]
    pub use crate::flow_viz::{
        generate_flow_arrows, generate_streamlines, FlowArrow, FlowVizConfig, Streamlines,
    };
    pub use crate::fluid::{Fluid, FluidConfig};
    #[cfg(feature = "std")]
    pub use crate::fluid_netcode::{FluidDelta, FluidSnapshot};
    pub use crate::force::{apply_force_fields, ForceField, ForceFieldInstance};
    #[cfg(feature = "std")]
    pub use crate::fracture::{Crack, FractureConfig, FractureModifier};
    #[cfg(feature = "std")]
    pub use crate::gpu_sdf::{
        batch_size, GpuDispatchConfig, GpuSdfBatch, GpuSdfInstancedBatch, GpuSdfMultiDispatch,
        GpuSdfQuery, GpuSdfResult,
    };
    pub use crate::heatmap::{
        generate_stress_heatmap, generate_temperature_heatmap, heatmap_to_rgba, Heatmap,
        HeatmapConfig, SliceAxis,
    };
    pub use crate::heightfield::HeightField;
    pub use crate::interpolation::{BodySnapshot, InterpolationState, WorldSnapshot};
    #[allow(deprecated)] // re-exported for compatibility until 3.0
    pub use crate::joint::{
        solve_joints, solve_joints_breakable, solve_joints_breaking_on_force,
        solve_joints_with_reaction_forces,
    };
    pub use crate::joint::{
        BallJoint, ConeTwistJoint, D6Joint, D6Motion, FixedJoint, HingeJoint, Joint, JointType,
        SliderJoint, SpringJoint,
    };
    pub use crate::joint_extra::{
        solve_extra_joints, ExtraJoint, GearJoint, MouseJoint, PulleyJoint, RackAndPinionJoint,
        WeldJoint,
    };
    pub use crate::mass_properties::{
        box_mass_properties, capsule_mass_properties, convex_hull_mass_properties,
        cylinder_mass_properties, sphere_mass_properties, translate_inertia, MassProperties,
    };
    pub use crate::material::{
        CombineRule, CombinedMaterial, MaterialId, MaterialTable, PhysicsMaterial,
    };
    pub use crate::math::{simd_width, Fix128, Mat3Fix, QuatFix, Vec3Fix, SIMD_WIDTH};
    pub use crate::motor::{JointMotor, MotorMode, PdController};
    pub use crate::multi_world::{MultiWorld, Portal};
    pub use crate::netcode::{
        DeterministicSimulation, FrameInput, InputApplicator, NetcodeConfig, SimulationChecksum,
        SimulationSnapshot,
    };
    pub use crate::particle::{
        LandingEvent, LandingTarget, Particle, ParticleEmitter, ParticleSystem,
    };
    #[cfg(feature = "std")]
    pub use crate::phase_change::{Phase, PhaseChangeConfig, PhaseChangeModifier};
    #[cfg(feature = "std")]
    pub use crate::pipeline::{
        MetricEvent, MetricPipeline, MetricRegistry, MetricSnapshot, MetricType, RingBuffer,
    };
    pub use crate::plane_collider::PlaneCollider;
    #[cfg(feature = "std")]
    pub use crate::pressure::{PressureConfig, PressureModifier};
    #[cfg(feature = "privacy-crypto")]
    pub use crate::privacy::KeyedRappor;
    #[cfg(feature = "std")]
    #[allow(deprecated)] // kept for existing callers, who see the deprecation at their use
    pub use crate::privacy::{
        LaplaceNoise, PrivacyBudget, PrivateAggregator, RandomizedResponse, Rappor, XorShift64,
    };
    pub use crate::profiling::{PhysicsProfiler, ProfileEntry, StepStats};
    pub use crate::query::{
        batch_raycast, batch_sphere_cast, capsule_cast, overlap_aabb, overlap_aabb_bvh,
        overlap_sphere, overlap_sphere_bvh, sphere_cast, BatchRayQuery, OverlapResult,
        ShapeCastHit,
    };
    pub use crate::raycast::{
        raycast_all_aabbs, raycast_all_spheres, raycast_any_aabbs, raycast_any_spheres, Ray, RayHit,
    };
    pub use crate::rng::DeterministicRng;
    pub use crate::rope::{Rope, RopeConfig};
    pub use crate::rope_attach::{solve_rope_attachments, RopeAttachment};
    #[cfg(feature = "std")]
    pub use crate::scene_io::{
        load_scene, load_scene_json, save_scene, save_scene_json, PhysicsScene, SerializedBody,
        SerializedJoint,
    };
    #[cfg(feature = "std")]
    pub use crate::sdf_adaptive::{AdaptiveConfig, AdaptiveSdfEvaluator};
    pub use crate::sdf_ccd::SdfCcdConfig;
    pub use crate::sdf_collider::{ClosureSdf, SdfCollider, SdfContact, SdfField};
    #[cfg(feature = "std")]
    pub use crate::sdf_destruction::{DestructibleSdf, DestructionShape};
    pub use crate::sdf_force::{SdfForceField, SdfForceType};
    pub use crate::sdf_manifold::ManifoldConfig;
    #[cfg(feature = "std")]
    pub use crate::sdf_manifold::SdfManifold;
    #[cfg(feature = "std")]
    pub use crate::sim_field::{ScalarField3D, VectorField3D};
    #[cfg(feature = "std")]
    pub use crate::sim_modifier::{ModifiedSdf, PhysicsModifier, SingleModifiedSdf};
    #[cfg(feature = "std")]
    pub use crate::sketch::{
        CountMinSketch, DDSketch, FnvHasher, HeavyHitters, HyperLogLog, Mergeable,
    };
    pub use crate::sleeping::{Island, IslandManager, SleepConfig, SleepData, SleepState};
    pub use crate::soft_body_cut::{cut_cloth, cut_deformable, CutPlane, CutResult};
    #[cfg(feature = "std")]
    pub use crate::solver::ContactModifier;
    #[cfg(feature = "std")]
    pub use crate::solver::TgsCacheStats;
    pub use crate::solver::{
        BodyType, ContactConstraint, DistanceConstraint, LawCheck, PhysicsConfig, PhysicsWorld,
        RigidBody, SolverBackend, StageWork, WorldCcdConfig, WorldSnapshotError,
    };
    pub use crate::spatial::SpatialGrid;
    #[cfg(feature = "std")]
    pub use crate::thermal::{HeatSource, ThermalConfig, ThermalModifier};
    pub use crate::torus::Torus;
    pub use crate::trimesh::{TriMesh, Triangle};
    pub use crate::vehicle::{Vehicle, VehicleConfig};
    pub use crate::wedge::Wedge;
}

#[cfg(all(test, feature = "std"))]
mod compile_smoke_tests {
    //! Verify that core types from the prelude and key modules are accessible.
    //! These tests catch accidental breakage of public re-exports.

    use super::*;

    #[test]
    fn test_prelude_types_accessible() {
        let _ = Fix128::ZERO;
        let _ = Vec3Fix::ZERO;
        let _ = QuatFix::IDENTITY;
        let _ = Mat3Fix::IDENTITY;
        let _ = PhysicsConfig::default();
        let _ = CollisionFilter::default();
        let _ = SleepConfig::default();
    }

    #[test]
    fn test_error_type_accessible() {
        let e = PhysicsError::InvalidBodyIndex { index: 0, count: 0 };
        let _ = format!("{e}");
    }

    #[test]
    fn test_spatial_grid_accessible() {
        let mut grid = SpatialGrid::new(Fix128::ONE, 16);
        grid.insert(0, Vec3Fix::ZERO);
        grid.build();
        let mut neighbors = Vec::new();
        grid.query_neighbors_into(Vec3Fix::ZERO, Fix128::ONE, &mut neighbors);
        assert!(neighbors.contains(&0));
    }

    #[test]
    fn test_wasm_ffi_mutual_exclusion() {
        // The compile_error! macros in lib.rs guarantee that `wasm` + `ffi`
        // cannot be enabled together. This test documents the invariant.
        // If this crate compiles at all, the exclusion is enforced.
        // The compile_error! macros above enforce this at compile time.
        // If this test runs, the invariant holds.
    }
}

#[cfg(all(test, feature = "std"))]
mod tests {
    use super::*;

    #[test]
    fn test_basic_simulation() {
        // Create world with default config
        let config = PhysicsConfig::default();
        let mut world = PhysicsWorld::new(config);

        // Add a falling body
        let mut body = RigidBody::new_dynamic(Vec3Fix::from_int(0, 100, 0), Fix128::ONE);
        body.restitution = Fix128::from_ratio(5, 10); // 0.5 bounce

        let body_id = world.add_body(body);

        // Add ground (static body)
        let ground = RigidBody::new_static(Vec3Fix::ZERO);
        world.add_body(ground);

        // Step simulation
        let dt = Fix128::from_ratio(1, 60);
        for _ in 0..60 {
            world.step(dt);
        }

        // Body should have fallen
        let pos = world.bodies[body_id].position;
        assert!(pos.y < Fix128::from_int(100), "Body should have fallen");
    }

    #[test]
    fn test_determinism() {
        // Run simulation twice with same initial conditions
        fn run_simulation() -> Vec3Fix {
            let config = PhysicsConfig::default();
            let mut world = PhysicsWorld::new(config);

            let body = RigidBody::new_dynamic(
                Vec3Fix::from_int(5, 50, 3),
                Fix128::from_ratio(3, 2), // mass = 1.5
            );
            world.add_body(body);

            let dt = Fix128::from_ratio(1, 60);
            for _ in 0..120 {
                world.step(dt);
            }

            world.bodies[0].position
        }

        let result1 = run_simulation();
        let result2 = run_simulation();

        // Results must be bit-exact
        assert_eq!(result1.x.hi, result2.x.hi);
        assert_eq!(result1.x.lo, result2.x.lo);
        assert_eq!(result1.y.hi, result2.y.hi);
        assert_eq!(result1.y.lo, result2.y.lo);
        assert_eq!(result1.z.hi, result2.z.hi);
        assert_eq!(result1.z.lo, result2.z.lo);
    }

    #[test]
    fn test_state_serialization() {
        let config = PhysicsConfig::default();
        let mut world = PhysicsWorld::new(config);

        // Add body and simulate
        let body = RigidBody::new_dynamic(Vec3Fix::from_int(10, 20, 30), Fix128::ONE);
        world.add_body(body);

        let dt = Fix128::from_ratio(1, 60);
        for _ in 0..30 {
            world.step(dt);
        }

        // Serialize state
        let state = world.serialize_state();

        // Continue simulation
        for _ in 0..30 {
            world.step(dt);
        }
        let pos_after = world.bodies[0].position;

        // Restore state
        world.deserialize_state(&state);

        // Continue simulation from restored state
        for _ in 0..30 {
            world.step(dt);
        }
        let pos_restored = world.bodies[0].position;

        // Results must be identical
        assert_eq!(pos_after.x.hi, pos_restored.x.hi);
        assert_eq!(pos_after.y.hi, pos_restored.y.hi);
        assert_eq!(pos_after.z.hi, pos_restored.z.hi);
    }

    #[test]
    fn test_distance_constraint() {
        let config = PhysicsConfig::default();
        let mut world = PhysicsWorld::new(config);

        // Two bodies connected by distance constraint
        let body_a = RigidBody::new_dynamic(Vec3Fix::from_int(0, 10, 0), Fix128::ONE);
        let body_b = RigidBody::new_dynamic(Vec3Fix::from_int(5, 10, 0), Fix128::ONE);
        let id_a = world.add_body(body_a);
        let id_b = world.add_body(body_b);

        // Target distance = 5 units
        let constraint = DistanceConstraint {
            body_a: id_a,
            body_b: id_b,
            local_anchor_a: Vec3Fix::ZERO,
            local_anchor_b: Vec3Fix::ZERO,
            target_distance: Fix128::from_int(5),
            compliance: Fix128::ZERO,
            cached_lambda: Fix128::ZERO,
        };
        world.add_distance_constraint(constraint);

        // Simulate at 120 Hz for stricter convergence
        let dt = Fix128::from_ratio(1, 120);
        for _ in 0..120 {
            world.step(dt);
        }

        // Distance should remain approximately 5
        let pos_a = world.bodies[id_a].position;
        let pos_b = world.bodies[id_b].position;
        let dist = (pos_b - pos_a).length();

        let target = Fix128::from_int(5);
        let error = if dist > target {
            dist - target
        } else {
            target - dist
        };

        // Allow at most 2% error (target=5, tolerance=0.1) under gravity
        let tolerance = Fix128::from_ratio(1, 10);
        assert!(
            error < tolerance,
            "Distance constraint violated: error = {error:?}, tolerance = {tolerance:?}"
        );
    }
}