use crate::math::{Real, Vector};
use crate::shape::SupportMap;
#[cfg(feature = "alloc")]
use either::Either;
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]
#[cfg_attr(feature = "encase", derive(encase::ShaderType))]
#[cfg_attr(
feature = "rkyv",
derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)
)]
#[derive(PartialEq, Debug, Copy, Clone)]
#[repr(C)]
pub struct Cylinder {
pub half_height: Real,
pub radius: Real,
}
impl Cylinder {
pub fn new(half_height: Real, radius: Real) -> Cylinder {
assert!(half_height.is_sign_positive() && radius.is_sign_positive());
Cylinder {
half_height,
radius,
}
}
#[cfg(feature = "alloc")]
#[inline]
pub fn scaled(
self,
scale: Vector,
nsubdivs: u32,
) -> Option<Either<Self, super::ConvexPolyhedron>> {
if scale.x != scale.z {
let (mut vtx, idx) = self.to_trimesh(nsubdivs);
vtx.iter_mut().for_each(|pt| *pt *= scale);
Some(Either::Right(super::ConvexPolyhedron::from_convex_mesh(
vtx, &idx,
)?))
} else {
Some(Either::Left(Self::new(
self.half_height * scale.y,
self.radius * scale.x,
)))
}
}
}
impl SupportMap for Cylinder {
fn local_support_point(&self, dir: Vector) -> Vector {
let mut vres = dir;
vres[1] = 0.0;
vres = vres.normalize_or_zero() * self.radius;
vres[1] = self.half_height.copysign(dir[1]);
vres
}
}