Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Split RapierContext #585

Open
wants to merge 24 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
b9f3a6f
add example to output a debugdump of postupdate
Vrixyz Aug 8, 2024
ff03180
better multiple sets for propagate transforms
Vrixyz Sep 6, 2024
16c3e3f
allow system race for writeback
Vrixyz Sep 6, 2024
b669fe2
remove ambiguity from example
Vrixyz Sep 6, 2024
2c586e9
Merge remote-tracking branch 'upstream' into debugdump
Vrixyz Sep 10, 2024
310ab56
filter out some less relevant systems
Vrixyz Sep 10, 2024
8e553a8
Merge branch 'debugdump' into system_schedules
Vrixyz Sep 10, 2024
e32c4a6
remove dbg
Vrixyz Sep 10, 2024
ad498ee
Merge branch 'debugdump' into system_schedules
Vrixyz Sep 10, 2024
c7ee449
split joints and colliders out of rapier context
Vrixyz Sep 11, 2024
6beece6
split query pipeline + add a 'RapierContextWhole', designed to be the…
Vrixyz Sep 17, 2024
20c47d8
split rigidbody set
Vrixyz Sep 17, 2024
7519a8c
Merge branch 'master' into split_rapiercontext
Vrixyz Sep 17, 2024
4df1d88
use a RapierContext systemparam for a better API ; rework modules + u…
Vrixyz Sep 19, 2024
6b44512
add some missing doc for systemparams
Vrixyz Sep 20, 2024
7b93dba
remove unnecessary macro + fix clippy + docs
Vrixyz Oct 14, 2024
fe1b49a
use a bundle to create correct rapier context components
Vrixyz Oct 14, 2024
83c795f
Merge branch 'master' into split_rapiercontext
Vrixyz Oct 14, 2024
78dc64e
add an example to access a specific component of RapierContext
Vrixyz Oct 14, 2024
8d78d77
changelog adaptations
Vrixyz Oct 14, 2024
3e98da1
more functions transparent for RapierContext and RapierContextMut
Vrixyz Oct 15, 2024
a8c94b4
Merge branch 'master' into split_rapiercontext
Vrixyz Nov 18, 2024
e302ed9
avoid using term 'world' when referring to a physics context, to avoi…
Vrixyz Nov 18, 2024
7cff2c2
please clippy
Vrixyz Nov 19, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 21 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,36 @@ which was its hardcoded behaviour.

