Skip to main content

three_rs/extras/
shape.rs

1//! Port of `three.js/src/extras/core/Shape.js`.
2
3use std::ops::{Deref, DerefMut};
4
5use super::curve::Curve;
6use super::curve_path::delegate_curve_path;
7use super::path::Path;
8use crate::math::Vector2;
9
10/// `Shape`: a [`Path`] with optional holes, the input to
11/// [`shape_geometry`](crate::geometries::shape_geometry) and
12/// [`extrude_geometry`](crate::geometries::extrude_geometry).
13///
14/// `Shape extends Path` in three.js; here a `Shape` holds its `Path` and
15/// derefs to it, so the drawing API (`shape.move_to(..)`) reads the same.
16/// `uuid` is not ported: it only serves `toJSON`.
17#[derive(Clone, Debug, Default)]
18pub struct Shape {
19    /// The inherited `Path` state.
20    pub path: Path,
21    /// The paths that define the holes in the shape.
22    pub holes: Vec<Path>,
23}
24
25impl Deref for Shape {
26    type Target = Path;
27    fn deref(&self) -> &Self::Target {
28        &self.path
29    }
30}
31
32impl DerefMut for Shape {
33    fn deref_mut(&mut self) -> &mut Self::Target {
34        &mut self.path
35    }
36}
37
38delegate_curve_path!(Shape, path, Vector2, "Shape");
39
40/// The return value of [`Shape::extract_points`], three.js'
41/// `{ shape, holes }`.
42#[derive(Clone, Debug, Default, PartialEq)]
43pub struct ShapePoints {
44    /// The points of the shape's own outline.
45    pub shape: Vec<Vector2>,
46    /// The points of each hole's outline, one `Vec` per hole.
47    pub holes: Vec<Vec<Vector2>>,
48}
49
50impl Shape {
51    /// `new Shape()`.
52    pub fn new() -> Self {
53        Self::default()
54    }
55
56    /// `new Shape( points )`.
57    pub fn from_points(points: &[Vector2]) -> Self {
58        Self {
59            path: Path::from_points(points),
60            holes: Vec::new(),
61        }
62    }
63
64    /// `Shape.getPointsHoles( divisions )`.
65    pub fn get_points_holes(&self, divisions: usize) -> Vec<Vec<Vector2>> {
66        self.holes
67            .iter()
68            .map(|hole| hole.get_points(divisions))
69            .collect()
70    }
71
72    /// `Shape.extractPoints( divisions )`: the points of the outline and of
73    /// every hole.
74    pub fn extract_points(&self, divisions: usize) -> ShapePoints {
75        ShapePoints {
76            shape: self.get_points(divisions),
77            holes: self.get_points_holes(divisions),
78        }
79    }
80}