Skip to main content

jagua_rs/geometry/
original_shape.rs

1use crate::geometry::DTransformation;
2use crate::geometry::geo_traits::Transformable;
3use crate::geometry::primitives::{Point, Rect, SPolygon};
4use crate::geometry::shape_modification::{
5    ShapeModifyConfig, ShapeModifyMode, close_narrow_concavities, offset_shape,
6    shape_modification_valid, simplify_shape,
7};
8use anyhow::Result;
9
10#[derive(Clone, Debug)]
11/// A [`SPolygon`] exactly as is defined in the input file
12///
13/// Also contains all required operations to convert it to a shape that can be used internally.
14/// Currently, these are centering and simplification operations, but could be extended in the future.
15pub struct OriginalShape {
16    pub shape: SPolygon,
17    pub pre_transform: DTransformation,
18    pub modify_mode: ShapeModifyMode,
19    pub modify_config: ShapeModifyConfig,
20}
21
22impl OriginalShape {
23    pub fn convert_to_internal(&self) -> Result<SPolygon> {
24        // Apply the transformation.
25        // Rounding can shorten edges slightly, so the polygon is rebuilt to uphold its minimum edge length.
26        let transformed = self.shape.transform_clone(&self.pre_transform.compose());
27        let mut internal = SPolygon::new(transformed.vertices)?;
28
29        if let Some(offset) = self.modify_config.offset {
30            // Offset the shape
31            if offset != 0.0 {
32                internal = offset_shape(&internal, self.modify_mode, offset)?;
33            }
34        }
35        if let Some(tolerance) = self.modify_config.simplify_tolerance {
36            let pre_simplified = internal.clone();
37            // Simplify the shape
38            internal = simplify_shape(&internal, self.modify_mode, tolerance);
39            if let Some(narrow_concavity_cutoff) = self.modify_config.narrow_concavity_cutoff {
40                // Close narrow concavities
41                internal =
42                    close_narrow_concavities(&internal, self.modify_mode, narrow_concavity_cutoff);
43                // Do another simplification after closing concavities
44                internal = simplify_shape(&internal, self.modify_mode, tolerance / 10.0);
45            }
46            debug_assert!(shape_modification_valid(
47                &pre_simplified,
48                &internal,
49                self.modify_mode
50            ));
51        }
52
53        Ok(internal)
54    }
55
56    #[must_use]
57    pub fn centroid(&self) -> Point {
58        self.shape.centroid()
59    }
60
61    #[must_use]
62    pub fn area(&self) -> f32 {
63        self.shape.area
64    }
65
66    #[must_use]
67    pub fn bbox(&self) -> Rect {
68        self.shape.bbox
69    }
70
71    #[must_use]
72    pub fn diameter(&self) -> f32 {
73        self.shape.diameter
74    }
75}