Skip to main content

box3d_rust/
core.rs

1// Port of the surviving behavior from box3d-cpp-reference/src/core.c, core.h,
2// include/box3d/base.h, and src/ctz.h needed by math_functions / constants /
3// bitset / table.
4//
5// core.c is largely an allocator / threading / timing shim. Rust covers that
6// natively, so those pieces are not ported. What remains here is the runtime
7// length-unit scale, the precision query, and the ctz.h bit helpers.
8//
9// SPDX-FileCopyrightText: 2025 Erin Catto
10// SPDX-License-Identifier: MIT
11
12use core::sync::atomic::{AtomicU32, Ordering};
13
14/// Used to indicate an unset or invalid index value. (base.h: B3_NULL_INDEX)
15pub const NULL_INDEX: i32 = -1;
16
17/// Use to validate definitions. (core.h: B3_SECRET_COOKIE)
18pub const SECRET_COOKIE: i32 = 1152023;
19
20// The length-unit scale is a single global that the user sets once at startup.
21// C stores it as a plain `static float`; we store the bit pattern in an atomic
22// so the global is sound under Rust's threading rules. The observable value is
23// identical. 0x3F80_0000 is the bit pattern of 1.0f32.
24static LENGTH_UNITS_PER_METER_BITS: AtomicU32 = AtomicU32::new(0x3F80_0000);
25
26/// Box3D bases all length units on meters. Set this to use different units for
27/// all length values passed to and returned from Box3D. Must be set at
28/// application startup, before any other Box3D calls.
29pub fn set_length_units_per_meter(length_units: f32) {
30    debug_assert!(crate::math_functions::is_valid_float(length_units) && length_units > 0.0);
31    LENGTH_UNITS_PER_METER_BITS.store(length_units.to_bits(), Ordering::Relaxed);
32}
33
34/// Get the current length units per meter.
35pub fn get_length_units_per_meter() -> f32 {
36    f32::from_bits(LENGTH_UNITS_PER_METER_BITS.load(Ordering::Relaxed))
37}
38
39/// @return true if the library was built with the `double-precision` feature
40/// (large world mode), mirroring `BOX3D_DOUBLE_PRECISION`.
41pub fn is_double_precision() -> bool {
42    cfg!(feature = "double-precision")
43}
44
45// ---------------------------------------------------------------------------
46// Bit helpers (ctz.h). The C versions are thin wrappers over compiler
47// intrinsics (__builtin_ctz / _BitScanForward / __popcnt). The count-leading
48// and count-trailing intrinsics are undefined for a zero argument in C; every
49// caller guarantees a nonzero argument, and Rust's intrinsics are well defined
50// (returning the bit width) even for zero, so the ported callers behave
51// identically.
52// ---------------------------------------------------------------------------
53
54/// Count trailing zeros of a 32-bit block. (ctz.h: b3CTZ32)
55pub fn ctz32(block: u32) -> u32 {
56    block.trailing_zeros()
57}
58
59/// Count leading zeros of a 32-bit value. (ctz.h: b3CLZ32)
60pub fn clz32(value: u32) -> u32 {
61    value.leading_zeros()
62}
63
64/// Count trailing zeros of a 64-bit block. (ctz.h: b3CTZ64)
65pub fn ctz64(block: u64) -> u32 {
66    block.trailing_zeros()
67}
68
69/// Population count of a 64-bit block. (ctz.h: b3PopCount64)
70pub fn pop_count64(block: u64) -> i32 {
71    block.count_ones() as i32
72}
73
74/// (ctz.h: b3IsPowerOf2)
75pub fn is_power_of2(x: i32) -> bool {
76    (x & (x - 1)) == 0
77}
78
79/// (ctz.h: b3BoundingPowerOf2)
80pub fn bounding_power_of2(x: i32) -> i32 {
81    if x <= 1 {
82        return 1;
83    }
84
85    32 - clz32((x as u32) - 1) as i32
86}
87
88/// (ctz.h: b3RoundUpPowerOf2)
89pub fn round_up_power_of2(x: i32) -> i32 {
90    if x <= 1 {
91        return 1;
92    }
93
94    1 << (32 - clz32((x as u32) - 1))
95}
96
97/// Position of the most significant bit = floor(log2(x)). (ctz.h: b3LowerPowerOf2Exponent)
98pub fn lower_power_of_2_exponent(x: i32) -> i32 {
99    debug_assert!(x > 0);
100    let clz = clz32(x as u32) as i32;
101
102    // Position of most significant bit = floor(log2(M))
103    31 - clz
104}
105
106// ---------------------------------------------------------------------------
107// Content hash (base.h / timer.c). Word-oriented djb2 over 8-byte little-endian
108// chunks — not the byte-wise recurrence used by Box2D.
109// ---------------------------------------------------------------------------
110
111/// Initial value for [`hash`]. (base.h: B3_HASH_INIT)
112pub const HASH_INIT: u32 = 5381;
113
114/// Hash `data` into `hash` (djb2-style, 8-byte little-endian words then bytes).
115/// (timer.c: b3Hash)
116pub fn hash(hash: u32, data: &[u8]) -> u32 {
117    let mut result = hash;
118    let mut i = 0;
119    let count = data.len();
120
121    while i + 8 <= count {
122        // Little-endian load; matches memcpy of uint64_t on LE hosts (and the
123        // explicit byte-swap path on BE in the C source).
124        let word = u64::from_le_bytes(data[i..i + 8].try_into().unwrap());
125        result = result
126            .wrapping_shl(5)
127            .wrapping_add(result)
128            .wrapping_add(word as u32);
129        result = result
130            .wrapping_shl(5)
131            .wrapping_add(result)
132            .wrapping_add((word >> 32) as u32);
133        i += 8;
134    }
135
136    while i < count {
137        result = result
138            .wrapping_shl(5)
139            .wrapping_add(result)
140            .wrapping_add(data[i] as u32);
141        i += 1;
142    }
143
144    result
145}
146
147/// Geometry content hashes reserve zero to mean unhashed. (core.h: b3NonZeroHash)
148pub fn non_zero_hash(hash: u32) -> u32 {
149    if hash != 0 {
150        hash
151    } else {
152        1
153    }
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159
160    #[test]
161    fn bit_helpers() {
162        assert_eq!(ctz32(0b1000), 3);
163        assert_eq!(clz32(1), 31);
164        assert_eq!(clz32(9), 31 - 3);
165        assert_eq!(ctz64(1u64 << 40), 40);
166        assert_eq!(pop_count64(0xFFFF_FFFF_FFFF_FFFF), 64);
167        assert!(is_power_of2(8));
168        assert!(!is_power_of2(6));
169        assert_eq!(round_up_power_of2(5), 8);
170        assert_eq!(round_up_power_of2(1), 1);
171        assert_eq!(bounding_power_of2(5), 3);
172        assert_eq!(lower_power_of_2_exponent(9), 3);
173    }
174}