parry3d/shape/cylinder.rs
1//! Support mapping based Cylinder shape.
2
3use crate::math::{Point, Real, Vector};
4use crate::shape::SupportMap;
5use na;
6use num::Zero;
7
8#[cfg(feature = "alloc")]
9use either::Either;
10
11#[cfg(feature = "rkyv")]
12use rkyv::{bytecheck, CheckBytes};
13
14/// A 3D cylinder shape with axis aligned along the Y axis.
15///
16/// A cylinder is a shape with circular cross-sections perpendicular to its axis.
17/// In Parry, cylinders are always aligned with the Y axis in their local coordinate
18/// system and centered at the origin.
19///
20/// # Structure
21///
22/// - **Axis**: Always aligned with Y axis (up/down)
23/// - **half_height**: Half the length along the Y axis
24/// - **radius**: The radius of the circular cross-section
25/// - **Height**: Total height = `2 * half_height`
26///
27/// # Properties
28///
29/// - **3D only**: Only available with the `dim3` feature
30/// - **Convex**: Yes, cylinders are convex shapes
31/// - **Flat caps**: The top and bottom are flat circles (not rounded)
32/// - **Sharp edges**: The rim where cap meets side is a sharp edge
33///
34/// # vs Capsule
35///
36/// If you need rounded ends instead of flat caps, use [`Capsule`](super::Capsule):
37/// - **Cylinder**: Flat circular caps, sharp edges at rims
38/// - **Capsule**: Hemispherical caps, completely smooth (no edges)
39/// - **Capsule**: Better for characters and rolling objects
40/// - **Cylinder**: Better for columns, cans, pipes
41///
42/// # Use Cases
43///
44/// - Pillars and columns
45/// - Cans and barrels
46/// - Wheels and disks
47/// - Pipes and tubes
48/// - Any object with flat circular ends
49///
50/// # Example
51///
52/// ```rust
53/// # #[cfg(all(feature = "dim3", feature = "f32"))] {
54/// use parry3d::shape::Cylinder;
55///
56/// // Create a cylinder: radius 2.0, total height 10.0
57/// let cylinder = Cylinder::new(5.0, 2.0);
58///
59/// assert_eq!(cylinder.half_height, 5.0);
60/// assert_eq!(cylinder.radius, 2.0);
61///
62/// // Total height is 2 * half_height
63/// let total_height = cylinder.half_height * 2.0;
64/// assert_eq!(total_height, 10.0);
65/// # }
66/// ```
67#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
68#[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]
69#[cfg_attr(
70 feature = "rkyv",
71 derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize, CheckBytes),
72 archive(as = "Self")
73)]
74#[derive(PartialEq, Debug, Copy, Clone)]
75#[repr(C)]
76pub struct Cylinder {
77 /// Half the length of the cylinder along the Y axis.
78 ///
79 /// The cylinder extends from `-half_height` to `+half_height` along Y.
80 /// Total height = `2 * half_height`. Must be positive.
81 pub half_height: Real,
82
83 /// The radius of the circular cross-section.
84 ///
85 /// All points on the cylindrical surface are at this distance from the Y axis.
86 /// Must be positive.
87 pub radius: Real,
88}
89
90impl Cylinder {
91 /// Creates a new cylinder aligned with the Y axis.
92 ///
93 /// # Arguments
94 ///
95 /// * `half_height` - Half the total height along the Y axis
96 /// * `radius` - The radius of the circular cross-section
97 ///
98 /// # Panics
99 ///
100 /// Panics if `half_height` or `radius` is not positive.
101 ///
102 /// # Example
103 ///
104 /// ```
105 /// # #[cfg(all(feature = "dim3", feature = "f32"))] {
106 /// use parry3d::shape::Cylinder;
107 ///
108 /// // Create a cylinder with radius 3.0 and height 8.0
109 /// let cylinder = Cylinder::new(4.0, 3.0);
110 ///
111 /// assert_eq!(cylinder.half_height, 4.0);
112 /// assert_eq!(cylinder.radius, 3.0);
113 ///
114 /// // The cylinder:
115 /// // - Extends from y = -4.0 to y = 4.0 (total height 8.0)
116 /// // - Has circular cross-section with radius 3.0 in the XZ plane
117 /// # }
118 /// ```
119 pub fn new(half_height: Real, radius: Real) -> Cylinder {
120 assert!(half_height.is_sign_positive() && radius.is_sign_positive());
121
122 Cylinder {
123 half_height,
124 radius,
125 }
126 }
127
128 /// Computes a scaled version of this cylinder.
129 ///
130 /// Scaling a cylinder can produce different results depending on the scale factors:
131 ///
132 /// - **Uniform scaling** (all axes equal): Produces another cylinder
133 /// - **Y different from X/Z**: Produces another cylinder (if X == Z)
134 /// - **Non-uniform X/Z**: Produces an elliptical cylinder approximated as a convex mesh
135 ///
136 /// # Arguments
137 ///
138 /// * `scale` - Scaling factors for X, Y, Z axes
139 /// * `nsubdivs` - Number of subdivisions for mesh approximation (if needed)
140 ///
141 /// # Returns
142 ///
143 /// * `Some(Either::Left(Cylinder))` - If X and Z scales are equal
144 /// * `Some(Either::Right(ConvexPolyhedron))` - If X and Z scales differ (elliptical)
145 /// * `None` - If mesh approximation failed (e.g., zero scale on an axis)
146 ///
147 /// # Example
148 ///
149 /// ```
150 /// # #[cfg(all(feature = "dim3", feature = "f32", feature = "alloc"))] {
151 /// use parry3d::shape::Cylinder;
152 /// use nalgebra::Vector3;
153 /// use either::Either;
154 ///
155 /// let cylinder = Cylinder::new(2.0, 1.0);
156 ///
157 /// // Uniform scaling: produces a larger cylinder
158 /// let scale1 = Vector3::new(2.0, 2.0, 2.0);
159 /// if let Some(Either::Left(scaled)) = cylinder.scaled(&scale1, 20) {
160 /// assert_eq!(scaled.radius, 2.0); // 1.0 * 2.0
161 /// assert_eq!(scaled.half_height, 4.0); // 2.0 * 2.0
162 /// }
163 ///
164 /// // Different Y scale: still a cylinder
165 /// let scale2 = Vector3::new(1.5, 3.0, 1.5);
166 /// if let Some(Either::Left(scaled)) = cylinder.scaled(&scale2, 20) {
167 /// assert_eq!(scaled.radius, 1.5); // 1.0 * 1.5
168 /// assert_eq!(scaled.half_height, 6.0); // 2.0 * 3.0
169 /// }
170 ///
171 /// // Non-uniform X/Z: produces elliptical cylinder (mesh approximation)
172 /// let scale3 = Vector3::new(2.0, 1.0, 1.0);
173 /// if let Some(Either::Right(polyhedron)) = cylinder.scaled(&scale3, 20) {
174 /// // Result is a convex mesh approximating an elliptical cylinder
175 /// assert!(polyhedron.points().len() > 0);
176 /// }
177 /// # }
178 /// ```
179 #[cfg(feature = "alloc")]
180 #[inline]
181 pub fn scaled(
182 self,
183 scale: &Vector<Real>,
184 nsubdivs: u32,
185 ) -> Option<Either<Self, super::ConvexPolyhedron>> {
186 if scale.x != scale.z {
187 // The scaled shape isn’t a cylinder.
188 let (mut vtx, idx) = self.to_trimesh(nsubdivs);
189 vtx.iter_mut()
190 .for_each(|pt| pt.coords = pt.coords.component_mul(scale));
191 Some(Either::Right(super::ConvexPolyhedron::from_convex_mesh(
192 vtx, &idx,
193 )?))
194 } else {
195 Some(Either::Left(Self::new(
196 self.half_height * scale.y,
197 self.radius * scale.x,
198 )))
199 }
200 }
201}
202
203impl SupportMap for Cylinder {
204 fn local_support_point(&self, dir: &Vector<Real>) -> Point<Real> {
205 let mut vres = *dir;
206
207 vres[1] = 0.0;
208
209 if vres.normalize_mut().is_zero() {
210 vres = na::zero()
211 } else {
212 vres *= self.radius;
213 }
214
215 vres[1] = self.half_height.copysign(dir[1]);
216
217 Point::from(vres)
218 }
219}