Struct ConvexPolygon

Source
pub struct ConvexPolygon { /* private fields */ }
Expand description

A 2D convex polygon.

A convex polygon is a closed 2D shape where all interior angles are less than 180 degrees, and any line segment drawn between two points inside the polygon stays entirely within the polygon. Common examples include triangles, rectangles, and regular polygons like hexagons.

§What is a convex polygon?

In 2D space, a polygon is convex if:

  • Every interior angle is less than or equal to 180 degrees
  • The line segment between any two points inside the polygon lies entirely inside the polygon
  • All vertices “bulge outward” - there are no indentations or concave areas

Examples of convex polygons: triangle, square, regular pentagon, regular hexagon Examples of non-convex (concave) polygons: star shapes, L-shapes, crescents

§Use cases

Convex polygons are widely used in:

  • Game development: Character hitboxes, platform boundaries, simple building shapes
  • Physics simulations: Rigid body collision detection (more efficient than arbitrary polygons)
  • Robotics: Simplified environment representations, obstacle boundaries
  • Computer graphics: Fast rendering primitives, clipping regions
  • Computational geometry: As building blocks for more complex operations

§Representation

This structure stores:

  • Points: The vertices of the polygon in counter-clockwise order
  • Normals: Unit vectors perpendicular to each edge, pointing outward

The normals are pre-computed for efficient collision detection algorithms.

§Example: Creating a simple triangle

use parry2d::shape::ConvexPolygon;
use nalgebra::Point2;

// Create a triangle from three vertices (counter-clockwise order)
let vertices = vec![
    Point2::origin(),    // bottom-left
    Point2::new(2.0, 0.0),    // bottom-right
    Point2::new(1.0, 2.0),    // top
];

let triangle = ConvexPolygon::from_convex_polyline(vertices)
    .expect("Failed to create triangle");

// The polygon has 3 vertices
assert_eq!(triangle.points().len(), 3);
// and 3 edge normals (one per edge)
assert_eq!(triangle.normals().len(), 3);

Implementations§

Source§

impl ConvexPolygon

Source

pub fn aabb(&self, pos: &Isometry<f32>) -> Aabb

Computes the world-space Aabb of this convex polygon, transformed by pos.

Source

pub fn local_aabb(&self) -> Aabb

Computes the local-space Aabb of this convex polygon.

Source§

impl ConvexPolygon

Source

pub fn bounding_sphere(&self, pos: &Isometry<f32>) -> BoundingSphere

Computes the world-space bounding sphere of this convex polygon, transformed by pos.

Source

pub fn local_bounding_sphere(&self) -> BoundingSphere

Computes the local-space bounding sphere of this convex polygon.

Source§

impl ConvexPolygon

Source

pub fn from_convex_hull(points: &[Point<f32>]) -> Option<Self>

Creates a new 2D convex polygon from an arbitrary set of points by computing their convex hull.

This is the most flexible constructor - it automatically computes the convex hull of the given points, which is the smallest convex polygon that contains all the input points. Think of it as wrapping a rubber band around the points.

Use this when:

  • You have an arbitrary collection of points and want the convex boundary
  • You’re not sure if your points form a convex shape
  • You want to simplify a point cloud to its convex outline
§Returns
  • Some(ConvexPolygon) if successful
  • None if the convex hull computation failed (e.g., all points are collinear or coincident)
§Example: Creating a convex polygon from arbitrary points
use parry2d::shape::ConvexPolygon;
use nalgebra::Point2;

// Some arbitrary points (including one inside the convex hull)
let points = vec![
    Point2::origin(),
    Point2::new(4.0, 0.0),
    Point2::new(2.0, 3.0),
    Point2::new(2.0, 1.0),  // This point is inside the triangle
];

let polygon = ConvexPolygon::from_convex_hull(&points)
    .expect("Failed to create convex hull");

// The convex hull only has 3 vertices (the interior point was excluded)
assert_eq!(polygon.points().len(), 3);
§Example: Simplifying a point cloud
use parry2d::shape::ConvexPolygon;
use nalgebra::Point2;

