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
#![deny(future_incompatible, nonstandard_style)]
#![warn(missing_docs, rust_2018_idioms, clippy::pedantic)]
#![allow(clippy::needless_pass_by_value)]
#![cfg(all(
    any(feature = "2d", feature = "3d"),
    not(all(feature = "2d", feature = "3d")),
))]

//! Physics behavior for Heron, using [rapier](https://rapier.rs/)

#[cfg(feature = "2d")]
pub extern crate rapier2d as rapier;
#[cfg(feature = "3d")]
pub extern crate rapier3d as rapier;

use bevy::app::{AppBuilder, Plugin};
use bevy::ecs::{IntoSystem, Schedule, SystemStage};

use heron_core::CollisionEvent;

use crate::body::HandleMap;
use crate::rapier::dynamics::{IntegrationParameters, JointSet, RigidBodyHandle, RigidBodySet};
use crate::rapier::geometry::{BroadPhase, ColliderHandle, ColliderSet, NarrowPhase};
pub use crate::rapier::na as nalgebra;
use crate::rapier::pipeline::PhysicsPipeline;

mod body;
pub mod convert;
mod pipeline;
mod velocity;

#[allow(unused)]
mod stage {
    pub(crate) const PRE_STEP: &str = "heron-pre-step";
    pub(crate) const STEP: &str = "heron-step";
    pub(crate) const POST_STEP: &str = "heron-post-step";
}

/// Plugin to install in order to enable collision detection and physics behavior, powered by rapier.
///
/// When creating the plugin, you may choose the number of physics steps per second.
/// For more advanced configuration, you can create the plugin from a rapier `IntegrationParameters` definition.
#[must_use]
#[derive(Clone)]
pub struct RapierPlugin {
    /// Number of step per second, None for a step each frame.
    pub step_per_second: Option<f64>,

    /// Integration parameters, incl. delta-time at each step.
    pub parameters: IntegrationParameters,
}

/// Components automatically register, by the plugin that references the body in rapier's world
///
/// It can be used to get direct access to rapier's world.
#[derive(Debug, Copy, Clone)]
pub struct BodyHandle {
    rigid_body: RigidBodyHandle,
    collider: ColliderHandle,
}

impl RapierPlugin {
    /// Configure how many times per second the physics world needs to be updated
    ///
    /// # Panics
    ///
    /// Panic if the number of `steps_per_second` is 0
    pub fn from_steps_per_second(steps_per_second: u8) -> Self {
        assert!(
            steps_per_second > 0,
            "Invalid number of step per second: {}",
            steps_per_second
        );
        let parameters = IntegrationParameters {
            dt: 1.0 / f32::from(steps_per_second),
            ..IntegrationParameters::default()
        };

        Self {
            parameters,
            step_per_second: Some(steps_per_second.into()),
        }
    }
}

impl Default for RapierPlugin {
    fn default() -> Self {
        Self::from(IntegrationParameters::default())
    }
}

impl From<IntegrationParameters> for RapierPlugin {
    fn from(parameters: IntegrationParameters) -> Self {
        Self {
            #[allow(clippy::cast_possible_truncation)]
            step_per_second: Some(1.0 / f64::from(parameters.dt)),
            parameters,
        }
    }
}

impl Plugin for RapierPlugin {
    fn build(&self, app: &mut AppBuilder) {
        app.add_plugin(heron_core::CorePlugin {
            steps_per_second: self.step_per_second,
        })
        .init_resource::<PhysicsPipeline>()
        .init_resource::<HandleMap>()
        .add_event::<CollisionEvent>()
        .add_resource(self.parameters)
        .add_resource(BroadPhase::new())
        .add_resource(NarrowPhase::new())
        .add_resource(RigidBodySet::new())
        .add_resource(ColliderSet::new())
        .add_resource(JointSet::new())
        .stage(heron_core::stage::ROOT, |schedule: &mut Schedule| {
            schedule
                .add_stage(
                    "heron-pre-step",
                    SystemStage::serial()
                        .with_system(
                            bevy::transform::transform_propagate_system::transform_propagate_system
                                .system(),
                        )
                        .with_system(body::remove.system())
                        .with_system(body::recreate_collider.system())
                        .with_system(body::update_rapier_position.system())
                        .with_system(velocity::update_rapier_velocity.system())
                        .with_system(body::update_rapier_status.system())
                        .with_system(body::create.system()),
                )
                .add_stage(
                    "heron-step",
                    SystemStage::serial()
                        .with_system(velocity::apply_velocity_to_kinematic_bodies.system())
                        .with_system(pipeline::step.system()),
                )
                .add_stage(
                    "heron-post-step",
                    SystemStage::parallel()
                        .with_system(body::update_bevy_transform.system())
                        .with_system(velocity::update_velocity_component.system()),
                )
        });
    }
}

impl BodyHandle {
    /// Creates the new `BodyHandle`
    #[must_use]
    pub fn new(rigid_body: RigidBodyHandle, collider: ColliderHandle) -> BodyHandle {
        BodyHandle {
            rigid_body,
            collider,
        }
    }

    /// Returns the rapier's rigid body handle
    #[must_use]
    pub fn rigid_body(&self) -> RigidBodyHandle {
        self.rigid_body
    }

    /// Returns the rapier's collider handle
    #[must_use]
    pub fn collider(&self) -> ColliderHandle {
        self.collider
    }
}