rocketsim 0.3.7

Simulate Rocket League games at maximum efficiency
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
//! Wheel raycast update and chassis impulse phases.

mod steering;

use glam::{Affine3A, Vec3A};

use super::{
    NUM_WHEELS,
    raycaster::{VehicleRaycaster, VehicleRaycasterResult},
    wheel_info::{FrictionCurveInput, WheelInfo},
};
use crate::{
    bullet::{
        collision::broadphase::CollisionFilterGroups,
        dynamics::{
            discrete_dynamics_world::DiscreteDynamicsWorld,
            rigid_body::{Impulse, RigidBody},
        },
    },
    consts::BT_TO_UU,
    sim::UserInfoType,
};

/// Wheel order for every impulse combine pass.
///
/// Add wheels 1, 0, 3, and 2 in that order. Changing the order can change
/// the floating-point sum.
const COMBINE_ORDER: [usize; NUM_WHEELS] = [1, 0, 3, 2];

#[derive(Clone, Copy)]
pub struct VehicleRL {
    raycaster: VehicleRaycaster,
    chassis_body_idx: usize,
    pub wheels: [WheelInfo; NUM_WHEELS],
}

impl VehicleRL {
    pub const fn new(
        chassis_body_idx: usize,
        wheels: [WheelInfo; NUM_WHEELS],
        min_hit_dist_sq: f32,
    ) -> Self {
        Self {
            raycaster: VehicleRaycaster::new(
                CollisionFilterGroups::DropshotFloor as u8,
                min_hit_dist_sq,
            ),
            chassis_body_idx,
            wheels,
        }
    }

    pub(crate) fn remove_body(&mut self, body_idx: usize) {
        debug_assert_ne!(self.chassis_body_idx, body_idx);
        if self.chassis_body_idx > body_idx {
            self.chassis_body_idx -= 1;
        }
        for wheel in &mut self.wheels {
            if let Some(info) = &mut wheel.raycast_info {
                if info.ground_body_idx == body_idx {
                    wheel.reset_wheel_suspension();
                } else if info.ground_body_idx > body_idx {
                    info.ground_body_idx -= 1;
                }
            }
        }
    }

    /// Reset transient wheel contacts for planning reuse. Keeps config.
    pub(crate) fn reset_transient_contacts(&mut self) {
        for wheel in &mut self.wheels {
            wheel.raycast_info = None;
            wheel.hard_point = Vec3A::ZERO;
            wheel.axle_dir = Vec3A::ZERO;
            wheel.engine_force = 0.0;
            wheel.brake = 0.0;
            wheel.steer_angle = 0.0;
            wheel.vel_at_contact_point = Vec3A::ZERO;
            wheel.lat_friction = 1.0;
            wheel.long_friction = 1.0;
            wheel.extra_pushback = 0.0;
            // Keep chassis_connection_point_cs, suspension_rest_length_1,
            // wheels_radius, suspension_force_scale, real_ray_length.
        }
    }

    pub fn get_upwards_dir_from_wheel_contacts(&self, cb: &RigidBody) -> Vec3A {
        let mut sum_contact_dir = Vec3A::ZERO;
        for wheel in &self.wheels {
            if let Some(raycast_info) = wheel.raycast_info.as_ref()
                && raycast_info.is_in_contact_with_world
            {
                sum_contact_dir += raycast_info.contact_normal;
            }
        }

        sum_contact_dir
            .try_normalize()
            .unwrap_or_else(|| cb.get_up_vector())
    }

    /// Query wheel contacts without changing wheel state.
    #[must_use]
    pub(crate) fn query_wheel_contacts(
        &self,
        world: &DiscreteDynamicsWorld,
        chassis: &RigidBody,
    ) -> [Option<crate::RaycastHitInfo>; NUM_WHEELS] {
        let chassis_trans = *chassis.get_world_trans();
        let mut sources = [Vec3A::ZERO; NUM_WHEELS];
        let mut targets = [Vec3A::ZERO; NUM_WHEELS];
        for (i, wheel) in self.wheels.iter().enumerate() {
            let source = chassis_trans.transform_point3a(wheel.chassis_connection_point_cs);
            sources[i] = source;
            targets[i] = source - chassis_trans.matrix3.z_axis * wheel.real_ray_length;
        }

        let hits = self.raycaster.cast_rays(world, &sources, &targets, chassis);
        std::array::from_fn(|i| {
            hits[i].map(|info| crate::RaycastHitInfo {
                hit_point: info.hit_point_in_world * BT_TO_UU,
                hit_normal: info.hit_normal_in_world,
                hit_fraction: (sources[i] - info.hit_point_in_world).length()
                    / self.wheels[i].real_ray_length,
                user_info: info.rigid_body.user_idx,
            })
        })
    }

