use crcbl_ecs::Entity;
use super::{BodyId, PhysicsSystem};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ContactPairError {
UnknownBody(Entity),
SameBody,
}
impl core::fmt::Display for ContactPairError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::UnknownBody(entity) => write!(f, "{entity:?} is not registered"),
Self::SameBody => f.write_str("a contact pair is two different bodies"),
}
}
}
impl std::error::Error for ContactPairError {}
impl PhysicsSystem {
pub fn ignore_contacts(&mut self, a: Entity, b: Entity) -> Result<bool, ContactPairError> {
let (a, b) = self.contact_pair(a, b)?;
self.wake(a);
self.wake(b);
let pipeline = self.contacts.as_mut().expect("checked by contact_pair");
let added = pipeline.ignored.insert(a, b);
if added {
pipeline.destroy_contacts_between(a, b);
}
Ok(added)
}
pub fn restore_contacts(&mut self, a: Entity, b: Entity) -> Result<bool, ContactPairError> {
let (a, b) = self.contact_pair(a, b)?;
self.wake(a);
self.wake(b);
let removed = self
.contacts
.as_mut()
.expect("checked by contact_pair")
.ignored
.remove(a, b);
if removed {
self.let_collide(a, b);
}
Ok(removed)
}
#[must_use]
pub fn ignores_contacts(&self, a: Entity, b: Entity) -> bool {
let (Some(pipeline), Some(&a), Some(&b)) = (
self.contacts.as_ref(),
self.entity_to_body.get(&a),
self.entity_to_body.get(&b),
) else {
return false;
};
pipeline.ignored.contains(a, b)
}
fn contact_pair(&self, a: Entity, b: Entity) -> Result<(BodyId, BodyId), ContactPairError> {
assert!(
self.contacts.is_some(),
"ignored pairs are a contact-pipeline rule: build the system with_contacts"
);
let id = |entity: Entity| {
self.entity_to_body
.get(&entity)
.copied()
.ok_or(ContactPairError::UnknownBody(entity))
};
let (a, b) = (id(a)?, id(b)?);
if a == b {
return Err(ContactPairError::SameBody);
}
Ok((a, b))
}
}