### 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.
- Rapier now supports multiple independent physics contexts, see example `multi_contexts3` for usage details.
- Each entity managed by bevy_rapier has a `RapierContextEntityLink` pointing to the entity containing the components above.
- If you are building a library on top of `bevy_rapier` and would want to support multiple independent physics contexts too,
you can check out the details of [#545](https://github.com/dimforge/bevy_rapier/pull/545)
to find more information.
- Rapier now supports multiple independent physics contexts, see example `multi_contexts3` 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,
- If you are building a library on top of `bevy_rapier` and would want to support multiple independent physics contexts too,
you can check out the details of [#545](https://github.com/dimforge/bevy_rapier/pull/545)
to get more context and information.
- `colliders_with_aabb_intersecting_aabb` now takes `bevy::math::bounding::Aabb3d` (or `[..]::Aabb2d` in 2D) as parameter.
- it is now accessible with `headless` feature enabled.
- `RapierContext`, `RapierConfiguration` and `SimulationToRenderTime` are no longer `Resource`s.
- They have been split in multiple `Component`s:
- `RapierContextColliders`
- `RapierContextJoints`
- `RapierContextSimulation`
- `RapierRigidBodySet`
- `SimulationToRenderTime`
- `RapierConfiguration`
- Migration guide:
- `ResMut<mut RapierContext>` -> `WriteRapierContext`
- `Res<RapierContext>` -> `ReadRapierContext`
- Access to `RapierConfiguration` and `SimulationToRenderTime` should query for it
on the responsible entity owning the `RenderContext`.
- See [`ray_casting`](bevy_rapier3d/examples/ray_casting3.rs) example for a usage example.

## v0.27.0 (07 July 2024)

Expand Down
2 changes: 1 addition & 1 deletion bevy_rapier2d/examples/debugdump2.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Example using bevy_mod_debugdump to output a graph of systems execution order.
//! run with:
//! `cargo run --example debugdump2 > dump.dot && dot -Tsvg dump.dot > dump.svg`
//! `cargo run --example debugdump2 > dump.dot && dot -Tsvg dump.dot > dump.svg`

use bevy::prelude::*;
use bevy_mod_debugdump::{schedule_graph, schedule_graph_dot};
Expand Down
9 changes: 5 additions & 4 deletions bevy_rapier2d/examples/testbed2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,11 +204,12 @@ fn main() {
OnExit(Examples::PlayerMovement2),
(
cleanup,
|mut rapier_config: Query<&mut RapierConfiguration>,
ctxt: ReadDefaultRapierContext| {
|mut rapier_config: Query<&mut RapierConfiguration>, ctxt: ReadRapierContext| {
let mut rapier_config = rapier_config.single_mut();
rapier_config.gravity =
RapierConfiguration::new(ctxt.integration_parameters.length_unit).gravity;
rapier_config.gravity = RapierConfiguration::new(
ctxt.single().simulation.integration_parameters.length_unit,
)
.gravity;
},
),
)
Expand Down
4 changes: 2 additions & 2 deletions 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: ReadRapierContext,
joints: Query<(Entity, &ImpulseJoint)>,
) {
for (entity, impulse_joint) in joints.iter() {
Expand All @@ -293,7 +293,7 @@ pub fn print_impulse_revolute_joints(
println!(
"angle for {}: {:?}",
entity,
context.impulse_revolute_joint_angle(entity),
context.single().impulse_revolute_joint_angle(entity),
);
}
_ => {}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use bevy::{input::common_conditions::input_just_pressed, prelude::*};
use bevy_rapier3d::prelude::*;

const N_WORLDS: usize = 2;
const N_CONTEXTS: usize = 2;

fn main() {
App::new()
Expand All @@ -18,21 +18,21 @@ fn main() {
))
.add_systems(
Startup,
((create_worlds, setup_physics).chain(), setup_graphics),
((create_contexts, setup_physics).chain(), setup_graphics),
)
.add_systems(Update, move_platforms)
.add_systems(
Update,
change_world.run_if(input_just_pressed(KeyCode::KeyC)),
change_context.run_if(input_just_pressed(KeyCode::KeyC)),
)
.run();
}

fn create_worlds(mut commands: Commands) {
for i in 0..N_WORLDS {
let mut world = commands.spawn((RapierContext::default(), WorldId(i)));
fn create_contexts(mut commands: Commands) {
for i in 0..N_CONTEXTS {
let mut context = commands.spawn((RapierContextBundle::default(), ContextId(i)));
if i == 0 {
world.insert(DefaultRapierContext);
context.insert((DefaultRapierContext, RapierContextBundle::default()));
}
}
}
Expand All @@ -46,7 +46,7 @@ fn setup_graphics(mut commands: Commands) {
}

#[derive(Component)]
pub struct WorldId(pub usize);
pub struct ContextId(pub usize);

#[derive(Component)]
struct Platform {
Expand All @@ -59,8 +59,8 @@ fn move_platforms(time: Res<Time>, mut query: Query<(&mut Transform, &Platform)>
}
}

/// Demonstrates how easy it is to move one entity to another world.
fn change_world(
/// Demonstrates how easy it is to move one entity to another context.
fn change_context(
query_context: Query<Entity, With<DefaultRapierContext>>,
mut query_links: Query<(Entity, &mut RapierContextEntityLink)>,
) {
Expand All @@ -70,12 +70,12 @@ fn change_world(
continue;
}
link.0 = default_context;
println!("changing world of {} for world {}", e, link.0);
println!("changing context of {} for context {}", e, link.0);
}
}

pub fn setup_physics(
context: Query<(Entity, &WorldId), With<RapierContext>>,
context: Query<(Entity, &ContextId), With<RapierContextSimulation>>,
mut commands: Commands,
) {
for (context_entity, id) in context.iter() {
Expand Down
61 changes: 61 additions & 0 deletions bevy_rapier3d/examples/rapier_context_component.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
use bevy::prelude::*;
use bevy_rapier3d::prelude::*;

fn main() {
App::new()
.add_plugins((
DefaultPlugins,
RapierPhysicsPlugin::<NoUserData>::default(),
RapierDebugRenderPlugin::default(),
))
.add_systems(Startup, (setup_physics, setup_graphics))
.add_systems(PostUpdate, display_nb_colliders)
.run();
}

/// Demonstrates how to access a more specific component of [`RapierContext`]
fn display_nb_colliders(
query_context: Query<&RapierContextColliders, With<DefaultRapierContext>>,
mut exit: EventWriter<AppExit>,
) {
let nb_colliders = query_context.single().colliders.len();
println!("There are {nb_colliders} colliders.");
if nb_colliders > 0 {
exit.send(AppExit::Success);
}
}

pub fn setup_physics(mut commands: Commands) {
/*
* Ground
*/
let ground_size = 5.1;
let ground_height = 0.1;

let starting_y = -0.5 - ground_height;

commands.spawn((
TransformBundle::from(Transform::from_xyz(0.0, starting_y, 0.0)),
Collider::cuboid(ground_size, ground_height, ground_size),
));

for _ in 0..3 {
/*
* Create the cubes
*/

commands.spawn((
TransformBundle::default(),
RigidBody::Dynamic,
Collider::cuboid(0.5, 0.5, 0.5),
));
}
}

fn setup_graphics(mut commands: Commands) {
commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(0.0, 3.0, -10.0)
.looking_at(Vec3::new(0.0, 0.0, 0.0), Vec3::Y),
..Default::default()
});
}
6 changes: 3 additions & 3 deletions 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: ReadRapierContext,
cameras: Query<(&Camera, &GlobalTransform)>,
) {
let window = windows.single();
Expand All @@ -91,9 +91,9 @@ pub fn cast_ray(
let Some(ray) = camera.viewport_to_world(camera_transform, cursor_position) else {
return;
};

let context = rapier_context.single();
// Then cast the ray.
let hit = rapier_context.cast_ray(
let hit = context.cast_ray(
ray.origin,
ray.direction.into(),
f32::MAX,
Expand Down
4 changes: 2 additions & 2 deletions bevy_rapier_benches3d/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use common::default_app;
use common::wait_app_start;

use bevy::prelude::*;
use bevy_rapier3d::plugin::RapierContext;
use bevy_rapier3d::plugin::context::RapierContextSimulation;

pub fn custom_bencher(steps: usize, setup: impl Fn(&mut App)) {
let mut app = default_app();
Expand All @@ -28,7 +28,7 @@ pub fn custom_bencher(steps: usize, setup: impl Fn(&mut App)) {
let elapsed_time = timer_full_update.time() as f32;
let rc = app
.world_mut()
.query::<&RapierContext>()
.query::<&RapierContextSimulation>()
.single(app.world());
rapier_step_times.push(rc.pipeline.counters.step_time.time() as f32);
total_update_times.push(elapsed_time);
Expand Down
6 changes: 3 additions & 3 deletions src/control/character_controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::geometry::{Collider, CollisionGroups, ShapeCastHit};
use crate::math::{Real, Rot, Vect};
use bevy::prelude::*;

use crate::plugin::RapierContext;
use crate::plugin::context::RapierContextColliders;
pub use rapier::control::CharacterAutostep;
pub use rapier::control::CharacterLength;
use rapier::prelude::{ColliderSet, QueryFilterFlags};
Expand All @@ -26,7 +26,7 @@ pub struct CharacterCollision {

impl CharacterCollision {
pub(crate) fn from_raw(
ctxt: &RapierContext,
ctxt: &RapierContextColliders,
c: &rapier::control::CharacterCollision,
) -> Option<Self> {
Self::from_raw_with_set(&ctxt.colliders, c, true)
Expand All @@ -37,7 +37,7 @@ impl CharacterCollision {
c: &rapier::control::CharacterCollision,
details_always_computed: bool,
) -> Option<Self> {
RapierContext::collider_entity_with_set(colliders, c.handle).map(|entity| {
RapierContextColliders::collider_entity_with_set(colliders, c.handle).map(|entity| {
CharacterCollision {
entity,
character_translation: c.character_pos.translation.vector.into(),
Expand Down
17 changes: 10 additions & 7 deletions src/dynamics/revolute_joint.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
use crate::dynamics::{GenericJoint, GenericJointBuilder};
use crate::math::{Real, Vect};
use crate::plugin::RapierContext;
use crate::plugin::context::RapierRigidBodySet;
use bevy::prelude::Entity;
use rapier::dynamics::{
JointAxesMask, JointAxis, JointLimits, JointMotor, MotorModel, RigidBodyHandle, RigidBodySet,
};

#[cfg(doc)]
use crate::prelude::RapierContext;

use super::TypedJoint;

#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
Expand Down Expand Up @@ -147,7 +150,7 @@ impl RevoluteJoint {
/// Similarly [`RapierContext::impulse_revolute_joint_angle`] only takes a single entity as argument to compute that angle.
///
/// # Parameters
/// - `bodies` : the rigid body set from [`RapierContext`]
/// - `bodies` : the rigid body set from [`RapierRigidBodySet`]
/// - `body1`: the first rigid-body attached to this revolute joint, obtained through [`rapier::dynamics::ImpulseJoint`] or [`rapier::dynamics::MultibodyJoint`].
/// - `body2`: the second rigid-body attached to this revolute joint, obtained through [`rapier::dynamics::ImpulseJoint`] or [`rapier::dynamics::MultibodyJoint`].
pub fn angle_from_handles(
Expand All @@ -167,13 +170,13 @@ impl RevoluteJoint {
/// The angle along the free degree of freedom of this revolute joint in `[-π, π]`.
///
/// # Parameters
/// - `bodies` : the rigid body set from [`RapierContext`]
/// - `bodies` : the rigid body set from [`RapierRigidBodySet`]
/// - `body1`: the first rigid-body attached to this revolute joint.
/// - `body2`: the second rigid-body attached to this revolute joint.
pub fn angle(&self, context: &RapierContext, body1: Entity, body2: Entity) -> f32 {
let rb1 = context.entity2body().get(&body1).unwrap();
let rb2 = context.entity2body().get(&body2).unwrap();
self.angle_from_handles(&context.bodies, *rb1, *rb2)
pub fn angle(&self, rigidbody_set: &RapierRigidBodySet, body1: Entity, body2: Entity) -> f32 {
let rb1 = rigidbody_set.entity2body().get(&body1).unwrap();
let rb2 = rigidbody_set.entity2body().get(&body2).unwrap();
self.angle_from_handles(&rigidbody_set.bodies, *rb1, *rb2)
}
}

Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ pub mod prelude {
pub use crate::geometry::*;
pub use crate::math::*;
pub use crate::pipeline::*;
pub use crate::plugin::context::systemparams::*;
pub use crate::plugin::context::*;
pub use crate::plugin::*;
#[cfg(any(feature = "debug-render-3d", feature = "debug-render-2d"))]
pub use crate::render::*;
Expand Down
2 changes: 1 addition & 1 deletion src/pipeline/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ mod test {
));
// 2 seconds should be plenty of time for the cube to fall on the
// lowest collider.
for _ in 0..120 {
for _ in 0..1020 {
app.update();
}
let saved_collisions = app
Expand Down
4 changes: 2 additions & 2 deletions src/pipeline/query_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ pub use rapier::pipeline::QueryFilterFlags;
use crate::geometry::CollisionGroups;

#[cfg(doc)]
use crate::prelude::RapierContext;
use crate::prelude::RapierRigidBodySet;

/// A filter that describes what collider should be included or excluded from a scene query.
///
/// For testing manually check [`RapierContext::with_query_filter`].
/// For testing manually check [`RapierRigidBodySet::with_query_filter`].
#[derive(Copy, Clone, Default)]
pub struct QueryFilter<'a> {
/// Flags indicating what particular type of colliders should be excluded.
Expand Down
9 changes: 2 additions & 7 deletions src/plugin/configuration.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Components used to configure a simulation run by rapier, these are not modified by bevy_rapier.

use bevy::{
prelude::{Component, Resource},
reflect::Reflect,
Expand All @@ -8,13 +10,6 @@ use crate::math::{Real, Vect};
#[cfg(doc)]
use {crate::prelude::TransformInterpolation, rapier::dynamics::IntegrationParameters};

/// Difference between simulation and rendering time
#[derive(Component, Default, Reflect)]
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)]
pub enum TimestepMode {
Expand Down
Loading