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
use super::*;
/// Constructors and bounding-box helpers for `RigidBody3D`.
impl RigidBody3D {
/// Creates a dynamic 3D rigid body with given mass, position, and box half-extents.
///
/// # Arguments
///
/// - `Vec3` - Initial center position.
/// - `Vec3` - Box half-extents `(hx, hy, hz)`.
/// - `f32` - Positive mass in kilograms.
///
/// # Returns
///
/// - `Self` - Dynamic rigid body.
#[must_use]
pub fn dynamic_box(position: Vec3, half_extents: Vec3, mass: f32) -> Self {
Self {
position,
velocity: Vec3::zero(),
half_extents,
inv_mass: 1.0 / mass.max(0.01),
restitution: 0.35,
linear_damping: 0.04,
grounded: false,
}
}
/// Creates a static immovable 3D box collider.
///
/// # Arguments
///
/// - `Vec3` - Center position.
/// - `Vec3` - Box half-extents `(hx, hy, hz)`.
///
/// # Returns
///
/// - `Self` - Static rigid body (`inv_mass = 0.0`).
#[must_use]
pub fn static_box(position: Vec3, half_extents: Vec3) -> Self {
Self {
position,
velocity: Vec3::zero(),
half_extents,
inv_mass: 0.0,
restitution: 0.25,
linear_damping: 0.0,
grounded: true,
}
}
/// Computes this body's world-space `Aabb3D`.
///
/// # Arguments
///
/// - `&Self` - Body reference.
///
/// # Returns
///
/// - `Aabb3D` - World-space bounding box.
#[must_use]
pub fn world_aabb(&self) -> Aabb3D {
let p: Vec3 = self.get_position();
let h: Vec3 = self.get_half_extents();
Aabb3D::new(p.sub(h), p.add(h))
}
/// Applies an instantaneous linear impulse to a dynamic rigid body.
///
/// # Arguments
///
/// - `&Self` - Mutable body reference.
/// - `Vec3` - Linear impulse vector in `N*s`.
pub fn apply_impulse(&mut self, impulse: Vec3) {
let inv_m: f32 = self.get_inv_mass();
if inv_m > 0.0 {
let next_v: Vec3 = self.get_velocity().add(impulse.scale(inv_m));
self.set_velocity(next_v);
}
}
}
/// Default Earth-gravity 3D physics world.
impl Default for PhysicsWorld3D {
/// Creates an empty `PhysicsWorld3D` with `-9.81 m/s^2` gravity and ground at `y = 0.0`.
///
/// # Returns
///
/// - `Self` - Ready 3D physics world.
fn default() -> Self {
Self {
gravity: Vec3::new(0.0, -9.81, 0.0),
ground_y: 0.0,
bodies: Vec::new(),
hash_heads: Vec::new(),
hash_next: Vec::new(),
hash_body: Vec::new(),
touched_buckets: Vec::new(),
pair_scratch: Vec::new(),
}
}
}
/// Rigid-body integration, spatial-hash broadphase, AABB collision resolution, and raycasting for `PhysicsWorld3D`.
impl PhysicsWorld3D {
/// Computes the bucket index in `0..bucket_count` for integer 3D grid cell `(cx, cy, cz)`.
///
/// # Arguments
///
/// - `i32` - Cell X coordinate.
/// - `i32` - Cell Y coordinate.
/// - `i32` - Cell Z coordinate.
/// - `usize` - Power-of-two bucket mask (`bucket_count - 1`).
///
/// # Returns
///
/// - `usize` - Hash bucket index.
#[inline(always)]
#[must_use]
fn hash_cell(cx: i32, cy: i32, cz: i32, mask: usize) -> usize {
let h: u32 = (cx.wrapping_mul(73_856_093) as u32)
^ (cy.wrapping_mul(19_349_663) as u32)
^ (cz.wrapping_mul(83_492_791) as u32);
(h as usize) & mask
}
/// Resolves a single candidate rigid-body pair `(i, j)` in place and returns `true` if colliding.
///
/// # Arguments
///
/// - `&mut [RigidBody3D]` - Mutable rigid-body slice.
/// - `usize` - First body index.
/// - `usize` - Second body index.
///
/// # Returns
///
/// - `bool` - `true` when an overlap was resolved.
#[inline(always)]
fn resolve_body_pair(bodies: &mut [RigidBody3D], i: usize, j: usize) -> bool {
let a: RigidBody3D = bodies[i];
let b: RigidBody3D = bodies[j];
let inv_sum: f32 = a.get_inv_mass() + b.get_inv_mass();
if inv_sum <= 0.0 {
return false;
}
let delta: Vec3 = b.get_position().sub(a.get_position());
let ox: f32 =
a.get_half_extents().get_x() + b.get_half_extents().get_x() - delta.get_x().abs();
let oy: f32 =
a.get_half_extents().get_y() + b.get_half_extents().get_y() - delta.get_y().abs();
let oz: f32 =
a.get_half_extents().get_z() + b.get_half_extents().get_z() - delta.get_z().abs();
if ox <= 0.0 || oy <= 0.0 || oz <= 0.0 {
return false;
}
let (normal, pen): (Vec3, f32) = if ox <= oy && ox <= oz {
let s: f32 = if delta.get_x() < 0.0 { -1.0 } else { 1.0 };
(Vec3::new(s, 0.0, 0.0), ox)
} else if oy <= oz {
let s: f32 = if delta.get_y() < 0.0 { -1.0 } else { 1.0 };
(Vec3::new(0.0, s, 0.0), oy)
} else {
let s: f32 = if delta.get_z() < 0.0 { -1.0 } else { 1.0 };
(Vec3::new(0.0, 0.0, s), oz)
};
let corr: Vec3 = normal.scale(pen / inv_sum);
let a_pos: Vec3 = a.get_position().sub(corr.scale(a.get_inv_mass()));
let b_pos: Vec3 = b.get_position().add(corr.scale(b.get_inv_mass()));
let rel_v: Vec3 = b.get_velocity().sub(a.get_velocity());
let vn: f32 = rel_v.dot(normal);
let mut a_vel: Vec3 = a.get_velocity();
let mut b_vel: Vec3 = b.get_velocity();
if vn < 0.0 {
let rest: f32 = a.get_restitution().min(b.get_restitution());
let j_imp: f32 = -(1.0 + rest) * vn / inv_sum;
let imp: Vec3 = normal.scale(j_imp);
a_vel = a_vel.sub(imp.scale(a.get_inv_mass()));
b_vel = b_vel.add(imp.scale(b.get_inv_mass()));
}
bodies[i].set_position(a_pos);
bodies[i].set_velocity(a_vel);
bodies[j].set_position(b_pos);
bodies[j].set_velocity(b_vel);
true
}
/// Adds a `RigidBody3D` to the simulation and returns its handle index.
///
/// # Arguments
///
/// - `&Self` - Mutable physics world.
/// - `RigidBody3D` - Body to insert.
///
/// # Returns
///
/// - `usize` - Body index.
pub fn add_body(&mut self, body: RigidBody3D) -> usize {
let idx: usize = self.get_bodies().len();
self.get_mut_bodies().push(body);
idx
}
/// Advances all rigid bodies by `dt` seconds using gravity, ground collisions, and an O(N) zero-allocation 3D spatial hash grid broadphase.
///
/// # Arguments
///
/// - `&Self` - Mutable physics world.
/// - `f32` - Timestep in seconds.
///
/// # Returns
///
/// - `usize` - Number of collisions resolved during this step.
pub fn step(&mut self, dt: f32) -> usize {
let step_dt: f32 = dt.clamp(0.0, 0.1);
let gravity: Vec3 = self.get_gravity();
let ground_y: f32 = self.get_ground_y();
let mut collisions: usize = 0;
let mut max_extent: f32 = 0.5;
let Self {
bodies,
hash_heads,
hash_next,
hash_body,
touched_buckets,
pair_scratch,
..
} = self;
for body in bodies.iter_mut() {
let h: Vec3 = body.get_half_extents();
let extent: f32 = h.get_x().max(h.get_y()).max(h.get_z());
if extent > max_extent {
max_extent = extent;
}
let inv_m: f32 = body.get_inv_mass();
if inv_m <= 0.0 {
continue;
}
let damp: f32 = (1.0 - body.get_linear_damping() * step_dt).clamp(0.0, 1.0);
let mut vel: Vec3 = body.get_velocity().add(gravity.scale(step_dt)).scale(damp);
let mut pos: Vec3 = body.get_position().add(vel.scale(step_dt));
let min_y: f32 = ground_y + h.get_y();
let mut grounded: bool = false;
if pos.get_y() <= min_y {
pos.set_y(min_y);
if vel.get_y() < 0.0 {
vel.set_y(-vel.get_y() * body.get_restitution());
if vel.get_y().abs() < 0.25 {
vel.set_y(0.0);
}
vel.set_x(vel.get_x() * 0.92);
vel.set_z(vel.get_z() * 0.92);
collisions += 1;
}
grounded = true;
}
body.set_position(pos);
body.set_velocity(vel);
body.set_grounded(grounded);
}
let count: usize = bodies.len();
if count <= 1 {
return collisions;
}
if count <= 16 {
for i in 0..count {
for j in (i + 1)..count {
if Self::resolve_body_pair(bodies.as_mut_slice(), i, j) {
collisions += 1;
}
}
}
return collisions;
}
let target_buckets: usize = (count * 4).next_power_of_two().clamp(256, 16_384);
if hash_heads.len() != target_buckets {
hash_heads.clear();
hash_heads.resize(target_buckets, u32::MAX);
touched_buckets.clear();
} else {
for &b in touched_buckets.iter() {
hash_heads[b] = u32::MAX;
}
touched_buckets.clear();
}
hash_next.clear();
hash_body.clear();
pair_scratch.clear();
let cell_size: f32 = (max_extent * 2.5).max(1.0);
let inv_cell: f32 = 1.0 / cell_size;
let mask: usize = target_buckets - 1;
for (idx, body) in bodies.iter().enumerate() {
let p: Vec3 = body.get_position();
let h: Vec3 = body.get_half_extents();
let min_cx: i32 = ((p.get_x() - h.get_x()) * inv_cell).floor() as i32;
let max_cx: i32 = ((p.get_x() + h.get_x()) * inv_cell).floor() as i32;
let min_cy: i32 = ((p.get_y() - h.get_y()) * inv_cell).floor() as i32;
let max_cy: i32 = ((p.get_y() + h.get_y()) * inv_cell).floor() as i32;
let min_cz: i32 = ((p.get_z() - h.get_z()) * inv_cell).floor() as i32;
let max_cz: i32 = ((p.get_z() + h.get_z()) * inv_cell).floor() as i32;
for cx in min_cx..=max_cx {
for cy in min_cy..=max_cy {
for cz in min_cz..=max_cz {
let bucket: usize = Self::hash_cell(cx, cy, cz, mask);
let mut cur: u32 = hash_heads[bucket];
if cur == u32::MAX {
touched_buckets.push(bucket);
} else {
while cur != u32::MAX {
let other: usize = hash_body[cur as usize] as usize;
if other != idx {
let pair: (usize, usize) = if other < idx {
(other, idx)
} else {
(idx, other)
};
pair_scratch.push(pair);
}
cur = hash_next[cur as usize];
}
}
let entry: u32 = hash_body.len() as u32;
hash_body.push(idx as u32);
hash_next.push(hash_heads[bucket]);
hash_heads[bucket] = entry;
}
}
}
}
pair_scratch.sort_unstable();
pair_scratch.dedup();
for &(i, j) in pair_scratch.iter() {
if Self::resolve_body_pair(bodies.as_mut_slice(), i, j) {
collisions += 1;
}
}
collisions
}
/// Casts a `Ray3D` against all 3D rigid bodies up to `max_distance` and returns the closest hit.
///
/// # Arguments
///
/// - `&Self` - Physics world reference.
/// - `&Ray3D` - Query ray.
/// - `f32` - Maximum cast distance in meters.
///
/// # Returns
///
/// - `Option<RayHitPhysics3D>` - Closest hit body and contact position if any.
#[must_use]
pub fn raycast(&self, ray: &Ray3D, max_distance: f32) -> Option<RayHitPhysics3D> {
let mut best: Option<RayHitPhysics3D> = None;
let mut best_t: f32 = max_distance.max(0.0);
for (idx, body) in self.get_bodies().iter().enumerate() {
let aabb: Aabb3D = body.world_aabb();
let t: f32 =
aabb.intersect_ray_near(ray.get_origin(), ray.get_inv_direction(), 0.001, best_t);
if t.is_finite() && t < best_t {
best_t = t;
let pt: Vec3 = ray.get_origin().add(ray.get_direction().scale(t));
best = Some(RayHitPhysics3D::new(idx, t, pt));
}
}
best
}
}