// A cloud of points that roughly forms a circle
let mut points = Vec::new();
for i in 0..20 {
    let angle = (i as f32) * std::f32::consts::TAU / 20.0;
    points.push(Point2::new(angle.cos(), angle.sin()));
}
// Add some interior points
points.push(Point2::origin());
points.push(Point2::new(0.5, 0.5));

let polygon = ConvexPolygon::from_convex_hull(&points)
    .expect("Failed to create convex hull");

// The convex hull has 20 vertices (the boundary points)
assert_eq!(polygon.points().len(), 20);
Source

pub fn from_convex_polyline(points: Vec<Point<f32>>) -> Option<Self>

Creates a new 2D convex polygon from vertices that already form a convex shape.

This constructor is more efficient than from_convex_hull because it assumes the input points already form a convex polygon in counter-clockwise order, and it doesn’t compute the convex hull. The convexity is not verified - if you pass non-convex points, the resulting shape may behave incorrectly in collision detection.

Important: Points must be ordered counter-clockwise (CCW). If you’re unsure about the ordering or convexity, use from_convex_hull instead.

This method automatically removes collinear vertices (points that lie on the line between their neighbors) to simplify the polygon. If you want to preserve all vertices exactly as given, use from_convex_polyline_unmodified.

§When to use this

Use this constructor when:

  • You already know your points form a convex polygon
  • The points are ordered counter-clockwise around the shape
  • You want better performance by skipping convex hull computation
§Returns
  • Some(ConvexPolygon) if successful
  • None if all points are nearly collinear (form an almost flat line) or there are fewer than 3 vertices after removing collinear points
§Example: Creating a square
use parry2d::shape::ConvexPolygon;
use nalgebra::Point2;

// A square with vertices in counter-clockwise order
let square = ConvexPolygon::from_convex_polyline(vec![
    Point2::origin(),  // bottom-left
    Point2::new(1.0, 0.0),  // bottom-right
    Point2::new(1.0, 1.0),  // top-right
    Point2::new(0.0, 1.0),  // top-left
]).expect("Failed to create square");

assert_eq!(square.points().len(), 4);
§Example: Collinear points are automatically removed
use parry2d::shape::ConvexPolygon;
use nalgebra::Point2;

// A quadrilateral with one vertex on an edge (making it collinear)
let polygon = ConvexPolygon::from_convex_polyline(vec![
    Point2::origin(),
    Point2::new(2.0, 0.0),
    Point2::new(2.0, 1.0),   // This point is on the line from (2,0) to (2,2)
    Point2::new(2.0, 2.0),
    Point2::new(0.0, 2.0),
]).expect("Failed to create polygon");

// The collinear point at (2.0, 1.0) was removed, leaving a rectangle
assert_eq!(polygon.points().len(), 4);
Source

pub fn from_convex_polyline_unmodified(points: Vec<Point<f32>>) -> Option<Self>

Creates a new 2D convex polygon from a set of points assumed to describe a counter-clockwise convex polyline.

This is the same as ConvexPolygon::from_convex_polyline but without removing any point from the input even if some are coplanar.

Returns None if points doesn’t contain at least three points.

Source

pub fn points(&self) -> &[Point<f32>]

Returns the vertices of this convex polygon.

The vertices are stored in counter-clockwise order around the polygon. This is a slice reference to the internal vertex storage.

§Example
use parry2d::shape::ConvexPolygon;
use nalgebra::Point2;

let triangle = ConvexPolygon::from_convex_polyline(vec![
    Point2::origin(),
    Point2::new(1.0, 0.0),
    Point2::new(0.5, 1.0),
]).unwrap();

let vertices = triangle.points();
assert_eq!(vertices.len(), 3);
assert_eq!(vertices[0], Point2::origin());
Source

pub fn normals(&self) -> &[Unit<Vector<f32>>]

Returns the outward-pointing normals of the edges of this convex polygon.

