Skip to content

Commit

Permalink
Add log crate logging
Browse files Browse the repository at this point in the history
  • Loading branch information
distransient committed Dec 19, 2018
1 parent e328b68 commit ddde4b8
Show file tree
Hide file tree
Showing 8 changed files with 95 additions and 52 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ num-traits = "0.2"
derive-new = "0.5.6"
derive_builder = "0.7.0"
serde = { version = "1.0", features = ["derive"] }
log = "*"

[dependencies.amethyst]
git = "https://github.com/amethyst/amethyst"
Expand Down
9 changes: 4 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ both amethyst and plain specs interfaces to be exposed, also behind configuratio
I'll update this as I go along.

1.
- `"sync_force_generators_to_physics_system"` - Synchronize changes to force generators to physics world
- `"sync_bodies_to_physics_system"` - Synchronize changes to dynamics bodies to physics world
- `"sync_gravity_to_physics_system"` - Update gravity of physics world from resource
1. `"physics_stepper_system"` - Step physics world simulation
Expand All @@ -25,15 +24,15 @@ Full *TODO* sheet can be found in [this nphysics issue](https://github.com/rusts
Ongoing work:

- [x] RigidBody Components
- [ ] Force Generator Components
- [x] External force property
- [x] `log` based logging
- [ ] Collider Components
- [ ] Proximity & Curve-based external force utility
- [ ] Proximity and Contact EventChannels
- [ ] Handling Body Activation & Sleeping

Investigating:

- [ ] Multibody-based Component Joints
- [ ] Constraint-based Joints
- [ ] Kinematics
- [ ] Body Activation & Sleeping.

Also, implement logging using the log crate.
6 changes: 3 additions & 3 deletions src/bodies.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use nphysics3d::object::BodyHandle;
use std::collections::HashMap;

/// Physics body component for describing (currently) rigid body dynamics.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub enum DynamicBody {
RigidBody(RigidPhysicsBody),
Multibody(PhysicsMultibody),
Expand Down Expand Up @@ -57,7 +57,7 @@ impl Component for DynamicBody {
/// Rigid physics body, for use in `PhysicsBody` Component.
/// Currently only the velocity is read and updated at runtime.
/// The properties of mass are only written at physics body creation time.
#[derive(Serialize, Deserialize, Clone, Debug, new)]
#[derive(Serialize, Deserialize, Clone, Copy, Debug, new)]
pub struct RigidPhysicsBody {
#[serde(skip)]
#[new(default)]
Expand All @@ -73,7 +73,7 @@ pub struct RigidPhysicsBody {
}

/// Multipart physics body, for use in `PhysicsBody` Component. Not implemented yet.
#[derive(Serialize, Deserialize, Clone, Debug)]
#[derive(Serialize, Deserialize, Clone, Copy, Debug)]
pub struct PhysicsMultibody {
#[serde(skip)]
pub handle: Option<BodyHandle>,
Expand Down
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ extern crate derive_new;
#[macro_use]
extern crate serde;

#[macro_use]
extern crate log;

pub mod bodies;
pub mod colliders;
pub mod systems;
Expand Down
11 changes: 8 additions & 3 deletions src/systems/physics_stepper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,15 @@ impl PhysicsStepperSystem {
impl<'a> System<'a> for PhysicsStepperSystem {
type SystemData = (WriteExpect<'a, PhysicsWorld>, Read<'a, Time>);

// Simulate world using the current time frame
// TODO: Bound timestep deltas
fn run(&mut self, (mut physical_world, time): Self::SystemData) {
// Simulate world using the current time frame
// TODO: Bound timestep deltas
physical_world.set_timestep(time.delta_seconds());
let delta = time.delta_seconds();

trace!("Setting timestep with delta: {}", delta);
physical_world.set_timestep(delta);

trace!("Stepping physical world simulation.");
physical_world.step();
}
}
28 changes: 19 additions & 9 deletions src/systems/sync_bodies_from_physics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ impl<'a> System<'a> for SyncBodiesFromPhysicsSystem {
colliders,
) = data;

trace!("Synchronizing bodies from physical world.");

// Apply the updated values of the simulated world to our Components
#[allow(unused_mut)]
for (mut global_transform, mut body, local_transform) in (
Expand All @@ -59,6 +61,7 @@ impl<'a> System<'a> for SyncBodiesFromPhysicsSystem {
let updated_body = physical_world.body(body.handle().unwrap());

if updated_body.is_ground() || !updated_body.is_active() || updated_body.is_static() {
trace!("Skipping synchronizing data from non-dynamic body: {:?}", updated_body.handle());
continue;
}

Expand All @@ -67,11 +70,9 @@ impl<'a> System<'a> for SyncBodiesFromPhysicsSystem {
DynamicBody::RigidBody(ref mut rigid_body),
Body::RigidBody(ref updated_rigid_body),
) => {
println!(
"super power: change mehhh! new pos: {:?}",
updated_rigid_body.position()
);
trace!("Synchronizing RigidBody from handle: {:?}", updated_rigid_body.handle());

trace!("Synchronized RigidBody's updated position: {}", updated_rigid_body.position());
// TODO: Might get rid of the scale!!!
global_transform.0 = updated_rigid_body
.position()
Expand All @@ -82,25 +83,32 @@ impl<'a> System<'a> for SyncBodiesFromPhysicsSystem {
.unwrap_or(&Vector3::new(1.0, 1.0, 1.0)),
);

trace!("Synchronized RigidBody's updated velocity: {:?}", updated_rigid_body.velocity());
rigid_body.velocity = *updated_rigid_body.velocity();

trace!("Synchronized RigidBody's updated inertia: {:?}", updated_rigid_body.inertia());
let inertia = updated_rigid_body.inertia();
rigid_body.mass = inertia.linear;
rigid_body.angular_mass = inertia.angular;

trace!("Synchronized RigidBody's updated center of mass: {}", updated_rigid_body.center_of_mass());
rigid_body.center_of_mass = updated_rigid_body.center_of_mass();
}
(DynamicBody::Multibody(_multibody), Body::Multibody(_updated_multibody)) => {
// match updated_multibody.links().next() {
// Some(link) => link.position(),
// None => continue,
// };
error!("Multibody found; not implemented currently, sorry!")
}
_ => println!("Unexpected dynamics body pair."),
// TODO: Add data to unexpected pair message. Not straightforward.
_ => error!("Unexpected dynamics body pair!"),
};
}

trace!("Iterating collision events.");

let collision_world = physical_world.collision_world();

contact_events.iter_write(collision_world.contact_events().iter().cloned().map(|ev| {
trace!("Emitting contact event: {}", ev);

let (handle1, handle2) = match ev {
ContactEvent::Started(h1, h2) => (h1, h2),
ContactEvent::Stopped(h1, h2) => (h1, h2),
Expand All @@ -119,6 +127,8 @@ impl<'a> System<'a> for SyncBodiesFromPhysicsSystem {
.iter()
.cloned()
.map(|ev| {
trace!("Emitting proximity event: {}", ev);

let e1 = entity_from_handle(&entities, &colliders, &ev.collider1)
.expect("Failed to find entity for collider.");
let e2 = entity_from_handle(&entities, &colliders, &ev.collider2)
Expand Down
54 changes: 35 additions & 19 deletions src/systems/sync_bodies_to_physics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use amethyst::ecs::{
};
use core::ops::Deref;
use nalgebra::try_convert;
use nphysics3d::math::Inertia;
use nphysics3d::math::{Inertia, Force, Isometry};

#[derive(Default)]
pub struct SyncBodiesToPhysicsSystem {
Expand Down Expand Up @@ -39,6 +39,7 @@ impl<'a> System<'a> for SyncBodiesToPhysicsSystem {
let mut modified_physics_bodies = BitSet::new();

// Get change flag events for transforms, removing deleted ones from the physics world.
trace!("Iterating transform storage events.");
iterate_events(
&transforms,
self.transforms_reader_id.as_mut().unwrap(),
Expand All @@ -50,6 +51,7 @@ impl<'a> System<'a> for SyncBodiesToPhysicsSystem {
);

// Get change flag events for physics bodies, removing deleted ones from the physics world.
trace!("Iterating physics body storage events.");
iterate_events(
&physics_bodies,
self.physics_bodies_reader_id.as_mut().unwrap(),
Expand All @@ -74,16 +76,16 @@ impl<'a> System<'a> for SyncBodiesToPhysicsSystem {
.join()
{
if inserted_transforms.contains(id) || inserted_physics_bodies.contains(id) {
println!("Detected inserted dynamics body with id {:?}", id);
trace!("Detected inserted dynamics body with id {}", id);

match body {
DynamicBody::RigidBody(ref mut rigid_body) => {
// Just inserted. Remove old one and insert new.
if rigid_body.handle.is_some()
&& physical_world
.rigid_body(rigid_body.handle.unwrap())
.is_some()
{
physical_world.remove_bodies(&[rigid_body.handle.unwrap()]);
if let Some(handle) = rigid_body.handle {
if physical_world.rigid_body(handle).is_some() {
trace!("Removing body marked as inserted that already exists with handle: {:?}", handle);
physical_world.remove_bodies(&[handle]);
}
}

rigid_body.handle = Some(physical_world.add_rigid_body(
Expand All @@ -92,33 +94,45 @@ impl<'a> System<'a> for SyncBodiesToPhysicsSystem {
rigid_body.center_of_mass,
));

trace!("Inserted rigid body to world with values: {:?}", rigid_body);

let physical_body = physical_world
.rigid_body_mut(rigid_body.handle.unwrap())
.unwrap();

physical_body.set_velocity(rigid_body.velocity);
physical_body.apply_force(&rigid_body.external_forces);
rigid_body.external_forces = Force::<f32>::zero();

trace!("Velocity and external forces applied, external forces reset to zero, for body with handle: {:?}", rigid_body.handle);
}
DynamicBody::Multibody(_) => {
// TODO
error!("Multibody found; not implemented currently, sorry!")
}
}
} else if modified_transforms.contains(id) || modified_physics_bodies.contains(id) {
println!("Detected changed dynamics body with id {:?}", id);
trace!("Detected changed dynamics body with id {}", id);
match body {
DynamicBody::RigidBody(ref mut rigid_body) => {
let physical_body = physical_world
.rigid_body_mut(rigid_body.handle.unwrap())
.unwrap();

physical_body.set_position(try_convert(transform.0).unwrap());
physical_body.set_velocity(rigid_body.velocity);
physical_body.apply_force(&rigid_body.external_forces);
match physical_world.rigid_body_mut(rigid_body.handle.unwrap()) {
Some(physical_body) => {
let position: Isometry<f32> = try_convert(transform.0).unwrap();
trace!("Updating rigid body in physics world with isometry: {}", position);
physical_body.set_position(position);
physical_body.set_velocity(rigid_body.velocity);
physical_body.apply_force(&rigid_body.external_forces);

// if you changed the mass properties at all... too bad!
},
None => {

// if you changed the mass properties at all... too bad!
}
}
}
DynamicBody::Multibody(_) => {
// TODO
error!("Multibody found; not implemented currently, sorry!")
}
}
}
Expand Down Expand Up @@ -165,15 +179,17 @@ fn iterate_events<'a, T, D, S>(
Some(body) => {
match body.handle() {
Some(handle) => {
trace!("Removing body with id: {}", id);

world.remove_bodies(&[handle]);
}
None => {
// TODO: Log missing handle
error!("Missing handle in body: {}", id);
}
};
}
None => {
// TODO: Log missing body
error!("Missing body with id: {}", id);
}
};
}
Expand Down
35 changes: 22 additions & 13 deletions src/systems/sync_colliders_to_physics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,19 +49,26 @@ impl<'a> System<'a> for SyncCollidersToPhysicsSystem {
.join()
{
if inserted_colliders.contains(id) {
println!("Detected inserted collider with id {:?}", id);
trace!("Detected inserted collider with id {}", id);

// Just inserted. Remove old one and insert new.
if collider.handle.is_some()
&& physical_world.collider(collider.handle.unwrap()).is_some()
{
physical_world.remove_colliders(&[collider.handle.unwrap()]);
if let Some(handle) = collider.handle {
if physical_world.collider(handle).is_some() {
trace!("Removing collider marked as inserted that already exists with handle: {:?}", handle);

physical_world.remove_colliders(&[handle]);
}
}

let parent = if let Some(rb) = rigid_bodies.get(entity) {
trace!("Attaching inserted collider to rigid body: {}", entity);

rb.handle().expect(
"You should normally have a body handle at this point. This is a bug.",
)
} else {
trace!("Attaching inserted collider to ground.");

BodyHandle::ground()
};

Expand All @@ -73,21 +80,21 @@ impl<'a> System<'a> for SyncCollidersToPhysicsSystem {
collider.physics_material.clone(),
));

trace!("Inserted collider to world with values: {}", collider);

let prediction = physical_world.prediction();
let angular_prediction = physical_world.angular_prediction();

let collision_world = physical_world.collision_world_mut();
let collider_handle = collision_world
.collision_object(collider.handle.unwrap())
.unwrap()
.handle()
.clone();
collision_world.set_collision_group(collider_handle, collider.collision_group);

let collider_object = collision_world
.collision_object_mut(collider.handle.unwrap())
.unwrap();

let collider_handle = collider_object.handle().clone();

collision_world.set_collision_group(collider_handle, collider.collision_group);

collider_object.set_query_type(collider.query_type.to_geometric_query_type(
collider.margin,
prediction,
Expand Down Expand Up @@ -163,15 +170,17 @@ fn iterate_events<'a, T, D, S>(
Some(collider) => {
match collider.handle {
Some(handle) => {
trace!("Removing collider with id: {}", id);

world.remove_colliders(&[handle]);
}
None => {
// TODO: Log missing handle
error!("Missing handle in collider: {}", id);
}
};
}
None => {
// TODO: Log missing body
error!("Missing collider with id: {}", id);
}
};
}
Expand Down

0 comments on commit ddde4b8

Please sign in to comment.