Skip to content

Commit

Permalink
Revert "Rapier context as a Component (dimforge#545)"
Browse files Browse the repository at this point in the history
This reverts commit bab3431.
  • Loading branch information
jeyum2 committed Sep 10, 2024
1 parent 8d10abc commit efb71e5
Show file tree
Hide file tree
Showing 25 changed files with 418 additions and 1,558 deletions.
13 changes: 0 additions & 13 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,6 @@ which was its hardcoded behaviour.
`RapierDebugColliderPlugin` and `DebugRenderContext`, as well as individual collider setup via
a `ColliderDebug` component.

### Modified

- `RapierContext`, `RapierConfiguration` and `RenderToSimulationTime` are now a `Component` instead of resources.
- Rapier now supports multiple independent physics worlds, see example `multi_world3` for usage details.
- Migration guide:
- `ResMut<mut RapierContext>` -> `WriteDefaultRapierContext`
- `Res<RapierContext>` -> `ReadDefaultRapierContext`
- Access to `RapierConfiguration` and `RenderToSimulationTime` should query for it
on the responsible entity owning the `RenderContext`.
- If you are building a library on top of `bevy_rapier` and would want to support multiple independent physics worlds too,
you can check out the details of [#545](https://github.com/dimforge/bevy_rapier/pull/545)
to get more context and information.

## v0.27.0 (07 July 2024)

**This is an update from rapier 0.19 to Rapier 0.21 which includes several stability improvements
Expand Down
1 change: 0 additions & 1 deletion bevy_rapier2d/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ serde = { version = "1", features = ["derive"], optional = true }
bevy = { version = "0.14", default-features = false, features = [
"x11",
"bevy_state",
"bevy_debug_stepping",
] }
oorandom = "11"
approx = "0.5.1"
Expand Down
3 changes: 1 addition & 2 deletions bevy_rapier2d/examples/player_movement2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ fn main() {
#[derive(Component)]
pub struct Player(f32);

pub fn spawn_player(mut commands: Commands, mut rapier_config: Query<&mut RapierConfiguration>) {
let mut rapier_config = rapier_config.single_mut();
pub fn spawn_player(mut commands: Commands, mut rapier_config: ResMut<RapierConfiguration>) {
// Set gravity to 0.0 and spawn camera.
rapier_config.gravity = Vec2::ZERO;
commands.spawn(Camera2dBundle::default());
Expand Down
4 changes: 1 addition & 3 deletions bevy_rapier2d/examples/testbed2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,9 +204,7 @@ fn main() {
OnExit(Examples::PlayerMovement2),
(
cleanup,
|mut rapier_config: Query<&mut RapierConfiguration>,
ctxt: ReadDefaultRapierContext| {
let mut rapier_config = rapier_config.single_mut();
|mut rapier_config: ResMut<RapierConfiguration>, ctxt: Res<RapierContext>| {
rapier_config.gravity =
RapierConfiguration::new(ctxt.integration_parameters.length_unit).gravity;
},
Expand Down
1 change: 0 additions & 1 deletion bevy_rapier3d/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ bevy = { version = "0.14", default-features = false, features = [
"x11",
"tonemapping_luts",
"bevy_state",
"bevy_debug_stepping",
] }
approx = "0.5.1"
glam = { version = "0.27", features = ["approx"] }
Expand Down
2 changes: 1 addition & 1 deletion bevy_rapier3d/examples/joints3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ pub fn setup_physics(mut commands: Commands) {
}

pub fn print_impulse_revolute_joints(
context: ReadDefaultRapierContext,
context: Res<RapierContext>,
joints: Query<(Entity, &ImpulseJoint)>,
) {
for (entity, impulse_joint) in joints.iter() {
Expand Down
120 changes: 0 additions & 120 deletions bevy_rapier3d/examples/multi_world3.rs

This file was deleted.

2 changes: 1 addition & 1 deletion bevy_rapier3d/examples/ray_casting3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ pub fn setup_physics(mut commands: Commands) {
pub fn cast_ray(
mut commands: Commands,
windows: Query<&Window, With<PrimaryWindow>>,
rapier_context: ReadDefaultRapierContext,
rapier_context: Res<RapierContext>,
cameras: Query<(&Camera, &GlobalTransform)>,
) {
let window = windows.single();
Expand Down
5 changes: 1 addition & 4 deletions bevy_rapier_benches3d/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,7 @@ pub fn custom_bencher(steps: usize, setup: impl Fn(&mut App)) {
app.update();
timer_full_update.pause();
let elapsed_time = timer_full_update.time() as f32;
let rc = app
.world_mut()
.query::<&RapierContext>()
.single(app.world());
let rc = app.world().resource::<RapierContext>();
rapier_step_times.push(rc.pipeline.counters.step_time.time() as f32);
total_update_times.push(elapsed_time);
}
Expand Down
32 changes: 19 additions & 13 deletions src/pipeline/events.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::math::{Real, Vect};
use bevy::prelude::{Entity, Event};
use bevy::prelude::{Entity, Event, EventWriter};
use rapier::dynamics::RigidBodySet;
use rapier::geometry::{
ColliderHandle, ColliderSet, CollisionEvent as RapierCollisionEvent, CollisionEventFlags,
Expand Down Expand Up @@ -58,8 +58,8 @@ pub(crate) struct EventQueue<'a> {
// Used to retrieve the entity of colliders that have been removed from the simulation
// since the last physics step.
pub deleted_colliders: &'a HashMap<ColliderHandle, Entity>,
pub collision_events: RwLock<Vec<CollisionEvent>>,
pub contact_force_events: RwLock<Vec<ContactForceEvent>>,
pub collision_events: RwLock<EventWriter<'a, CollisionEvent>>,
pub contact_force_events: RwLock<EventWriter<'a, ContactForceEvent>>,
}

impl<'a> EventQueue<'a> {
Expand Down Expand Up @@ -94,7 +94,7 @@ impl<'a> EventHandler for EventQueue<'a> {
};

if let Ok(mut events) = self.collision_events.write() {
events.push(event);
events.send(event);
}
}

Expand All @@ -118,7 +118,7 @@ impl<'a> EventHandler for EventQueue<'a> {
};

if let Ok(mut events) = self.contact_force_events.write() {
events.push(event);
events.send(event);
}
}
}
Expand Down Expand Up @@ -155,13 +155,15 @@ mod test {
pub struct EventsSaver<E: Event> {
pub events: Vec<E>,
}

impl<E: Event> Default for EventsSaver<E> {
fn default() -> Self {
Self {
events: Default::default(),
}
}
}

pub fn save_events<E: Event + Clone>(
mut events: EventReader<E>,
mut saver: ResMut<EventsSaver<E>>,
Expand All @@ -170,6 +172,7 @@ mod test {
saver.events.push(event.clone());
}
}

fn run_test(app: &mut App) {
app.add_systems(PostUpdate, save_events::<CollisionEvent>)
.add_systems(PostUpdate, save_events::<ContactForceEvent>)
Expand All @@ -189,12 +192,12 @@ mod test {
.world()
.get_resource::<EventsSaver<CollisionEvent>>()
.unwrap();
assert!(saved_collisions.events.len() > 0);
assert_eq!(saved_collisions.events.len(), 3);
let saved_contact_forces = app
.world()
.get_resource::<EventsSaver<CollisionEvent>>()
.get_resource::<EventsSaver<ContactForceEvent>>()
.unwrap();
assert!(saved_contact_forces.events.len() > 0);
assert_eq!(saved_contact_forces.events.len(), 1);
}

/// Adapted from events example
Expand Down Expand Up @@ -229,7 +232,7 @@ mod test {
TransformBundle::from(Transform::from_xyz(0.0, 13.0, 0.0)),
RigidBody::Dynamic,
cuboid(0.5, 0.5, 0.5),
ActiveEvents::COLLISION_EVENTS,
ActiveEvents::COLLISION_EVENTS | ActiveEvents::CONTACT_FORCE_EVENTS,
ContactForceEventThreshold(30.0),
));
}
Expand All @@ -244,10 +247,13 @@ mod test {
TransformPlugin,
RapierPhysicsPlugin::<NoUserData>::default(),
))
.insert_resource(TimestepMode::Interpolated {
dt: 1.0 / 30.0,
time_scale: 1.0,
substeps: 2,
.insert_resource(RapierConfiguration {
timestep_mode: TimestepMode::Interpolated {
dt: 1.0 / 30.0,
time_scale: 1.0,
substeps: 2,
},
..RapierConfiguration::new(1f32)
})
.add_systems(Startup, setup_physics)
.add_systems(Update, remove_collider);
Expand Down
43 changes: 24 additions & 19 deletions src/plugin/configuration.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
use bevy::{
prelude::{Component, Resource},
reflect::Reflect,
};
use bevy::prelude::{FromWorld, Resource, World};

use crate::math::{Real, Vect};
use crate::plugin::RapierContext;

#[cfg(doc)]
use {crate::prelude::TransformInterpolation, rapier::dynamics::IntegrationParameters};

/// Difference between simulation and rendering time
#[derive(Component, Default, Reflect)]
#[derive(Resource, Default)]
pub struct SimulationToRenderTime {
/// Difference between simulation and rendering time
pub diff: f32,
}

/// The different ways of adjusting the timestep length each frame.
#[derive(Copy, Clone, Debug, PartialEq, Resource)]
/// The different ways of adjusting the timestep length.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum TimestepMode {
/// Use a fixed timestep: the physics simulation will be advanced by the fixed value
/// `dt` seconds at each Bevy tick by performing `substeps` of length `dt / substeps`.
Expand Down Expand Up @@ -55,25 +53,17 @@ pub enum TimestepMode {
},
}

impl Default for TimestepMode {
fn default() -> Self {
TimestepMode::Variable {
max_dt: 1.0 / 60.0,
time_scale: 1.0,
substeps: 1,
}
}
}

#[derive(Component, Copy, Clone, Debug, Reflect)]
/// A component for specifying configuration information for the physics simulation
#[derive(Resource, Copy, Clone, Debug)]
/// A resource for specifying configuration information for the physics simulation
pub struct RapierConfiguration {
/// Specifying the gravity of the physics simulation.
pub gravity: Vect,
/// Specifies if the physics simulation is active and update the physics world.
pub physics_pipeline_active: bool,
/// Specifies if the query pipeline is active and update the query pipeline.
pub query_pipeline_active: bool,
/// Specifies the way the timestep length should be adjusted at each frame.
pub timestep_mode: TimestepMode,
/// Specifies the number of subdivisions along each axes a shape should be subdivided
/// if its scaled representation cannot be represented with the same shape type.
///
Expand All @@ -86,6 +76,16 @@ pub struct RapierConfiguration {
pub force_update_from_transform_changes: bool,
}

impl FromWorld for RapierConfiguration {
fn from_world(world: &mut World) -> Self {
let length_unit = world
.get_resource::<RapierContext>()
.map(|ctxt| ctxt.integration_parameters.length_unit)
.unwrap_or(1.0);
Self::new(length_unit)
}
}

impl RapierConfiguration {
/// Configures rapier with the specified length unit.
///
Expand All @@ -98,6 +98,11 @@ impl RapierConfiguration {
gravity: Vect::Y * -9.81 * length_unit,
physics_pipeline_active: true,
query_pipeline_active: true,
timestep_mode: TimestepMode::Variable {
max_dt: 1.0 / 60.0,
time_scale: 1.0,
substeps: 1,
},
scaled_shape_subdivision: 10,
force_update_from_transform_changes: false,
}
Expand Down
Loading

0 comments on commit efb71e5

Please sign in to comment.