Each normal is a unit vector perpendicular to an edge, pointing outward from the polygon. The normals are stored in the same order as the edges, so normals()[i] is the normal for the edge from points()[i] to points()[(i+1) % len].

These pre-computed normals are used internally for efficient collision detection.

§Example
use parry2d::shape::ConvexPolygon;
use nalgebra::{Point2, Vector2};

// Create a square aligned with the axes
let square = ConvexPolygon::from_convex_polyline(vec![
    Point2::origin(),  // bottom-left
    Point2::new(1.0, 0.0),  // bottom-right
    Point2::new(1.0, 1.0),  // top-right
    Point2::new(0.0, 1.0),  // top-left
]).unwrap();

let normals = square.normals();
assert_eq!(normals.len(), 4);

// The first normal points downward (perpendicular to bottom edge)
let bottom_normal = normals[0];
assert!((bottom_normal.y - (-1.0)).abs() < 1e-5);
assert!(bottom_normal.x.abs() < 1e-5);
Source

pub fn scaled(self, scale: &Vector<f32>) -> Option<Self>

Computes a scaled version of this convex polygon.

This method scales the polygon by multiplying each vertex coordinate by the corresponding component of the scale vector. This allows for non-uniform scaling (different scale factors for x and y axes).

The normals are also updated to reflect the scaling transformation.

§Returns
  • Some(ConvexPolygon) with the scaled shape
  • None if the scaling results in degenerate normals (e.g., if the scale factor along one axis is zero or nearly zero)
§Example: Uniform scaling
use parry2d::shape::ConvexPolygon;
use nalgebra::{Point2, Vector2};

let triangle = ConvexPolygon::from_convex_polyline(vec![
    Point2::origin(),
    Point2::new(1.0, 0.0),
    Point2::new(0.5, 1.0),
]).unwrap();

// Scale uniformly by 2x
let scaled = triangle.scaled(&Vector2::new(2.0, 2.0))
    .expect("Failed to scale");

// All coordinates are doubled
assert_eq!(scaled.points()[1], Point2::new(2.0, 0.0));
assert_eq!(scaled.points()[2], Point2::new(1.0, 2.0));
§Example: Non-uniform scaling
use parry2d::shape::ConvexPolygon;
use nalgebra::{Point2, Vector2};

let square = ConvexPolygon::from_convex_polyline(vec![
    Point2::origin(),
    Point2::new(1.0, 0.0),
    Point2::new(1.0, 1.0),
    Point2::new(0.0, 1.0),
]).unwrap();

// Scale to make it wider (2x) and taller (3x)
let rectangle = square.scaled(&Vector2::new(2.0, 3.0))
    .expect("Failed to scale");

assert_eq!(rectangle.points()[2], Point2::new(2.0, 3.0));
Source

pub fn offsetted(&self, amount: f32) -> Self

Returns a mitered offset (expanded or contracted) version of the polygon.

This method creates a new polygon by moving each edge outward (or inward for negative values) by the specified amount. The vertices are adjusted to maintain sharp corners (mitered joints). This is also known as “polygon dilation” or “Minkowski sum with a circle”.

§Use cases
  • Creating “safe zones” or margins around objects
  • Implementing “thick” polygon collision detection
  • Creating rounded rectangular shapes (when combined with rounding)
  • Growing or shrinking shapes for morphological operations
§Arguments
  • amount - The distance to move each edge. Positive values expand the polygon outward, making it larger. Must be a non-negative finite number.
§Panics

Panics if amount is not a non-negative finite number (NaN, infinity, or negative).

§Example: Expanding a triangle
use parry2d::shape::ConvexPolygon;
use nalgebra::Point2;

let triangle = ConvexPolygon::from_convex_polyline(vec![
    Point2::origin(),
    Point2::new(2.0, 0.0),
    Point2::new(1.0, 2.0),
]).unwrap();

// Expand the triangle by 0.5 units
let expanded = triangle.offsetted(0.5);

