### Link and Start 3D Examples Source: https://github.com/dimforge/rapier/blob/master/CONTRIBUTING.md Link the local rapier3d package and start the 3D examples in the browser to test changes. Ensure you are in the repository's root directory before running. ```bash cd testbed3d; npm install; npm link ../rapier3d/pkg; npm run start ``` -------------------------------- ### Basic Physics Pipeline Setup and Simulation Loop Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/physics_pipeline.md Demonstrates how to initialize the PhysicsPipeline, create physics objects like rigid bodies and colliders, and run a basic simulation loop. This snippet is useful for getting started with Rapier's physics simulation. ```rust use rapier3d::prelude::*; let mut physics_pipeline = PhysicsPipeline::new(); let mut gravity = Vector::new(0.0, -9.81, 0.0); let integration_params = IntegrationParameters::default(); let mut rigid_body_set = RigidBodySet::new(); let mut collider_set = ColliderSet::new(); let mut impulse_joint_set = ImpulseJointSet::new(); let mut multibody_joint_set = MultibodyJointSet::new(); let mut broad_phase = BroadPhaseBvh::new(); let mut narrow_phase = NarrowPhase::new(); let mut islands = IslandManager::new(); // Create physics objects... let body = RigidBodyBuilder::dynamic() .translation(Vector::new(0.0, 10.0, 0.0)) .build(); let body_handle = rigid_body_set.insert(body); let collider = ColliderBuilder::ball(0.5).build(); collider_set.insert_with_parent(collider, body_handle, &mut rigid_body_set); // Simulation loop for _ in 0..100 { physics_pipeline.step( &gravity, &integration_params, &mut islands, &mut broad_phase, &mut narrow_phase, &mut rigid_body_set, &mut collider_set, &mut impulse_joint_set, &mut multibody_joint_set, &mut physics_hooks, &mut event_handler, ); // Read results... let pos = rigid_body_set[body_handle].translation(); println!("Position: {:?}", pos); } ``` -------------------------------- ### Start Docusaurus Development Server Source: https://github.com/dimforge/rapier/blob/master/CONTRIBUTING.md Install dependencies and start the Docusaurus development server to preview website changes locally. The website will be available at http://localhost:3000. ```bash cd website; yarn install; yarn start; ``` -------------------------------- ### Run All 2D Examples Source: https://github.com/dimforge/rapier/blob/master/README.md Execute all 2D examples in release mode. Source code is available in the examples2d/ directory. ```bash cargo run --release --bin all_examples2 ``` -------------------------------- ### Run All 3D Examples Source: https://github.com/dimforge/rapier/blob/master/README.md Execute all 3D examples in release mode. Source code is available in the examples3d/ directory. ```bash cargo run --release --bin all_examples3 ``` -------------------------------- ### Complete Collision Detection Example Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/collision_pipeline.md A comprehensive example demonstrating the setup and execution of the Rapier 3D collision detection pipeline. It includes initializing physics objects, creating colliders, running the collision detection loop, and querying for contact pairs. ```rust use rapier3d::prelude::*; let mut collision_pipeline = CollisionPipeline::new(); let mut broad_phase = BroadPhaseBvh::new(); let mut narrow_phase = NarrowPhase::new(); let mut islands = IslandManager::new(); let mut bodies = RigidBodySet::new(); let mut colliders = ColliderSet::new(); let impulse_joints = ImpulseJointSet::new(); let multibody_joints = MultibodyJointSet::new(); // Create bodies and colliders... let body1 = RigidBodyBuilder::dynamic() .translation(Vector::new(0.0, 5.0, 0.0)) .build(); let body1_handle = bodies.insert(body1); let collider1 = ColliderBuilder::ball(0.5).build(); colliders.insert_with_parent(collider1, body1_handle, &mut bodies); let body2 = RigidBodyBuilder::fixed() .translation(Vector::new(0.0, -1.0, 0.0)) .build(); let body2_handle = bodies.insert(body2); let collider2 = ColliderBuilder::cuboid(10.0, 0.1, 10.0).build(); colliders.insert_with_parent(collider2, body2_handle, &mut bodies); // Collision detection loop let integration_params = IntegrationParameters::default(); let physics_hooks = DefaultHooks; let event_handler = MyEventHandler; for _ in 0..100 { // Detect collisions collision_pipeline.step( &integration_params, &mut islands, &mut broad_phase, &mut narrow_phase, &mut bodies, &mut colliders, &impulse_joints, &multibody_joints, &physics_hooks, &event_handler, true, ); // Query collision results for (h1, h2, contact) in narrow_phase.contact_pairs() { if contact.has_any_active_contact { println!("Colliders {:?} and {:?} are in contact", h1, h2); for manifold in &contact.manifolds { for contact_data in &manifold.data { println!(" Contact impulse: {}", contact_data.impulse); } } } } } ``` -------------------------------- ### RigidBodyBuilder Example Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/rigid_body.md Example demonstrating how to use the RigidBodyBuilder to create and configure a dynamic rigid body. ```APIDOC ## RigidBodyBuilder Example ### Description This example shows how to create a dynamic rigid body with specific properties like translation, linear velocity, damping, sleepability, CCD, and gravity scale. ### Code Example ```rust let body = RigidBodyBuilder::dynamic() .translation(Vector::new(0.0, 5.0, 0.0)) .linvel(Vector::new(1.0, 0.0, 0.0)) .linear_damping(0.1) .angular_damping(0.2) .can_sleep(true) .ccd_enabled(true) .gravity_scale(1.5) .build(); let handle = bodies.insert(body); ``` ``` -------------------------------- ### Complete Query Pipeline Example Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/query_pipeline.md A comprehensive example demonstrating raycasting, AABB intersection queries, and ground detection using the QueryPipeline. ```rust use rapier3d::prelude::*; let mut query_pipeline = QueryPipeline::new(); let mut colliders = ColliderSet::new(); let mut bodies = RigidBodySet::new(); // ... create bodies/colliders ... // Update query pipeline before queries query_pipeline.update(&colliders); // 1. Raycast for line of sight let eye_pos = bodies[player].translation(); let look_dir = Vector::new(1.0, 0.0, 0.0); let ray = Ray::new(Point::from(eye_pos), look_dir); let filter = QueryFilter::default() .exclude_sensors() .exclude_rigid_body(player); if let Some((obstacle_handle, dist)) = query_pipeline.cast_ray( &colliders, &ray, 100.0, false, filter, ) { println!("Line of sight blocked by {:?} at distance {}", obstacle_handle, dist); } // 2. Find nearby objects let region = Aabb::new( Point::from(eye_pos - Vector::new(10.0, 10.0, 10.0)), Point::from(eye_pos + Vector::new(10.0, 10.0, 10.0)), ); let mut nearby = Vec::new(); query_pipeline.colliders_with_aabb_intersecting_aabb( ®ion, QueryFilter::default().exclude_fixed(), |handle| { nearby.push(handle); true }, ); println!("Found {} nearby objects", nearby.len()); // 3. Test if character is grounded let feet_pos = bodies[player].translation() + Vector::new(0.0, -1.0, 0.0); let capsule = Capsule::new_y(0.5, 0.3); let capsule_pos = Isometry::translation(feet_pos.x, feet_pos.y, feet_pos.z); if query_pipeline.cast_shape( &colliders, &capsule_pos, &Vector::new(0.0, -0.1, 0.0), &capsule, 0.1, false, QueryFilter::default(), ).is_some() { println!("Player is grounded"); } ``` -------------------------------- ### Basic Physics World Setup and Simulation Source: https://github.com/dimforge/rapier/blob/master/_autodocs/EXAMPLES.md Demonstrates the minimal setup for a Rapier 3D physics world, including creating static ground and a dynamic falling ball, and running a short simulation loop. ```rust use rapier3d::prelude::*; fn main() { let mut physics_pipeline = PhysicsPipeline::new(); let mut gravity = Vector::new(0.0, -9.81, 0.0); let integration_params = IntegrationParameters::default(); let mut islands = IslandManager::new(); let mut broad_phase = BroadPhaseBvh::new(); let mut narrow_phase = NarrowPhase::new(); let mut bodies = RigidBodySet::new(); let mut colliders = ColliderSet::new(); let mut impulse_joints = ImpulseJointSet::new(); let mut multibody_joints = MultibodyJointSet::new(); // Create ground let ground_body = RigidBodyBuilder::fixed().build(); let ground_handle = bodies.insert(ground_body); let ground_shape = ColliderBuilder::cuboid(50.0, 1.0, 50.0).build(); colliders.insert_with_parent(ground_shape, ground_handle, &mut bodies); // Create falling ball let ball_body = RigidBodyBuilder::dynamic() .translation(Vector::new(0.0, 10.0, 0.0)) .build(); let ball_handle = bodies.insert(ball_body); let ball_shape = ColliderBuilder::ball(1.0).density(1.0).build(); colliders.insert_with_parent(ball_shape, ball_handle, &mut bodies); // Simulation loop for frame in 0..500 { physics_pipeline.step( &gravity, &integration_params, &mut islands, &mut broad_phase, &mut narrow_phase, &mut bodies, &mut colliders, &mut impulse_joints, &mut multibody_joints, &DefaultHooks, &DefaultEventHandler, ); let pos = bodies[ball_handle].translation(); println!("Frame {}: Ball at y={{:.2}}", frame, pos.y); } } struct DefaultHooks; impl PhysicsHooks for DefaultHooks { fn filter_contact_pair(&self, _: &PairFilterContext) -> bool { true } fn filter_intersection_pair(&self, _: &PairFilterContext) -> bool { true } fn modify_solver_contact(&self, _: &mut ContactModificationContext) {} } struct DefaultEventHandler; impl EventHandler for DefaultEventHandler { fn handle_collision_event(&self, _: &RigidBodySet, _: &ColliderSet, _: &CollisionEvent, _: Option<&ContactPair>) {} fn handle_contact_force_event(&self, _: Real, _: &ContactForceEvent, _: &RigidBodySet, _: &ColliderSet) {} } ``` -------------------------------- ### Example: Detect Collision Events Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/collider.md Shows how to configure a collider to generate collision start and stop events by setting the active events to COLLISION_EVENTS. ```rust let collider = ColliderBuilder::ball(0.5) .active_events(ActiveEvents::COLLISION_EVENTS) .build(); ``` -------------------------------- ### Ray Usage Example Source: https://github.com/dimforge/rapier/blob/master/_autodocs/types.md Example demonstrating how to create and use a Ray object for raycasting. Shows how to define a ray's origin and direction. ```rust let ray = Ray::new(Point::new(0.0, 0.0, 0.0), Vector::new(0.0, 1.0, 0.0)); ray.point_at(distance) // Point along ray ``` -------------------------------- ### Look-ahead for AI Pathfinding Example Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/rigid_body.md Example demonstrating how to use `predict_position_using_velocity` to predict a body's future position for AI pathfinding calculations. ```rust let future_pos = bodies[handle].predict_position_using_velocity(0.033); // 33ms ahead ``` -------------------------------- ### Complete Example: Raycast, Nearby Objects, and Grounded Check Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/query_pipeline.md A comprehensive example demonstrating raycasting, finding nearby objects using AABB intersection, and checking if a character is grounded using shape casting, all with appropriate query filtering. ```APIDOC --- ## Complete Example ```rust use rapier3d::prelude::*; let mut query_pipeline = QueryPipeline::new(); let mut colliders = ColliderSet::new(); let mut bodies = RigidBodySet::new(); // ... create bodies/colliders ... // Update query pipeline before queries query_pipeline.update(&colliders); // 1. Raycast for line of sight let eye_pos = bodies[player].translation(); let look_dir = Vector::new(1.0, 0.0, 0.0); let ray = Ray::new(Point::from(eye_pos), look_dir); let filter = QueryFilter::default() .exclude_sensors() .exclude_rigid_body(player); if let Some((obstacle_handle, dist)) = query_pipeline.cast_ray( &colliders, &ray, 100.0, false, filter, ) { println!("Line of sight blocked by {:?} at distance {}", obstacle_handle, dist); } // 2. Find nearby objects let region = Aabb::new( Point::from(eye_pos - Vector::new(10.0, 10.0, 10.0)), Point::from(eye_pos + Vector::new(10.0, 10.0, 10.0)), ); let mut nearby = Vec::new(); query_pipeline.colliders_with_aabb_intersecting_aabb( ®ion, QueryFilter::default().exclude_fixed(), |handle| { nearby.push(handle); true }, ); println!("Found {} nearby objects", nearby.len()); // 3. Test if character is grounded let feet_pos = bodies[player].translation() + Vector::new(0.0, -1.0, 0.0); let capsule = Capsule::new_y(0.5, 0.3); let capsule_pos = Isometry::translation(feet_pos.x, feet_pos.y, feet_pos.z); if query_pipeline.cast_shape( &colliders, &capsule_pos, &Vector::new(0.0, -0.1, 0.0), &capsule, 0.1, false, QueryFilter::default(), ).is_some() { println!("Player is grounded"); } ``` ``` -------------------------------- ### Run Rapier 3D Examples with Parallel and SIMD Features Source: https://github.com/dimforge/rapier/blob/master/CONTRIBUTING.md Execute the 3D examples with parallel processing and SIMD stable features enabled. This is useful for testing performance optimizations. ```bash cargo run --release --bin all_examples3 --features parallel,simd-stable ``` -------------------------------- ### Find Heaviest Collider Example Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/collider.md An example demonstrating how to iterate through all colliders in the `ColliderSet` to find the one with the highest density. ```rust let heaviest = colliders.iter() .max_by(|(_, c1), (_, c2)| { c1.density().partial_cmp(&c2.density()).unwrap() }); ``` -------------------------------- ### Example: Managing multiple RigidBodies Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/rigid_body_set.md This example demonstrates the creation, insertion, modification, querying, and removal of multiple rigid bodies within a `RigidBodySet`. ```rust use rapier3d::prelude::*; let mut bodies = RigidBodySet::new(); let mut handles = Vec::new(); // Create multiple bodies for i in 0..10 { let body = RigidBodyBuilder::dynamic() .translation(Vector::new(i as f32 * 2.0, 5.0, 0.0)) .build(); let handle = bodies.insert(body); handles.push(handle); } // Modify all bodies for &handle in &handles { if bodies.contains(handle) { bodies[handle].set_linear_damping(0.1); } } // Find bodies in region let region = Vector::new(5.0, 0.0, 0.0); for (handle, body) in bodies.iter() { let distance = (body.translation() - region).length(); if distance < 10.0 { println!("Body near region at distance {}", distance); } } // Clean up - remove first 3 for handle in handles.iter().take(3) { bodies.remove(*handle); } println!("Remaining bodies: {}", bodies.len()); ``` -------------------------------- ### Run Rapier 2D Examples with Parallel and SIMD Features Source: https://github.com/dimforge/rapier/blob/master/CONTRIBUTING.md Execute the 2D examples with parallel processing and SIMD stable features enabled. This is useful for testing performance optimizations. ```bash cargo run --release --bin all_examples2 --features parallel,simd-stable ``` -------------------------------- ### Calculate Impact Speed at Contact Point Example Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/rigid_body.md Example demonstrating how to calculate the impact speed at a specific contact point using `velocity_at_point`. ```rust let impact_vel = bodies[handle].velocity_at_point(contact_point); let speed = impact_vel.length(); ``` -------------------------------- ### Raycast Example with Filters Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/query_pipeline.md Demonstrates how to use `QueryFilter` to exclude sensors and specific rigid bodies during a raycast. ```APIDOC **Example**: Query filter for line of sight. ```rust let filter = QueryFilter::default() .exclude_sensors() .exclude_rigid_body(player_body); // Don't hit player if query_pipeline.cast_ray(&colliders, &ray, 100.0, false, filter).is_some() { println!("Blocked"); } ``` ``` -------------------------------- ### Raycast Filter Example Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/query_pipeline.md Example of using query filters to exclude sensors and a specific rigid body during a raycast. ```rust let filter = QueryFilter::default() .exclude_sensors() .exclude_rigid_body(player_body); if query_pipeline.cast_ray(&colliders, &ray, 100.0, false, filter).is_some() { println!("Blocked"); } ``` -------------------------------- ### Draw Penetration Visualization Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/collision_pipeline.md Example showing how to use `find_deepest_contact` to get penetration details and print them. This is useful for debugging or visualizing collision depths. ```rust if let Some((normal, point, depth)) = contact_pair.find_deepest_contact() { println!("Penetration: {} at {:?}", depth, point); } ``` -------------------------------- ### Example: Creating and Configuring a Dynamic Rigid Body Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/rigid_body.md Demonstrates how to use the `RigidBodyBuilder` to create a dynamic rigid body with specific initial properties like translation, velocity, damping, and CCD enabled, then insert it into the physics world. ```rust let body = RigidBodyBuilder::dynamic() .translation(Vector::new(0.0, 5.0, 0.0)) .linvel(Vector::new(1.0, 0.0, 0.0)) .linear_damping(0.1) .angular_damping(0.2) .can_sleep(true) .ccd_enabled(true) .gravity_scale(1.5) .build(); let handle = bodies.insert(body); ``` -------------------------------- ### Example: Create a 2x4x1 Box Collider Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/collider.md Demonstrates the creation of a cuboid collider with specific half-extents to form a 2x4x1 box. ```rust let box_collider = ColliderBuilder::cuboid(1.0, 2.0, 0.5); ``` -------------------------------- ### Initialize CollisionPipeline Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/collision_pipeline.md Initializes a new CollisionPipeline, BroadPhaseBvh, and NarrowPhase. This setup is typically done once at the beginning of the physics simulation. ```rust use rapier3d::prelude::*; let mut collision_pipeline = CollisionPipeline::new(); let mut broad_phase = BroadPhaseBvh::new(); let mut narrow_phase = NarrowPhase::new(); let mut bodies = RigidBodySet::new(); let mut colliders = ColliderSet::new(); // ... add bodies and colliders ... ``` -------------------------------- ### Complete Rapier 3D Physics Simulation Example Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/physics_pipeline.md Sets up and runs a basic 3D physics simulation using `PhysicsPipeline`. This includes initializing simulation parameters, creating static and dynamic rigid bodies with colliders, and running a simulation loop. ```rust use rapier3d::prelude::*; // Create simulation structures let mut physics_pipeline = PhysicsPipeline::new(); let mut gravity = Vector::new(0.0, -9.81, 0.0); let mut integration_params = IntegrationParameters::default(); integration_params.dt = 1.0 / 120.0; // 120 FPS integration_params.num_solver_iterations = 5; let mut rigid_body_set = RigidBodySet::new(); let mut collider_set = ColliderSet::new(); let mut impulse_joint_set = ImpulseJointSet::new(); let mut multibody_joint_set = MultibodyJointSet::new(); let mut broad_phase = BroadPhaseBvh::new(); let mut narrow_phase = NarrowPhase::new(); let mut islands = IslandManager::new(); let physics_hooks = DefaultHooks; let event_handler = MyEventHandler; // Create ground let ground = RigidBodyBuilder::fixed() .translation(Vector::new(0.0, -1.0, 0.0)) .build(); let ground_handle = rigid_body_set.insert(ground); let ground_collider = ColliderBuilder::cuboid(10.0, 0.1, 10.0) .friction(0.7) .build(); collider_set.insert_with_parent(ground_collider, ground_handle, &mut rigid_body_set); // Create falling box let box_body = RigidBodyBuilder::dynamic() .translation(Vector::new(0.0, 5.0, 0.0)) .build(); let box_handle = rigid_body_set.insert(box_body); let box_collider = ColliderBuilder::cuboid(0.5, 0.5, 0.5) .density(1.0) .friction(0.5) .restitution(0.3) .active_events(ActiveEvents::COLLISION_EVENTS) .build(); collider_set.insert_with_parent(box_collider, box_handle, &mut rigid_body_set); // Simulation loop for frame in 0..1000 { // Step physics physics_pipeline.step( &gravity, &integration_params, &mut islands, &mut broad_phase, &mut narrow_phase, &mut rigid_body_set, &mut collider_set, &mut impulse_joint_set, &mut multibody_joint_set, &physics_hooks, &event_handler, ); // Read results let pos = rigid_body_set[box_handle].translation(); println!("Frame {}: Box at {:.2}, {:.2}, {:.2}", frame, pos.x, pos.y, pos.z); } ``` -------------------------------- ### Configure 3D Physics with f32 Precision Source: https://github.com/dimforge/rapier/blob/master/_autodocs/configuration.md Example of adding the rapier3d crate with 3D geometry and 32-bit floating-point precision enabled. ```toml [dependencies] rapier3d = { version = "0.32", features = ["dim3", "f32"] } ``` -------------------------------- ### Offset Collider Example Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/collider.md Demonstrates how to offset a collider from its parent body's center using the `translation` builder method. ```rust let collider = ColliderBuilder::ball(0.3) .translation(Vector::new(0.5, 0.0, 0.0)) // 0.5 units right .build(); ``` -------------------------------- ### Configure 3D Physics with f64 Precision Source: https://github.com/dimforge/rapier/blob/master/_autodocs/configuration.md Example of adding the rapier3d crate with 3D geometry and 64-bit floating-point precision enabled for higher accuracy. ```toml [dependencies] rapier3d = { version = "0.32", features = ["dim3", "f64"] } ``` -------------------------------- ### Configure 2D Physics with f32 Precision Source: https://github.com/dimforge/rapier/blob/master/_autodocs/configuration.md Example of adding the rapier2d crate with 2D geometry and 32-bit floating-point precision enabled. ```toml [dependencies] rapier2d = { version = "0.32", features = ["dim2", "f32"] } ``` -------------------------------- ### RigidBodySet Creation Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/rigid_body_set.md Creates a new, empty RigidBodySet. This is the starting point for managing rigid bodies. ```APIDOC ## RigidBodySet::new() ### Description Creates an empty rigid body set. ### Method `new()` ### Returns `Self` - A new `RigidBodySet` instance. ``` -------------------------------- ### Prevent Z Movement Example Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/rigid_body.md Example demonstrating how to prevent movement along the Z-axis for a character in a 2D game simulated in 3D space. ```rust bodies[character].set_enabled_translations(true, true, false, true); ``` -------------------------------- ### ImpulseJointSet::new Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/joints.md Creates a new, empty ImpulseJointSet. No setup is required before calling this. ```rust pub fn new() -> Self ``` -------------------------------- ### Complex Character Collider Example Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/collider.md An example demonstrating the creation of a complex character collider with multiple properties configured, including friction, restitution, collision groups, active events, and user data. ```rust // Complex character collider let collider = ColliderBuilder::capsule_y(1.0, 0.3) .friction(0.7) .restitution(0.0) .collision_groups(InteractionGroups::new( Group::GROUP_1, Group::all() )) .active_events(ActiveEvents::COLLISION_EVENTS) .user_data(PLAYER_COLLIDER_ID) .build(); colliders.insert_with_parent(collider, player_body, &mut bodies); ``` -------------------------------- ### Rapier 3D Feature Flags Configuration Source: https://github.com/dimforge/rapier/blob/master/_autodocs/configuration.md Example of enabling various features for rapier3d, including standard library, parallelism, SIMD, and serialization. ```toml [dependencies] rapier3d = { version = "0.32", features = [ "dim3", "f32", "std", "parallel", "simd-stable", "serde-serialize", "enhanced-determinism", "debug-render", ] } ``` -------------------------------- ### Example: Assign and Track Collider with User Data Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/collider.md Illustrates how to assign a custom ID using user data to a collider and later retrieve it to identify or track that specific collider. ```rust let collider = ColliderBuilder::ball(0.5) .user_data(123) // Custom ID .build(); if colliders[handle].user_data() == 123 { println!("Found the tracked collider!"); } ``` -------------------------------- ### Default IntegrationParameters Implementation Source: https://github.com/dimforge/rapier/blob/master/_autodocs/configuration.md Provides the default values for all `IntegrationParameters` fields, offering a balanced starting point for most physics simulations. ```rust impl Default for IntegrationParameters { fn default() -> Self { IntegrationParameters { dt: 1.0 / 60.0, num_solver_iterations: 4, num_additional_friction_iterations: 0, num_internal_pgs_iterations: 1, erp: 0.1, damping_ratio: 0.0, joint_erp: 0.1, joint_damping_ratio: 0.0, allowed_linear_error: 0.001, max_ccd_substeps: 1, ccd_on_penetration: true, #[cfg(feature = "dim3")] friction_model: FrictionModel::Standard, } } } ``` -------------------------------- ### Create an Empty ColliderSet Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/collider_set.md Initializes a new, empty collider set. This is the starting point for managing colliders. ```rust pub fn new() -> Self ``` ```rust let mut colliders = ColliderSet::new(); ``` -------------------------------- ### Set Timestep for 120 FPS Source: https://github.com/dimforge/rapier/blob/master/_autodocs/configuration.md Example of setting the simulation timestep to achieve approximately 120 frames per second. ```rust let mut params = IntegrationParameters::default(); params.dt = 1.0 / 120.0; // 120 FPS ``` -------------------------------- ### Create a Dynamic Body and Sphere Collider Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/collider.md Demonstrates creating a dynamic rigid body and attaching a sphere collider to it. This is a common setup for dynamic physics objects. ```rust use rapier3d::prelude::*; let mut bodies = RigidBodySet::new(); let mut colliders = ColliderSet::new(); // Create a dynamic body let body = RigidBodyBuilder::dynamic() .translation(Vector::new(0.0, 10.0, 0.0)) .build(); let body_handle = bodies.insert(body); // Create a sphere collider and attach it let collider = ColliderBuilder::ball(0.5) // 0.5 unit radius .density(2.0) // Mass density .friction(0.7) .restitution(0.3); colliders.insert_with_parent(collider, body_handle, &mut bodies); ``` -------------------------------- ### Vehicle Suspension Setup Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/joints.md Connects a wheel to a chassis using a SpringJoint to simulate suspension. Requires defining anchors, rest distance, and stiffness. ```rust // Connect wheel to chassis with spring let spring = SpringJoint::new( point![1.0, 0.0, 0.0], // Anchor on chassis point![0.0, 0.0, 0.0], // Anchor on wheel 0.5, // Rest distance 500.0, // Stiffness ); impulse_joints.insert(chassis, wheel, spring.into(), true); ``` -------------------------------- ### PhysicsPipeline::new Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/physics_pipeline.md Creates a new instance of the PhysicsPipeline. This should be called once during the setup of your physics world. The pipeline can be reused across frames to improve memory efficiency by reusing pre-allocated buffers. ```APIDOC ## PhysicsPipeline::new ### Description Creates a new physics pipeline. Call once when setting up your physics world. The pipeline can be reused across frames for better memory efficiency (pre-allocated buffers are reused). ### Method `new()` ### Returns `Self` - A new PhysicsPipeline instance. ``` -------------------------------- ### Physics Pipeline API Reference Source: https://github.com/dimforge/rapier/blob/master/_autodocs/GENERATION_SUMMARY.txt Documentation for the PhysicsPipeline class, detailing IntegrationParameters, EventHandler interface, PhysicsHooks interface, and a complete simulation loop example. ```APIDOC ## Physics Pipeline API Reference ### Description This section documents the `PhysicsPipeline` class, which orchestrates the physics simulation. It provides detailed explanations of `IntegrationParameters`, the `EventHandler` interface for custom event handling, and the `PhysicsHooks` interface for custom physics logic. A complete simulation loop example is also included. ### Key Areas Covered - `PhysicsPipeline` class functionality - `IntegrationParameters` (all fields explained) - `EventHandler` interface - `PhysicsHooks` interface ### Examples A complete simulation loop example is provided. ``` -------------------------------- ### Collision Pipeline API Reference Source: https://github.com/dimforge/rapier/blob/master/_autodocs/GENERATION_SUMMARY.txt Documentation for the CollisionPipeline class, covering BroadPhaseBvh, NarrowPhase, ContactPair structure, BroadPhasePairEvent, and a complete collision detection example. ```APIDOC ## Collision Pipeline API Reference ### Description This section details the `CollisionPipeline` class, responsible for the collision detection process. It covers the `BroadPhaseBvh` for initial broad-phase detection, the `NarrowPhase` for precise collision detection, the `ContactPair` structure, and `BroadPhasePairEvent`. A complete collision detection example is also provided. ### Key Areas Covered - `CollisionPipeline` class functionality - `BroadPhaseBvh` (AABB detection) - `NarrowPhase` (precise detection) - `ContactPair` structure - `BroadPhasePairEvent` ### Examples A complete collision detection example is provided. ``` -------------------------------- ### Collider Configuration with Combine Rules Source: https://github.com/dimforge/rapier/blob/master/_autodocs/configuration.md Example of setting friction and restitution with their respective combine rules on a collider. Use Max for grippier objects and Average for general cases. ```rust let collider = ColliderBuilder::ball(0.5) .friction(0.5) .friction_combine_rule(CoefficientCombineRule::Max) .restitution(0.3) .restitution_combine_rule(CoefficientCombineRule::Average) .build(); ``` -------------------------------- ### Iterate over all RigidBodies to find the heaviest Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/rigid_body_set.md Use `iter()` to get an iterator over all bodies and their handles. This example finds the body with the maximum mass. ```rust let heaviest = bodies.iter() .max_by(|(_, b1), (_, b2)| { b1.mass().partial_cmp(&b2.mass()).unwrap() }); if let Some((handle, body)) = heaviest { println!("Heaviest body: {} kg", body.mass()); } ``` -------------------------------- ### Iterate over RigidBodies to wake up sleeping bodies Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/rigid_body_set.md Use `iter_mut()` to get a mutable iterator over bodies. This example wakes up any body that is currently sleeping. ```rust for (_, body) in bodies.iter_mut() { if body.is_sleeping() { body.wake_up(true); } } ``` -------------------------------- ### Query Pipeline API Reference Source: https://github.com/dimforge/rapier/blob/master/_autodocs/GENERATION_SUMMARY.txt Documentation for the QueryPipeline class, including raycasting, point queries, shape casting, AABB queries, QueryFilter, and complete query examples. ```APIDOC ## Query Pipeline API Reference ### Description This section documents the `QueryPipeline` class, which enables querying the physics world. It covers various query types including raycasting (`cast_ray`, `get_normal`, `find_all`), point queries (`point_intersection_test`), shape casting, and AABB queries. The `QueryFilter` for filtering query results is also detailed, along with complete query examples. ### Key Areas Covered - `QueryPipeline` class functionality - Raycasting methods - Point queries - Shape casting - AABB queries - `QueryFilter` and filtering options ### Examples Complete query examples are provided. ``` -------------------------------- ### Implementing Collision Event Handling Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/physics_pipeline.md Example implementation of the handle_collision_event method from the EventHandler trait. This code detects when colliders start or stop colliding and prints messages accordingly. ```rust impl EventHandler for MyEventHandler { fn handle_collision_event( &self, bodies: &RigidBodySet, colliders: &ColliderSet, event: &CollisionEvent, contact_pair: Option<&ContactPair>, ) { match event { CollisionEvent::Started(h1, h2, _) => { println!("Colliders {:?} and {:?} collided", h1, h2); } CollisionEvent::Stopped(_, _, _) => { println!("Collision ended"); } } } fn handle_contact_force_event(&self, _dt, _event, _bodies, _colliders) {} } ``` -------------------------------- ### Get and Set Rigid Body Position and Rotation Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/rigid_body.md Retrieve the current pose (position and rotation) of a rigid body or set its new pose. This example shows how to access and print the translation and rotation components. ```rust let pos = bodies[handle].position(); println!("Position: {:?}, Rotation: {:?}", pos.translation, pos.rotation); ``` -------------------------------- ### Set Up Physics Simulation Source: https://github.com/dimforge/rapier/blob/master/_autodocs/README.md Initializes the necessary components for running a physics simulation, including the pipeline, gravity, and event handlers. ```rust let mut physics_pipeline = PhysicsPipeline::new(); let gravity = Vector::new(0.0, -9.81, 0.0); let integration_params = IntegrationParameters::default(); let mut islands = IslandManager::new(); let mut broad_phase = BroadPhaseBvh::new(); let mut narrow_phase = NarrowPhase::new(); let mut impulse_joints = ImpulseJointSet::new(); let mut multibody_joints = MultibodyJointSet::new(); let physics_hooks = DefaultHooks; let event_handler = DefaultEventHandler; ``` -------------------------------- ### Build JavaScript Bindings and Documentation Source: https://github.com/dimforge/rapier/blob/master/CONTRIBUTING.md Build the JavaScript bindings, TypeScript definitions, and generate documentation for the 3D version of Rapier. This process may take several minutes. ```bash cd rapier3d; npm install; ./build_all.sh ``` -------------------------------- ### Customizing Integration Parameters Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/physics_pipeline.md Demonstrates how to create default integration parameters and then modify them for specific simulation needs, such as adjusting timestep duration and solver iterations. ```rust let mut params = IntegrationParameters::default(); params.dt = 1.0 / 120.0; // 120 FPS params.num_solver_iterations = 6; // More accurate ``` -------------------------------- ### Recommended Prelude Import Source: https://github.com/dimforge/rapier/blob/master/_autodocs/MODULE_REFERENCE.md This is the recommended way to import all necessary types for common use cases, providing a concise and convenient way to access Rapier's functionality. ```rust use rapier3d::prelude::*; ``` -------------------------------- ### Get Collider Access Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/collider_set.md Retrieves read-only or mutable access to a collider by its handle. ```APIDOC ## `ColliderSet::get()` and `ColliderSet::get_mut()` ### Description Provides read-only (`get`) or mutable (`get_mut`) access to a collider using its `ColliderHandle`. ### Parameters - **handle** (`ColliderHandle`) - Required - The unique identifier of the collider. ### Returns - `Option<&Collider>` for `get` - A reference to the collider if the handle is valid, otherwise `None`. - `Option<&mut Collider>` for `get_mut` - A mutable reference to the collider if the handle is valid, otherwise `None`. ### Example ```rust // Get mutable access and modify friction. if let Some(collider) = colliders.get_mut(col_handle) { collider.set_friction(0.8); } ``` ``` -------------------------------- ### Check if a Pile of Objects Settled Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/rigid_body.md Example showing how to check if an object has settled by verifying if it is sleeping. ```rust if bodies[handle].is_sleeping() { println!("Object at rest"); } ``` -------------------------------- ### Apply Forces and Impulses Source: https://github.com/dimforge/rapier/blob/master/_autodocs/README.md Shows how to apply forces, impulses, and set linear velocities for rigid bodies. ```rust // Apply continuous force bodies[handle].add_force(Vector::new(100.0, 0.0, 0.0), true); // Apply instant impulse bodies[handle].apply_impulse(Vector::new(0.0, 300.0, 0.0), true); // Set velocity directly bodies[handle].set_linvel(Vector::new(5.0, 0.0, 0.0), true); ``` -------------------------------- ### Vector and Point Construction Source: https://github.com/dimforge/rapier/blob/master/_autodocs/types.md Demonstrates how to create and access components of Vector and Point types using their constructors and macros. Includes common constants and operations. ```rust // Create vectors let v = Vector::new(1.0, 2.0, 3.0); let v = vector![1.0, 2.0, 3.0]; // With macro // Create points let p = Point::new(0.0, 1.0, 0.0); let p = point![0.0, 1.0, 0.0]; // With macro // Component access let x = v.x; let y = v.y; let z = v.z; let v_array = v.as_slice(); // [1.0, 2.0, 3.0] // Useful constants Vector::ZERO // (0, 0, 0) Vector::X // (1, 0, 0) Vector::Y // (0, 1, 0) Vector::Z // (0, 0, 1) Vector::new(x, y, z) // Operations v1 + v2 // Vector addition v1 - v2 // Vector subtraction v * scalar // Scalar multiplication v.length() // Magnitude v.normalize() // Unit vector v.dot(v2) // Dot product v.cross(v2) // Cross product (3D) ``` -------------------------------- ### RigidBodyBuilder Methods Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/rigid_body.md Methods for setting the initial state, velocity, damping, and other properties of a rigid body using the builder pattern. ```APIDOC ## RigidBodyBuilder Methods ### Description Methods for setting the initial state, velocity, damping, and other properties of a rigid body using the builder pattern. ### Methods Set initial position/rotation: - `translation(translation: Vector)`: Sets the initial translation of the rigid body. - `rotation(angle: AngVector)`: Sets the initial rotation of the rigid body. - `pose(pos: Pose)`: Sets the initial pose (position and rotation) of the rigid body. Set initial velocity: - `linvel(linvel: Vector)`: Sets the initial linear velocity of the rigid body. - `angvel(angvel: AngVector)`: Sets the initial angular velocity of the rigid body. Set damping (velocity slowdown): - `linear_damping(factor: Real)`: Sets the linear damping factor. - `angular_damping(factor: Real)`: Sets the angular damping factor. Set gravity multiplier: - `gravity_scale(scale: Real)`: Sets the gravity scale multiplier (default 1.0). Set collision dominance: - `dominance_group(group: i8)`: Sets the collision dominance group (higher group wins contacts). Add extra mass: - `additional_mass(mass: Real)`: Adds extra mass beyond collider-computed mass. - `additional_mass_properties(props: MassProperties)`: Adds extra mass properties beyond collider-computed mass. Lock specific movement directions: - `locked_axes(locked: LockedAxes)`: Locks specific axes of movement. - `lock_translations()`: Locks all translation axes. - `lock_rotations()`: Locks all rotation axes. - `enabled_translations(x: bool, y: bool, z: bool)`: Enables or disables translations along specific axes. - `enabled_rotations(x: bool, y: bool, z: bool)`: Enables or disables rotations around specific axes. Allow body to sleep: - `can_sleep(can_sleep: bool)`: Allows the body to sleep (default true). Enable Continuous Collision Detection: - `ccd_enabled(enabled: bool)`: Enables Continuous Collision Detection. - `soft_ccd_prediction(distance: Real)`: Sets the distance for soft CCD prediction. Attach user data: - `user_data(data: u128)`: Attaches 128-bit user data. Run more constraint solver iterations: - `additional_solver_iterations(iterations: usize)`: Increases the number of constraint solver iterations for accuracy. Construct the rigid body: - `build()`: Constructs and returns the `RigidBody`. ``` -------------------------------- ### Get Attached Colliders Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/rigid_body.md Retrieves a slice of `ColliderHandle`s, representing all colliders currently attached to this rigid body. ```rust pub fn colliders(&self) -> &[ColliderHandle] ``` -------------------------------- ### Set ERP for More Aggressive Correction Source: https://github.com/dimforge/rapier/blob/master/_autodocs/configuration.md Example of increasing the ERP value to make contact corrections slightly more aggressive. ```rust params.erp = 0.2; // Slightly more aggressive ``` -------------------------------- ### Fixed Timestep for Deterministic Physics Source: https://github.com/dimforge/rapier/blob/master/_autodocs/EXAMPLES.md Demonstrates how to achieve deterministic physics simulation by accumulating delta time and stepping the physics pipeline with a fixed timestep. This ensures consistent results across different frame rates. ```rust // Use fixed timestep for determinism let mut dt_accumulator = 0.0; let fixed_dt = 1.0 / 60.0; for frame in 0..1000 { dt_accumulator += actual_delta_time; while dt_accumulator >= fixed_dt { physics_pipeline.step(/* ... */); dt_accumulator -= fixed_dt; } } ``` -------------------------------- ### Get RigidBody Mass Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/rigid_body.md Retrieves the total mass of the rigid body in kilograms. For fixed bodies, this returns 0.0. ```rust pub fn mass(&self) -> Real ``` -------------------------------- ### Rapier Integration Parameters for Responsiveness Source: https://github.com/dimforge/rapier/blob/master/_autodocs/configuration.md Tune integration parameters for better responsiveness by using a small timestep and a normal number of solver iterations. ```rust let mut params = IntegrationParameters::default(); params.dt = 1.0 / 120.0; params.num_solver_iterations = 4; ``` -------------------------------- ### Enable Standard 3D Physics in Cargo.toml Source: https://github.com/dimforge/rapier/blob/master/_autodocs/README.md Include the rapier3d crate with standard 3D physics, 32-bit floats, and the standard library features enabled in your Cargo.toml. ```toml # Standard 3D physics rapier3d = { version = "0.32", features = ["dim3", "f32", "std"] } ``` -------------------------------- ### Create a Dynamic Rigid Body Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/rigid_body.md Demonstrates how to create a dynamic rigid body with initial translation and linear velocity using RigidBodyBuilder. You can also adjust its gravity scale after creation. ```rust use rapier3d::prelude::*; let mut bodies = RigidBodySet::new(); // Create a falling box let body = RigidBodyBuilder::dynamic() .translation(Vector::new(0.0, 10.0, 0.0)) .linvel(Vector::new(1.0, 0.0, 0.0)) .build(); let handle = bodies.insert(body); bodies[handle].set_gravity_scale(1.5, true); // Make it fall faster ``` -------------------------------- ### Custom Filter Example Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/query_pipeline.md Demonstrates using a custom predicate to filter for colliders with specific user data during an intersection query. ```rust let filter = QueryFilter::default() .predicate(&|handle, collider| { collider.user_data == ENEMY_COLLIDER_ID }); let mut enemies = Vec::new(); query_pipeline.intersections_with_point( &colliders, Point::from(center), filter, |handle| { enemies.push(handle); true }, ); ``` -------------------------------- ### Create Rigid Body Types Source: https://github.com/dimforge/rapier/blob/master/_autodocs/README.md Demonstrates the creation of different types of rigid bodies: dynamic, static, and kinematic. ```rust // Dynamic body let body = RigidBodyBuilder::dynamic() .translation(Vector::new(0.0, 5.0, 0.0)) .build(); // Static wall let wall = RigidBodyBuilder::fixed() .translation(Vector::new(10.0, 0.0, 0.0)) .build(); // Moving platform let platform = RigidBodyBuilder::kinematic_velocity_based() .build(); ``` -------------------------------- ### ImpulseJointSet Access and Removal Source: https://github.com/dimforge/rapier/blob/master/_autodocs/api-reference/joints.md Provides methods to get mutable or immutable references to joints by handle, and to remove joints from the set. ```rust pub fn get(&self, handle: ImpulseJointHandle) -> Option<&ImpulseJoint> pub fn get_mut(&mut self, handle: ImpulseJointHandle) -> Option<&mut ImpulseJoint> pub fn remove(&mut self, handle: ImpulseJointHandle, wake_up: bool) -> Option ``` -------------------------------- ### Rapier Integration Parameters for Realism Source: https://github.com/dimforge/rapier/blob/master/_autodocs/configuration.md Configure integration parameters to achieve more realistic physics behavior with a moderate timestep, sufficient iterations, and specific damping/ERP values. ```rust let mut params = IntegrationParameters::default(); params.dt = 1.0 / 60.0; params.num_solver_iterations = 6; params.damping_ratio = 0.1; params.erp = 0.2; ```