    /// Refresh wheel raycast records for the sticky gate.
    #[must_use]
    pub(crate) fn refresh_wheel_contacts(
        &mut self,
        collision_world: &DiscreteDynamicsWorld,
        chassis: &RigidBody,
        time_step: f32,
    ) -> bool {
        let chassis_trans = *chassis.get_world_trans();
        let mut sources = [Vec3A::ZERO; NUM_WHEELS];
        let mut targets = [Vec3A::ZERO; NUM_WHEELS];
        for (i, wheel) in self.wheels.iter_mut().enumerate() {
            (sources[i], targets[i]) = wheel.prepare_for_raycast(&chassis_trans);
        }

        let ray_results = self
            .raycaster
            .cast_rays(collision_world, &sources, &targets, chassis);

        let mut front_axle_cache: Option<(f32, Vec3A)> = None;
        for (i, wheel) in self.wheels.iter_mut().enumerate() {
            let front = i < 2;
            if let Some(ray_result) = ray_results[i] {
                let steer_angle = wheel.steer_angle;
                let axle_dir = if front {
                    match front_axle_cache {
                        Some((cached_angle, cached_axle)) if cached_angle == steer_angle => {
                            cached_axle
                        }
                        _ => {
                            let axle = steering::steered_right_column(
                                chassis_trans.matrix3.z_axis,
                                chassis_trans.matrix3.y_axis,
                                steer_angle,
                            );
                            front_axle_cache = Some((steer_angle, axle));
                            axle
                        }
                    }
                } else {
                    chassis_trans.matrix3.y_axis
                };

                wheel.apply_ray_cast(
                    chassis,
                    &chassis_trans,
                    axle_dir,
                    ray_result,
                    time_step,
                    front,
                );
            } else {
                wheel.reset_wheel_suspension();
            }
        }

        self.wheels.iter().any(|wheel| {
            wheel
                .raycast_info
                .as_ref()
                .is_some_and(|info| info.is_in_contact_with_world)
        })
    }

    pub const fn get_num_wheels(&self) -> usize {
        self.wheels.len()
    }

    /// Number of wheels whose last raycast hit a world body.
    pub(crate) fn num_world_contacts(&self) -> usize {
        self.wheels
            .iter()
            .filter(|wheel| {
                wheel
                    .raycast_info
                    .as_ref()
                    .is_some_and(|info| info.is_in_contact_with_world)
            })
            .count()
    }

    /// Apply victim impulses before the next wheel reads the victim velocity.
    /// Keep chassis suspension and friction deferred.
    ///
    /// The car-victim pushback comes first. The non-world ground stick comes
    /// second. World-body pushback is a separate write. The order changes the
    /// two adds into the victim velocity, so keep this order.
    fn apply_single_wheel_dynamic_effects(
        wheel: &WheelInfo,
        collision_world: &mut DiscreteDynamicsWorld,
    ) {
        let Some(info) = wheel.raycast_info.as_ref() else {
            return;
        };

        if wheel.extra_pushback > 0.0 {
            let victim = &mut collision_world.bodies_mut()[info.ground_body_idx];
            if victim.user_idx == UserInfoType::Car {
                let full_pushback = wheel.extra_pushback * NUM_WHEELS as f32;
                let victim_offset = info.contact_point - victim.get_world_trans().translation;
                victim.add_impulse(
                    Impulse::LinearRelPos(-info.contact_normal * full_pushback, victim_offset),
                    true,
                    false,
                );
            }
        }

        // The ground-stick vector is the inverted contact normal for a
        // non-world hit. Derive it here so the wheel record does not store a copy.
        if !info.is_in_contact_with_world {
            let ground = &mut collision_world.bodies_mut()[info.ground_body_idx];
            let ground_offset = info.contact_point - ground.get_world_trans().translation;
            ground.add_impulse(
                Impulse::LinearRelPos(-info.contact_normal, ground_offset),
                true,
                false,
            );
        }
    }