// The expanded triangle has the same number of vertices
assert_eq!(expanded.points().len(), 3);
// But the vertices have moved outward
// (exact positions depend on the miter calculation)
§Example: Creating a margin around a square
use parry2d::shape::ConvexPolygon;
use nalgebra::Point2;

let square = ConvexPolygon::from_convex_polyline(vec![
    Point2::origin(),
    Point2::new(1.0, 0.0),
    Point2::new(1.0, 1.0),
    Point2::new(0.0, 1.0),
]).unwrap();

// Create a 0.2 unit margin around the square
let margin = square.offsetted(0.2);

// The shape is still a square (4 vertices)
assert_eq!(margin.points().len(), 4);
Source

pub fn support_feature_id_toward( &self, local_dir: &Unit<Vector<f32>>, ) -> FeatureId

Get the ID of the feature with a normal that maximizes the dot product with local_dir.

Source

pub fn feature_normal(&self, feature: FeatureId) -> Option<Unit<Vector<f32>>>

The normal of the given feature.

Trait Implementations§

Source§

impl Clone for ConvexPolygon

Source§

fn clone(&self) -> ConvexPolygon

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ConvexPolygon

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PointQuery for ConvexPolygon

Source§

fn project_local_point( &self, point: &Point<f32>, solid: bool, ) -> PointProjection

Projects a point on self. Read more
Source§

fn project_local_point_and_get_feature( &self, point: &Point<f32>, ) -> (PointProjection, FeatureId)

Projects a point on the boundary of self and returns the id of the feature the point was projected on.
Source§

fn project_local_point_with_max_dist( &self, pt: &Point<f32>, solid: bool, max_dist: f32, ) -> Option<PointProjection>

Projects a point onto the shape, with a maximum distance limit. Read more
Source§

fn project_point_with_max_dist( &self, m: &Isometry<f32>, pt: &Point<f32>, solid: bool, max_dist: f32, ) -> Option<PointProjection>

Projects a point on self transformed by m, unless the projection lies further than the given max distance.
Source§

fn distance_to_local_point(&self, pt: &Point<f32>, solid: bool) -> f32

Computes the minimal distance between a point and self.
Source§

fn contains_local_point(&self, pt: &Point<f32>) -> bool

Tests if the given point is inside of self.
Source§

fn project_point( &self, m: &Isometry<f32>, pt: &Point<f32>, solid: bool, ) -> PointProjection

Projects a point on self transformed by m.
Source§

fn distance_to_point( &self, m: &Isometry<f32>, pt: &Point<f32>, solid: bool, ) -> f32

Computes the minimal distance between a point and self transformed by m.
Source§

fn project_point_and_get_feature( &self, m: &Isometry<f32>, pt: &Point<f32>, ) -> (PointProjection, FeatureId)

Projects a point on the boundary of self transformed by m and returns the id of the feature the point was projected on.
Source§

fn contains_point(&self, m: &Isometry<f32>, pt: &Point<f32>) -> bool

Tests if the given point is inside of self transformed by m.
Source§

impl PolygonalFeatureMap for ConvexPolygon

Source§

fn local_support_feature( &self, dir: &Unit<Vector<f32>>, out_feature: &mut PolygonalFeature, )

Compute the support polygonal face of self towards the dir.
Source§

fn is_convex_polyhedron(&self) -> bool

Is this shape a ConvexPolyhedron?
Source§

impl RayCast for ConvexPolygon

Source§

fn cast_local_ray_and_get_normal( &self, ray: &Ray, max_time_of_impact: f32, solid: bool, ) -> Option<RayIntersection>

Computes the time of impact, and normal between this transformed shape and a ray.
Source§

fn cast_local_ray( &self, ray: &Ray, max_time_of_impact: f32, solid: bool, ) -> Option<f32>

Computes the time of impact between this transform shape and a ray.
Source§

fn intersects_local_ray(&self, ray: &Ray, max_time_of_impact: f32) -> bool

Tests whether a ray intersects this transformed shape.
Source§

fn cast_ray( &self, m: &Isometry<f32>, ray: &Ray, max_time_of_impact: f32, solid: bool, ) -> Option<f32>

