1use crate::geometry::{Point, Polygon, segments_interact};
2
3#[derive(Debug, Clone)]
5pub struct Section {
6 pub outer: Polygon,
8 pub holes: Vec<Polygon>,
10}
11
12impl Section {
13 pub fn new(mut outer: Polygon, mut holes: Vec<Polygon>) -> Self {
18 if outer.signed_area() < 0.0 {
23 outer.vertices.reverse();
24 }
25
26 for hole in &mut holes {
27 if hole.signed_area() > 0.0 {
28 hole.vertices.reverse();
29 }
30 }
31
32 Self { outer, holes }
33 }
34
35 pub fn area(&self) -> f64 {
37 let mut a = self.outer.area();
38 for h in &self.holes {
39 a -= h.area();
40 }
41 a
42 }
43
44 pub fn centroid(&self) -> Point {
52 self.try_centroid()
53 .expect("Section area is too small to compute centroid")
54 }
55
56 pub fn try_centroid(&self) -> Option<Point> {
59 let mut sum_x = 0.0;
60 let mut sum_y = 0.0;
61 let mut total_area = 0.0;
62
63 let outer_c = self.outer.centroid();
65 let outer_a = self.outer.area();
66 sum_x += outer_c.x * outer_a;
67 sum_y += outer_c.y * outer_a;
68 total_area += outer_a;
69
70 for h in &self.holes {
72 let a = h.area(); let c = h.centroid();
74 sum_x -= c.x * a;
75 sum_y -= c.y * a;
76 total_area -= a;
77 }
78
79 if total_area.abs() <= f64::EPSILON {
80 return None;
81 }
82
83 Some(Point::new(sum_x / total_area, sum_y / total_area))
84 }
85
86 pub fn bounds(&self) -> (f64, f64, f64, f64) {
88 let mut min_x = f64::INFINITY;
89 let mut max_x = f64::NEG_INFINITY;
90 let mut min_y = f64::INFINITY;
91 let mut max_y = f64::NEG_INFINITY;
92
93 for v in &self.outer.vertices {
94 min_x = min_x.min(v.x);
95 max_x = max_x.max(v.x);
96 min_y = min_y.min(v.y);
97 max_y = max_y.max(v.y);
98 }
99 for hole in &self.holes {
100 for v in &hole.vertices {
101 min_x = min_x.min(v.x);
102 max_x = max_x.max(v.x);
103 min_y = min_y.min(v.y);
104 max_y = max_y.max(v.y);
105 }
106 }
107 (min_x, max_x, min_y, max_y)
108 }
109
110 pub fn width(&self) -> f64 {
112 let (min_x, max_x, _, _) = self.bounds();
113 max_x - min_x
114 }
115
116 pub fn height(&self) -> f64 {
118 let (_, _, min_y, max_y) = self.bounds();
119 max_y - min_y
120 }
121
122 pub fn contains_point(&self, point: Point) -> bool {
124 if !self.outer.contains_point(point) {
126 return false;
127 }
128 for hole in &self.holes {
130 if hole.contains_point(point) {
131 return false;
132 }
133 }
134 true
135 }
136
137 pub fn perimeter(&self) -> f64 {
139 let mut p = self.outer.perimeter();
140 for hole in &self.holes {
141 p += hole.perimeter();
142 }
143 p
144 }
145
146 pub fn frame_properties(&self, nu: f64) -> (f64, f64, f64, f64, f64, f64) {
158 use crate::plastic::warping::WarpingProperties;
159 use crate::section_properties::SectionProperties;
160
161 let props = SectionProperties::from_section(self);
162 let warping = WarpingProperties::from_section(self, nu);
163 let principal = props.principal_properties();
164
165 (
166 props.area,
167 props.ix,
168 props.iy,
169 props.ixy,
170 warping.j,
171 principal.phi,
172 )
173 }
174
175 pub fn frame_properties_with_material(
190 &self,
191 material: &crate::material::Material,
192 ) -> Result<TransformedFrameProperties, MaterialError> {
193 if !material.is_valid() {
194 return Err(MaterialError::InvalidMaterial(format!(
195 "E={}, G={}, nu={}, rho={}",
196 material.youngs_modulus,
197 material.shear_modulus,
198 material.poissons_ratio,
199 material.density
200 )));
201 }
202
203 let fp = self.frame_properties_full(material.poissons_ratio);
204 let e = material.youngs_modulus;
205 let g = material.shear_modulus;
206
207 Ok(TransformedFrameProperties {
208 e_ref: e,
209 area: fp.area,
210 ea: e * fp.area,
211 ei_xx: e * fp.ixx,
212 ei_yy: e * fp.iyy,
213 ei_w: e * fp.iw,
214 gj: g * fp.j,
215 mass_per_length: material.density * fp.area,
216 geometric: fp,
217 })
218 }
219}
220
221#[derive(Debug, Clone, Copy)]
224pub struct FrameProperties {
225 pub area: f64,
227 pub ixx: f64,
229 pub iyy: f64,
231 pub ixy: f64,
233 pub j: f64,
235 pub phi: f64,
237 pub i11: f64,
239 pub i22: f64,
241 pub delta_x: f64,
243 pub delta_y: f64,
245 pub iw: f64,
247}
248
249#[derive(Debug, Clone, PartialEq, Eq)]
252pub enum MaterialError {
253 InvalidMaterial(String),
256}
257
258impl std::fmt::Display for MaterialError {
259 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
260 match self {
261 MaterialError::InvalidMaterial(reason) => {
262 write!(f, "invalid material: {reason}")
263 }
264 }
265 }
266}
267
268impl std::error::Error for MaterialError {}
269
270#[derive(Debug, Clone, Copy)]
282pub struct TransformedFrameProperties {
283 pub e_ref: f64,
285 pub area: f64,
287 pub ea: f64,
289 pub ei_xx: f64,
291 pub ei_yy: f64,
293 pub ei_w: f64,
295 pub gj: f64,
297 pub mass_per_length: f64,
299 pub geometric: FrameProperties,
301}
302
303impl Section {
304 pub fn frame_properties_full(&self, nu: f64) -> FrameProperties {
309 use crate::plastic::warping::WarpingProperties;
310 use crate::section_properties::SectionProperties;
311
312 let props = SectionProperties::from_section(self);
313 let principal = props.principal_properties();
314 let warping = WarpingProperties::from_section(self, nu);
315
316 FrameProperties {
317 area: props.area,
318 ixx: props.ix,
319 iyy: props.iy,
320 ixy: props.ixy,
321 j: warping.j,
322 phi: principal.phi,
323 i11: principal.i11,
324 i22: principal.i22,
325 delta_x: warping.shear_center.x,
326 delta_y: warping.shear_center.y,
327 iw: warping.iw,
328 }
329 }
330
331 pub fn validate(&self) -> Result<(), String> {
344 for (hi, hole) in self.holes.iter().enumerate() {
346 for v in &hole.vertices {
347 if !self.outer.contains_point(*v) {
348 return Err(format!(
349 "Hole {} vertex {:?} lies outside outer boundary",
350 hi, v
351 ));
352 }
353 }
354
355 for i in 0..hole.vertices.len() {
357 let h1 = hole.vertices[i];
358 let h2 = hole.vertices[(i + 1) % hole.vertices.len()];
359 for j in 0..self.outer.vertices.len() {
360 let o1 = self.outer.vertices[j];
361 let o2 = self.outer.vertices[(j + 1) % self.outer.vertices.len()];
362 if segments_interact(h1, h2, o1, o2) {
363 return Err(format!(
364 "Hole {} edge ({:?}-{:?}) intersects outer boundary",
365 hi, h1, h2
366 ));
367 }
368 }
369 }
370 }
371
372 let n = self.holes.len();
374 for i in 0..n {
375 for j in (i + 1)..n {
376 let hi = &self.holes[i];
377 let hj = &self.holes[j];
378
379 let i_contains_j = hj.vertices.iter().all(|v| hi.contains_point(*v));
381 let j_contains_i = hi.vertices.iter().all(|v| hj.contains_point(*v));
382
383 if i_contains_j || j_contains_i {
384 return Err(format!(
385 "Holes {} and {} are nested (one contains the other)",
386 i, j
387 ));
388 }
389
390 for a in 0..hi.vertices.len() {
393 let h1 = hi.vertices[a];
394 let h2 = hi.vertices[(a + 1) % hi.vertices.len()];
395 for b in 0..hj.vertices.len() {
396 let h3 = hj.vertices[b];
397 let h4 = hj.vertices[(b + 1) % hj.vertices.len()];
398 if segments_interact(h1, h2, h3, h4) {
399 return Err(format!("Holes {} and {} have intersecting edges", i, j));
400 }
401 }
402 }
403 }
404 }
405
406 if self.outer.signed_area() < 0.0 {
408 return Err("Outer boundary must be CCW (positive area)".into());
409 }
410 for (hi, hole) in self.holes.iter().enumerate() {
411 if hole.signed_area() > 0.0 {
412 return Err(format!("Hole {} must be CW (negative area)", hi));
413 }
414 }
415
416 Ok(())
417 }
418
419 pub fn new_validated(outer: Polygon, holes: Vec<Polygon>) -> Result<Self, String> {
430 let section = Self::new(outer, holes);
431 section.validate()?;
432 Ok(section)
433 }
434}
435
436impl crate::section_library::ParametricSection for Section {
437 fn build(&self) -> Section {
438 self.clone()
439 }
440
441 fn designation(&self) -> String {
442 "Section".to_string()
443 }
444}
445
446#[cfg(test)]
447mod tests {
448 use super::*;
449 use crate::section_library::ParametricSection;
450
451 #[test]
452 fn frame_properties_full_i_section() {
453 let i = crate::section_library::steel::ISection::from_designation("IPE300").unwrap();
454 let sec = i.build();
455 let fp = sec.frame_properties_full(0.3);
456 assert!(fp.area > 0.0);
457 assert!(fp.iw.abs() > 0.0, "I-section must have warping constant");
458 let c = sec.centroid();
460 assert!((fp.delta_x - c.x).abs() < 5e-3);
461 assert!((fp.delta_y - c.y).abs() < 5e-3);
462 assert!((fp.j / (fp.area * 1e6)).abs() < 1e3); }
464
465 #[test]
466 fn geometry_from_points_rectangle() {
467 let pts = vec![
468 Point::new(0.0, 0.0),
469 Point::new(0.2, 0.0),
470 Point::new(0.2, 0.1),
471 Point::new(0.0, 0.1),
472 ];
473 let g = crate::geometry::Geometry::from_points(pts, vec![]);
474 assert!((g.area() - 0.02).abs() < 1e-12);
475
476 let outer = vec![
477 Point::new(0.0, 0.0),
478 Point::new(4.0, 0.0),
479 Point::new(4.0, 4.0),
480 Point::new(0.0, 4.0),
481 ];
482 let hole = vec![
483 Point::new(1.0, 1.0),
484 Point::new(3.0, 1.0),
485 Point::new(3.0, 3.0),
486 Point::new(1.0, 3.0),
487 ];
488 let g2 = crate::geometry::Geometry::from_points(outer, vec![hole]);
489 assert!((g2.area() - 12.0).abs() < 1e-12);
490 }
491
492 #[test]
493 fn frame_properties_with_material_rejects_invalid() {
494 let sec = crate::section_library::primitive::RectangularSection::new(0.1, 0.2).build();
495 let mut bad = crate::material::Material::default();
496 bad.youngs_modulus = -1.0;
497 assert!(sec.frame_properties_with_material(&bad).is_err());
498 }
499
500 #[test]
501 fn transformed_frame_properties_scale_with_e() {
502 let sec = crate::section_library::primitive::RectangularSection::new(0.1, 0.2).build();
503 let geo = sec.frame_properties_full(0.3);
504
505 let steel = crate::material::presets::STEEL_S355;
506 let t_steel = sec.frame_properties_with_material(&steel).unwrap();
507 assert!((t_steel.ea - steel.youngs_modulus * t_steel.area).abs() < 1e-6);
508 assert!((t_steel.ei_xx - steel.youngs_modulus * geo.ixx).abs() < 1e-9);
509 let g_expected = steel.shear_modulus;
511 assert!((t_steel.gj - g_expected * geo.j).abs() < 1e-3);
512
513 let alu = crate::material::Material::new(69e9, 0.33, 2700.0, "alu");
515 let t_alu = sec.frame_properties_with_material(&alu).unwrap();
516 let ratio = t_alu.ei_xx / t_steel.ei_xx;
517 assert!((ratio - alu.youngs_modulus / steel.youngs_modulus).abs() < 1e-9);
518 assert!((t_alu.mass_per_length - 2700.0 * t_alu.area).abs() < 1e-9);
520 }
521
522 #[test]
523 fn section_new_validated_rejects_hole_outside_outer() {
524 let outer = crate::geometry::Polygon::new(vec![
525 Point::new(0.0, 0.0),
526 Point::new(10.0, 0.0),
527 Point::new(10.0, 10.0),
528 Point::new(0.0, 10.0),
529 ]);
530 let hole = crate::geometry::Polygon::new(vec![
531 Point::new(11.0, 11.0),
532 Point::new(12.0, 11.0),
533 Point::new(12.0, 12.0),
534 Point::new(11.0, 12.0),
535 ]);
536 let err = Section::new_validated(outer, vec![hole]).unwrap_err();
537 assert!(err.contains("outside outer boundary"));
538 }
539
540 #[test]
541 fn section_new_validated_rejects_nested_holes() {
542 let outer = crate::geometry::Polygon::new(vec![
543 Point::new(0.0, 0.0),
544 Point::new(10.0, 0.0),
545 Point::new(10.0, 10.0),
546 Point::new(0.0, 10.0),
547 ]);
548 let hole_outer = crate::geometry::Polygon::new(vec![
549 Point::new(1.0, 1.0),
550 Point::new(9.0, 1.0),
551 Point::new(9.0, 9.0),
552 Point::new(1.0, 9.0),
553 ]);
554 let hole_inner = crate::geometry::Polygon::new(vec![
555 Point::new(3.0, 3.0),
556 Point::new(5.0, 3.0),
557 Point::new(5.0, 5.0),
558 Point::new(3.0, 5.0),
559 ]);
560 let err = Section::new_validated(outer, vec![hole_outer, hole_inner]).unwrap_err();
561 assert!(err.contains("nested"));
562 }
563
564 #[test]
565 fn section_new_validated_rejects_overlapping_holes() {
566 let outer = crate::geometry::Polygon::new(vec![
567 Point::new(0.0, 0.0),
568 Point::new(10.0, 0.0),
569 Point::new(10.0, 10.0),
570 Point::new(0.0, 10.0),
571 ]);
572 let hole_a = crate::geometry::Polygon::new(vec![
573 Point::new(1.0, 1.0),
574 Point::new(5.0, 1.0),
575 Point::new(5.0, 5.0),
576 Point::new(1.0, 5.0),
577 ]);
578 let hole_b = crate::geometry::Polygon::new(vec![
579 Point::new(3.0, 3.0),
580 Point::new(7.0, 3.0),
581 Point::new(7.0, 7.0),
582 Point::new(3.0, 7.0),
583 ]);
584 let err = Section::new_validated(outer, vec![hole_a, hole_b]).unwrap_err();
585 assert!(err.contains("intersecting edges") || err.contains("nested"));
586 }
587
588 #[test]
589 fn section_new_validated_accepts_valid_section() {
590 let outer = crate::geometry::Polygon::new(vec![
591 Point::new(0.0, 0.0),
592 Point::new(10.0, 0.0),
593 Point::new(10.0, 10.0),
594 Point::new(0.0, 10.0),
595 ]);
596 let hole_a = crate::geometry::Polygon::new(vec![
597 Point::new(1.0, 1.0),
598 Point::new(4.0, 1.0),
599 Point::new(4.0, 4.0),
600 Point::new(1.0, 4.0),
601 ]);
602 let hole_b = crate::geometry::Polygon::new(vec![
603 Point::new(6.0, 6.0),
604 Point::new(9.0, 6.0),
605 Point::new(9.0, 9.0),
606 Point::new(6.0, 9.0),
607 ]);
608 let section = Section::new_validated(outer, vec![hole_a, hole_b]).unwrap();
609 assert_eq!(section.holes.len(), 2);
610 }
611
612 fn rect_frame_props(mat: &crate::material::Material) -> TransformedFrameProperties {
618 let sec = crate::section_library::primitive::RectangularSection::new(0.1, 0.2).build();
619 sec.frame_properties_with_material(mat).unwrap()
620 }
621
622 #[test]
626 fn gj_uses_material_shear_modulus_timber() {
627 use crate::material::presets::TIMBER_GL24H;
628
629 let t = rect_frame_props(&TIMBER_GL24H);
630 let fp = {
631 let sec = crate::section_library::primitive::RectangularSection::new(0.1, 0.2).build();
632 sec.frame_properties_full(TIMBER_GL24H.poissons_ratio)
633 };
634
635 let gj_expected = TIMBER_GL24H.shear_modulus * fp.j;
637 assert!(
638 (t.gj - gj_expected).abs() < 1e-3,
639 "GJ ({:.6e}) must use shear_modulus * J ({:.6e})",
640 t.gj,
641 gj_expected
642 );
643
644 let g_iso = TIMBER_GL24H.youngs_modulus / (2.0 * (1.0 + TIMBER_GL24H.poissons_ratio));
646 let gj_iso = g_iso * fp.j;
647 assert!(
648 (t.gj - gj_iso).abs() > 1e3,
649 "GJ ({:.6e}) must NOT use isotropic G * J ({:.6e})",
650 t.gj,
651 gj_iso
652 );
653 }
654
655 #[test]
658 fn gj_uses_independent_shear_modulus() {
659 let mat = crate::material::Material::with_all(
660 100e9, 10e9, 0.30, 5000.0, 0.0, 0.0, 0.0, "custom",
664 );
665
666 let t = rect_frame_props(&mat);
667 let fp = {
668 let sec = crate::section_library::primitive::RectangularSection::new(0.1, 0.2).build();
669 sec.frame_properties_full(mat.poissons_ratio)
670 };
671
672 let gj_expected = mat.shear_modulus * fp.j;
673 assert!(
674 (t.gj - gj_expected).abs() < 1e-3,
675 "GJ ({:.6e}) must use independent G * J ({:.6e})",
676 t.gj,
677 gj_expected
678 );
679 }
680
681 #[test]
684 fn gj_isotropic_materials_unchanged() {
685 use crate::material::presets::*;
686
687 for mat in &[STEEL_S355, ALUMINUM_6061_T6, CONCRETE_C25_30] {
688 let t = rect_frame_props(mat);
689 let fp = {
690 let sec =
691 crate::section_library::primitive::RectangularSection::new(0.1, 0.2).build();
692 sec.frame_properties_full(mat.poissons_ratio)
693 };
694
695 let gj_from_stored = mat.shear_modulus * fp.j;
698 let g_iso = mat.youngs_modulus / (2.0 * (1.0 + mat.poissons_ratio));
699 let gj_from_iso = g_iso * fp.j;
700
701 assert!(
702 (t.gj - gj_from_stored).abs() < 1e-3,
703 "{}: GJ ({:.6e}) must use stored G * J ({:.6e})",
704 mat.name,
705 t.gj,
706 gj_from_stored
707 );
708 assert!(
710 (t.gj - gj_from_iso).abs() / gj_from_stored.abs() < 0.01,
711 "{}: GJ should be close to isotropic (stored={:.6e}, iso={:.6e})",
712 mat.name,
713 gj_from_stored,
714 gj_from_iso
715 );
716 }
717 }
718
719 #[test]
726 fn gj_never_recomputed_from_e_and_nu() {
727 use crate::material::presets::*;
728
729 let mats = [
730 STEEL_S235,
731 STEEL_S275,
732 STEEL_S355,
733 STEEL_S460,
734 STAINLESS_304,
735 STAINLESS_316,
736 ALUMINUM_6061_T6,
737 ALUMINUM_6063_T5,
738 ALUMINUM_7075_T6,
739 CONCRETE_C25_30,
740 CONCRETE_C30_37,
741 CONCRETE_C40_50,
742 TIMBER_GL24H,
743 TITANIUM_GR5,
744 ];
745
746 for mat in mats {
747 let t = rect_frame_props(&mat);
748 let j = t.geometric.j;
749 assert!(
750 j > 0.0 && j.is_finite(),
751 "{}: J must be finite and > 0, got {j}",
752 mat.name
753 );
754
755 let expected = mat.shear_modulus * j;
756 let rel = (t.gj - expected).abs() / expected.abs();
757 assert!(
758 rel < 1e-12,
759 "{}: gj={:.6e} but shear_modulus*J={:.6e} (rel={:.3e}); G was recomputed from E and nu",
760 mat.name,
761 t.gj,
762 expected,
763 rel
764 );
765 }
766 }
767
768 #[test]
771 fn gj_independent_of_nu_for_fixed_shear_modulus() {
772 for nu in [0.2, 0.3, 0.35] {
773 let mat = crate::material::Material::with_all(
774 200e9,
775 1e9,
776 nu,
777 7850.0,
778 1.2e-5,
779 355e6,
780 510e6,
781 "synthetic-g",
782 );
783 assert!(mat.is_valid(), "synthetic material must be valid");
784
785 let t = rect_frame_props(&mat);
786 let expected = mat.shear_modulus * t.geometric.j;
787 let rel = (t.gj - expected).abs() / expected.abs();
788 assert!(
789 rel < 1e-12,
790 "nu={nu}: gj={:.6e} but G*J={:.6e} (rel={:.3e})",
791 t.gj,
792 expected,
793 rel
794 );
795 }
796 }
797}