    pub fn update(
        &mut self,
        collision_world: &mut DiscreteDynamicsWorld,
        time_step: f32,
        handbrake_val: f32,
        real_throttle: f32,
        three_wheels: bool,
    ) {
        let chassis_trans = *collision_world.bodies()[self.chassis_body_idx].get_world_trans();
        let chassis_translation = chassis_trans.translation;
        let friction_scale = collision_world.bodies()[self.chassis_body_idx].get_mass() / 3.0;

        let mut sources = [Vec3A::ZERO; NUM_WHEELS];
        let mut targets = [Vec3A::ZERO; NUM_WHEELS];

        for (i, wheel) in self.wheels.iter_mut().enumerate() {
            (sources[i], targets[i]) = wheel.prepare_for_raycast(&chassis_trans);
        }

        // Copy hit geometry so later wheel resolves can read updated body velocities.
        struct OwnedHit {
            point: Vec3A,
            normal: Vec3A,
            body_idx: usize,
        }
        let owned_hits: [Option<OwnedHit>; NUM_WHEELS] = {
            let chassis = &collision_world.bodies()[self.chassis_body_idx];
            let ray_results =
                self.raycaster
                    .cast_rays(collision_world, &sources, &targets, chassis);
            ray_results.map(|slot| {
                slot.map(|hit| OwnedHit {
                    point: hit.hit_point_in_world,
                    normal: hit.hit_normal_in_world,
                    body_idx: hit.rigid_body_idx,
                })
            })
        };

        // Front wheels normally share one steer angle, so their steered
        // axle is identical. Compute it lazily and reuse it while the
        // steer angle matches (each build needs a sin/cos pair). If a
        // front wheel ever carries a different angle, fall back to its
        // own axle with the original formula.
        let mut front_axle_cache: Option<(f32, Vec3A)> = None;
        let mut num_wheels_in_contact = 0;
        for (i, (owned_opt, wheel)) in owned_hits.iter().zip(self.wheels.iter_mut()).enumerate() {
            let Some(owned) = owned_opt else {
                wheel.reset_wheel_suspension();
                continue;
            };

            // Release body references before applying this wheel's victim impulses.
            {
                let chassis = &collision_world.bodies()[self.chassis_body_idx];
                let hit_body = &collision_world.bodies()[owned.body_idx];
                num_wheels_in_contact += 1;
                let front = i < 2;
                let steer_angle = wheel.steer_angle;
                let axle_dir = if front {
                    match front_axle_cache {
                        Some((cached_angle, cached_axle)) if cached_angle == steer_angle => {
                            cached_axle
                        }
                        _ => {
                            let axle = steering::steered_right_column(
                                chassis_trans.matrix3.z_axis,
                                chassis_trans.matrix3.y_axis,
                                steer_angle,
                            );
                            front_axle_cache = Some((steer_angle, axle));
                            axle
                        }
                    }
                } else {
                    chassis_trans.matrix3.y_axis
                };

                let ray_result = VehicleRaycasterResult {
                    hit_point_in_world: owned.point,
                    hit_normal_in_world: owned.normal,
                    rigid_body_idx: owned.body_idx,
                    rigid_body: hit_body,
                };
                wheel.apply_ray_cast(
                    chassis,
                    &chassis_trans,
                    axle_dir,
                    ray_result,
                    time_step,
                    front,
                );

                let is_dynamic_hit = !hit_body.is_static_obj();
                wheel.refresh_friction_curves(
                    chassis,
                    FrictionCurveInput {
                        chassis_translation,
                        contact_normal: owned.normal,
                        handbrake_val,
                        real_throttle,
                        three_wheels,
                        is_dynamic_hit,
                    },
                );
            }
            Self::apply_single_wheel_dynamic_effects(wheel, collision_world);
        }

        if num_wheels_in_contact < 3 {
            for wheel in &mut self.wheels {
                wheel.engine_force /= 4.0;
            }
        }

        if num_wheels_in_contact == 0 {
            return;
        }

        let chassis = &mut collision_world.bodies_mut()[self.chassis_body_idx];
        Self::apply_wheel_impulses(
            chassis,
            &mut self.wheels,
            &chassis_trans,
            chassis_translation,
            time_step,
            friction_scale,
            three_wheels,
        );
    }

    /// Apply the wheel suspension and friction impulses to the chassis.
    ///
    /// All four suspension impulses resolve from the same snapshot. Then all
    /// four friction impulses resolve from the post-suspension state. Both
    /// combine passes use [`COMBINE_ORDER`]. The friction apply pass receives
    /// `time_step` because `calc_friction_impulses` does not include the time
    /// step in the cached impulse.
    fn apply_wheel_impulses(
        chassis: &mut RigidBody,
        wheels: &mut [WheelInfo; NUM_WHEELS],
        chassis_trans: &Affine3A,
        chassis_translation: Vec3A,
        time_step: f32,
        friction_scale: f32,
        three_wheels: bool,
    ) {
        for i in COMBINE_ORDER {
            wheels[i].update_suspension(chassis, chassis_translation, time_step);
        }

        for i in COMBINE_ORDER {
            wheels[i].update_friction_impulse(chassis, time_step, friction_scale);
        }

        // Note: all suspension must be applied before any friction impulse.
        for i in COMBINE_ORDER {
            wheels[i].apply_friction_impulses(chassis, chassis_trans, time_step, three_wheels);
        }
    }
}