Computes the time of impact between this transform shape and a ray.
Source§

fn cast_ray_and_get_normal( &self, m: &Isometry<f32>, ray: &Ray, max_time_of_impact: f32, solid: bool, ) -> Option<RayIntersection>

Computes the time of impact, and normal between this transformed shape and a ray.
Source§

fn intersects_ray( &self, m: &Isometry<f32>, ray: &Ray, max_time_of_impact: f32, ) -> bool

Tests whether a ray intersects this transformed shape.
Source§

impl Shape for ConvexPolygon

Source§

fn clone_dyn(&self) -> Box<dyn Shape>

Clones this shape into a boxed trait-object. Read more
Source§

fn scale_dyn( &self, scale: &Vector<f32>, _num_subdivisions: u32, ) -> Option<Box<dyn Shape>>

Scales this shape by scale into a boxed trait-object. Read more
Source§

fn compute_local_aabb(&self) -> Aabb

Computes the Aabb of this shape.
Source§

fn compute_local_bounding_sphere(&self) -> BoundingSphere

Computes the bounding-sphere of this shape.
Source§

fn compute_aabb(&self, position: &Isometry<f32>) -> Aabb

Computes the Aabb of this shape with the given position.
Source§

fn mass_properties(&self, density: f32) -> MassProperties

Compute the mass-properties of this shape given its uniform density.
Source§

fn is_convex(&self) -> bool

Is this shape known to be convex? Read more
Source§

fn shape_type(&self) -> ShapeType

Gets the type tag of this shape.
Source§

fn as_typed_shape(&self) -> TypedShape<'_>

Gets the underlying shape as an enum.
Source§

fn ccd_thickness(&self) -> f32

Source§

fn ccd_angular_thickness(&self) -> f32

Source§

fn as_support_map(&self) -> Option<&dyn SupportMap>

Converts this shape into its support mapping, if it has one.
Source§

fn as_polygonal_feature_map(&self) -> Option<(&dyn PolygonalFeatureMap, f32)>

Converts this shape to a polygonal feature-map, if it is one.
Source§

fn feature_normal_at_point( &self, feature: FeatureId, _point: &Point<f32>, ) -> Option<Unit<Vector<f32>>>

The shape’s normal at the given point located on a specific feature.
Source§

fn clone_box(&self) -> Box<dyn Shape>

👎Deprecated: renamed to clone_dyn
Clones this shape into a boxed trait-object. Read more
Source§

fn compute_bounding_sphere(&self, position: &Isometry<f32>) -> BoundingSphere

Computes the bounding-sphere of this shape with the given position.
Source§

fn as_composite_shape(&self) -> Option<&dyn CompositeShape>

Source§

fn compute_swept_aabb( &self, start_pos: &Isometry<f32>, end_pos: &Isometry<f32>, ) -> Aabb

Computes the swept Aabb of this shape, i.e., the space it would occupy by moving from the given start position to the given end position.
Source§

impl SupportMap for ConvexPolygon

Source§

fn local_support_point(&self, dir: &Vector<f32>) -> Point<f32>

Evaluates the support function of this shape in local space. Read more
Source§

fn local_support_point_toward(&self, dir: &Unit<Vector<f32>>) -> Point<f32>

Same as local_support_point except that dir is guaranteed to be normalized (unit length). Read more
Source§

fn support_point( &self, transform: &Isometry<f32>, dir: &Vector<f32>, ) -> Point<f32>

Evaluates the support function of this shape transformed by transform. Read more
Source§

fn support_point_toward( &self, transform: &Isometry<f32>, dir: &Unit<Vector<f32>>, ) -> Point<f32>

Same as support_point except that dir is guaranteed to be normalized (unit length). Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_sync(self: Box<T>) -> Box<dyn Any + Sync + Send>

Converts Box<Trait> (where Trait: DowncastSync) to Box<dyn Any + Send + Sync>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Converts Arc<Trait> (where Trait: DowncastSync) to Arc<Any>, which can then be downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.