1use std::f64::consts::PI;
71
72use hpr_core::quadrature::{Tolerance, integrate};
73use hpr_core::{DMat3, DQuat, DVec3};
74use serde::{Deserialize, Serialize};
75
76use crate::error::DesignError;
77use crate::mass::MassProperties;
78use crate::material::Material;
79use crate::shapes::{Profile, check_dimension};
80
81#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
83#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
84#[non_exhaustive]
85pub enum FinPlanform {
86 Trapezoidal {
88 root_chord_m: f64,
90 tip_chord_m: f64,
92 span_m: f64,
94 sweep_m: f64,
96 },
97 Elliptical {
99 root_chord_m: f64,
101 span_m: f64,
103 },
104 Freeform {
109 points_m: Vec<[f64; 2]>,
111 #[serde(default, skip_serializing_if = "Vec::is_empty")]
114 root_m: Vec<[f64; 2]>,
115 },
116}
117
118#[derive(
120 Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize, schemars::JsonSchema,
121)]
122#[serde(rename_all = "snake_case")]
123#[non_exhaustive]
124pub enum FinCrossSection {
125 #[default]
127 Square,
128 Rounded,
130 Airfoil,
132}
133
134#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
144#[serde(deny_unknown_fields)]
145pub struct FinTab {
146 pub height_m: f64,
148 pub length_m: f64,
150 pub offset_m: f64,
153}
154
155#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
157#[serde(deny_unknown_fields)]
158pub struct FinFillet {
159 pub radius_m: f64,
161 pub material: Material,
163}
164
165#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
167#[serde(deny_unknown_fields)]
168pub struct FinSet {
169 pub count: u32,
171 pub planform: FinPlanform,
173 pub thickness_m: f64,
175 #[serde(default)]
177 pub cross_section: FinCrossSection,
178 #[serde(default)]
180 pub tab: Option<FinTab>,
181 #[serde(default, skip_serializing_if = "Option::is_none")]
183 pub fillet: Option<FinFillet>,
184 #[serde(default)]
186 pub cant_rad: f64,
187 #[serde(default)]
189 pub base_angle_rad: f64,
190 pub material: Material,
192}
193
194#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
196pub struct PlanformGeometry {
197 pub area_m2: f64,
199 pub centroid_x_m: f64,
201 pub centroid_span_m: f64,
203}
204
205#[cfg(test)]
208fn naca_polynomial(xi: f64) -> f64 {
209 0.2969 * xi.sqrt() - 0.1260 * xi - 0.3516 * xi * xi + 0.2843 * xi.powi(3) - 0.1015 * xi.powi(4)
210}
211
212const AIRFOIL_PHI: [f64; 3] = [
214 10.0 * (0.2969 * 2.0 / 3.0 - 0.1260 / 2.0 - 0.3516 / 3.0 + 0.2843 / 4.0 - 0.1015 / 5.0),
215 10.0 * (0.2969 * 2.0 / 5.0 - 0.1260 / 3.0 - 0.3516 / 4.0 + 0.2843 / 5.0 - 0.1015 / 6.0),
216 10.0 * (0.2969 * 2.0 / 7.0 - 0.1260 / 4.0 - 0.3516 / 5.0 + 0.2843 / 6.0 - 0.1015 / 7.0),
217];
218
219const AIRFOIL_PSI: f64 = 0.472_889_488_894_451_523_708_489_652_762;
222
223fn chord_moments(section: FinCrossSection, a: f64, b: f64, t: f64) -> [f64; 4] {
225 let c = b - a;
226 if c <= 0.0 {
227 return [0.0; 4];
228 }
229 match section {
230 FinCrossSection::Square => [
231 t * c,
232 0.5 * t * (b * b - a * a),
233 t * (b.powi(3) - a.powi(3)) / 3.0,
234 t.powi(3) * c / 12.0,
235 ],
236 FinCrossSection::Airfoil => {
237 let [p0, p1, p2] = AIRFOIL_PHI;
238 [
239 t * c * p0,
240 t * (a * c * p0 + c * c * p1),
241 t * (a * a * c * p0 + 2.0 * a * c * c * p1 + c.powi(3) * p2),
242 t.powi(3) * c * AIRFOIL_PSI / 12.0,
243 ]
244 }
245 FinCrossSection::Rounded => {
246 let mid = t.min(c);
250 let r = 0.5 * mid;
251 let d0 = r * r * (2.0 - PI / 2.0);
252 let d1 = r * d0 - r.powi(3) / 3.0;
253 let d2 = r * r * d0 - PI * r.powi(4) / 8.0;
254 let e0 = 8.0 * r.powi(4) - 1.5 * PI * r.powi(4);
255 let m0 = mid * c - 2.0 * d0;
256 [
257 m0,
258 m0 * 0.5 * (a + b),
259 mid * (b.powi(3) - a.powi(3)) / 3.0
260 - (a * a * d0 + 2.0 * a * d1 + d2)
261 - (b * b * d0 - 2.0 * b * d1 + d2),
262 (mid.powi(3) * c - 2.0 * e0) / 12.0,
263 ]
264 }
265 }
266}
267
268impl FinPlanform {
269 pub fn root_chord_m(&self) -> f64 {
271 match self {
272 Self::Trapezoidal { root_chord_m, .. } | Self::Elliptical { root_chord_m, .. } => {
273 *root_chord_m
274 }
275 Self::Freeform { points_m, .. } => points_m.last().map_or(0.0, |p| p[0]),
276 }
277 }
278
279 pub fn aft_extent_m(&self) -> f64 {
284 match self {
285 Self::Trapezoidal {
286 root_chord_m,
287 tip_chord_m,
288 sweep_m,
289 ..
290 } => root_chord_m.max(sweep_m + tip_chord_m),
291 Self::Elliptical { root_chord_m, .. } => *root_chord_m,
292 Self::Freeform { points_m, root_m } => points_m
293 .iter()
294 .chain(root_m)
295 .fold(self.root_chord_m(), |m, p| m.max(p[0])),
296 }
297 }
298
299 pub fn span_m(&self) -> f64 {
301 match self {
302 Self::Trapezoidal { span_m, .. } | Self::Elliptical { span_m, .. } => *span_m,
303 Self::Freeform { points_m, root_m } => {
304 points_m.iter().chain(root_m).fold(0.0, |m, p| m.max(p[1]))
305 }
306 }
307 }
308
309 pub fn validate(&self) -> Result<(), DesignError> {
316 match self {
317 Self::Trapezoidal {
318 root_chord_m,
319 tip_chord_m,
320 span_m,
321 sweep_m,
322 } => {
323 check_dimension("fin root chord", *root_chord_m, false)?;
324 check_dimension("fin tip chord", *tip_chord_m, true)?;
325 check_dimension("fin span", *span_m, false)?;
326 if !sweep_m.is_finite() {
327 return Err(DesignError::Domain {
328 what: "fin sweep",
329 value: *sweep_m,
330 });
331 }
332 }
333 Self::Elliptical {
334 root_chord_m,
335 span_m,
336 } => {
337 check_dimension("fin root chord", *root_chord_m, false)?;
338 check_dimension("fin span", *span_m, false)?;
339 }
340 Self::Freeform { points_m, root_m } => validate_outline(points_m, root_m)?,
341 }
342 Ok(())
343 }
344
345 pub fn chords_at(&self, h: f64, out: &mut Vec<(f64, f64)>) {
349 out.clear();
350 match self {
351 Self::Trapezoidal {
352 root_chord_m,
353 tip_chord_m,
354 span_m,
355 sweep_m,
356 } => {
357 if (0.0..*span_m).contains(&h) {
358 let f = h / span_m;
359 let lead = sweep_m * f;
360 out.push((lead, lead + root_chord_m + (tip_chord_m - root_chord_m) * f));
361 }
362 }
363 Self::Elliptical {
364 root_chord_m,
365 span_m,
366 } => {
367 if (0.0..*span_m).contains(&h) {
368 let f = h / span_m;
369 let chord = root_chord_m * (1.0 - f * f).max(0.0).sqrt();
370 let lead = 0.5 * (root_chord_m - chord);
371 out.push((lead, lead + chord));
372 }
373 }
374 Self::Freeform { points_m, root_m } => {
375 let mut crossings: Vec<f64> = Vec::new();
376 let polygon = || points_m.iter().chain(root_m);
377 for (&p, &q) in polygon().zip(polygon().cycle().skip(1)) {
378 let (lo, hi) = (p[1].min(q[1]), p[1].max(q[1]));
379 if p[1] != q[1] && h >= lo && h < hi {
380 crossings.push(p[0] + (h - p[1]) * (q[0] - p[0]) / (q[1] - p[1]));
381 }
382 }
383 crossings.sort_by(f64::total_cmp);
384 let (pairs, _) = crossings.as_chunks::<2>();
385 out.extend(pairs.iter().map(|&[a, b]| (a, b)));
386 }
387 }
388 }
389
390 fn breakpoints(&self) -> Vec<f64> {
392 let mut points = vec![0.0, self.span_m()];
393 if let Self::Freeform { points_m, root_m } = self {
394 points.extend(points_m.iter().chain(root_m).map(|p| p[1]));
395 }
396 points.sort_by(f64::total_cmp);
397 points.dedup();
398 points
399 }
400
401 pub fn geometry(&self) -> Result<PlanformGeometry, DesignError> {
407 self.validate()?;
408 let scale = self.root_chord_m() + self.span_m();
409 let mut chords = Vec::new();
410 let mut total = [0.0; 3];
411 for pair in self.breakpoints().windows(2) {
412 let piece = integrate(
413 |h| {
414 self.chords_at(h * scale, &mut chords);
415 chords.iter().fold([0.0; 3], |acc, &(a, b)| {
416 let (a, b) = (a / scale, b / scale);
417 [
418 acc[0] + (b - a),
419 acc[1] + 0.5 * (b * b - a * a),
420 acc[2] + h * (b - a),
421 ]
422 })
423 },
424 pair[0] / scale,
425 pair[1] / scale,
426 PLATE,
427 )?;
428 for (sum, value) in total.iter_mut().zip(piece.value) {
429 *sum += value;
430 }
431 }
432 let area = total[0] * scale * scale;
433 if area <= 0.0 {
434 return Err(DesignError::Geometry("the fin has no area".to_owned()));
435 }
436 Ok(PlanformGeometry {
437 area_m2: area,
438 centroid_x_m: scale * total[1] / total[0],
439 centroid_span_m: scale * total[2] / total[0],
440 })
441 }
442}
443
444const PLATE: Tolerance = Tolerance {
446 relative: 1e-12,
447 absolute: 1e-16,
448 max_intervals: 4000,
449};
450
451fn validate_outline(outline: &[[f64; 2]], root: &[[f64; 2]]) -> Result<(), DesignError> {
455 if outline.len() < 3 {
456 return Err(DesignError::Geometry(format!(
457 "a freeform fin needs at least 3 points, got {}",
458 outline.len()
459 )));
460 }
461 let points: Vec<[f64; 2]> = outline.iter().chain(root).copied().collect();
462 for p in &points {
463 for (what, value) in [("freeform fin x", p[0]), ("freeform fin span", p[1])] {
464 if !value.is_finite() {
465 return Err(DesignError::Domain { what, value });
466 }
467 }
468 if p[1] < 0.0 {
469 return Err(DesignError::Domain {
470 what: "freeform fin span",
471 value: p[1],
472 });
473 }
474 }
475 let (first, last) = (outline[0], outline[outline.len() - 1]);
476 if first != [0.0, 0.0] || last[0] <= 0.0 {
477 return Err(DesignError::Geometry(
478 "a freeform fin must start at the root leading edge [0, 0] and end at the root \
479 trailing edge [c, h] with c > 0"
480 .to_owned(),
481 ));
482 }
483 let mut aft = last[0];
485 for p in root {
486 if !(p[0] < aft && p[0] > 0.0) {
487 return Err(DesignError::Geometry(format!(
488 "a freeform fin's root points must run fore, strictly between its trailing edge \
489 at x = {} m and its leading edge. One is at x = {} m",
490 last[0], p[0]
491 )));
492 }
493 aft = p[0];
494 }
495 let points = points.as_slice();
496 let n = points.len();
497 let edge = |i: usize| (points[i], points[(i + 1) % n]);
498 for i in 0..n {
499 for j in (i + 1)..n {
500 if j == i + 1 || (i == 0 && j == n - 1) {
502 continue;
503 }
504 let (p, q) = edge(i);
505 let (r, s) = edge(j);
506 if segments_touch(p, q, r, s) {
507 return Err(DesignError::Geometry(format!(
508 "the freeform fin outline crosses itself (edges {i} and {j})"
509 )));
510 }
511 }
512 }
513 let twice_area: f64 = (0..n)
514 .map(|i| {
515 let (p, q) = edge(i);
516 p[0] * q[1] - q[0] * p[1]
517 })
518 .sum();
519 if twice_area == 0.0 {
520 return Err(DesignError::Geometry("the fin has no area".to_owned()));
521 }
522 if twice_area > 0.0 {
526 return Err(DesignError::Geometry(
527 "the freeform fin outline runs below its root".to_owned(),
528 ));
529 }
530 Ok(())
531}
532
533fn segments_touch(p: [f64; 2], q: [f64; 2], r: [f64; 2], s: [f64; 2]) -> bool {
535 let cross = |o: [f64; 2], a: [f64; 2], b: [f64; 2]| {
536 (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
537 };
538 let within = |a: [f64; 2], b: [f64; 2], c: [f64; 2]| {
539 c[0] >= a[0].min(b[0])
540 && c[0] <= a[0].max(b[0])
541 && c[1] >= a[1].min(b[1])
542 && c[1] <= a[1].max(b[1])
543 };
544 let d1 = cross(r, s, p);
545 let d2 = cross(r, s, q);
546 let d3 = cross(p, q, r);
547 let d4 = cross(p, q, s);
548 if ((d1 > 0.0 && d2 < 0.0) || (d1 < 0.0 && d2 > 0.0))
549 && ((d3 > 0.0 && d4 < 0.0) || (d3 < 0.0 && d4 > 0.0))
550 {
551 return true;
552 }
553 (d1 == 0.0 && within(r, s, p))
554 || (d2 == 0.0 && within(r, s, q))
555 || (d3 == 0.0 && within(p, q, r))
556 || (d4 == 0.0 && within(p, q, s))
557}
558
559type PlateIntegrals = [f64; 7];
562
563impl FinSet {
564 pub const ROOT_ON_SURFACE_M: f64 = 1e-6;
568
569 pub const ROOT_SLIVER_SHARE: f64 = 1e-3;
575
576 fn root_points(&self) -> Vec<[f64; 2]> {
579 let mut points = vec![[0.0, 0.0]];
580 match &self.planform {
581 FinPlanform::Freeform { points_m, root_m } => {
582 points.extend(root_m.iter().rev());
583 points.extend(points_m.last());
584 }
585 other => points.push([other.root_chord_m(), 0.0]),
586 }
587 points
588 }
589
590 pub fn check_level_root(&self) -> Result<(), DesignError> {
597 if self.root_points().iter().any(|p| p[1] != 0.0) {
598 return Err(DesignError::Geometry(
599 "a fin set on a body tube needs a level root: a freeform outline that ends at \
600 h = 0, with every root point there too"
601 .to_owned(),
602 ));
603 }
604 Ok(())
605 }
606
607 pub fn root_on_surface(&self, profile: &Profile, fore_m: f64) -> (f64, f64) {
614 let base = profile.radius_m(fore_m);
615 let miss = |[x, h]: [f64; 2]| h - (profile.radius_m(fore_m + x) - base);
616 let points = self.root_points();
617 let off = points
619 .iter()
620 .map(|&p| miss(p).abs())
621 .fold(0.0, |a: f64, m| {
622 if a.is_nan() || m.is_nan() {
623 f64::NAN
624 } else {
625 a.max(m)
626 }
627 });
628 let sliver = points
629 .windows(2)
630 .map(|pair| {
631 let middle = [
632 0.5 * (pair[0][0] + pair[1][0]),
633 0.5 * (pair[0][1] + pair[1][1]),
634 ];
635 2.0 / 3.0 * miss(middle).abs() * (pair[1][0] - pair[0][0])
636 })
637 .sum();
638 (off, sliver)
639 }
640 pub fn root_radius_on(&self, profile: &Profile, fore_m: f64) -> Result<f64, DesignError> {
651 let length = profile.length_m();
652 let chord = self.planform.root_chord_m();
653 let slack = Self::ROOT_ON_SURFACE_M;
654 if !(fore_m >= -slack && fore_m + chord <= length + slack) {
655 return Err(DesignError::Geometry(format!(
656 "a fin set's root runs from {fore_m} m to {} m along a body {length} m long. On a \
657 nose cone or a transition it must stay on it",
658 fore_m + chord
659 )));
660 }
661 if self.tab.is_some() || self.fillet.is_some() {
662 return Err(DesignError::Geometry(
663 "a fin set on a nose cone or a transition with a tab or a fillet: their models \
664 take a body tube"
665 .to_owned(),
666 ));
667 }
668 let (off, sliver) = self.root_on_surface(profile, fore_m);
669 if off.is_nan() || off > slack {
671 return Err(DesignError::Geometry(format!(
672 "a fin set's root stands {off} m off the surface of the nose cone or transition it \
673 sits on, at one of its points"
674 )));
675 }
676 let share = sliver / self.planform.geometry()?.area_m2;
677 if share.is_nan() || share > Self::ROOT_SLIVER_SHARE {
678 return Err(DesignError::Geometry(format!(
679 "a fin set's root cuts across the curved surface it sits on between its points, by \
680 {:.3}% of the fin's area, more than {}%. Draw it through more points on the \
681 surface",
682 100.0 * share,
683 100.0 * Self::ROOT_SLIVER_SHARE
684 )));
685 }
686 Ok(profile.radius_m(fore_m))
687 }
688
689 pub const MAX_COUNT: u32 = 64;
701
702 pub fn validate(&self) -> Result<(), DesignError> {
710 if self.count == 0 || self.count > Self::MAX_COUNT {
711 return Err(DesignError::Domain {
712 what: "fin count (1 to 64)",
713 value: f64::from(self.count),
714 });
715 }
716 self.planform.validate()?;
717 check_dimension("fin thickness", self.thickness_m, false)?;
718 for (what, value) in [
719 ("fin cant", self.cant_rad),
720 ("fin base angle", self.base_angle_rad),
721 ] {
722 if !value.is_finite() {
723 return Err(DesignError::Domain { what, value });
724 }
725 }
726 if let Some(fillet) = &self.fillet {
727 check_dimension("fin fillet radius", fillet.radius_m, true)?;
728 }
729 if let Some(tab) = self.tab {
730 check_dimension("fin tab height", tab.height_m, false)?;
731 check_dimension("fin tab length", tab.length_m, false)?;
732 if !tab.offset_m.is_finite() {
733 return Err(DesignError::Domain {
734 what: "fin tab offset",
735 value: tab.offset_m,
736 });
737 }
738 let root = self.planform.root_chord_m();
741 if tab.offset_m >= root || tab.offset_m + tab.length_m <= 0.0 {
742 return Err(DesignError::Geometry(format!(
743 "a fin tab must meet its fin's root chord, from 0 to {root} m, over some length"
744 )));
745 }
746 }
747 Ok(())
748 }
749
750 fn fin_integrals(&self, body_radius_m: f64) -> Result<PlateIntegrals, DesignError> {
752 let scale = self.planform.root_chord_m() + self.planform.span_m();
753 let rb = body_radius_m / scale;
754 let t = self.thickness_m / scale;
755 let mut chords = Vec::new();
756 let mut total = [0.0; 7];
757 for pair in self.planform.breakpoints().windows(2) {
758 let piece = integrate(
759 |h| {
760 self.planform.chords_at(h * scale, &mut chords);
761 let mut m = [0.0; 4];
762 for &(a, b) in &chords {
763 let c = chord_moments(self.cross_section, a / scale, b / scale, t);
764 for k in 0..4 {
765 m[k] += c[k];
766 }
767 }
768 let r = rb + h;
769 [m[0], r * m[0], r * r * m[0], m[1], m[2], r * m[1], m[3]]
770 },
771 pair[0] / scale,
772 pair[1] / scale,
773 PLATE,
774 )?;
775 for (sum, value) in total.iter_mut().zip(piece.value) {
776 *sum += value;
777 }
778 }
779 let powers = [3, 4, 5, 4, 5, 5, 5];
781 Ok(std::array::from_fn(|k| total[k] * scale.powi(powers[k])))
782 }
783
784 fn tab_integrals(&self, body_radius_m: f64) -> PlateIntegrals {
786 let Some(tab) = self.tab else {
787 return [0.0; 7];
788 };
789 let t = self.thickness_m;
790 let (x0, x1) = (tab.offset_m, tab.offset_m + tab.length_m);
791 let (r0, r1) = (body_radius_m - tab.height_m, body_radius_m);
792 let (h, l) = (tab.height_m, tab.length_m);
793 let r_first = 0.5 * (r1 * r1 - r0 * r0);
794 let x_first = 0.5 * (x1 * x1 - x0 * x0);
795 [
796 t * l * h,
797 t * l * r_first,
798 t * l * (r1.powi(3) - r0.powi(3)) / 3.0,
799 t * h * x_first,
800 t * h * (x1.powi(3) - x0.powi(3)) / 3.0,
801 t * x_first * r_first,
802 t.powi(3) / 12.0 * l * h,
803 ]
804 }
805
806 pub fn single_fin(&self, body_radius_m: f64) -> Result<MassProperties, DesignError> {
816 self.validate()?;
817 check_dimension("fin body radius", body_radius_m, true)?;
818 if let Some(tab) = self.tab
819 && tab.height_m > body_radius_m
820 {
821 return Err(DesignError::Geometry(format!(
822 "a fin tab must reach no deeper than the body radius ({body_radius_m} m)"
823 )));
824 }
825 let density = self.material.bulk_kg_m3("fin set")?;
826 let fin = self.fin_integrals(body_radius_m)?;
827 let tab = self.tab_integrals(body_radius_m);
828 let [v, r1, r2, x1, x2, rx, tau2] = std::array::from_fn(|k| fin[k] + tab[k]);
829 if v <= 0.0 {
830 return Err(DesignError::Geometry("the fin has no volume".to_owned()));
831 }
832 let mass = density * v;
833 let about_origin = DMat3::from_cols(
835 DVec3::new(tau2 + x2, 0.0, rx),
836 DVec3::new(0.0, r2 + x2, 0.0),
837 DVec3::new(rx, 0.0, r2 + tau2),
838 ) * density;
839 let cg = DVec3::new(r1 / v, 0.0, -x1 / v);
840 let at_origin = MassProperties {
841 mass_kg: mass,
842 cg_m: cg,
843 inertia_kg_m2: DMat3::ZERO,
844 };
845 let inertia = about_origin - at_origin.inertia_about(DVec3::ZERO);
847 let plate = MassProperties {
848 inertia_kg_m2: inertia,
849 ..at_origin
850 };
851 let fin = match self.fillets(body_radius_m)? {
852 Some(fillets) => MassProperties::combine([&plate, &fillets]),
853 None => plate,
854 };
855 let fin = if self.cant_rad == 0.0 {
856 fin
857 } else {
858 let pivot = DVec3::new(body_radius_m, 0.0, -0.5 * self.planform.root_chord_m());
859 fin.translated(-pivot)
860 .rotated(DQuat::from_rotation_x(self.cant_rad))
861 .translated(pivot)
862 };
863 fin.validate()?;
866 Ok(fin)
867 }
868
869 fn fillets(&self, body_radius_m: f64) -> Result<Option<MassProperties>, DesignError> {
881 let Some(fillet) = self.fillet.as_ref().filter(|f| f.radius_m > 0.0) else {
882 return Ok(None);
883 };
884 let density = fillet.material.bulk_kg_m3("fin fillet")?;
885 if body_radius_m == 0.0 {
887 return Ok(None);
888 }
889 let ratio = fillet.radius_m / body_radius_m;
895 if ratio < 1e-6 {
896 return Ok(None);
897 }
898 if ratio > FILLET_RATIO_MAX {
899 return Err(DesignError::Domain {
900 what: "fin fillet radius over the body radius (at most 1000)",
901 value: ratio,
902 });
903 }
904 let [area, sx, sxx, syy] = fillet_section(body_radius_m, fillet.radius_m);
905 if !(area > 0.0 && [sx, sxx, syy].iter().all(|v| v.is_finite())) {
907 return Err(DesignError::Domain {
908 what: "fin fillet section area",
909 value: area,
910 });
911 }
912 let l = self.planform.root_chord_m();
913 let mass = 2.0 * density * area * l;
914 if mass == 0.0 {
915 return Ok(None);
916 }
917 let ixz = density * sx * l * l;
918 let about_origin = DMat3::from_cols(
919 DVec3::new(2.0 * density * (syy * l + area * l.powi(3) / 3.0), 0.0, ixz),
920 DVec3::new(0.0, 2.0 * density * (sxx * l + area * l.powi(3) / 3.0), 0.0),
921 DVec3::new(ixz, 0.0, 2.0 * density * (sxx + syy) * l),
922 );
923 let at_origin = MassProperties {
924 mass_kg: mass,
925 cg_m: DVec3::new(sx / area, 0.0, -0.5 * l),
926 inertia_kg_m2: DMat3::ZERO,
927 };
928 Ok(Some(MassProperties {
929 inertia_kg_m2: about_origin - at_origin.inertia_about(DVec3::ZERO),
930 ..at_origin
931 }))
932 }
933
934 pub fn mass_properties(&self, body_radius_m: f64) -> Result<MassProperties, DesignError> {
940 let fin = self.single_fin(body_radius_m)?;
941 let fins: Vec<MassProperties> = (0..self.count)
942 .map(|k| {
943 fin.rolled(self.base_angle_rad + 2.0 * PI * f64::from(k) / f64::from(self.count))
944 })
945 .collect();
946 Ok(MassProperties::combine(&fins))
947 }
948}
949
950pub const FILLET_RATIO_MAX: f64 = 1e3;
952
953pub(crate) fn fillet_section(body_radius_m: f64, radius_m: f64) -> [f64; 4] {
960 let (rb, r) = (body_radius_m, radius_m);
961 let c = (rb * rb + 2.0 * rb * r).sqrt();
962 let theta = r.atan2(c);
963 let triangle_area = 0.5 * c * r;
965 let triangle = [
966 triangle_area,
967 triangle_area * 2.0 * c / 3.0,
968 triangle_area * c * c / 2.0,
969 triangle_area * r * r / 6.0,
970 ];
971 let body = sector([0.0, 0.0], rb, 0.0, theta);
972 let joint = sector([c, r], r, theta - PI, -0.5 * PI);
973 std::array::from_fn(|k| triangle[k] - body[k] - joint[k])
974}
975
976fn sector([x0, y0]: [f64; 2], rho: f64, from: f64, to: f64) -> [f64; 4] {
982 let (span, sum) = (to - from, to + from);
983 let area = 0.5 * rho * rho * span;
984 let chord = 2.0 * (0.5 * span).sin() * rho.powi(3) / 3.0;
985 let (sx, sy) = (chord * (0.5 * sum).cos(), chord * (0.5 * sum).sin());
986 let (lean, sine) = (span_less_sine(span), span.sin());
987 let (sxx, syy) = (
988 rho.powi(4) / 8.0 * (lean + sine * 2.0 * (0.5 * sum).cos().powi(2)),
989 rho.powi(4) / 8.0 * (lean + sine * 2.0 * (0.5 * sum).sin().powi(2)),
990 );
991 [
992 area,
993 sx + x0 * area,
994 sxx + 2.0 * x0 * sx + x0 * x0 * area,
995 syy + 2.0 * y0 * sy + y0 * y0 * area,
996 ]
997}
998
999fn span_less_sine(x: f64) -> f64 {
1002 if x.abs() >= 0.25 {
1003 return x - x.sin();
1004 }
1005 let mut term = x.powi(3) / 6.0;
1007 let mut sum = 0.0;
1008 for k in 2..=8 {
1009 sum += term;
1010 term *= -x * x / f64::from((2 * k) * (2 * k + 1));
1011 }
1012 sum
1013}
1014
1015#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
1017#[serde(deny_unknown_fields)]
1018pub struct TubeFinSet {
1019 pub count: u32,
1021 pub length_m: f64,
1023 pub outer_radius_m: f64,
1025 pub thickness_m: f64,
1027 #[serde(default)]
1029 pub base_angle_rad: f64,
1030 pub material: Material,
1032}
1033
1034impl TubeFinSet {
1035 pub const MAX_COUNT: u32 = 64;
1039
1040 pub fn closing_radius_m(body_radius_m: f64, count: u32) -> f64 {
1056 if count < 3 {
1057 return body_radius_m;
1058 }
1059 let s = (PI / f64::from(count)).sin();
1060 body_radius_m * s / (1.0 - s)
1061 }
1062
1063 pub fn mass_properties(&self, body_radius_m: f64) -> Result<MassProperties, DesignError> {
1073 if self.count == 0 || self.count > Self::MAX_COUNT {
1074 return Err(DesignError::Domain {
1075 what: "tube fin count (1 to 64)",
1076 value: f64::from(self.count),
1077 });
1078 }
1079 check_dimension("body radius", body_radius_m, true)?;
1080 if !self.base_angle_rad.is_finite() {
1081 return Err(DesignError::Domain {
1082 what: "tube fin base angle",
1083 value: self.base_angle_rad,
1084 });
1085 }
1086 let density = self.material.bulk_kg_m3("tube fin set")?;
1087 let tube = crate::parts::hollow_cylinder(
1088 "tube fin",
1089 density,
1090 self.length_m,
1091 self.outer_radius_m,
1092 self.thickness_m,
1093 )?;
1094 let one = tube.translated(DVec3::new(body_radius_m + self.outer_radius_m, 0.0, 0.0));
1095 let tubes: Vec<MassProperties> = (0..self.count)
1096 .map(|k| {
1097 one.rolled(self.base_angle_rad + 2.0 * PI * f64::from(k) / f64::from(self.count))
1098 })
1099 .collect();
1100 Ok(MassProperties::combine(&tubes))
1101 }
1102}
1103
1104#[cfg(test)]
1105mod tests {
1106 use super::*;
1107 use hpr_core::quadrature::integrate_scalar;
1108
1109 fn close(got: f64, want: f64, rel: f64, what: &str) {
1110 let err = if want == 0.0 {
1111 got.abs()
1112 } else {
1113 ((got - want) / want).abs()
1114 };
1115 assert!(err <= rel, "{what}: {got} vs {want} (relative {err:e})");
1116 }
1117
1118 fn mat_close(a: DMat3, b: DMat3, rel: f64, what: &str) {
1119 let scale = b.to_cols_array().iter().fold(0.0f64, |m, v| m.max(v.abs()));
1120 let diff = (a - b)
1121 .to_cols_array()
1122 .iter()
1123 .fold(0.0f64, |m, v| m.max(v.abs()));
1124 assert!(diff <= rel * scale, "{what}: {a:?}\nvs\n{b:?}");
1125 }
1126
1127 fn ply() -> Material {
1128 Material::bulk("plywood", 630.0)
1129 }
1130
1131 fn rectangle(chord: f64, span: f64) -> FinPlanform {
1132 FinPlanform::Trapezoidal {
1133 root_chord_m: chord,
1134 tip_chord_m: chord,
1135 span_m: span,
1136 sweep_m: 0.0,
1137 }
1138 }
1139
1140 fn set(count: u32, planform: FinPlanform, thickness: f64) -> FinSet {
1141 FinSet {
1142 count,
1143 planform,
1144 thickness_m: thickness,
1145 cross_section: FinCrossSection::Square,
1146 tab: None,
1147 fillet: None,
1148 cant_rad: 0.0,
1149 base_angle_rad: 0.0,
1150 material: ply(),
1151 }
1152 }
1153
1154 #[test]
1155 fn airfoil_constants_are_the_integrals() {
1156 let tol = Tolerance::default();
1158 let p = naca_polynomial;
1159 for (k, want) in AIRFOIL_PHI.iter().enumerate() {
1160 let power = i32::try_from(2 * k).unwrap();
1161 let got = 10.0
1162 * integrate_scalar(|u| u.powi(power) * p(u * u) * 2.0 * u, 0.0, 1.0, tol).unwrap();
1163 close(got, *want, 1e-14, "phi");
1164 }
1165 let psi = 1000.0 * integrate_scalar(|u| p(u * u).powi(3) * 2.0 * u, 0.0, 1.0, tol).unwrap();
1166 close(psi, AIRFOIL_PSI, 1e-14, "psi");
1167 }
1168
1169 #[test]
1170 fn chord_moments_match_quadrature_of_each_section() {
1171 let tol = Tolerance {
1173 relative: 0.0,
1174 absolute: 0.0,
1175 max_intervals: 4000,
1176 };
1177 let t: f64 = 0.004;
1178 for (a, b) in [(0.02, 0.17), (0.05, 0.053)] {
1180 let c: f64 = b - a;
1181 let rounded = |x: f64| {
1182 let mid = t.min(c);
1183 let r = 0.5 * mid;
1184 let u = (x - a).min(b - x);
1185 if u >= r {
1186 mid
1187 } else {
1188 2.0 * (r * r - (r - u).powi(2)).max(0.0).sqrt()
1189 }
1190 };
1191 let airfoil = |x: f64| 10.0 * t * naca_polynomial((x - a) / c);
1192 let square = |_x: f64| t;
1193 let sections: [(FinCrossSection, &dyn Fn(f64) -> f64); 3] = [
1194 (FinCrossSection::Square, &square),
1195 (FinCrossSection::Rounded, &rounded),
1196 (FinCrossSection::Airfoil, &airfoil),
1197 ];
1198 let edge = 0.5 * t.min(c);
1201 let reference = |f: &dyn Fn(f64) -> f64| -> f64 {
1202 let fore = integrate_scalar(|v| f(a + v * v) * 2.0 * v, 0.0, edge.sqrt(), tol);
1203 let aft = integrate_scalar(|v| f(b - v * v) * 2.0 * v, 0.0, edge.sqrt(), tol);
1204 let middle = integrate_scalar(f, a + edge, b - edge, tol);
1205 fore.unwrap() + aft.unwrap() + middle.unwrap()
1206 };
1207 for (section, thickness) in sections {
1208 let got = chord_moments(section, a, b, t);
1209 for (k, &moment) in got.iter().take(3).enumerate() {
1210 let power = i32::try_from(k).unwrap();
1211 let want = reference(&|x: f64| x.powi(power) * thickness(x));
1212 close(
1213 moment,
1214 want,
1215 1e-13,
1216 &format!("{section:?} M{k} on [{a}, {b}]"),
1217 );
1218 }
1219 let want = reference(&|x: f64| thickness(x).powi(3) / 12.0);
1220 close(got[3], want, 1e-13, &format!("{section:?} T on [{a}, {b}]"));
1221 }
1222 }
1223 let m = chord_moments(FinCrossSection::Rounded, 0.0, 0.1, t);
1225 close(
1226 m[0],
1227 0.1 * t - (1.0 - PI / 4.0) * t * t,
1228 1e-14,
1229 "rounded area",
1230 );
1231 }
1232
1233 #[test]
1234 fn the_aft_extent_is_the_outline_s_aft_most_point() {
1235 let trapezoid = |root: f64, tip: f64, sweep: f64| FinPlanform::Trapezoidal {
1239 root_chord_m: root,
1240 tip_chord_m: tip,
1241 span_m: 0.1,
1242 sweep_m: sweep,
1243 };
1244 assert_eq!(trapezoid(0.2, 0.1, 0.15).aft_extent_m(), 0.15 + 0.1);
1245 assert_eq!(trapezoid(0.2, 0.1, 0.05).aft_extent_m(), 0.2);
1246 assert_eq!(trapezoid(0.2, 0.1, -0.05).aft_extent_m(), 0.2);
1247 let elliptical = FinPlanform::Elliptical {
1248 root_chord_m: 0.2,
1249 span_m: 0.1,
1250 };
1251 assert_eq!(elliptical.aft_extent_m(), 0.2);
1252 let raked = FinPlanform::Freeform {
1254 points_m: vec![[0.0, 0.0], [0.18, 0.1], [0.26, 0.1], [0.2, 0.0]],
1255 root_m: Vec::new(),
1256 };
1257 raked.validate().unwrap();
1258 assert_eq!(raked.aft_extent_m(), 0.26);
1259 let swept = FinPlanform::Freeform {
1260 points_m: vec![[0.0, 0.0], [0.1, 0.1], [0.15, 0.1], [0.2, 0.0]],
1261 root_m: Vec::new(),
1262 };
1263 swept.validate().unwrap();
1264 assert_eq!(swept.aft_extent_m(), swept.root_chord_m());
1265 }
1266
1267 #[test]
1268 fn planform_areas_and_centroids_are_the_closed_forms() {
1269 let (cr, ct, s, xt) = (0.15, 0.06, 0.1, 0.07);
1270 let trapezoid = FinPlanform::Trapezoidal {
1271 root_chord_m: cr,
1272 tip_chord_m: ct,
1273 span_m: s,
1274 sweep_m: xt,
1275 };
1276 let g = trapezoid.geometry().unwrap();
1277 close(g.area_m2, 0.5 * s * (cr + ct), 1e-13, "trapezoid area");
1278 close(
1279 g.centroid_x_m,
1280 (xt * (cr + 2.0 * ct) + cr * cr + cr * ct + ct * ct) / (3.0 * (cr + ct)),
1281 1e-13,
1282 "trapezoid centroid x",
1283 );
1284 close(
1285 g.centroid_span_m,
1286 s * (cr + 2.0 * ct) / (3.0 * (cr + ct)),
1287 1e-13,
1288 "trapezoid centroid h",
1289 );
1290 let freeform = FinPlanform::Freeform {
1292 points_m: vec![[0.0, 0.0], [xt, s], [xt + ct, s], [cr, 0.0]],
1293 root_m: Vec::new(),
1294 };
1295 let f = freeform.geometry().unwrap();
1296 close(f.area_m2, g.area_m2, 1e-13, "freeform area");
1297 close(f.centroid_x_m, g.centroid_x_m, 1e-13, "freeform centroid x");
1298 close(
1299 f.centroid_span_m,
1300 g.centroid_span_m,
1301 1e-13,
1302 "freeform centroid h",
1303 );
1304 let e = FinPlanform::Elliptical {
1306 root_chord_m: cr,
1307 span_m: s,
1308 }
1309 .geometry()
1310 .unwrap();
1311 close(e.area_m2, PI * cr * s / 4.0, 1e-12, "ellipse area");
1312 close(e.centroid_x_m, cr / 2.0, 1e-12, "ellipse centroid x");
1313 close(
1314 e.centroid_span_m,
1315 4.0 * s / (3.0 * PI),
1316 1e-12,
1317 "ellipse centroid h",
1318 );
1319 }
1320
1321 #[test]
1322 fn a_rectangular_fin_set_matches_box_inertia_by_hand() {
1323 let (c, s, t, rb, rho) = (0.12, 0.08, 0.003, 0.04, 630.0);
1324 let m = rho * c * s * t;
1325 let d = rb + s / 2.0;
1326 let one = set(1, rectangle(c, s), t).single_fin(rb).unwrap();
1328 close(one.mass_kg, m, 1e-13, "mass");
1329 assert!((one.cg_m - DVec3::new(d, 0.0, -c / 2.0)).length() < 1e-15);
1330 let box_inertia = DMat3::from_diagonal(DVec3::new(
1331 m * (t * t + c * c) / 12.0,
1332 m * (s * s + c * c) / 12.0,
1333 m * (s * s + t * t) / 12.0,
1334 ));
1335 mat_close(one.inertia_kg_m2, box_inertia, 1e-12, "one fin");
1336 let four = set(4, rectangle(c, s), t).mass_properties(rb).unwrap();
1338 close(four.mass_kg, 4.0 * m, 1e-13, "four fins");
1339 assert!(four.cg_m.truncate().length() < 1e-15);
1340 let transverse =
1341 2.0 * m * (t * t + c * c) / 12.0 + 2.0 * (m * (s * s + c * c) / 12.0 + m * d * d);
1342 let axial = 4.0 * (m * (s * s + t * t) / 12.0 + m * d * d);
1343 mat_close(
1344 four.inertia_kg_m2,
1345 DMat3::from_diagonal(DVec3::new(transverse, transverse, axial)),
1346 1e-12,
1347 "four fins",
1348 );
1349 let three = set(3, rectangle(c, s), t)
1351 .mass_properties(rb)
1352 .unwrap()
1353 .inertia_kg_m2;
1354 close(
1355 three.x_axis.x,
1356 three.y_axis.y,
1357 1e-12,
1358 "three fins isotropic",
1359 );
1360 assert!(three.y_axis.x.abs() < 1e-12 * three.x_axis.x);
1361 let two = set(2, rectangle(c, s), t)
1362 .mass_properties(rb)
1363 .unwrap()
1364 .inertia_kg_m2;
1365 assert!((two.x_axis.x - two.y_axis.y).abs() > 1e-4 * two.y_axis.y);
1366
1367 let d = s / 2.0;
1369 let on_axis = set(4, rectangle(c, s), t).mass_properties(0.0).unwrap();
1370 let transverse =
1371 2.0 * m * (t * t + c * c) / 12.0 + 2.0 * (m * (s * s + c * c) / 12.0 + m * d * d);
1372 let axial = 4.0 * (m * (s * s + t * t) / 12.0 + m * d * d);
1373 mat_close(
1374 on_axis.inertia_kg_m2,
1375 DMat3::from_diagonal(DVec3::new(transverse, transverse, axial)),
1376 1e-12,
1377 "four fins from the axis",
1378 );
1379 }
1380
1381 #[test]
1382 fn cant_turns_the_fin_about_its_span_axis() {
1383 let (c, s, t, rb, rho) = (0.12, 0.08, 0.003, 0.04, 630.0);
1384 let m = rho * c * s * t;
1385 let mut fins = set(1, rectangle(c, s), t);
1388 fins.cant_rad = PI / 2.0;
1389 let turned = fins.single_fin(rb).unwrap();
1390 assert!((turned.cg_m - DVec3::new(rb + s / 2.0, 0.0, -c / 2.0)).length() < 1e-15);
1391 let expected = DMat3::from_diagonal(DVec3::new(
1392 m * (c * c + t * t) / 12.0,
1393 m * (s * s + t * t) / 12.0,
1394 m * (s * s + c * c) / 12.0,
1395 ));
1396 mat_close(turned.inertia_kg_m2, expected, 1e-12, "canted 90°");
1397 fins.cant_rad = 0.05;
1399 let small = fins.single_fin(rb).unwrap();
1400 let flat = set(1, rectangle(c, s), t).single_fin(rb).unwrap();
1401 close(small.mass_kg, flat.mass_kg, 1e-15, "mass");
1402 let trace = |i: DMat3| i.x_axis.x + i.y_axis.y + i.z_axis.z;
1403 close(
1404 trace(small.inertia_kg_m2),
1405 trace(flat.inertia_kg_m2),
1406 1e-12,
1407 "trace",
1408 );
1409 }
1410
1411 #[test]
1412 fn positive_cant_turns_the_leading_edge_toward_negative_y() {
1413 let (cr, ct, s, xt) = (0.15, 0.05, 0.1, 0.09);
1417 let planform = FinPlanform::Trapezoidal {
1418 root_chord_m: cr,
1419 tip_chord_m: ct,
1420 span_m: s,
1421 sweep_m: xt,
1422 };
1423 let centroid = planform.geometry().unwrap().centroid_x_m;
1424 assert!(centroid > cr / 2.0);
1425 let mut fins = set(1, planform, 0.003);
1426 let delta: f64 = 0.2;
1427 fins.cant_rad = delta;
1428 let fin = fins.single_fin(0.04).unwrap();
1429 close(
1430 fin.cg_m.y,
1431 (centroid - cr / 2.0) * delta.sin(),
1432 1e-12,
1433 "centroid y",
1434 );
1435 close(
1436 fin.cg_m.z,
1437 -cr / 2.0 - (centroid - cr / 2.0) * delta.cos(),
1438 1e-12,
1439 "centroid z",
1440 );
1441 assert!(fin.cg_m.y > 0.0);
1442 let leading_edge = DQuat::from_rotation_x(delta) * DVec3::new(0.04, 0.0, cr / 2.0);
1443 assert!(leading_edge.y < 0.0);
1444 }
1445
1446 #[test]
1447 fn a_tab_must_meet_the_root_and_fit_the_body() {
1448 let mut fins = set(3, rectangle(0.1, 0.05), 0.003);
1452 let tab = |length_m: f64, offset_m: f64| {
1453 Some(FinTab {
1454 height_m: 0.01,
1455 length_m,
1456 offset_m,
1457 })
1458 };
1459 let refusal = |fins: &FinSet| match fins.validate() {
1460 Err(DesignError::Geometry(why)) => why.contains("must meet its fin's root chord"),
1461 _ => false,
1462 };
1463 for (length_m, offset_m, meets) in [
1466 (0.02, 0.1, false),
1467 (0.02, 0.1 + 1e-9, false),
1468 (0.02, 0.1 - 1e-9, true),
1469 (0.02, -0.02, false),
1470 (0.02, -0.02 - 1e-9, false),
1471 (0.02 + 1e-9, -0.02, true),
1472 (0.08, 0.03, true),
1474 (0.02, -0.01, true),
1475 (0.12, -0.01, true),
1476 ] {
1477 fins.tab = tab(length_m, offset_m);
1478 assert_eq!(refusal(&fins), !meets, "{:?}", fins.tab);
1479 assert_eq!(fins.mass_properties(0.03).is_ok(), meets, "{:?}", fins.tab);
1480 }
1481 fins.tab = Some(FinTab {
1482 height_m: 0.05,
1483 length_m: 0.02,
1484 offset_m: 0.0,
1485 });
1486 assert!(
1487 matches!(fins.mass_properties(0.03), Err(DesignError::Geometry(why)) if why.contains("no deeper than the body radius"))
1488 );
1489 fins.tab = Some(FinTab {
1490 height_m: 0.03,
1491 length_m: 0.1,
1492 offset_m: 0.0,
1493 });
1494 fins.mass_properties(0.03).unwrap();
1495 }
1496
1497 #[test]
1498 fn a_tab_past_the_root_is_weighed_as_its_whole_slab() {
1499 let (t, h, rb) = (0.003, 0.01, 0.03);
1506 let about_origin = |m: &MassProperties| {
1507 let c = m.cg_m;
1508 m.inertia_kg_m2
1509 + (DMat3::IDENTITY * c.length_squared()
1510 - DMat3::from_cols(c * c.x, c * c.y, c * c.z))
1511 * m.mass_kg
1512 };
1513 let bare = set(3, rectangle(0.1, 0.05), t);
1514 let without = bare.single_fin(rb).unwrap();
1515 for (l, o) in [(0.08, 0.03), (0.02, -0.01), (0.12, -0.01), (0.04, 0.03)] {
1516 let mut tabbed = bare.clone();
1517 tabbed.tab = Some(FinTab {
1518 height_m: h,
1519 length_m: l,
1520 offset_m: o,
1521 });
1522 let with = tabbed.single_fin(rb).unwrap();
1523 let slab = 630.0 * t * l * h;
1524 assert!(
1525 ((with.mass_kg - without.mass_kg) - slab).abs() < 1e-12 * slab,
1526 "{l} {o}"
1527 );
1528 let z = (with.cg_m.z * with.mass_kg - without.cg_m.z * without.mass_kg) / slab;
1529 assert!((z + (o + 0.5 * l)).abs() < 1e-9, "{l} {o}: {z}");
1530 let c = DVec3::new(rb - 0.5 * h, 0.0, -(o + 0.5 * l));
1531 let own = DMat3::from_diagonal(DVec3::new(t * t + l * l, h * h + l * l, h * h + t * t))
1532 * (slab / 12.0);
1533 let expected = own
1534 + (DMat3::IDENTITY * c.length_squared()
1535 - DMat3::from_cols(c * c.x, c * c.y, c * c.z))
1536 * slab;
1537 let got = about_origin(&with) - about_origin(&without);
1538 let scale = slab * (rb * rb + (o + l).powi(2));
1539 for (g, e) in got.to_cols_array().iter().zip(expected.to_cols_array()) {
1540 assert!(
1541 (g - e).abs() < 1e-9 * scale,
1542 "{l} {o}: {got:?} against {expected:?}"
1543 );
1544 }
1545 }
1546 let mut tabbed = set(3, rectangle(0.1, 0.05), t);
1548 tabbed.tab = Some(FinTab {
1549 height_m: h,
1550 length_m: 0.08,
1551 offset_m: 0.03,
1552 });
1553 let added =
1554 tabbed.mass_properties(rb).unwrap().mass_kg - bare.mass_properties(rb).unwrap().mass_kg;
1555 let slab = 3.0 * 630.0 * t * 0.08 * h;
1556 assert!((added - slab).abs() < 1e-12 * slab, "{added}");
1557 }
1558
1559 #[test]
1560 fn a_tab_too_long_for_its_moments_is_refused() {
1561 let mut fins = set(3, rectangle(0.1, 0.05), 0.003);
1564 fins.tab = Some(FinTab {
1565 height_m: 0.01,
1566 length_m: 1e103,
1567 offset_m: 0.0,
1568 });
1569 assert!(
1570 matches!(fins.single_fin(0.03), Err(DesignError::UnphysicalInertia(why)) if why.contains("non-finite")),
1571 "{:?}",
1572 fins.single_fin(0.03)
1573 );
1574 }
1575
1576 #[test]
1577 fn a_swept_fin_has_the_parallel_axis_product_of_inertia() {
1578 let (cr, ct, s, xt, t, rb, rho) = (0.15, 0.05, 0.1, 0.09, 0.004, 0.05, 1800.0);
1582 let planform = FinPlanform::Trapezoidal {
1583 root_chord_m: cr,
1584 tip_chord_m: ct,
1585 span_m: s,
1586 sweep_m: xt,
1587 };
1588 let mut fins = set(1, planform, t);
1589 fins.material = Material::bulk("G10", rho);
1590 let fin = fins.single_fin(rb).unwrap();
1591 let tol = Tolerance::default();
1592 let lead = |h: f64| xt * h / s;
1593 let chord = |h: f64| cr + (ct - cr) * h / s;
1594 let area = integrate_scalar(chord, 0.0, s, tol).unwrap();
1595 let mx = integrate_scalar(|h| chord(h) * (lead(h) + chord(h) / 2.0), 0.0, s, tol).unwrap();
1596 let mr = integrate_scalar(|h| chord(h) * (rb + h), 0.0, s, tol).unwrap();
1597 let mrx = integrate_scalar(
1598 |h| (rb + h) * chord(h) * (lead(h) + chord(h) / 2.0),
1599 0.0,
1600 s,
1601 tol,
1602 )
1603 .unwrap();
1604 let m = rho * t * area;
1605 close(fin.mass_kg, m, 1e-13, "mass");
1606 let product = rho * t * mrx - m * (mr / area) * (mx / area);
1607 close(fin.inertia_kg_m2.z_axis.x, product, 1e-11, "I_xz");
1608 close(fin.inertia_kg_m2.x_axis.z, product, 1e-11, "I_zx");
1609 }
1610
1611 #[test]
1612 fn a_closing_ring_of_tubes_touches_the_body_and_its_neighbors() {
1613 let body = 0.05;
1614 for count in 3..=12 {
1615 let r = TubeFinSet::closing_radius_m(body, count);
1616 assert!(r > 0.0 && r.is_finite(), "{count}: {r}");
1617 let step = 2.0 * PI / f64::from(count);
1619 let (a, b) = (
1620 DVec3::new(body + r, 0.0, 0.0),
1621 DVec3::new((body + r) * step.cos(), (body + r) * step.sin(), 0.0),
1622 );
1623 close(a.distance(b), 2.0 * r, 1e-14, "neighbors touch");
1624 }
1625 close(TubeFinSet::closing_radius_m(body, 6), body, 1e-15, "six");
1627 close(
1628 TubeFinSet::closing_radius_m(body, 4),
1629 body * (1.0 + 2f64.sqrt()),
1630 1e-15,
1631 "four",
1632 );
1633 assert_eq!(TubeFinSet::closing_radius_m(body, 1), body);
1635 assert_eq!(TubeFinSet::closing_radius_m(body, 2), body);
1636 }
1637
1638 #[test]
1639 fn tube_fins_are_hollow_cylinders_around_the_body() {
1640 let tubes = TubeFinSet {
1641 count: 6,
1642 length_m: 0.1,
1643 outer_radius_m: 0.012,
1644 thickness_m: 0.001,
1645 base_angle_rad: 0.0,
1646 material: Material::bulk("cardboard", 790.0),
1647 };
1648 let rb = 0.02;
1649 let g = tubes.mass_properties(rb).unwrap();
1650 let (ro, ri) = (0.012, 0.011);
1651 let m1 = 790.0 * PI * (ro * ro - ri * ri) * 0.1;
1652 close(g.mass_kg, 6.0 * m1, 1e-13, "mass");
1653 let d = rb + ro;
1654 let axial = 6.0 * (0.5 * m1 * (ro * ro + ri * ri) + m1 * d * d);
1655 close(g.inertia_kg_m2.z_axis.z, axial, 1e-13, "axial");
1656 let transverse = 6.0 * m1 * ((ro * ro + ri * ri) / 4.0 + 0.01 / 12.0) + 3.0 * m1 * d * d;
1657 close(g.inertia_kg_m2.x_axis.x, transverse, 1e-12, "transverse");
1658 close(g.cg_m.z, -0.05, 1e-15, "center");
1659 }
1660
1661 fn cockpit(pieces: u32) -> (FinSet, Profile, f64) {
1665 let nose = Profile::nose(
1666 crate::NoseShape::Ogive { radius_ratio: 1.0 },
1667 0.136525,
1668 0.0168275,
1669 )
1670 .unwrap();
1671 let (chord, fore) = (0.05, 0.136525 - 0.05);
1672 let base = nose.radius_m(fore);
1673 let rise = |x: f64| nose.radius_m(fore + x) - base;
1674 let root_m = (1..pieces)
1675 .rev()
1676 .map(|i| {
1677 let x = chord * f64::from(i) / f64::from(pieces);
1678 [x, rise(x)]
1679 })
1680 .collect();
1681 let planform = FinPlanform::Freeform {
1682 points_m: vec![
1683 [0.0, 0.0],
1684 [0.009347826086956524, 0.006956521739130436],
1685 [chord, 0.0022276567072510058],
1686 ],
1687 root_m,
1688 };
1689 let mut set = set(1, planform, 0.006985);
1690 set.material = Material::bulk("balsa", 170.0);
1691 (set, nose, fore)
1692 }
1693
1694 #[test]
1701 fn a_root_along_a_nose_cone_is_openrockets() {
1702 let (set, nose, fore) = cockpit(20);
1703 let radius = set.root_radius_on(&nose, fore).unwrap();
1704 close(
1705 radius,
1706 0.0145998,
1707 1e-5,
1708 "body radius at the root leading edge",
1709 );
1710 let g = set.planform.geometry().unwrap();
1711 close(g.area_m2, 1.449544e-4, 1e-6, "OpenRocket's planform area");
1712 let m = set.mass_properties(radius).unwrap();
1713 close(m.mass_kg, 1.72126e-4, 1e-5, "OpenRocket's mass");
1714 close(
1716 -m.cg_m.z,
1717 0.0191163,
1718 1e-5,
1719 "OpenRocket's center of mass, aft",
1720 );
1721 close(m.cg_m.x, 0.017882, 1e-5, "OpenRocket's center of mass, out");
1722 let fine = |pieces| cockpit(pieces).0.planform.geometry().unwrap().area_m2;
1723 let (ours, curve) = (fine(64), fine(1024));
1724 assert!(
1725 ours < g.area_m2 && curve < ours,
1726 "{curve} < {ours} < {}",
1727 g.area_m2
1728 );
1729 close(ours, g.area_m2, 3.0e-4, "64 pieces against OpenRocket's 20");
1730 close(ours, curve, 3.5e-5, "64 pieces against the curve");
1731 let share = |pieces| {
1733 let (set, nose, fore) = cockpit(pieces);
1734 set.root_on_surface(&nose, fore).1 / set.planform.geometry().unwrap().area_m2
1735 };
1736 for (pieces, want) in [(20, 3.2e-4), (64, 3.1e-5), (1, 0.114)] {
1737 close(share(pieces), want, 0.1, "sliver share");
1738 }
1739 let (chord, nose, fore) = cockpit(1);
1740 let err = chord.root_radius_on(&nose, fore).unwrap_err();
1741 assert!(
1742 matches!(&err, DesignError::Geometry(m) if m.contains("cuts across")),
1743 "{err}"
1744 );
1745 close(set.planform.span_m(), 0.006956521739130436, 1e-15, "span");
1747 }
1748
1749 #[test]
1752 fn a_root_off_the_surface_is_refused_by_name() {
1753 let cone =
1755 Profile::transition(crate::NoseShape::Conical {}, 0.2, 0.02, 0.04, false).unwrap();
1756 let rise = 0.02 / 0.2 * 0.05;
1757 let on_cone = |end_h: f64| {
1758 set(
1759 3,
1760 FinPlanform::Freeform {
1761 points_m: vec![[0.0, 0.0], [0.03, 0.04], [0.05, end_h]],
1762 root_m: Vec::new(),
1763 },
1764 0.003,
1765 )
1766 };
1767 close(
1768 on_cone(rise).root_radius_on(&cone, 0.1).unwrap(),
1769 0.03,
1770 1e-14,
1771 "radius at x = 0.1 m",
1772 );
1773 let says = |set: FinSet, fore: f64, what: &str| {
1774 let err = set.root_radius_on(&cone, fore).unwrap_err();
1775 assert!(
1776 matches!(&err, DesignError::Geometry(m) if m.contains(what)),
1777 "{what}: {err}"
1778 );
1779 };
1780 assert!(on_cone(rise + 0.9e-6).root_radius_on(&cone, 0.1).is_ok());
1782 says(on_cone(rise + 1.1e-6), 0.1, "stands");
1783 says(on_cone(rise - 1.1e-6), 0.1, "stands");
1784 says(set(3, rectangle(0.05, 0.04), 0.003), 0.1, "stands");
1786 says(on_cone(rise), -2e-6, "must stay on it");
1788 says(on_cone(rise), 0.15 + 2e-6, "must stay on it");
1789 assert!(on_cone(rise).root_radius_on(&cone, 0.15).is_ok());
1790 let mut tabbed = on_cone(rise);
1791 tabbed.tab = Some(FinTab {
1792 height_m: 0.005,
1793 length_m: 0.02,
1794 offset_m: 0.01,
1795 });
1796 says(tabbed, 0.1, "tab or a fillet");
1797 let mut filleted = on_cone(rise);
1798 filleted.fillet = Some(FinFillet {
1799 radius_m: 0.005,
1800 material: ply(),
1801 });
1802 says(filleted, 0.1, "tab or a fillet");
1803 }
1804
1805 #[test]
1806 fn bad_outlines_and_dimensions_are_rejected() {
1807 let bowtie = FinPlanform::Freeform {
1808 points_m: vec![[0.0, 0.0], [0.1, 0.1], [0.0, 0.1], [0.1, 0.0]],
1809 root_m: Vec::new(),
1810 };
1811 assert!(matches!(bowtie.validate(), Err(DesignError::Geometry(_))));
1812 let below = FinPlanform::Freeform {
1813 points_m: vec![[0.0, 0.0], [0.05, -0.01], [0.1, 0.0]],
1814 root_m: Vec::new(),
1815 };
1816 assert!(below.validate().is_err());
1817 let open = FinPlanform::Freeform {
1820 points_m: vec![[0.0, 0.0], [0.05, 0.05], [0.1, 0.02]],
1821 root_m: Vec::new(),
1822 };
1823 assert!(open.validate().is_ok());
1824 let err = set(1, open, 0.003).check_level_root().unwrap_err();
1825 assert!(
1826 matches!(&err, DesignError::Geometry(m) if m.contains("needs a level root")),
1827 "{err}"
1828 );
1829 let outline = vec![[0.0, 0.0], [0.05, 0.05], [0.1, 0.02]];
1832 let with_root = |root_m: Vec<[f64; 2]>| FinPlanform::Freeform {
1833 points_m: outline.clone(),
1834 root_m,
1835 };
1836 assert!(
1837 with_root(vec![[0.07, 0.012], [0.03, 0.004]])
1838 .validate()
1839 .is_ok()
1840 );
1841 for (root, says) in [
1842 (vec![[0.03, 0.004], [0.07, 0.012]], "must run fore"),
1843 (vec![[0.1, 0.02]], "must run fore"),
1844 (vec![[0.12, 0.02]], "must run fore"),
1845 (vec![[0.0, 0.0]], "must run fore"),
1846 (vec![[0.05, 0.06]], "runs below its root"),
1847 (vec![[0.07, 0.04], [0.03, 0.004]], "crosses itself"),
1848 ] {
1849 let err = with_root(root.clone()).validate().unwrap_err();
1850 assert!(
1851 matches!(&err, DesignError::Geometry(m) if m.contains(says)),
1852 "{root:?}: {err}"
1853 );
1854 }
1855 assert!(matches!(
1856 with_root(vec![[0.05, -0.001]]).validate(),
1857 Err(DesignError::Domain {
1858 what: "freeform fin span",
1859 ..
1860 })
1861 ));
1862 let shifted = FinPlanform::Freeform {
1864 points_m: vec![[0.03, 0.0], [0.08, 0.05], [0.13, 0.0]],
1865 root_m: Vec::new(),
1866 };
1867 assert!(shifted.validate().is_err());
1868 let backwards = FinPlanform::Freeform {
1869 points_m: vec![[0.0, 0.0], [-0.05, 0.05], [-0.1, 0.0]],
1870 root_m: Vec::new(),
1871 };
1872 assert!(backwards.validate().is_err());
1873 assert!(
1874 set(0, rectangle(0.1, 0.1), 0.003)
1875 .mass_properties(0.03)
1876 .is_err()
1877 );
1878 assert!(
1879 set(3, rectangle(0.1, 0.1), 0.0)
1880 .mass_properties(0.03)
1881 .is_err()
1882 );
1883 let mut fabric = set(3, rectangle(0.1, 0.1), 0.003);
1884 fabric.material = Material::surface("ripstop", 0.04);
1885 assert!(matches!(
1886 fabric.mass_properties(0.03),
1887 Err(DesignError::MaterialKind { .. })
1888 ));
1889 }
1890
1891 fn fillet_section_by_quadrature(rb: f64, r: f64) -> [f64; 4] {
1896 let tol = Tolerance {
1897 relative: 1e-12,
1898 absolute: 1e-24,
1899 ..Tolerance::default()
1900 };
1901 let c = (rb * rb + 2.0 * rb * r).sqrt();
1902 let joint = |x: f64| r - (r * r - (x - c) * (x - c)).max(0.0).sqrt();
1903 let body = |x: f64| (rb * rb - x * x).max(0.0).sqrt();
1904 let moments = |bottom: f64, top: f64, x: f64| {
1905 [
1906 top - bottom,
1907 x * (top - bottom),
1908 x * x * (top - bottom),
1909 (top.powi(3) - bottom.powi(3)) / 3.0,
1910 ]
1911 };
1912 let near = integrate(
1913 |v| {
1914 let x = rb - v * v;
1915 moments(body(x), joint(x), x).map(|m| m * 2.0 * v)
1916 },
1917 0.0,
1918 (rb - c * rb / (rb + r)).sqrt(),
1919 tol,
1920 )
1921 .unwrap();
1922 let far = integrate(|x| moments(0.0, joint(x), x), rb, c, tol).unwrap();
1923 std::array::from_fn(|k| near.value[k] + far.value[k])
1924 }
1925
1926 #[test]
1927 fn fillet_section_is_its_region_by_quadrature() {
1928 for (rb, r) in [
1929 (0.05, 0.005),
1930 (0.05, 0.01),
1931 (0.05, 0.03),
1932 (0.1, 0.001),
1933 (0.02, 0.05),
1934 ] {
1935 let got = fillet_section(rb, r);
1936 let want = fillet_section_by_quadrature(rb, r);
1937 for (k, what) in ["A", "S_x", "S_xx", "S_yy"].into_iter().enumerate() {
1938 close(got[k], want[k], 1e-11, what);
1939 }
1940 }
1941 assert_eq!(fillet_section(0.0, 0.01)[0], 0.0);
1943 let x: f64 = 0.25;
1945 close(
1946 span_less_sine(x.next_down()),
1947 x - x.sin(),
1948 1e-13,
1949 "x − sin x",
1950 );
1951 close(
1952 span_less_sine(1e-3),
1953 1e-9 / 6.0 - 1e-15 / 120.0 + 1e-21 / 5040.0,
1954 1e-15,
1955 "x − sin x",
1956 );
1957 }
1958
1959 #[test]
1960 fn a_fillet_on_a_flat_body_is_a_square_less_a_quarter_circle() {
1961 let r = 0.01;
1963 close(
1964 fillet_section(1e6, r)[0],
1965 r * r * (1.0 - PI / 4.0),
1966 1e-6,
1967 "flat",
1968 );
1969 }
1970
1971 #[test]
1975 fn the_worked_fillet_example_is_the_docs() {
1976 let [a, ..] = fillet_section(0.030, 0.005);
1977 assert!((a * 1e6 - 4.253).abs() < 5e-4, "{}", a * 1e6);
1978 let planform = FinPlanform::Trapezoidal {
1979 root_chord_m: 0.1,
1980 tip_chord_m: 0.05,
1981 span_m: 0.05,
1982 sweep_m: 0.05,
1983 };
1984 let bare = set(3, planform.clone(), 0.003);
1985 let mut filleted = set(3, planform, 0.003);
1986 filleted.fillet = Some(FinFillet {
1987 radius_m: 0.005,
1988 material: Material::bulk("cardboard", 680.0),
1989 });
1990 let mass_g = (filleted.mass_properties(0.030).unwrap().mass_kg
1991 - bare.mass_properties(0.030).unwrap().mass_kg)
1992 * 1e3;
1993 assert!((mass_g - 1.735).abs() < 5e-4, "{mass_g}");
1994 }
1995
1996 #[test]
2000 fn a_fillet_far_from_the_body_s_size_is_refused_or_none() {
2001 let planform = FinPlanform::Trapezoidal {
2002 root_chord_m: 0.1,
2003 tip_chord_m: 0.05,
2004 span_m: 0.05,
2005 sweep_m: 0.05,
2006 };
2007 let filleted = |radius_m: f64| {
2008 let mut fins = set(3, planform.clone(), 0.003);
2009 fins.fillet = Some(FinFillet {
2010 radius_m,
2011 material: Material::bulk("epoxy", 1200.0),
2012 });
2013 fins
2014 };
2015 let bare = set(3, planform.clone(), 0.003);
2016 let rb = 0.05;
2017 let widest = FILLET_RATIO_MAX * rb;
2018 for radius_m in [widest * (1.0 + 1e-12), 1e10, 1e12, 1e100] {
2019 let error = filleted(radius_m).single_fin(rb).unwrap_err();
2020 assert!(
2021 matches!(error, DesignError::Domain { what, value }
2022 if what.starts_with("fin fillet radius") && value == radius_m / rb),
2023 "{radius_m}: {error:?}"
2024 );
2025 }
2026 let mass = |fins: &FinSet, rb: f64| fins.single_fin(rb).unwrap().mass_kg;
2027 assert!(mass(&filleted(widest), rb) > mass(&bare, rb));
2028 assert!(mass(&filleted(1e-6 * rb), rb) > mass(&bare, rb));
2029 for (radius_m, body_m) in [(1e-6 * rb * (1.0 - 1e-12), rb), (1e-20, rb), (0.005, 0.0)] {
2030 assert_eq!(
2031 mass(&filleted(radius_m), body_m),
2032 mass(&bare, body_m),
2033 "{radius_m} on {body_m}"
2034 );
2035 }
2036 let mut fins = set(3, planform, 0.003);
2038 fins.fillet = Some(FinFillet {
2039 radius_m: 0.005,
2040 material: Material::bulk("air", 0.0),
2041 });
2042 assert_eq!(
2043 fins.single_fin(0.05).unwrap().mass_kg,
2044 set(3, fins.planform.clone(), 0.003)
2045 .single_fin(0.05)
2046 .unwrap()
2047 .mass_kg
2048 );
2049 }
2050
2051 #[test]
2052 fn fillets_are_a_prism_of_their_section_along_the_root() {
2053 let (rb, r, rho) = (0.05, 0.005, 1200.0);
2055 let planform = FinPlanform::Trapezoidal {
2056 root_chord_m: 0.1,
2057 tip_chord_m: 0.05,
2058 span_m: 0.05,
2059 sweep_m: 0.05,
2060 };
2061 let mut fins = set(3, planform, 0.003);
2062 let bare = fins.single_fin(rb).unwrap();
2063 fins.fillet = Some(FinFillet {
2064 radius_m: r,
2065 material: Material::bulk("epoxy", rho),
2066 });
2067 let with = fins.single_fin(rb).unwrap();
2068 let pair = with.without_part(&bare);
2069 let [a, sx, sxx, syy] = fillet_section_by_quadrature(rb, r);
2070 let l = 0.1;
2071 close(pair.mass_kg, 2.0 * rho * a * l, 1e-10, "mass");
2072 assert!((pair.cg_m - DVec3::new(sx / a, 0.0, -0.5 * l)).length() < 1e-12);
2073 let about_origin = with.inertia_about(DVec3::ZERO) - bare.inertia_about(DVec3::ZERO);
2074 let want = DMat3::from_cols(
2075 DVec3::new(
2076 2.0 * rho * (syy * l + a * l.powi(3) / 3.0),
2077 0.0,
2078 rho * sx * l * l,
2079 ),
2080 DVec3::new(0.0, 2.0 * rho * (sxx * l + a * l.powi(3) / 3.0), 0.0),
2081 DVec3::new(rho * sx * l * l, 0.0, 2.0 * rho * (sxx + syy) * l),
2082 );
2083 mat_close(about_origin, want, 1e-9, "fillets about the origin");
2084 fins.fillet = Some(FinFillet {
2086 radius_m: 0.0,
2087 material: Material::bulk("epoxy", rho),
2088 });
2089 assert_eq!(fins.single_fin(rb).unwrap(), bare);
2090 fins.fillet = Some(FinFillet {
2091 radius_m: -0.001,
2092 material: Material::bulk("epoxy", rho),
2093 });
2094 assert!(matches!(
2095 fins.single_fin(rb),
2096 Err(DesignError::Domain {
2097 what: "fin fillet radius",
2098 ..
2099 })
2100 ));
2101 }
2102
2103 #[test]
2107 fn a_fin_count_over_the_bound_is_refused_and_the_bound_is_weighed() {
2108 let rb = 0.028;
2109 let planform = FinPlanform::Trapezoidal {
2110 root_chord_m: 0.05,
2111 tip_chord_m: 0.02,
2112 span_m: 0.03,
2113 sweep_m: 0.02,
2114 };
2115 for count in [0, FinSet::MAX_COUNT + 1, 4_000_000_000, u32::MAX] {
2116 let fins = set(count, planform.clone(), 0.003);
2117 for result in [fins.validate(), fins.mass_properties(rb).map(|_| ())] {
2118 match result {
2119 Err(DesignError::Domain { what, value }) => {
2120 assert_eq!(what, "fin count (1 to 64)", "{count}");
2121 assert_eq!(value, f64::from(count), "{count}");
2122 }
2123 other => panic!("{count} fins: {other:?}"),
2124 }
2125 }
2126 }
2127 let most = set(FinSet::MAX_COUNT, planform.clone(), 0.003);
2128 most.validate().unwrap();
2129 let one = set(1, planform, 0.003).mass_properties(rb).unwrap();
2130 let all = most.mass_properties(rb).unwrap();
2131 close(all.mass_kg, 64.0 * one.mass_kg, 1e-13, "64 fins' mass");
2132 assert!(
2134 all.cg_m.x.abs() < 1e-15 && all.cg_m.y.abs() < 1e-15,
2135 "{:?}",
2136 all.cg_m
2137 );
2138 }
2139
2140 #[test]
2143 fn a_tube_fin_count_over_the_bound_is_refused_and_the_bound_is_weighed() {
2144 let tubes = |count| TubeFinSet {
2145 count,
2146 length_m: 0.1,
2147 outer_radius_m: 0.012,
2148 thickness_m: 0.001,
2149 base_angle_rad: 0.0,
2150 material: Material::bulk("cardboard", 790.0),
2151 };
2152 for count in [0, TubeFinSet::MAX_COUNT + 1, 4_000_000_000, u32::MAX] {
2153 match tubes(count).mass_properties(0.02) {
2154 Err(DesignError::Domain { what, value }) => {
2155 assert_eq!(what, "tube fin count (1 to 64)", "{count}");
2156 assert_eq!(value, f64::from(count), "{count}");
2157 }
2158 other => panic!("{count} tubes: {other:?}"),
2159 }
2160 }
2161 let one = tubes(1).mass_properties(0.02).unwrap();
2162 let all = tubes(TubeFinSet::MAX_COUNT).mass_properties(0.02).unwrap();
2163 close(all.mass_kg, 64.0 * one.mass_kg, 1e-13, "64 tubes' mass");
2164 }
2165}