Skip to main content

section_properties/section_library/
primitive.rs

1//! Primitive section shapes (rectangles, circles, triangles, etc.)
2
3use crate::geometry::{Point, Polygon};
4use crate::section::Section;
5use crate::section_library::{
6    ParametricSection, circle_polygon, draw_radius, hollow_circle_polygon, rotate_point,
7    rounded_rectangle_polygon,
8};
9use std::f64::consts::PI;
10
11/// Solid rectangular section.
12#[derive(Debug, Clone, Copy, PartialEq)]
13pub struct RectangularSection {
14    pub width: f64,  // b (x-direction)
15    pub height: f64, // h (y-direction)
16}
17
18impl RectangularSection {
19    pub fn new(width: f64, height: f64) -> Self {
20        assert!(width > 0.0 && height > 0.0, "Dimensions must be positive");
21        Self { width, height }
22    }
23
24    pub fn square(side: f64) -> Self {
25        Self::new(side, side)
26    }
27}
28
29impl ParametricSection for RectangularSection {
30    fn build(&self) -> Section {
31        // Match Python sectionproperties: bottom-left corner at the origin,
32        // extending to (b, d).
33        let b = self.width;
34        let d = self.height;
35        Section::new(
36            Polygon::new(vec![
37                Point::new(0.0, 0.0),
38                Point::new(b, 0.0),
39                Point::new(b, d),
40                Point::new(0.0, d),
41            ]),
42            Vec::new(),
43        )
44    }
45
46    fn designation(&self) -> String {
47        format!(
48            "RECT {:.0}x{:.0}",
49            self.width * 1000.0,
50            self.height * 1000.0
51        )
52    }
53}
54
55/// Solid circular section.
56#[derive(Debug, Clone, Copy, PartialEq)]
57pub struct CircularSection {
58    pub radius: f64,
59    pub n_vertices: usize,
60}
61
62impl CircularSection {
63    pub fn new(radius: f64) -> Self {
64        Self::with_vertices(radius, 64)
65    }
66
67    pub fn with_vertices(radius: f64, n_vertices: usize) -> Self {
68        assert!(radius > 0.0, "Radius must be positive");
69        assert!(n_vertices >= 8, "At least 8 vertices");
70        Self { radius, n_vertices }
71    }
72
73    pub fn diameter(d: f64) -> Self {
74        Self::new(d / 2.0)
75    }
76}
77
78impl ParametricSection for CircularSection {
79    fn build(&self) -> Section {
80        Section::new(circle_polygon(self.radius, self.n_vertices), Vec::new())
81    }
82
83    fn designation(&self) -> String {
84        format!("CIRC Ø{:.0}", self.radius * 2000.0)
85    }
86}
87
88/// Circular hollow section (CHS / tube).
89#[derive(Debug, Clone, Copy, PartialEq)]
90pub struct CircularHollowSection {
91    pub outer_radius: f64,
92    pub inner_radius: f64,
93    pub n_vertices: usize,
94}
95
96impl CircularHollowSection {
97    pub fn new(outer_radius: f64, inner_radius: f64) -> Self {
98        Self::with_vertices(outer_radius, inner_radius, 64)
99    }
100
101    pub fn with_vertices(outer_radius: f64, inner_radius: f64, n_vertices: usize) -> Self {
102        assert!(
103            outer_radius > inner_radius,
104            "Outer radius must exceed inner radius"
105        );
106        assert!(inner_radius > 0.0, "Inner radius must be positive");
107        assert!(n_vertices >= 8, "At least 8 vertices");
108        Self {
109            outer_radius,
110            inner_radius,
111            n_vertices,
112        }
113    }
114
115    pub fn from_dimensions(outer_diameter: f64, wall_thickness: f64) -> Self {
116        let ro = outer_diameter / 2.0;
117        let ri = ro - wall_thickness;
118        Self::new(ro, ri)
119    }
120}
121
122impl ParametricSection for CircularHollowSection {
123    fn build(&self) -> Section {
124        let (outer, inner) =
125            hollow_circle_polygon(self.outer_radius, self.inner_radius, self.n_vertices);
126        Section::new(outer, vec![inner])
127    }
128
129    fn designation(&self) -> String {
130        format!(
131            "CHS Ø{:.0}x{:.1}",
132            self.outer_radius * 2000.0,
133            (self.outer_radius - self.inner_radius) * 1000.0
134        )
135    }
136}
137
138/// Elliptical section.
139#[derive(Debug, Clone, Copy, PartialEq)]
140pub struct EllipticalSection {
141    pub semi_major: f64, // a (x-direction)
142    pub semi_minor: f64, // b (y-direction)
143    pub n_vertices: usize,
144}
145
146impl EllipticalSection {
147    pub fn new(semi_major: f64, semi_minor: f64) -> Self {
148        Self::with_vertices(semi_major, semi_minor, 64)
149    }
150
151    pub fn with_vertices(semi_major: f64, semi_minor: f64, n_vertices: usize) -> Self {
152        assert!(
153            semi_major > 0.0 && semi_minor > 0.0,
154            "Axes must be positive"
155        );
156        assert!(n_vertices >= 8, "At least 8 vertices");
157        Self {
158            semi_major,
159            semi_minor,
160            n_vertices,
161        }
162    }
163}
164
165impl ParametricSection for EllipticalSection {
166    fn build(&self) -> Section {
167        let mut vertices = Vec::with_capacity(self.n_vertices);
168        for i in 0..self.n_vertices {
169            let theta = 2.0 * PI * i as f64 / self.n_vertices as f64;
170            vertices.push(Point::new(
171                self.semi_major * theta.cos(),
172                self.semi_minor * theta.sin(),
173            ));
174        }
175        Section::new(Polygon::new(vertices), Vec::new())
176    }
177
178    fn designation(&self) -> String {
179        format!(
180            "ELLIPSE {:.0}x{:.0}",
181            self.semi_major * 2000.0,
182            self.semi_minor * 2000.0
183        )
184    }
185}
186
187/// Solid triangular section.
188#[derive(Debug, Clone, Copy, PartialEq)]
189pub struct TriangularSection {
190    pub base: f64,
191    pub height: f64,
192    /// Apex position along base (0.0 = left, 0.5 = centered, 1.0 = right)
193    pub apex_ratio: f64,
194}
195
196impl TriangularSection {
197    pub fn new(base: f64, height: f64) -> Self {
198        Self::with_apex(base, height, 0.5)
199    }
200
201    pub fn with_apex(base: f64, height: f64, apex_ratio: f64) -> Self {
202        assert!(base > 0.0 && height > 0.0, "Dimensions must be positive");
203        assert!(
204            apex_ratio >= 0.0 && apex_ratio <= 1.0,
205            "Apex ratio must be in [0,1]"
206        );
207        Self {
208            base,
209            height,
210            apex_ratio,
211        }
212    }
213
214    pub fn equilateral(side: f64) -> Self {
215        let h = side * 3.0_f64.sqrt() / 2.0;
216        Self::new(side, h)
217    }
218
219    pub fn right_angle(base: f64, height: f64) -> Self {
220        Self::with_apex(base, height, 0.0)
221    }
222}
223
224impl ParametricSection for TriangularSection {
225    fn build(&self) -> Section {
226        let apex_x = (self.apex_ratio - 0.5) * self.base;
227        let poly = Polygon::new(vec![
228            Point::new(-self.base / 2.0, -self.height / 3.0),
229            Point::new(self.base / 2.0, -self.height / 3.0),
230            Point::new(apex_x, 2.0 * self.height / 3.0),
231        ]);
232        Section::new(poly, Vec::new())
233    }
234
235    fn designation(&self) -> String {
236        format!("TRI {:.0}x{:.0}", self.base * 1000.0, self.height * 1000.0)
237    }
238}
239
240/// Rounded rectangle (rectangle with filleted corners).
241#[derive(Debug, Clone, Copy, PartialEq)]
242pub struct RoundedRectangleSection {
243    pub width: f64,
244    pub height: f64,
245    pub radius: f64,
246    pub n_per_corner: usize,
247}
248
249impl RoundedRectangleSection {
250    pub fn new(width: f64, height: f64, radius: f64) -> Self {
251        Self::with_vertices(width, height, radius, 16)
252    }
253
254    pub fn with_vertices(width: f64, height: f64, radius: f64, n_per_corner: usize) -> Self {
255        assert!(width > 0.0 && height > 0.0, "Dimensions must be positive");
256        assert!(radius >= 0.0, "Radius must be non-negative");
257        assert!(
258            radius <= width / 2.0 && radius <= height / 2.0,
259            "Radius too large for dimensions"
260        );
261        assert!(n_per_corner >= 1, "At least 1 vertex per corner");
262        Self {
263            width,
264            height,
265            radius,
266            n_per_corner,
267        }
268    }
269}
270
271impl ParametricSection for RoundedRectangleSection {
272    fn build(&self) -> Section {
273        Section::new(
274            rounded_rectangle_polygon(self.width, self.height, self.radius, self.n_per_corner),
275            Vec::new(),
276        )
277    }
278
279    fn designation(&self) -> String {
280        format!(
281            "RRECT {:.0}x{:.0} R{:.0}",
282            self.width * 1000.0,
283            self.height * 1000.0,
284            self.radius * 1000.0
285        )
286    }
287}
288
289/// Regular polygon section (n-gon).
290#[derive(Debug, Clone, Copy, PartialEq)]
291pub struct RegularPolygonSection {
292    pub circumradius: f64, // Radius of circumscribed circle
293    pub n_sides: usize,
294}
295
296impl RegularPolygonSection {
297    pub fn new(circumradius: f64, n_sides: usize) -> Self {
298        assert!(circumradius > 0.0, "Radius must be positive");
299        assert!(n_sides >= 3, "At least 3 sides");
300        Self {
301            circumradius,
302            n_sides,
303        }
304    }
305
306    pub fn from_inscribed_radius(inradius: f64, n_sides: usize) -> Self {
307        let circumradius = inradius / (PI / n_sides as f64).cos();
308        Self::new(circumradius, n_sides)
309    }
310}
311
312impl ParametricSection for RegularPolygonSection {
313    fn build(&self) -> Section {
314        let mut vertices = Vec::with_capacity(self.n_sides);
315        for i in 0..self.n_sides {
316            // Rotate so one vertex is at top (like a hexagon flat on top)
317            let theta = -PI / 2.0 + 2.0 * PI * i as f64 / self.n_sides as f64;
318            vertices.push(Point::new(
319                self.circumradius * theta.cos(),
320                self.circumradius * theta.sin(),
321            ));
322        }
323        Section::new(Polygon::new(vertices), Vec::new())
324    }
325
326    fn designation(&self) -> String {
327        format!("{}-GON R{:.0}", self.n_sides, self.circumradius * 1000.0)
328    }
329}
330
331/// Cruciform (cross) section.
332#[derive(Debug, Clone, Copy, PartialEq)]
333pub struct CruciformSection {
334    pub width: f64,
335    pub height: f64,
336    pub flange_width: f64,
337    pub flange_thickness: f64,
338    pub web_thickness: f64,
339}
340
341impl CruciformSection {
342    pub fn new(
343        width: f64,
344        height: f64,
345        flange_width: f64,
346        flange_thickness: f64,
347        web_thickness: f64,
348    ) -> Self {
349        assert!(
350            width > 0.0 && height > 0.0,
351            "Overall dimensions must be positive"
352        );
353        assert!(
354            flange_width > 0.0 && flange_thickness > 0.0,
355            "Flange dims must be positive"
356        );
357        assert!(web_thickness > 0.0, "Web thickness must be positive");
358        assert!(
359            flange_width <= width,
360            "Flange width cannot exceed overall width"
361        );
362        assert!(
363            flange_thickness <= height / 2.0,
364            "Flange thickness cannot exceed half height"
365        );
366        assert!(
367            web_thickness <= width,
368            "Web thickness cannot exceed overall width"
369        );
370        Self {
371            width,
372            height,
373            flange_width,
374            flange_thickness,
375            web_thickness,
376        }
377    }
378
379    pub fn symmetric(size: f64, flange: f64, web: f64) -> Self {
380        Self::new(size, size, flange, flange, web)
381    }
382}
383
384impl ParametricSection for CruciformSection {
385    fn build(&self) -> Section {
386        let fw = self.flange_width / 2.0;
387        let ft = self.flange_thickness;
388        let wt = self.web_thickness / 2.0;
389        let hh = self.height / 2.0;
390
391        let vertices = vec![
392            Point::new(-wt, hh),
393            Point::new(wt, hh),
394            Point::new(wt, ft),
395            Point::new(fw, ft),
396            Point::new(fw, -ft),
397            Point::new(wt, -ft),
398            Point::new(wt, -hh),
399            Point::new(-wt, -hh),
400            Point::new(-wt, -ft),
401            Point::new(-fw, -ft),
402            Point::new(-fw, ft),
403            Point::new(-wt, ft),
404        ];
405
406        Section::new(Polygon::new(vertices), Vec::new())
407    }
408
409    fn designation(&self) -> String {
410        format!(
411            "CRUCIFORM {:.0}x{:.0}",
412            self.width * 1000.0,
413            self.height * 1000.0
414        )
415    }
416}
417
418/// Elliptical hollow section (EHS) centered at origin.
419///
420/// Mirrors Python `elliptical_hollow_section(d_x, d_y, t, n)`.
421#[derive(Debug, Clone, Copy, PartialEq)]
422pub struct EllipticalHollowSection {
423    pub d_x: f64,
424    pub d_y: f64,
425    pub t: f64,
426    pub n: usize,
427}
428
429impl EllipticalHollowSection {
430    pub fn new(d_x: f64, d_y: f64, t: f64, n: usize) -> Self {
431        assert!(
432            d_x > 0.0 && d_y > 0.0 && t > 0.0,
433            "Dimensions must be positive"
434        );
435        assert!(2.0 * t < d_x && 2.0 * t < d_y, "Thickness too large");
436        assert!(n >= 3, "Need at least 3 points");
437        Self { d_x, d_y, t, n }
438    }
439}
440
441impl ParametricSection for EllipticalHollowSection {
442    fn build(&self) -> Section {
443        let n = self.n;
444        let mut outer_pts = Vec::with_capacity(n);
445        let mut inner_pts = Vec::with_capacity(n);
446        for i in 0..n {
447            let theta = 2.0 * PI * i as f64 / n as f64;
448            outer_pts.push(Point::new(
449                0.5 * self.d_x * theta.cos(),
450                0.5 * self.d_y * theta.sin(),
451            ));
452            inner_pts.push(Point::new(
453                (0.5 * self.d_x - self.t) * theta.cos(),
454                (0.5 * self.d_y - self.t) * theta.sin(),
455            ));
456        }
457        // Inner polygon CW for hole
458        inner_pts.reverse();
459        Section::new(Polygon::new(outer_pts), vec![Polygon::new(inner_pts)])
460    }
461
462    fn designation(&self) -> String {
463        format!(
464            "EHS {:.0}x{:.0}x{:.0}",
465            self.d_x * 1000.0,
466            self.d_y * 1000.0,
467            self.t * 1000.0
468        )
469    }
470}
471
472/// Regular hollow polygon section centered at origin.
473///
474/// Mirrors Python `polygon_hollow_section(d, t, n_sides, r_in, n_r, rot)`.
475#[derive(Debug, Clone, Copy, PartialEq)]
476pub struct PolygonHollowSection {
477    pub d: f64,
478    pub t: f64,
479    pub n_sides: usize,
480    pub r_in: f64,
481    pub n_r: usize,
482    pub rot: f64,
483}
484
485impl PolygonHollowSection {
486    pub fn new(d: f64, t: f64, n_sides: usize) -> Self {
487        Self::with_radius(d, t, n_sides, 0.0, 1, 0.0)
488    }
489
490    pub fn with_radius(
491        d: f64,
492        t: f64,
493        n_sides: usize,
494        r_in: f64,
495        n_r: usize,
496        rot_deg: f64,
497    ) -> Self {
498        assert!(d > 0.0 && t > 0.0, "Dimensions must be positive");
499        assert!(n_sides >= 3, "Need at least 3 sides");
500        Self {
501            d,
502            t,
503            n_sides,
504            r_in,
505            n_r,
506            rot: rot_deg * PI / 180.0,
507        }
508    }
509}
510
511impl ParametricSection for PolygonHollowSection {
512    fn build(&self) -> Section {
513        let alpha = 2.0 * PI / self.n_sides as f64;
514        let a_out = self.d / 2.0 * (alpha / 2.0).cos();
515        let a_in = a_out - self.t;
516        let side_length_out = self.d * (alpha / 2.0).sin();
517        let side_length_in = a_in / a_out * side_length_out;
518
519        let r_in = self.r_in.min(a_in);
520        let (r_out, n_r) = if r_in == 0.0 {
521            (0.0, 1)
522        } else {
523            (r_in + self.t, self.n_r)
524        };
525
526        let c_out = r_out * (side_length_out / 2.0) / a_out;
527        let c_in = r_in * (side_length_in / 2.0) / a_in;
528        let sl_straight_out = side_length_out - 2.0 * c_out;
529        let sl_straight_in = side_length_in - 2.0 * c_in;
530
531        // Build one corner radius, then rotate for each side
532        let mut outer_base = Vec::new();
533        let mut inner_base = Vec::new();
534        for i in 0..n_r {
535            let theta = 0.5 * PI + i as f64 / (n_r.max(1) - 1).max(1) as f64 * alpha;
536            outer_base.push(Point::new(
537                sl_straight_out / 2.0 - r_out * theta.cos(),
538                -a_out + r_out - r_out * theta.sin(),
539            ));
540            inner_base.push(Point::new(
541                sl_straight_in / 2.0 - r_in * theta.cos(),
542                -a_in + r_in - r_in * theta.sin(),
543            ));
544        }
545
546        let mut outer_pts = Vec::new();
547        let mut inner_pts = Vec::new();
548        for i in 0..self.n_sides {
549            let angle = alpha * i as f64 + self.rot;
550            for pt in &outer_base {
551                outer_pts.push(rotate_point(*pt, angle));
552            }
553            for pt in &inner_base {
554                inner_pts.push(rotate_point(*pt, angle));
555            }
556        }
557        inner_pts.reverse();
558        Section::new(Polygon::new(outer_pts), vec![Polygon::new(inner_pts)])
559    }
560
561    fn designation(&self) -> String {
562        format!(
563            "PHS {}-sides {:.0}x{:.0}",
564            self.n_sides,
565            self.d * 1000.0,
566            self.t * 1000.0
567        )
568    }
569}
570
571/// Right-angled isosceles triangle with concave radius on hypotenuse.
572///
573/// Mirrors Python `triangular_radius_section(b, n_r)`.
574#[derive(Debug, Clone, Copy, PartialEq)]
575pub struct TriangularRadiusSection {
576    pub b: f64,
577    pub n_r: usize,
578}
579
580impl TriangularRadiusSection {
581    pub fn new(b: f64, n_r: usize) -> Self {
582        assert!(b > 0.0, "Base must be positive");
583        assert!(n_r >= 2, "Need at least 2 points for radius");
584        Self { b, n_r }
585    }
586}
587
588impl ParametricSection for TriangularRadiusSection {
589    fn build(&self) -> Section {
590        let mut points = vec![Point::new(0.0, 0.0)];
591        let arc = draw_radius(
592            Point::new(self.b, self.b),
593            self.b,
594            3.0 * PI / 2.0,
595            self.n_r,
596            false,
597            PI / 2.0,
598        );
599        points.extend(arc);
600        Section::new(Polygon::new(points), vec![])
601    }
602
603    fn designation(&self) -> String {
604        format!("TriR {:.0}", self.b * 1000.0)
605    }
606}
607
608/// Pentagon section.
609///
610/// Mirrors Python `pentagon_section(d, n, rot)`. `d` is the diameter of the
611/// circumscribed circle.
612#[derive(Debug, Clone, Copy, PartialEq)]
613pub struct PentagonSection {
614    pub d: f64,
615    pub n: usize,
616}
617
618impl PentagonSection {
619    pub fn new(d: f64) -> Self {
620        Self::with_vertices(d, 64)
621    }
622
623    pub fn with_vertices(d: f64, n: usize) -> Self {
624        assert!(d > 0.0, "Diameter must be positive");
625        Self { d, n }
626    }
627}
628
629impl ParametricSection for PentagonSection {
630    fn build(&self) -> Section {
631        RegularPolygonSection::new(self.d / 2.0, 5).build()
632    }
633
634    fn designation(&self) -> String {
635        format!("PENTAGON Ø{:.0}", self.d * 1000.0)
636    }
637}
638
639/// Hexagon section.
640///
641/// Mirrors Python `hexagon_section(d, n, rot)`.
642#[derive(Debug, Clone, Copy, PartialEq)]
643pub struct HexagonSection {
644    pub d: f64,
645    pub n: usize,
646}
647
648impl HexagonSection {
649    pub fn new(d: f64) -> Self {
650        Self::with_vertices(d, 64)
651    }
652
653    pub fn with_vertices(d: f64, n: usize) -> Self {
654        assert!(d > 0.0, "Diameter must be positive");
655        Self { d, n }
656    }
657}
658
659impl ParametricSection for HexagonSection {
660    fn build(&self) -> Section {
661        RegularPolygonSection::new(self.d / 2.0, 6).build()
662    }
663
664    fn designation(&self) -> String {
665        format!("HEXAGON Ø{:.0}", self.d * 1000.0)
666    }
667}
668
669/// Octagon section.
670///
671/// Mirrors Python `octagon_section(d, n, rot)`.
672#[derive(Debug, Clone, Copy, PartialEq)]
673pub struct OctagonSection {
674    pub d: f64,
675    pub n: usize,
676}
677
678impl OctagonSection {
679    pub fn new(d: f64) -> Self {
680        Self::with_vertices(d, 64)
681    }
682
683    pub fn with_vertices(d: f64, n: usize) -> Self {
684        assert!(d > 0.0, "Diameter must be positive");
685        Self { d, n }
686    }
687}
688
689impl ParametricSection for OctagonSection {
690    fn build(&self) -> Section {
691        RegularPolygonSection::new(self.d / 2.0, 8).build()
692    }
693
694    fn designation(&self) -> String {
695        format!("OCTAGON Ø{:.0}", self.d * 1000.0)
696    }
697}
698
699#[test]
700fn pentagon_section() {
701    let p = PentagonSection::new(0.1);
702    let sec = p.build();
703    // Area of regular pentagon with circumradius R: (5/2) R^2 sin(72°)
704    let r = 0.05_f64;
705    let expected = 2.5 * r * r * (2.0 * PI * 0.2).sin();
706    assert!((sec.area() - expected).abs() < 1e-8);
707}
708
709#[test]
710fn hexagon_section() {
711    let h = HexagonSection::new(0.12);
712    let sec = h.build();
713    let expected = 3.0 * 3.0_f64.sqrt() / 2.0 * 0.06_f64.powi(2);
714    assert!((sec.area() - expected).abs() < 1e-10);
715}
716
717#[test]
718fn octagon_section() {
719    let o = OctagonSection::new(0.2);
720    let sec = o.build();
721    let r = 0.1_f64;
722    let expected = 2.0 * 2.0_f64.sqrt() * r * r;
723    assert!((sec.area() - expected).abs() < 1e-8);
724}
725
726#[test]
727fn geometry_align_center_and_mirror() {
728    use crate::geometry::{Axis, Geometry};
729    let rect = Geometry::new(
730        Polygon::new(vec![
731            Point::new(0.0, 0.0),
732            Point::new(2.0, 0.0),
733            Point::new(2.0, 1.0),
734            Point::new(0.0, 1.0),
735        ]),
736        vec![],
737    );
738    let c = rect.align_center().apply_transforms();
739    assert!((c.centroid().x - 0.0).abs() < 1e-12);
740    assert!((c.centroid().y - 0.0).abs() < 1e-12);
741
742    let m = rect.clone().mirror(Axis::Y).apply_transforms();
743    assert!((m.centroid().x + 1.0).abs() < 1e-12);
744
745    let s = rect.clone().shift(1.0, -3.0).apply_transforms();
746    assert!((s.centroid().x - 2.0).abs() < 1e-12);
747    assert!((s.centroid().y + 2.5).abs() < 1e-12);
748
749    // Rotate about origin by 90 degrees: area preserved, centroid moved
750    let r = rect
751        .clone()
752        .rotate_about(90.0, Point::new(0.0, 0.0))
753        .apply_transforms();
754    assert!((r.area() - rect.area()).abs() < 1e-12);
755    assert!((r.centroid().x + 0.5).abs() < 1e-9);
756    assert!((r.centroid().y - 1.0).abs() < 1e-9);
757}
758
759#[test]
760fn geometry_align_to() {
761    use crate::geometry::Geometry;
762    let a = Geometry::new(
763        Polygon::new(vec![
764            Point::new(0.0, 0.0),
765            Point::new(1.0, 0.0),
766            Point::new(1.0, 1.0),
767            Point::new(0.0, 1.0),
768        ]),
769        vec![],
770    );
771    let b = Geometry::new(
772        Polygon::new(vec![
773            Point::new(10.0, 10.0),
774            Point::new(11.5, 10.0),
775            Point::new(11.5, 11.0),
776            Point::new(10.0, 11.0),
777        ]),
778        vec![],
779    );
780    let aligned = a.align_to(&b).apply_transforms();
781    assert!((aligned.centroid().y - 10.5).abs() < 1e-12);
782}
783
784#[test]
785fn geometry_offset_rectangle() {
786    use crate::geometry::Geometry;
787    let rect = Geometry::new(
788        Polygon::new(vec![
789            Point::new(0.0, 0.0),
790            Point::new(2.0, 0.0),
791            Point::new(2.0, 1.0),
792            Point::new(0.0, 1.0),
793        ]),
794        vec![],
795    );
796    // Grow by 0.1: area = 2.2 * 1.2
797    let grown = rect.offset(0.1).unwrap().apply_transforms();
798    assert!((grown.area() - 2.64).abs() < 1e-9);
799    // Shrink by 0.2: area = 1.6 * 0.6
800    let shrunk = rect.offset(-0.2).unwrap().apply_transforms();
801    assert!((shrunk.area() - 0.96).abs() < 1e-9);
802    // Over-shrink degenerates -> None
803    assert!(rect.offset(-0.6).is_none());
804}
805
806#[test]
807fn geometry_offset_circle() {
808    use crate::geometry::Geometry;
809    use std::f64::consts::PI;
810    let r = 0.5_f64;
811    let circ = Geometry::from_section(&CircularSection::new(r).build());
812    let grown = circ.offset(0.05).unwrap();
813    let expected = PI * (r + 0.05_f64).powi(2);
814    assert!((grown.area() - expected).abs() / expected < 5e-3);
815}
816
817#[cfg(test)]
818mod tests {
819    use super::*;
820
821    use std::f64::consts::PI;
822
823    #[test]
824    fn rectangular_section() {
825        let rect = RectangularSection::new(0.2, 0.1);
826        let sec = rect.build();
827        assert!((sec.area() - 0.02).abs() < 1e-10);
828    }
829
830    #[test]
831    fn circular_section() {
832        let circ = CircularSection::new(0.1);
833        let sec = circ.build();
834        assert!((sec.area() - PI * 0.01).abs() < 1e-4);
835    }
836
837    #[test]
838    fn chs_section() {
839        let chs = CircularHollowSection::from_dimensions(0.2191, 0.0082); // 219.1x8.2
840        let sec = chs.build();
841        let expected_area = PI * (0.10955_f64.powi(2) - 0.10135_f64.powi(2));
842        assert!((sec.area() - expected_area).abs() < 1e-4);
843    }
844
845    #[test]
846    fn triangular_section() {
847        let tri = TriangularSection::new(0.1, 0.1);
848        let sec = tri.build();
849        assert!((sec.area() - 0.005).abs() < 1e-10);
850    }
851
852    #[test]
853    fn equilateral_triangle() {
854        let tri = TriangularSection::equilateral(0.1);
855        let sec = tri.build();
856        let expected = 0.1_f64.powi(2) * 3.0_f64.sqrt() / 4.0;
857        assert!((sec.area() - expected).abs() < 1e-10);
858    }
859
860    #[test]
861    fn rounded_rectangle() {
862        let rrect = RoundedRectangleSection::new(0.2, 0.1, 0.01);
863        let sec = rrect.build();
864        let expected = 0.02 - (4.0 - PI) * 0.0001;
865        assert!((sec.area() - expected).abs() < 1e-6);
866    }
867
868    #[test]
869    fn regular_polygon_hexagon() {
870        let hex = RegularPolygonSection::new(0.1, 6);
871        let sec = hex.build();
872        // Area of regular hexagon: 3*sqrt(3)/2 * R^2
873        let expected = 3.0 * 3.0_f64.sqrt() / 2.0 * 0.01;
874        assert!((sec.area() - expected).abs() < 1e-6);
875    }
876
877    #[test]
878    fn cruciform_section() {
879        let cross = CruciformSection::new(0.2, 0.2, 0.15, 0.02, 0.01);
880        let sec = cross.build();
881        // Area = horizontal bar + vertical bar - overlap
882        let expected = 0.15 * 2.0 * 0.02 + 0.2 * 0.01 - 0.01 * 2.0 * 0.02;
883        assert!((sec.area() - expected).abs() < 1e-6);
884    }
885
886    #[test]
887    fn elliptical_hollow_section() {
888        let ehs = EllipticalHollowSection::new(0.05, 0.025, 0.002, 64);
889        let sec = ehs.build();
890        // Outer ellipse area = pi * a * b; inner = pi * (a-t) * (b-t)
891        let a = 0.025_f64;
892        let b = 0.0125_f64;
893        let t = 0.002_f64;
894        let expected = PI * (a * b - (a - t) * (b - t));
895        assert!(
896            (sec.area() - expected).abs() / expected < 0.02,
897            "EHS area: got {}, expected {}",
898            sec.area(),
899            expected
900        );
901    }
902
903    #[test]
904    fn polygon_hollow_octagon() {
905        let phs = PolygonHollowSection::new(0.2, 0.006, 8);
906        let sec = phs.build();
907        assert!(sec.area() > 0.0, "Polygon hollow area should be positive");
908        // Octagon outer area = 2*(1+sqrt(2))*s^2 where s = side length
909        // For circumscribed circle radius R=0.1, s = 2*R*sin(pi/8)
910        let r = 0.1_f64;
911        let s = 2.0 * r * (PI / 8.0).sin();
912        let outer_area = 2.0 * (1.0 + 2.0_f64.sqrt()) * s * s;
913        // Inner is scaled by (a_in/a_out)^2
914        let a_out = r * (PI / 8.0).cos();
915        let a_in = a_out - 0.006;
916        let inner_area = outer_area * (a_in / a_out).powi(2);
917        let expected = outer_area - inner_area;
918        assert!(
919            (sec.area() - expected).abs() / expected < 0.05,
920            "PHS area: got {}, expected {}",
921            sec.area(),
922            expected
923        );
924    }
925
926    #[test]
927    fn polygon_hollow_with_radius() {
928        let phs = PolygonHollowSection::with_radius(0.2, 0.006, 8, 0.02, 12, 0.0);
929        let sec = phs.build();
930        assert!(sec.area() > 0.0);
931    }
932
933    #[test]
934    fn triangular_radius_section() {
935        let tri = TriangularRadiusSection::new(0.06, 16);
936        let sec = tri.build();
937        // Area should be less than the full triangle (b*b/2) due to concave hypotenuse
938        let full_triangle = 0.5 * 0.06 * 0.06;
939        assert!(sec.area() < full_triangle);
940        assert!(sec.area() > 0.0);
941    }
942}