1use std::borrow::Cow;
19
20use hpr_aero::AeroModel;
21use hpr_design::{Assembly, Configuration, Ignition, MassProperties, MountedMotor, Rocket};
22
23use crate::error::SimError;
24use crate::recovery::Separation;
25
26#[derive(Debug, Clone)]
29#[non_exhaustive]
30pub struct FlownVehicle<'a> {
31 pub assembly: Cow<'a, Assembly>,
34 pub aero: Cow<'a, AeroModel>,
39 pub ignition_s: Vec<Option<f64>>,
42 pub from_s: Option<f64>,
45 pub until_s: Option<f64>,
48}
49
50impl FlownVehicle<'_> {
51 #[must_use]
61 pub fn mass_samples(&self) -> Vec<MassProperties> {
62 let start_s = self.from_s.unwrap_or(0.0);
63 let inside = |t: f64| t > start_s && self.until_s.is_none_or(|until_s| t < until_s);
64 let mut times_s = vec![start_s];
65 for (motor, ignition_s) in self.assembly.motors.iter().zip(&self.ignition_s) {
66 let Some(ignition_s) = *ignition_s else {
67 continue;
68 };
69 let burnout_s = ignition_s + motor.mounted.motor.burnout_time_s();
70 times_s.extend([ignition_s, burnout_s].into_iter().filter(|&t| inside(t)));
71 }
72 times_s.extend(self.until_s);
73 let mut samples: Vec<MassProperties> = times_s
74 .into_iter()
75 .map(|t| self.assembly.mass_properties_lit(t, &self.ignition_s))
76 .collect();
77 if self.from_s.is_none() {
78 samples.push(self.assembly.mass_properties(0.0));
79 samples.push(self.assembly.dry_mass_properties());
80 }
81 samples
82 }
83}
84
85#[derive(Debug, Clone)]
87pub(crate) struct Sustainer {
88 pub(crate) assembly: Assembly,
90 pub(crate) aero: AeroModel,
92 pub(crate) motors: Vec<usize>,
94}
95
96impl Sustainer {
97 pub(crate) fn of(
105 rocket: &Rocket,
106 configuration_id: &str,
107 stack: &Assembly,
108 separation: Separation,
109 ) -> Result<Self, SimError> {
110 let motors: Vec<usize> = stack
111 .motors
112 .iter()
113 .enumerate()
114 .filter(|(_, motor)| motor.stage <= separation.after_stage)
115 .map(|(index, _)| index)
116 .collect();
117 if motors.is_empty() {
118 return Err(SimError::Domain {
119 what: "count of motors in a sustainer (a powered separation's nose body has none)",
120 value: 0.0,
121 });
122 }
123 let mut cut = rocket.clone();
124 cut.stages.truncate(separation.after_stage + 1);
125 let mut mounts: Vec<MountedMotor> = Vec::new();
131 for &index in &motors {
132 let mounted = &stack.motors[index].mounted;
133 if mounts.iter().all(|m| m.mount != mounted.mount) {
134 let mut mounted = mounted.clone();
135 if mounted.ignition != Ignition::Never {
136 mounted.ignition = Ignition::Launch;
137 }
138 mounts.push(mounted);
139 }
140 }
141 cut.configurations = vec![Configuration {
142 id: configuration_id.to_owned(),
143 name: String::new(),
144 motors: mounts,
145 }];
146 let assembly = cut.assemble(configuration_id)?;
147 debug_assert!(
149 assembly.motors.len() == motors.len()
150 && assembly.motors.iter().zip(&motors).all(|(cut, &index)| {
151 let stacked = &stack.motors[index];
152 cut.nozzle_m == stacked.nozzle_m
153 && cut.tube == stacked.tube
154 && cut.fails == stacked.fails
155 })
156 );
157 let aero = AeroModel::new(&assembly.layout)?;
158 Ok(Self {
159 assembly,
160 aero,
161 motors,
162 })
163 }
164}
165
166#[cfg(test)]
167mod tests {
168 use hpr_design::{Ignition, Rocket};
169
170 use crate::environment::Environment;
171 use crate::error::SimError;
172 use crate::flight::{EventKind, FlightResult, FlightSettings, Simulation, Termination};
173 use crate::rail::Rail;
174 use crate::recorder::{FlightStep, Observer, Sample};
175 use crate::recovery::{CanopyType, Device, DeviceDrag, Separation, Trigger};
176 use hpr_core::{DQuat, DVec3};
177
178 use crate::testing::{
179 ConstantDrag, UniformAir, analytic_environment, constant_drag, design, site,
180 };
181
182 const CONFIGURATION: &str = "j760-i175";
185 const BOOSTER_MOUNT: &str = "booster-motor-mount";
186 const SUSTAINER_MOUNT: &str = "sustainer-motor-mount";
187
188 fn two_stage(ignition: Ignition) -> Rocket {
190 let mut rocket = design("synthetic-two-stage-75mm-54mm");
191 let configuration = rocket
192 .configurations
193 .iter_mut()
194 .find(|c| c.id == CONFIGURATION)
195 .unwrap();
196 let sustainer = configuration
197 .motors
198 .iter_mut()
199 .find(|m| m.mount == SUSTAINER_MOUNT)
200 .unwrap();
201 sustainer.ignition = ignition;
202 rocket
203 }
204
205 fn motor_index(sim: &Simulation, mount: &str) -> usize {
207 sim.assembly()
208 .motors
209 .iter()
210 .position(|m| m.mount == mount)
211 .unwrap()
212 }
213
214 fn staged(rocket: &Rocket, separation: impl Fn(&Simulation) -> Separation) -> Simulation {
217 staged_with(
218 rocket,
219 Rail::vertical(6.0),
220 BOOSTER_AT_SEPARATION,
221 separation,
222 )
223 .unwrap()
224 }
225
226 const BOOSTER_AT_SEPARATION: Trigger = Trigger::Time { time_s: 0.0 };
228
229 fn staged_with(
231 rocket: &Rocket,
232 rail: Rail,
233 booster: Trigger,
234 separation: impl Fn(&Simulation) -> Separation,
235 ) -> Result<Simulation, SimError> {
236 let sim = Simulation::new(
237 rocket,
238 CONFIGURATION,
239 Environment::standard(site()).unwrap(),
240 rail,
241 FlightSettings::default(),
242 )
243 .unwrap();
244 let tumble = DeviceDrag::tumbling_stages(sim.assembly(), (1, 1)).unwrap();
245 let separation = separation(&sim);
246 sim.with_recovery(vec![
247 Device::new(
248 "sustainer main",
249 DeviceDrag::canopy(CanopyType::FlatCircular, 1.2),
250 Trigger::Apogee,
251 ),
252 Device::new("booster tumble", tumble, booster).on_body(1),
253 ])
254 .unwrap()
255 .with_separation(separation)
256 }
257
258 fn booster_burnout_s(sim: &Simulation) -> f64 {
260 sim.assembly().motors[motor_index(sim, BOOSTER_MOUNT)]
261 .mounted
262 .motor
263 .burnout_time_s()
264 }
265
266 fn serial_plan() -> Simulation {
269 let rocket = two_stage(Ignition::Burnout {
270 mount: BOOSTER_MOUNT.to_owned(),
271 delay_s: 1.0,
272 });
273 staged(&rocket, |sim| {
274 Separation::new(
275 Trigger::Burnout {
276 motor: motor_index(sim, BOOSTER_MOUNT),
277 delay_s: 0.5,
278 },
279 0,
280 )
281 })
282 }
283
284 #[derive(Default)]
286 struct StepStarts(Vec<Sample>);
287
288 impl Observer for StepStarts {
289 fn step(&mut self, step: &dyn FlightStep) -> Result<(), SimError> {
290 self.0.push(step.sample(step.start_s())?);
291 Ok(())
292 }
293 }
294
295 fn time_of(result: &FlightResult, kind: EventKind) -> f64 {
296 result
297 .event(kind)
298 .unwrap_or_else(|| panic!("no {kind:?} in {:?}", kinds(result)))
299 .sample
300 .time_s
301 }
302
303 fn kinds(result: &FlightResult) -> Vec<EventKind> {
304 result.events.iter().map(|event| event.kind).collect()
305 }
306
307 #[test]
311 fn a_separation_on_the_rail_is_refused() {
312 let rocket = two_stage(Ignition::Burnout {
313 mount: BOOSTER_MOUNT.to_owned(),
314 delay_s: 1.0,
315 });
316 let separation = |sim: &Simulation| {
317 Separation::new(
318 Trigger::Burnout {
319 motor: motor_index(sim, BOOSTER_MOUNT),
320 delay_s: 0.5,
321 },
322 0,
323 )
324 };
325 let sim = staged_with(
326 &rocket,
327 Rail::vertical(2000.0),
328 BOOSTER_AT_SEPARATION,
329 separation,
330 )
331 .unwrap();
332 let separation_s = booster_burnout_s(&sim) + 0.5;
333 let error = sim.run(&mut ()).expect_err("a separation on the rail");
334 assert!(
335 matches!(error, SimError::Domain { what, value }
336 if what.starts_with("time of a separation, s (it must come once the rocket has \
337 left the rail)")
338 && value == separation_s),
339 "{error:?}"
340 );
341 let flown = serial_plan().run(&mut ()).unwrap();
343 assert_eq!(time_of(&flown, EventKind::Separation), separation_s);
344 }
345
346 #[test]
347 fn serial_plan_timing_and_mass_step() {
348 let sim = serial_plan();
352 let sustainer = motor_index(&sim, SUSTAINER_MOUNT);
353 let mut starts = StepStarts::default();
354 let result = sim.run(&mut starts).unwrap();
355 let burnout_s = booster_burnout_s(&sim);
356 let separation_s = time_of(&result, EventKind::Separation);
357 let ignition_s = time_of(&result, EventKind::Ignition(sustainer));
358 assert!(
359 (separation_s - (burnout_s + 0.5)).abs() < 1e-12,
360 "{separation_s}"
361 );
362 assert!(
363 (ignition_s - (burnout_s + 1.0)).abs() < 1e-12,
364 "{ignition_s}"
365 );
366
367 let stack_kg = result.event(EventKind::Separation).unwrap().sample.mass_kg;
369 assert_eq!(result.bodies.len(), 1, "the booster alone descends");
370 let booster = &result.bodies[0];
371 assert_eq!((booster.body, booster.stages), (1, (1, 1)));
372 let sustainer_kg = stack_kg - booster.mass_kg;
373 let coasting: Vec<&Sample> = starts
374 .0
375 .iter()
376 .filter(|s| s.time_s >= separation_s && s.time_s < ignition_s)
377 .collect();
378 assert!(coasting.len() >= 2, "{}", coasting.len());
379 for sample in coasting {
380 assert!(
381 (sample.mass_kg - sustainer_kg).abs() < 1e-12 * stack_kg,
382 "{} kg at {} s against {sustainer_kg}",
383 sample.mass_kg,
384 sample.time_s
385 );
386 }
387 assert!(booster.mass_kg > 0.2 * stack_kg && booster.mass_kg < 0.8 * stack_kg);
389 let spent = super::super::recovery::body_mass_properties(
391 sim.assembly(),
392 (0, 0),
393 f64::MAX,
394 &[Some(0.0), Some(0.0)],
395 );
396 assert_eq!(result.termination, Termination::GroundHit);
397 assert!(
398 (result.final_sample.mass_kg - spent.mass_kg).abs() < 1e-12 * spent.mass_kg,
399 "{} against {}",
400 result.final_sample.mass_kg,
401 spent.mass_kg
402 );
403
404 let rocket = two_stage(Ignition::Separation { delay_s: 0.0 });
407 let sim = staged(&rocket, |_| {
408 Separation::new(Trigger::Time { time_s: 3_000.0 }, 0)
409 });
410 let result = sim.run(&mut ()).unwrap();
411 assert_eq!(result.termination, Termination::GroundHit);
412 assert!(result.event(EventKind::Separation).is_none());
413 assert!(result.event(EventKind::Ignition(sustainer)).is_none());
414 assert!(result.bodies.is_empty());
415 let loaded = sim
416 .assembly()
417 .mass_properties_lit(f64::MAX, &[Some(0.0), None]);
418 assert!(
419 (result.final_sample.mass_kg - loaded.mass_kg).abs() < 1e-12 * loaded.mass_kg,
420 "{} against {}",
421 result.final_sample.mass_kg,
422 loaded.mass_kg
423 );
424 }
425
426 #[test]
432 fn a_clustered_sustainer_flies_on_with_every_motor() {
433 clustered_sustainer(&[]);
434 }
435
436 #[test]
439 fn a_failed_sustainer_tube_stays_out_after_the_separation() {
440 clustered_sustainer(&[1]);
441 }
442
443 fn clustered_sustainer(failed: &[usize]) {
446 let mut rocket = two_stage(Ignition::Burnout {
447 mount: BOOSTER_MOUNT.to_owned(),
448 delay_s: 1.0,
449 });
450 rocket.configurations[0]
451 .motors
452 .iter_mut()
453 .find(|m| m.mount == SUSTAINER_MOUNT)
454 .unwrap()
455 .failed_tubes = failed.to_vec();
456 let mount = rocket.stages[0].components[1]
457 .children
458 .iter_mut()
459 .find(|c| c.id == SUSTAINER_MOUNT)
460 .unwrap();
461 let hpr_design::Part::InnerTube(tube) = &mut mount.part else {
462 panic!("an inner tube");
463 };
464 tube.cluster_m = vec![[-0.004, 0.0], [0.004, 0.0]];
465 let separation = |sim: &Simulation| {
466 Separation::new(
467 Trigger::Burnout {
468 motor: motor_index(sim, BOOSTER_MOUNT),
469 delay_s: 0.5,
470 },
471 0,
472 )
473 };
474 let sim = staged(&rocket, separation);
475 assert_eq!(sim.assembly().motors.len(), 3);
476 let result = sim.run(&mut ()).unwrap();
477 let burnout_s = booster_burnout_s(&sim);
478 let mut ignitions = [Some(0.0); 3];
479 for tube in 0..2 {
480 let motor = 1 + tube;
481 assert_eq!(sim.assembly().motors[motor].tube, tube);
482 if failed.contains(&tube) {
483 assert!(result.event(EventKind::Ignition(motor)).is_none());
484 ignitions[motor] = None;
485 continue;
486 }
487 let lit = time_of(&result, EventKind::Ignition(motor));
488 assert!((lit - (burnout_s + 1.0)).abs() < 1e-12, "{motor}: {lit}");
489 }
490 let i175 = &sim.assembly().motors[1].mounted.motor;
491 assert!(
492 (time_of(&result, EventKind::Burnout) - (burnout_s + 1.0 + i175.burnout_time_s()))
493 .abs()
494 < 1e-12
495 );
496 let spent = super::super::recovery::body_mass_properties(
497 sim.assembly(),
498 (0, 0),
499 f64::MAX,
500 &ignitions,
501 );
502 assert_eq!(result.termination, Termination::GroundHit);
503 assert!(
504 (result.final_sample.mass_kg - spent.mass_kg).abs() < 1e-12 * spent.mass_kg,
505 "{} against {}",
506 result.final_sample.mass_kg,
507 spent.mass_kg
508 );
509 }
510
511 #[test]
514 fn a_sustainer_keeps_a_motor_set_never_to_light_through_the_separation() {
515 const SECOND: &str = "sustainer-second-mount";
516 let mut rocket = two_stage(Ignition::Burnout {
517 mount: BOOSTER_MOUNT.to_owned(),
518 delay_s: 1.0,
519 });
520 let airframe = &mut rocket.stages[0].components[1].children;
521 let mut mount = airframe
522 .iter()
523 .find(|c| c.id == SUSTAINER_MOUNT)
524 .unwrap()
525 .clone();
526 mount.id = SECOND.to_owned();
527 airframe.push(mount);
528 let motors = &mut rocket.configurations[0].motors;
529 let mut unlit = motors
530 .iter()
531 .find(|m| m.mount == SUSTAINER_MOUNT)
532 .unwrap()
533 .clone();
534 unlit.mount = SECOND.to_owned();
535 unlit.ignition = Ignition::Never;
536 motors.push(unlit);
537 let sim = staged(&rocket, |sim| {
538 Separation::new(
539 Trigger::Burnout {
540 motor: motor_index(sim, BOOSTER_MOUNT),
541 delay_s: 0.5,
542 },
543 0,
544 )
545 });
546 let second = motor_index(&sim, SECOND);
547 let result = sim.run(&mut ()).unwrap();
548 assert!(result.event(EventKind::Separation).is_some());
549 assert!(result.event(EventKind::Ignition(second)).is_none());
550 let lit = time_of(
551 &result,
552 EventKind::Ignition(motor_index(&sim, SUSTAINER_MOUNT)),
553 );
554 assert!(
555 (lit - (booster_burnout_s(&sim) + 1.0)).abs() < 1e-12,
556 "{lit}"
557 );
558 let mut ignitions = sim.assembly().ignition_times_s(|_| Some(0.0));
559 assert_eq!(ignitions[second], None);
560 ignitions[motor_index(&sim, BOOSTER_MOUNT)] = Some(0.0);
561 let spent = super::super::recovery::body_mass_properties(
562 sim.assembly(),
563 (0, 0),
564 f64::MAX,
565 &ignitions,
566 );
567 assert_eq!(result.termination, Termination::GroundHit);
568 assert!(
569 (result.final_sample.mass_kg - spent.mass_kg).abs() < 1e-12 * spent.mass_kg,
570 "{} against {}",
571 result.final_sample.mass_kg,
572 spent.mass_kg
573 );
574 }
575
576 #[test]
579 fn a_sustainer_set_never_to_light_flies_as_a_motor_out() {
580 let never = staged(&two_stage(Ignition::Never), |_| {
581 Separation::new(Trigger::Apogee, 0)
582 })
583 .run(&mut ())
584 .unwrap();
585 let mut out = two_stage(Ignition::Launch);
586 out.configurations[0]
587 .motors
588 .iter_mut()
589 .find(|m| m.mount == SUSTAINER_MOUNT)
590 .unwrap()
591 .failed_tubes = vec![0];
592 let out = staged(&out, |_| Separation::new(Trigger::Apogee, 0))
593 .run(&mut ())
594 .unwrap();
595 assert_eq!(kinds(&never), kinds(&out));
596 assert_eq!(
597 never.event(EventKind::Apogee).unwrap().sample,
598 out.event(EventKind::Apogee).unwrap().sample
599 );
600 assert!(never.bodies_landed(), "{:?}", never.bodies);
601 let ignitions = never
603 .events
604 .iter()
605 .filter_map(|e| match e.kind {
606 EventKind::Ignition(motor) => Some(motor),
607 _ => None,
608 })
609 .collect::<Vec<usize>>();
610 assert!(ignitions.is_empty(), "{ignitions:?}");
611 }
612
613 #[test]
614 fn apogee_separation_fires_in_flight_and_booster_flies_to_landing() {
615 let rocket = two_stage(Ignition::Launch);
620 let sim = staged(&rocket, |_| Separation::new(Trigger::Apogee, 0));
621 let result = sim.run(&mut ()).unwrap();
622 let apogee_s = time_of(&result, EventKind::Apogee);
623 let separation_s = time_of(&result, EventKind::Separation);
624 assert_eq!(separation_s, apogee_s);
625 assert!(separation_s > time_of(&result, EventKind::Burnout) + 5.0);
626 assert_eq!(result.termination, Termination::Separated);
627 assert!(result.bodies_landed(), "{:?}", result.bodies);
628 assert_eq!(result.landings().len(), 2);
629
630 let sim = staged(&rocket, |_| {
632 Separation::new(
633 Trigger::Altitude {
634 height_above_ground_m: 300.0,
635 },
636 0,
637 )
638 });
639 let result = sim.run(&mut ()).unwrap();
640 let at = result.event(EventKind::Separation).unwrap().sample;
641 assert!(
642 (at.height_above_ground_m - 300.0).abs() < 1e-6,
643 "{}",
644 at.height_above_ground_m
645 );
646 assert!(at.vertical_speed_m_s < 0.0);
647 assert!(result.bodies_landed(), "{:?}", result.bodies);
648
649 let result = serial_plan().run(&mut ()).unwrap();
651 assert_eq!(result.termination, Termination::GroundHit);
652 assert!(result.bodies_landed(), "{:?}", result.bodies);
653 let landings = result.landings();
654 assert_eq!(landings.len(), 2);
655 assert!(
656 landings
657 .iter()
658 .all(|l| l.height_above_ground_m.abs() < 1e-6)
659 );
660 assert!(landings[0].time_s != landings[1].time_s);
662 }
663
664 #[test]
665 fn staged_events_come_in_order() {
666 let sim = serial_plan();
667 let sustainer = motor_index(&sim, SUSTAINER_MOUNT);
668 let result = sim.run(&mut ()).unwrap();
669 let order = [
670 EventKind::Liftoff,
671 EventKind::RailExit,
672 EventKind::Separation,
673 EventKind::Ignition(sustainer),
674 EventKind::Burnout,
675 EventKind::Apogee,
676 EventKind::GroundHit,
677 ];
678 let times: Vec<f64> = order.iter().map(|&kind| time_of(&result, kind)).collect();
679 for pair in times.windows(2) {
680 assert!(pair[0] < pair[1], "{order:?}: {times:?}");
681 }
682 for kind in [EventKind::Trigger(0), EventKind::Deployment(0)] {
684 assert_eq!(time_of(&result, kind), time_of(&result, EventKind::Apogee));
685 }
686 for pair in result.events.windows(2) {
688 assert!(pair[0].sample.time_s <= pair[1].sample.time_s);
689 }
690 let burnouts = result
691 .events
692 .iter()
693 .filter(|e| e.kind == EventKind::Burnout)
694 .count();
695 assert_eq!(burnouts, 1);
696 let i175 = &sim.assembly().motors[sustainer].mounted.motor;
697 let expected = time_of(&result, EventKind::Ignition(sustainer)) + i175.burnout_time_s();
698 assert!((time_of(&result, EventKind::Burnout) - expected).abs() < 1e-12);
699 let booster = motor_index(&sim, BOOSTER_MOUNT);
701 assert!(result.event(EventKind::Ignition(booster)).is_none());
702 let body = &result.bodies[0];
704 assert_eq!(
705 body.start_sample.time_s,
706 time_of(&result, EventKind::Separation)
707 );
708 for pair in body.events.windows(2) {
709 assert!(pair[0].sample.time_s <= pair[1].sample.time_s);
710 }
711 assert_eq!(body.termination, Termination::GroundHit);
712
713 let rocket = two_stage(Ignition::Separation { delay_s: 0.25 });
716 let sim = staged(&rocket, |sim| {
717 Separation::new(
718 Trigger::Burnout {
719 motor: motor_index(sim, BOOSTER_MOUNT),
720 delay_s: 0.5,
721 },
722 0,
723 )
724 });
725 let result = sim.run(&mut ()).unwrap();
726 let burnouts: Vec<f64> = result
727 .events
728 .iter()
729 .filter(|e| e.kind == EventKind::Burnout)
730 .map(|e| e.sample.time_s)
731 .collect();
732 let separation_s = time_of(&result, EventKind::Separation);
733 let ignition_s = time_of(&result, EventKind::Ignition(sustainer));
734 assert!((ignition_s - (separation_s + 0.25)).abs() < 1e-12);
735 assert_eq!(burnouts.len(), 2, "{burnouts:?}");
736 assert!((burnouts[0] - booster_burnout_s(&sim)).abs() < 1e-12);
737 assert!((burnouts[1] - (ignition_s + i175.burnout_time_s())).abs() < 1e-12);
738 }
739
740 #[test]
741 fn a_powered_separation_conserves_linear_momentum() {
742 let rocket = two_stage(Ignition::Burnout {
748 mount: BOOSTER_MOUNT.to_owned(),
749 delay_s: 1.0,
750 });
751 let rail = Rail {
752 elevation_rad: 80.0_f64.to_radians(),
753 ..Rail::vertical(6.0)
754 };
755 let sim = staged_with(&rocket, rail, BOOSTER_AT_SEPARATION, |sim| {
756 Separation::new(
757 Trigger::Burnout {
758 motor: motor_index(sim, BOOSTER_MOUNT),
759 delay_s: 0.5,
760 },
761 0,
762 )
763 })
764 .unwrap();
765 let mut starts = StepStarts::default();
766 let result = sim.run(&mut starts).unwrap();
767 let stack = result.event(EventKind::Separation).unwrap().sample;
768 let booster = &result.bodies[0];
769 let sustainer = starts
770 .0
771 .iter()
772 .find(|s| s.time_s == stack.time_s && s.mass_kg < stack.mass_kg)
773 .expect("the sustainer's first step");
774 let rate = stack.state.body_rate_rad_s.length();
775 assert!(rate > 1e-3, "{rate}");
776 let before = stack.cg_velocity_enu_m_s * stack.mass_kg;
777 let after = sustainer.cg_velocity_enu_m_s * sustainer.mass_kg
778 + booster.start_sample.cg_velocity_enu_m_s * booster.mass_kg;
779 assert!(
780 (after - before).length() < 1e-9 * before.length(),
781 "{after:?} against {before:?}"
782 );
783 assert!(
785 (sustainer.mass_kg + booster.mass_kg - stack.mass_kg).abs() < 1e-12 * stack.mass_kg
786 );
787 }
788
789 const MIDDLE_MOUNT: &str = "middle-motor-mount";
790
791 fn three_stage(middle: Ignition, sustainer: Ignition) -> Rocket {
795 fn rename(component: &mut hpr_design::Component) {
796 component.id = component.id.replace("sustainer", "middle");
797 for child in &mut component.children {
798 rename(child);
799 }
800 }
801 let mut rocket = two_stage(sustainer);
802 let mut stage = rocket.stages[0].clone();
803 stage.id = "middle".to_owned();
804 stage.components.retain(|c| c.id != "nose");
805 stage.components.iter_mut().for_each(rename);
806 rocket.stages.insert(1, stage);
807 let configuration = rocket
808 .configurations
809 .iter_mut()
810 .find(|c| c.id == CONFIGURATION)
811 .unwrap();
812 let mut motor = configuration
813 .motors
814 .iter()
815 .find(|m| m.mount == SUSTAINER_MOUNT)
816 .unwrap()
817 .clone();
818 motor.mount = MIDDLE_MOUNT.to_owned();
819 motor.ignition = middle;
820 configuration.motors.push(motor);
821 rocket
822 }
823
824 fn three_staged(
827 rocket: &Rocket,
828 separations: impl Fn(&Simulation) -> Vec<Separation>,
829 ) -> Result<Simulation, SimError> {
830 let sim = Simulation::new(
831 rocket,
832 CONFIGURATION,
833 Environment::standard(site()).unwrap(),
834 Rail::vertical(6.0),
835 FlightSettings::default(),
836 )
837 .unwrap();
838 let booster = DeviceDrag::tumbling_stages(sim.assembly(), (2, 2)).unwrap();
839 let middle = DeviceDrag::tumbling_stages(sim.assembly(), (1, 1)).unwrap();
840 let separations = separations(&sim);
841 sim.with_recovery(vec![
842 Device::new(
843 "sustainer main",
844 DeviceDrag::canopy(CanopyType::FlatCircular, 1.2),
845 Trigger::Apogee,
846 ),
847 Device::new("booster tumble", booster, BOOSTER_AT_SEPARATION).on_body(1),
848 Device::new("middle tumble", middle, BOOSTER_AT_SEPARATION).on_body(2),
849 ])
850 .unwrap()
851 .with_separations(separations)
852 }
853
854 fn burnout_chain() -> (Rocket, impl Fn(&Simulation) -> Vec<Separation>) {
857 let rocket = three_stage(
858 Ignition::Burnout {
859 mount: BOOSTER_MOUNT.to_owned(),
860 delay_s: 0.0,
861 },
862 Ignition::Burnout {
863 mount: MIDDLE_MOUNT.to_owned(),
864 delay_s: 0.0,
865 },
866 );
867 let separations = |sim: &Simulation| {
868 vec![
869 Separation::new(
870 Trigger::Burnout {
871 motor: motor_index(sim, BOOSTER_MOUNT),
872 delay_s: 0.0,
873 },
874 1,
875 ),
876 Separation::new(
877 Trigger::Burnout {
878 motor: motor_index(sim, MIDDLE_MOUNT),
879 delay_s: 0.0,
880 },
881 0,
882 ),
883 ]
884 };
885 (rocket, separations)
886 }
887
888 #[derive(Default)]
891 struct BodySteps(Vec<(usize, f64, f64, crate::recovery::BodySample, DVec3)>);
892
893 impl Observer for BodySteps {
894 fn body_step(
895 &mut self,
896 body: usize,
897 step: &dyn crate::recorder::BodyStep,
898 ) -> Result<(), SimError> {
899 let middle = 0.5 * (step.start_s() + step.end_s());
900 self.0.push((
901 body,
902 step.start_s(),
903 step.end_s(),
904 step.sample(middle)?,
905 step.acceleration_enu_m_s2(middle)?,
906 ));
907 Ok(())
908 }
909 }
910
911 #[test]
912 fn an_observer_sees_each_accepted_step_of_a_separated_body_and_changes_no_flight() {
913 let sim = serial_plan();
914 let mut steps = BodySteps::default();
915 let watched = sim.run(&mut steps).unwrap();
916 assert_eq!(watched, sim.run(&mut ()).unwrap());
917 let [booster] = watched.bodies.as_slice() else {
918 panic!("one dropped body: {:?}", watched.bodies);
919 };
920 let seen = &steps.0;
921 assert!(seen.iter().all(|step| step.0 == booster.body));
922 assert_eq!(
925 seen.len() as u64,
926 booster.stats.accepted_steps,
927 "{:?}",
928 booster.stats
929 );
930 assert_eq!(seen[0].1, booster.start_sample.time_s);
931 assert!(seen.windows(2).all(|pair| pair[0].2 == pair[1].1));
932 assert_eq!(seen.last().unwrap().2, booster.final_sample.time_s);
933 let tall = seen.len() / 2;
937 let (a, b) = (&seen[tall], &seen[tall + 1]);
938 let dt = b.3.time_s - a.3.time_s;
939 let by_difference = (b.3.cg_velocity_enu_m_s - a.3.cg_velocity_enu_m_s) / dt;
940 let by_equation = (a.4 + b.4) * 0.5;
941 assert!(
942 (by_difference - by_equation).length() < 0.01 * by_equation.length().max(1.0),
943 "{by_difference} against {by_equation} over {dt} s"
944 );
945 }
946
947 #[test]
948 fn two_powered_separations_drop_the_booster_then_the_middle() {
949 let (rocket, separations) = burnout_chain();
953 let sim = three_staged(&rocket, separations).unwrap();
954 let booster_out_s = booster_burnout_s(&sim);
955 let middle_out_s = booster_out_s
956 + sim.assembly().motors[motor_index(&sim, MIDDLE_MOUNT)]
957 .mounted
958 .motor
959 .burnout_time_s();
960 let mut starts = StepStarts::default();
961 let result = sim.run(&mut starts).unwrap();
962 assert_eq!(result.termination, Termination::GroundHit);
963 let splits: Vec<_> = result
964 .events
965 .iter()
966 .filter(|event| event.kind == EventKind::Separation)
967 .map(|event| event.sample)
968 .collect();
969 assert_eq!(splits.len(), 2, "{:?}", kinds(&result));
970 assert!((splits[0].time_s - booster_out_s).abs() < 1e-9);
971 assert!((splits[1].time_s - middle_out_s).abs() < 1e-9);
972 let ignitions = result
974 .events
975 .iter()
976 .filter(|event| matches!(event.kind, EventKind::Ignition(_)))
977 .count();
978 assert_eq!(ignitions, 2, "{:?}", kinds(&result));
979 let bodies: Vec<_> = result
980 .bodies
981 .iter()
982 .map(|body| (body.body, body.stages))
983 .collect();
984 assert_eq!(bodies, [(1, (2, 2)), (2, (1, 1))]);
985 for (split, body) in splits.iter().zip(&result.bodies) {
986 assert_eq!(body.termination, Termination::GroundHit);
987 let flown = starts
988 .0
989 .iter()
990 .find(|s| s.time_s == split.time_s && s.mass_kg < split.mass_kg)
991 .expect("the sustainer's first step after the split");
992 assert!(
993 (flown.mass_kg + body.mass_kg - split.mass_kg).abs() < 1e-12 * split.mass_kg,
994 "{} + {} against {}",
995 flown.mass_kg,
996 body.mass_kg,
997 split.mass_kg
998 );
999 let before = split.cg_velocity_enu_m_s * split.mass_kg;
1000 let after = flown.cg_velocity_enu_m_s * flown.mass_kg
1001 + body.start_sample.cg_velocity_enu_m_s * body.mass_kg;
1002 assert!(
1003 (after - before).length() < 1e-9 * before.length(),
1004 "{after:?} against {before:?}"
1005 );
1006 }
1007 let apogee = result.event(EventKind::Apogee).unwrap().sample;
1009 assert!(apogee.time_s > middle_out_s);
1010 assert!(apogee.height_above_ground_m > splits[1].height_above_ground_m + 100.0);
1011 let again = three_staged(&rocket, burnout_chain().1)
1013 .unwrap()
1014 .run(&mut ())
1015 .unwrap();
1016 assert_eq!(again.final_sample, result.final_sample);
1017 assert_eq!(again.bodies, result.bodies);
1018 }
1019
1020 #[test]
1021 fn a_motor_lit_by_the_first_separation_counts_from_it_at_the_second() {
1022 let rocket = three_stage(
1027 Ignition::Separation { delay_s: 0.0 },
1028 Ignition::Separation { delay_s: 0.0 },
1029 );
1030 let flight = |second_s: f64| {
1031 three_staged(&rocket, |sim| {
1032 vec![
1033 Separation::new(
1034 Trigger::Burnout {
1035 motor: motor_index(sim, BOOSTER_MOUNT),
1036 delay_s: 0.0,
1037 },
1038 1,
1039 ),
1040 Separation::new(Trigger::Time { time_s: second_s }, 0),
1041 ]
1042 })
1043 .unwrap()
1044 };
1045 let probe = flight(30.0);
1046 let booster_out_s = booster_burnout_s(&probe);
1047 let middle = &probe.assembly().motors[motor_index(&probe, MIDDLE_MOUNT)];
1048 let middle_out_s = booster_out_s + middle.mounted.motor.burnout_time_s();
1049 let dry_kg = middle.dry_mass_properties().mass_kg;
1050 let loaded_kg = middle.mass_properties_lit(0.0, None).mass_kg;
1051 assert!(loaded_kg > dry_kg + 0.05);
1052 let result = flight(middle_out_s + 0.5).run(&mut ()).unwrap();
1053 let middle_body = result.bodies.iter().find(|body| body.body == 2).unwrap();
1054 let structure_kg = probe.assembly().layout.stages[1].mass.mass_kg;
1055 assert!(
1056 (middle_body.mass_kg - (structure_kg + dry_kg)).abs() < 1e-9,
1057 "{} against {} + {}",
1058 middle_body.mass_kg,
1059 structure_kg,
1060 dry_kg
1061 );
1062 let error = flight(middle_out_s - 0.2).run(&mut ()).unwrap_err();
1064 assert!(
1065 matches!(error, SimError::Domain { what, value }
1066 if what.contains("aft body's motors must have burned out")
1067 && (value - middle_out_s).abs() < 1e-9),
1068 "{error}"
1069 );
1070 }
1071
1072 #[test]
1073 fn several_separations_refuse_what_they_cannot_fly() {
1074 let (rocket, separations) = burnout_chain();
1075 let sim = || {
1076 Simulation::new(
1077 &rocket,
1078 CONFIGURATION,
1079 Environment::standard(site()).unwrap(),
1080 Rail::vertical(6.0),
1081 FlightSettings::default(),
1082 )
1083 .unwrap()
1084 };
1085 let (booster, middle) = (
1086 motor_index(&sim(), BOOSTER_MOUNT),
1087 motor_index(&sim(), MIDDLE_MOUNT),
1088 );
1089 let at = |motor, after_stage| {
1090 Separation::new(
1091 Trigger::Burnout {
1092 motor,
1093 delay_s: 0.0,
1094 },
1095 after_stage,
1096 )
1097 };
1098 let error = sim()
1100 .with_separations(vec![at(middle, 0), at(booster, 1)])
1101 .unwrap_err();
1102 assert!(
1103 matches!(error, SimError::Domain { what, value }
1104 if what.contains("forward of the one before") && value == 1.0),
1105 "{error}"
1106 );
1107 let error = sim()
1109 .with_separations(vec![
1110 Separation::new(Trigger::Time { time_s: 9.0 }, 1),
1111 Separation::new(Trigger::Time { time_s: 8.0 }, 0),
1112 ])
1113 .unwrap_err();
1114 assert!(
1115 matches!(error, SimError::Domain { what, value }
1116 if what.contains("before the separation ahead of it") && value == 8.0),
1117 "{error}"
1118 );
1119 let ejection = crate::Ejection::aft_of(Trigger::Apogee, "nose");
1121 let error = sim()
1122 .with_separations(separations(&sim()))
1123 .unwrap()
1124 .with_ejections(vec![ejection.clone()])
1125 .unwrap_err();
1126 assert!(
1127 matches!(error, SimError::Unsupported { what } if what.contains("more than one separation")),
1128 "{error}"
1129 );
1130 let error = sim()
1131 .with_ejections(vec![ejection])
1132 .unwrap()
1133 .with_separations(separations(&sim()))
1134 .unwrap_err();
1135 assert!(
1136 matches!(error, SimError::Unsupported { what } if what.contains("more than one separation")),
1137 "{error}"
1138 );
1139 let error = sim()
1141 .with_recovery(vec![
1142 Device::new(
1143 "sustainer main",
1144 DeviceDrag::canopy(CanopyType::FlatCircular, 1.2),
1145 Trigger::Apogee,
1146 ),
1147 Device::new(
1148 "booster tumble",
1149 DeviceDrag::tumbling_stages(sim().assembly(), (2, 2)).unwrap(),
1150 BOOSTER_AT_SEPARATION,
1151 )
1152 .on_body(1),
1153 ])
1154 .unwrap()
1155 .with_separations(separations(&sim()))
1156 .unwrap_err();
1157 assert!(
1158 matches!(error, SimError::Domain { what, value }
1159 if what.contains("every body needs one") && value == 2.0),
1160 "{error}"
1161 );
1162 let unlit = three_stage(Ignition::Never, Ignition::Never);
1165 let error = three_staged(&unlit, |sim| {
1166 vec![
1167 at(motor_index(sim, BOOSTER_MOUNT), 1),
1168 Separation::new(Trigger::Time { time_s: 40.0 }, 0),
1169 ]
1170 })
1171 .unwrap()
1172 .run(&mut ())
1173 .unwrap_err();
1174 assert!(
1175 matches!(error, SimError::Domain { what, .. }
1176 if what.contains("leaving nothing ahead to burn")),
1177 "{error}"
1178 );
1179 let error = three_staged(&rocket, |sim| {
1182 vec![
1183 Separation::new(Trigger::Apogee, 1),
1184 at(motor_index(sim, MIDDLE_MOUNT), 0),
1185 ]
1186 })
1187 .unwrap()
1188 .run(&mut ())
1189 .unwrap_err();
1190 assert!(
1191 matches!(error, SimError::Domain { what, .. }
1192 if what.contains("fires before the separation ahead of it")),
1193 "{error}"
1194 );
1195 }
1196
1197 #[test]
1198 fn a_whole_base_under_power_holds_through_a_powered_separation() {
1199 let rocket = two_stage(Ignition::Burnout {
1204 mount: BOOSTER_MOUNT.to_owned(),
1205 delay_s: 1.0,
1206 });
1207 let steps = |whole: bool| {
1208 let sim = staged(&rocket, |sim| {
1209 Separation::new(
1210 Trigger::Burnout {
1211 motor: motor_index(sim, BOOSTER_MOUNT),
1212 delay_s: 0.5,
1213 },
1214 0,
1215 )
1216 });
1217 let sim = if whole {
1218 sim.with_full_base_drag_under_power()
1219 } else {
1220 sim
1221 };
1222 let mut starts = StepStarts::default();
1223 let result = sim.run(&mut starts).unwrap();
1224 let burnouts = [
1225 booster_burnout_s(&sim),
1226 time_of(&result, EventKind::Burnout),
1227 ];
1228 burnouts
1231 .iter()
1232 .map(|&t| {
1233 let before = starts.0.iter().rfind(|s| s.time_s < t).unwrap();
1234 let after = starts.0.iter().find(|s| s.time_s >= t).unwrap();
1235 assert!(before.thrust_n > 0.0 && after.thrust_n == 0.0);
1236 after.axial_coefficient / before.axial_coefficient - 1.0
1237 })
1238 .collect::<Vec<f64>>()
1239 };
1240 let (relieved, whole) = (steps(false), steps(true));
1243 for (relieved, whole) in relieved.into_iter().zip(whole) {
1244 assert!(relieved > 0.1, "{relieved}");
1245 assert!(whole.abs() < 0.005, "{whole}");
1246 }
1247 }
1248
1249 #[test]
1250 fn a_drag_scale_holds_through_a_powered_separation() {
1251 let rocket = two_stage(Ignition::Burnout {
1258 mount: BOOSTER_MOUNT.to_owned(),
1259 delay_s: 1.0,
1260 });
1261 let step = |scale: f64| {
1262 let sim = staged(&rocket, |sim| {
1263 Separation::new(
1264 Trigger::Burnout {
1265 motor: motor_index(sim, BOOSTER_MOUNT),
1266 delay_s: 0.5,
1267 },
1268 0,
1269 )
1270 })
1271 .with_drag_scale(scale)
1272 .unwrap();
1273 let mut starts = StepStarts::default();
1274 let result = sim.run(&mut starts).unwrap();
1275 let separated_s = time_of(&result, EventKind::Separation);
1276 let before = starts.0.iter().rfind(|s| s.time_s < separated_s).unwrap();
1277 let after = starts.0.iter().find(|s| s.time_s > separated_s).unwrap();
1278 (
1279 after.axial_coefficient / before.axial_coefficient,
1280 before.mach,
1281 )
1282 };
1283 let (plain, plain_mach) = step(1.0);
1284 let (scaled, scaled_mach) = step(1.05);
1285 let change = scaled / plain - 1.0;
1286 assert!(
1287 change.abs() < 0.005,
1288 "{change}: {plain} {scaled} at Mach {plain_mach} and {scaled_mach}"
1289 );
1290 }
1291
1292 #[test]
1293 fn staging_refuses_what_it_cannot_fly() {
1294 let rocket = two_stage(Ignition::Burnout {
1297 mount: BOOSTER_MOUNT.to_owned(),
1298 delay_s: 1.0,
1299 });
1300 let booster = motor_index(
1301 &Simulation::new(
1302 &rocket,
1303 CONFIGURATION,
1304 Environment::standard(site()).unwrap(),
1305 Rail::vertical(6.0),
1306 FlightSettings::default(),
1307 )
1308 .unwrap(),
1309 BOOSTER_MOUNT,
1310 );
1311 type Override = fn(Simulation) -> Simulation;
1312 let overrides: [(Override, &str); 2] = [
1313 (|sim| sim.with_drag_table(constant_drag(0.5)), "a table"),
1314 (|sim| sim.with_drag_model(ConstantDrag(0.5)), "a drag model"),
1315 ];
1316 for (with_override, flown) in overrides {
1317 let sim = with_override(
1318 Simulation::new(
1319 &rocket,
1320 CONFIGURATION,
1321 Environment::standard(site()).unwrap(),
1322 Rail::vertical(6.0),
1323 FlightSettings::default(),
1324 )
1325 .unwrap(),
1326 );
1327 let tumble = DeviceDrag::tumbling_stages(sim.assembly(), (1, 1)).unwrap();
1328 let sim = sim
1329 .with_recovery(vec![
1330 Device::new(
1331 "sustainer main",
1332 DeviceDrag::canopy(CanopyType::FlatCircular, 1.2),
1333 Trigger::Apogee,
1334 ),
1335 Device::new("booster tumble", tumble, BOOSTER_AT_SEPARATION).on_body(1),
1336 ])
1337 .unwrap();
1338 let error = sim
1339 .with_separation(Separation::new(
1340 Trigger::Burnout {
1341 motor: booster,
1342 delay_s: 0.5,
1343 },
1344 0,
1345 ))
1346 .unwrap()
1347 .run(&mut ())
1348 .unwrap_err();
1349 assert!(
1350 matches!(error, SimError::Domain { what, .. }
1351 if what.starts_with("time of a powered separation (a drag table or drag model")),
1352 "{flown} flown past a powered separation: {error:?}"
1353 );
1354 }
1355
1356 for (motor_delay_s, what) in [(-0.5, "negative delay"), (f64::NAN, "delay NaN")] {
1358 let error = Simulation::new(
1359 &rocket,
1360 CONFIGURATION,
1361 Environment::standard(site()).unwrap(),
1362 Rail::vertical(6.0),
1363 FlightSettings::default(),
1364 )
1365 .unwrap()
1366 .with_separation(Separation::new(
1367 Trigger::Burnout {
1368 motor: booster,
1369 delay_s: motor_delay_s,
1370 },
1371 0,
1372 ))
1373 .expect_err(what);
1374 assert!(
1375 matches!(error, SimError::Domain { what, .. } if what.contains("after a motor's burnout")),
1376 "{what}: {error:?}"
1377 );
1378 }
1379 let error = Simulation::new(
1380 &rocket,
1381 CONFIGURATION,
1382 Environment::standard(site()).unwrap(),
1383 Rail::vertical(6.0),
1384 FlightSettings::default(),
1385 )
1386 .unwrap()
1387 .with_separation(Separation::new(Trigger::Time { time_s: 0.5 }, 0))
1388 .expect_err("the booster still burning");
1389 let burnout_s = rocket.assemble(CONFIGURATION).unwrap().motors[booster]
1390 .mounted
1391 .motor
1392 .burnout_time_s();
1393 assert!(
1394 matches!(error, SimError::Domain { value, .. } if value == burnout_s),
1395 "{error:?}"
1396 );
1397
1398 let sim = staged_with(&rocket, Rail::vertical(6.0), Trigger::Apogee, |_| {
1400 Separation::new(
1401 Trigger::Burnout {
1402 motor: booster,
1403 delay_s: 0.5,
1404 },
1405 0,
1406 )
1407 })
1408 .unwrap();
1409 let error = sim.run(&mut ()).expect_err("a booster with nothing open");
1410 let nothing_open = |error: &SimError| {
1411 matches!(error, SimError::Domain { what, value }
1412 if what.contains("booster has no airframe drag") && (value - (burnout_s + 0.5)).abs() < 1e-12)
1413 };
1414 assert!(nothing_open(&error), "{error:?}");
1415 let rocket_sim = Simulation::new(
1417 &rocket,
1418 CONFIGURATION,
1419 Environment::standard(site()).unwrap(),
1420 Rail::vertical(6.0),
1421 FlightSettings::default(),
1422 )
1423 .unwrap();
1424 let tumble = DeviceDrag::tumbling_stages(rocket_sim.assembly(), (1, 1)).unwrap();
1425 let error = rocket_sim
1426 .with_recovery(vec![
1427 Device::new(
1428 "sustainer main",
1429 DeviceDrag::canopy(CanopyType::FlatCircular, 1.2),
1430 Trigger::Apogee,
1431 ),
1432 Device::new("booster tumble", tumble, BOOSTER_AT_SEPARATION)
1433 .with_lag_s(0.1)
1434 .on_body(1),
1435 ])
1436 .unwrap()
1437 .with_separation(Separation::new(
1438 Trigger::Burnout {
1439 motor: booster,
1440 delay_s: 0.5,
1441 },
1442 0,
1443 ))
1444 .unwrap()
1445 .run(&mut ())
1446 .expect_err("a booster whose device opens after the split");
1447 assert!(nothing_open(&error), "{error:?}");
1448
1449 let lit_by_it = two_stage(Ignition::Separation { delay_s: 0.0 });
1451 let error = staged_with(
1452 &lit_by_it,
1453 Rail::vertical(6.0),
1454 BOOSTER_AT_SEPARATION,
1455 |sim| {
1456 Separation::new(
1457 Trigger::Burnout {
1458 motor: motor_index(sim, SUSTAINER_MOUNT),
1459 delay_s: 0.5,
1460 },
1461 0,
1462 )
1463 },
1464 )
1465 .expect_err("a separation that could never fire");
1466 let sustainer = rocket
1467 .assemble(CONFIGURATION)
1468 .unwrap()
1469 .motors
1470 .iter()
1471 .position(|m| m.mount == SUSTAINER_MOUNT)
1472 .unwrap();
1473 assert!(
1474 matches!(error, SimError::Domain { what, value }
1475 if what.contains("could never fire") && value == sustainer as f64),
1476 "{error:?}"
1477 );
1478
1479 let sim = Simulation::new(
1482 &rocket,
1483 CONFIGURATION,
1484 Environment::standard(site()).unwrap(),
1485 Rail::vertical(6.0),
1486 FlightSettings::default(),
1487 )
1488 .unwrap();
1489 let tumble = DeviceDrag::tumbling_stages(sim.assembly(), (1, 1)).unwrap();
1490 let error = sim
1491 .with_recovery(vec![
1492 Device::new(
1493 "sustainer main",
1494 DeviceDrag::canopy(CanopyType::FlatCircular, 1.2),
1495 Trigger::Time { time_s: 1.0 },
1496 ),
1497 Device::new("booster tumble", tumble, BOOSTER_AT_SEPARATION).on_body(1),
1498 ])
1499 .unwrap()
1500 .with_separation(Separation::new(
1501 Trigger::Burnout {
1502 motor: booster,
1503 delay_s: 0.5,
1504 },
1505 0,
1506 ))
1507 .unwrap()
1508 .run(&mut ())
1509 .expect_err("a powered separation in the descent");
1510 assert!(
1511 matches!(error, SimError::Domain { what, .. } if what.contains("still has a motor to burn")),
1512 "{error:?}"
1513 );
1514 }
1515
1516 #[test]
1517 fn an_air_start_lights_at_its_time_and_burns_on_its_own_clock() {
1518 let rocket = two_stage(Ignition::Time { time_s: 3.0 });
1520 let sim = Simulation::new(
1521 &rocket,
1522 CONFIGURATION,
1523 Environment::standard(site()).unwrap(),
1524 Rail::vertical(6.0),
1525 FlightSettings::default(),
1526 )
1527 .unwrap()
1528 .with_recovery(vec![Device::new(
1529 "main",
1530 DeviceDrag::canopy(CanopyType::FlatCircular, 1.5),
1531 Trigger::Apogee,
1532 )])
1533 .unwrap();
1534 let sustainer = motor_index(&sim, SUSTAINER_MOUNT);
1535 let result = sim.run(&mut ()).unwrap();
1536 let lit = result.event(EventKind::Ignition(sustainer)).unwrap().sample;
1537 assert_eq!(lit.time_s, 3.0);
1538 let mut ignition_s = vec![Some(0.0); sim.assembly().motors.len()];
1540 ignition_s[sustainer] = Some(3.0);
1541 let expected = sim.assembly().mass_properties_lit(3.0, &ignition_s);
1542 assert!((lit.mass_kg - expected.mass_kg).abs() < 1e-12 * expected.mass_kg);
1543 let full = sim.assembly().motors[sustainer]
1544 .mass_properties(0.0)
1545 .mass_kg;
1546 let dry = sim.assembly().motors[sustainer]
1547 .dry_mass_properties()
1548 .mass_kg;
1549 let booster_dry = sim.assembly().dry_mass_properties().mass_kg - dry;
1550 assert!(
1551 (lit.mass_kg - (booster_dry + full)).abs() < 1e-9,
1552 "{}",
1553 lit.mass_kg
1554 );
1555 let i175 = &sim.assembly().motors[sustainer].mounted.motor;
1557 assert!(
1558 (time_of(&result, EventKind::Burnout) - (3.0 + i175.burnout_time_s())).abs() < 1e-12
1559 );
1560 let spent = sim.assembly().dry_mass_properties().mass_kg;
1561 assert!((result.final_sample.mass_kg - spent).abs() < 1e-12 * spent);
1562 assert_eq!(result.termination, Termination::GroundHit);
1563 }
1564
1565 fn cluster_of_three(failed: Vec<usize>) -> hpr_design::Assembly {
1569 let mut rocket = design("synthetic-54mm-three-fin");
1570 let mount = rocket.stages[0].components[1]
1571 .children
1572 .iter_mut()
1573 .find(|c| c.id == SUSTAINER_MOUNT)
1574 .unwrap();
1575 let hpr_design::Part::InnerTube(tube) = &mut mount.part else {
1576 panic!("an inner tube");
1577 };
1578 tube.cluster_m = [0.0_f64, 120.0, 240.0]
1579 .iter()
1580 .map(|a| [A * a.to_radians().cos(), A * a.to_radians().sin()])
1581 .collect();
1582 rocket.configurations[0].motors[0].failed_tubes = failed;
1583 let id = rocket.configurations[0].id.clone();
1584 rocket.assemble(&id).unwrap()
1585 }
1586
1587 const A: f64 = 0.02;
1589
1590 fn at_rest(assembly: &hpr_design::Assembly, t: f64) -> (DVec3, crate::dynamics::Evaluation) {
1593 use crate::dynamics::{Conditions, Phase, Vehicle};
1594 let ignition_s = assembly.ignition_times_s(|_| None);
1595 let aero = hpr_aero::AeroModel::new(&assembly.layout).unwrap();
1596 let vehicle = Vehicle::lit(assembly.clone(), aero, ignition_s).unwrap();
1597 let environment = analytic_environment(UniformAir::vacuum(), 9.806_65);
1598 let state = crate::state::State {
1599 position_enu_m: DVec3::new(0.0, 0.0, 1000.0),
1600 velocity_enu_m_s: DVec3::ZERO,
1601 attitude: DQuat::IDENTITY,
1602 body_rate_rad_s: DVec3::ZERO,
1603 };
1604 let evaluation = vehicle
1605 .evaluate(
1606 &environment,
1607 0.0,
1608 Conditions {
1609 phase: Phase::Free,
1610 window: (t - 0.1, t + 0.1),
1611 drag_area_m2: 0.0,
1612 pivot: None,
1613 },
1614 t,
1615 &state.to_array(),
1616 )
1617 .unwrap();
1618 (
1619 DVec3::from_slice(&evaluation.derivative[10..13]),
1620 evaluation,
1621 )
1622 }
1623
1624 fn by_hand(assembly: &hpr_design::Assembly, t: f64) -> DVec3 {
1628 let lit = assembly.ignition_times_s(|_| None);
1629 let mass = assembly.mass_properties_lit(t, &lit);
1630 let c = mass.cg_m;
1631 let mut moment = DVec3::ZERO;
1632 for (placed, ignition) in assembly.motors.iter().zip(&lit) {
1633 if ignition.is_some() {
1634 let thrust = placed.mounted.motor.thrust_at_pressure_n(t, 0.0);
1635 let (x, y) = (placed.nozzle_m.x - c.x, placed.nozzle_m.y - c.y);
1636 moment += DVec3::new(thrust * y, -thrust * x, 0.0);
1637 }
1638 }
1639 mass.inertia_kg_m2.inverse() * moment
1640 }
1641
1642 #[test]
1648 fn a_cluster_sums_its_motors_thrust_and_mass() {
1649 let assembly = cluster_of_three(Vec::new());
1650 assert_eq!(assembly.motors.len(), 3);
1651 let motor = &assembly.motors[0].mounted.motor;
1652 let t = 1.0;
1653 let (omega_dot, evaluation) = at_rest(&assembly, t);
1654 let one = motor.thrust_at_pressure_n(t, 0.0);
1656 assert!((evaluation.thrust_n - 3.0 * one).abs() <= 1e-12 * one);
1657 let want = assembly.layout.structure.mass_kg + 3.0 * motor.state(t).total.mass_kg;
1658 assert!((evaluation.mass.mass_kg - want).abs() <= 1e-12 * want);
1659 let want = by_hand(&assembly, t);
1660 let error = (omega_dot - want).length() / want.length();
1661 assert!(error <= 1e-5, "{omega_dot:?} vs {want:?}: {error:e}");
1662 }
1663
1664 #[test]
1674 fn cluster_motor_out_produces_pitch_moment() {
1675 let assembly = cluster_of_three(vec![0]);
1676 let fails: Vec<bool> = assembly.motors.iter().map(|m| m.fails).collect();
1677 assert_eq!(fails, [true, false, false]);
1678 let t = 1.0;
1679 let (omega_dot, evaluation) = at_rest(&assembly, t);
1680 let motor = &assembly.motors[1].mounted.motor;
1681 let thrust = motor.thrust_at_pressure_n(t, 0.0);
1682 assert!((evaluation.thrust_n - 2.0 * thrust).abs() <= 1e-12 * thrust);
1683 let lit = assembly.ignition_times_s(|_| None);
1684 let mass = assembly.mass_properties_lit(t, &lit);
1685 let c = mass.cg_m;
1686 assert!(c.x > 1e-3, "{c:?}");
1687 let moment = DVec3::new(-2.0 * thrust * c.y, thrust * (A + 2.0 * c.x), 0.0);
1688 let want = mass.inertia_kg_m2.inverse() * moment;
1689 assert!((thrust - 193.98).abs() < 5e-3 && (c.x - 1.33e-3).abs() < 5e-6);
1691 assert!((moment.y - 4.396).abs() < 5e-4 && (want.y - 41.80).abs() < 5e-3);
1692 assert!(((by_hand(&assembly, t) - want).length()) <= 1e-12 * want.length());
1693 assert!(want.y > 0.0);
1694 let error = (omega_dot - want).length() / want.length();
1695 assert!(error <= 1e-6, "{omega_dot:?} vs {want:?}: {error:e}");
1696 assert!(omega_dot.y > 50.0 * omega_dot.x.abs().max(omega_dot.z.abs()));
1698 let (full, _) = at_rest(&cluster_of_three(Vec::new()), t);
1699 assert!(full.length() < omega_dot.length() / 40.0, "{full:?}");
1700 }
1701
1702 struct Scanned {
1705 metrics: crate::metrics::FlightMetrics,
1706 least_static: f64,
1707 least_flight: f64,
1708 }
1709
1710 impl Observer for Scanned {
1711 fn step(&mut self, step: &dyn FlightStep) -> Result<(), SimError> {
1712 let kept = self.metrics.stability().len();
1713 self.metrics.step(step)?;
1714 if self.metrics.stability().len() > kept {
1715 let (a, b) = (step.start_s(), step.end_s());
1716 for i in 0..=200 {
1717 let s = step.stability(a + (b - a) * f64::from(i) / 200.0)?;
1718 let least = |m: Option<f64>, least: f64| m.map_or(least, |m| m.min(least));
1719 self.least_static = least(s.static_margin.margin_cal, self.least_static);
1720 self.least_flight = least(s.flight_margin.margin_cal, self.least_flight);
1721 }
1722 }
1723 Ok(())
1724 }
1725
1726 fn event(&mut self, event: &crate::flight::FlightEvent) {
1727 self.metrics.event(event);
1728 }
1729
1730 fn body_step(
1732 &mut self,
1733 body: usize,
1734 step: &dyn crate::recorder::BodyStep,
1735 ) -> Result<(), SimError> {
1736 self.metrics.body_step(body, step)
1737 }
1738 }
1739
1740 #[test]
1741 fn metrics_follow_a_powered_separation() {
1742 let sim = serial_plan();
1747 let mut metrics = crate::metrics::FlightMetrics::new();
1748 let result = sim.run(&mut metrics).unwrap();
1749 let summary = metrics.summary(&result, sim.environment()).unwrap();
1750 assert!(summary.landing.is_some());
1751 assert_eq!(summary.body_landings.len(), 1);
1752 assert_eq!(summary.body_landings[0].body, Some(1));
1753 let split_s = time_of(&result, EventKind::Separation);
1754 let series = metrics.stability();
1755 let before = series.iter().find(|s| s.time_s < split_s).unwrap();
1756 let after = series.iter().rev().find(|s| s.time_s > split_s).unwrap();
1757 assert!(after.reference_diameter_m < before.reference_diameter_m);
1758 let at_split: Vec<_> = series.iter().filter(|s| s.time_s == split_s).collect();
1760 assert_eq!(at_split.len(), 2);
1761 assert_eq!(at_split[1].reference_diameter_m, after.reference_diameter_m);
1762
1763 let mut scanned = Scanned {
1768 metrics: crate::metrics::FlightMetrics::new(),
1769 least_static: f64::INFINITY,
1770 least_flight: f64::INFINITY,
1771 };
1772 let result = sim.run(&mut scanned).unwrap();
1773 let summary = scanned.metrics.summary(&result, sim.environment()).unwrap();
1774 let (least_static, least_flight) = (
1775 summary.min_static_margin_cal.unwrap(),
1776 summary.min_flight_margin_cal.unwrap(),
1777 );
1778 for (least, scan) in [
1779 (least_static.value, scanned.least_static),
1780 (least_flight.value, scanned.least_flight),
1781 ] {
1782 assert!(
1784 least <= scan + 1e-12 && scan - least < 1e-7,
1785 "{least} against {scan}"
1786 );
1787 }
1788 assert_eq!(least_static.time_s, split_s);
1789 assert_eq!(
1790 at_split[1].static_margin.margin_cal,
1791 Some(least_static.value)
1792 );
1793 let series = scanned.metrics.stability();
1794 assert!(series.iter().all(|s| s.time_s != least_flight.time_s));
1795
1796 let best = crate::metrics::optimum_delays(&sim).unwrap().unwrap();
1797 let sustainer = motor_index(&sim, SUSTAINER_MOUNT);
1798 assert_eq!(best.len(), 1);
1799 assert_eq!(best[0].motor, sustainer);
1800 let lit_s = booster_burnout_s(&sim) + 1.0;
1801 let burnout_s = lit_s
1802 + sim.assembly().motors[sustainer]
1803 .mounted
1804 .motor
1805 .burnout_time_s();
1806 assert!((best[0].burnout_s - burnout_s).abs() < 1e-9);
1807 assert!((best[0].delay_s - (best[0].apogee_s - burnout_s)).abs() < 1e-9);
1808 }
1809
1810 #[test]
1817 fn powered_at_is_the_flights_test_and_the_nose_body_has_the_apogee() {
1818 let sim = serial_plan();
1819 let assembly = sim.assembly();
1820 let separation = sim.separation().unwrap();
1821 let split_s = separation.trigger.known_time_s(assembly).unwrap().unwrap();
1822 assert_eq!(split_s, booster_burnout_s(&sim) + 0.5);
1823 assert!(separation.powered_at(assembly, split_s));
1824 let sustainer = motor_index(&sim, SUSTAINER_MOUNT);
1825 let burnout_s = booster_burnout_s(&sim)
1826 + 1.0
1827 + assembly.motors[sustainer].mounted.motor.burnout_time_s();
1828 assert!(separation.powered_at(assembly, burnout_s - 1e-9));
1829 assert!(!separation.powered_at(assembly, burnout_s));
1830 let result = sim.run(&mut ()).unwrap();
1831 assert_eq!(time_of(&result, EventKind::Separation), split_s);
1832 assert_eq!(result.termination, Termination::GroundHit);
1833 assert_eq!(result.bodies.len(), 1);
1834 assert_eq!(Trigger::Apogee.known_time_s(assembly).unwrap(), None);
1836
1837 let unlit = staged(&two_stage(Ignition::Never), |sim| {
1838 Separation::new(
1839 Trigger::Burnout {
1840 motor: motor_index(sim, BOOSTER_MOUNT),
1841 delay_s: 0.5,
1842 },
1843 0,
1844 )
1845 });
1846 let separation = unlit.separation().unwrap();
1847 assert!(!separation.powered_at(unlit.assembly(), split_s));
1848 let mut metrics = crate::metrics::FlightMetrics::new();
1849 let result = unlit.run(&mut metrics).unwrap();
1850 assert_eq!(result.termination, Termination::Separated);
1851 assert!(result.event(EventKind::Apogee).is_none());
1852 let nose = result.bodies.iter().find(|body| body.body == 0).unwrap();
1853 let apogee = nose.event(EventKind::Apogee).unwrap().sample;
1854 assert!(apogee.time_s > split_s);
1855 let summary = metrics.summary(&result, unlit.environment()).unwrap();
1856 let flown = summary.apogee.unwrap();
1857 assert_eq!(flown.time_s, apogee.time_s);
1858 assert_eq!(flown.height_above_ground_m, apogee.height_above_ground_m);
1859 assert_eq!(
1860 flown.gain_m,
1861 summary
1862 .launch_height_m
1863 .map(|start| apogee.height_above_ground_m - start)
1864 );
1865 }
1866
1867 #[test]
1868 fn a_held_flight_holds_a_separation_after_the_last_burnout() {
1869 let rocket = two_stage(Ignition::Burnout {
1873 mount: BOOSTER_MOUNT.to_owned(),
1874 delay_s: 1.0,
1875 });
1876 let with_delay = |delay_s: f64| {
1877 staged(&rocket, |sim| {
1878 Separation::new(
1879 Trigger::Burnout {
1880 motor: motor_index(sim, SUSTAINER_MOUNT),
1881 delay_s,
1882 },
1883 0,
1884 )
1885 })
1886 };
1887 let (short, long) = (with_delay(3.0), with_delay(30.0));
1888 let flown = short.run(&mut ()).unwrap();
1889 assert_eq!(flown.termination, Termination::Separated);
1890 let a = crate::metrics::optimum_delays(&short).unwrap().unwrap();
1891 let b = crate::metrics::optimum_delays(&long).unwrap().unwrap();
1892 assert_eq!(a.len(), 2);
1893 assert_eq!(b.len(), 2);
1894 for (a, b) in a.iter().zip(&b) {
1898 assert_eq!((a.motor, a.burnout_s), (b.motor, b.burnout_s));
1899 assert!((a.delay_s - b.delay_s).abs() < 1e-5, "{a:?} vs {b:?}");
1900 }
1901 assert!(time_of(&flown, EventKind::Separation) < a[0].apogee_s);
1903 }
1904
1905 fn strapped(count: u32) -> Rocket {
1909 let mut rocket = two_stage(Ignition::Launch);
1910 let booster = &mut rocket.stages[1];
1911 booster.components.retain(|c| c.id != "interstage");
1912 booster.parallel = Some(hpr_design::ParallelStage {
1913 on: "sustainer-airframe".to_owned(),
1914 position: hpr_design::Position::Bottom { aft_offset_m: 0.0 },
1915 pods: hpr_design::PodSet {
1916 count,
1917 radial_offset_m: 0.02815 + 0.04,
1918 angle_rad: 0.0,
1919 },
1920 });
1921 rocket
1922 }
1923
1924 #[test]
1930 fn strap_on_boosters_take_their_added_mass_with_them() {
1931 let flown = |rocket: &Rocket| {
1932 let sim = staged(rocket, |sim| {
1933 Separation::new(
1934 Trigger::Burnout {
1935 motor: motor_index(sim, BOOSTER_MOUNT),
1936 delay_s: 0.0,
1937 },
1938 0,
1939 )
1940 });
1941 let result = sim.run(&mut ()).unwrap();
1942 assert_eq!(result.bodies.len(), 1);
1943 [
1944 sim.assembly().layout.structure.mass_kg,
1945 result.bodies[0].mass_kg,
1946 result.final_sample.mass_kg,
1947 ]
1948 };
1949 let plain = flown(&strapped(2));
1950 for cg_aft_m in [None, Some(0.2)] {
1951 let mut rocket = strapped(2);
1952 rocket.stages[1].added_mass = Some(hpr_design::AddedMass {
1953 mass_kg: 0.3,
1954 cg_aft_m,
1955 });
1956 let added = flown(&rocket);
1957 assert!((added[0] - plain[0] - 0.3).abs() < 1e-12, "{added:?}");
1958 assert!((added[1] - plain[1] - 0.3).abs() < 1e-12, "{added:?}");
1959 assert!((added[2] - plain[2]).abs() < 1e-12, "{added:?}");
1960 }
1961 let mut rocket = strapped(2);
1962 rocket.stages[0].added_mass = Some(hpr_design::AddedMass {
1963 mass_kg: 0.3,
1964 cg_aft_m: Some(0.2),
1965 });
1966 let added = flown(&rocket);
1967 assert!((added[0] - plain[0] - 0.3).abs() < 1e-12, "{added:?}");
1968 assert!((added[1] - plain[1]).abs() < 1e-12, "{added:?}");
1969 assert!((added[2] - plain[2] - 0.3).abs() < 1e-12, "{added:?}");
1970 }
1971
1972 #[test]
1976 fn strap_on_boosters_burn_beside_the_sustainer_and_drop() {
1977 let rocket = strapped(2);
1978 let sim = staged(&rocket, |sim| {
1979 Separation::new(
1980 Trigger::Burnout {
1981 motor: motor_index(sim, BOOSTER_MOUNT),
1982 delay_s: 0.0,
1983 },
1984 0,
1985 )
1986 });
1987 assert_eq!(
1988 sim.assembly().motors.len(),
1989 3,
1990 "a J760 in each pod and the I175"
1991 );
1992 let result = sim.run(&mut ()).unwrap();
1993 let burnout_s = booster_burnout_s(&sim);
1994 let separation_s = time_of(&result, EventKind::Separation);
1995 assert!((separation_s - burnout_s).abs() < 1e-12, "{separation_s}");
1996 let sustainer = motor_index(&sim, SUSTAINER_MOUNT);
1997 let sustainer_burnout_s = sim.assembly().motors[sustainer]
1998 .mounted
1999 .motor
2000 .burnout_time_s();
2001 assert!(sustainer_burnout_s > separation_s, "a powered separation");
2002
2003 assert_eq!(result.bodies.len(), 1);
2005 let pods = &result.bodies[0];
2006 assert_eq!((pods.body, pods.stages), (1, (1, 1)));
2007 let spent = super::super::recovery::body_mass_properties(
2008 sim.assembly(),
2009 (1, 1),
2010 f64::MAX,
2011 &[Some(0.0); 3],
2012 );
2013 assert!(
2014 (pods.mass_kg - spent.mass_kg).abs() < 1e-12 * spent.mass_kg,
2015 "{} against {}",
2016 pods.mass_kg,
2017 spent.mass_kg
2018 );
2019 let structure = sim.assembly().layout.stages[1].mass.mass_kg;
2020 assert!(pods.mass_kg > structure, "the spent cases go with the pods");
2021
2022 let core = super::super::recovery::body_mass_properties(
2024 sim.assembly(),
2025 (0, 0),
2026 f64::MAX,
2027 &[Some(0.0); 3],
2028 );
2029 assert_eq!(result.termination, Termination::GroundHit);
2030 assert!(
2031 (result.final_sample.mass_kg - core.mass_kg).abs() < 1e-12 * core.mass_kg,
2032 "{} against {}",
2033 result.final_sample.mass_kg,
2034 core.mass_kg
2035 );
2036
2037 let carried = staged(&rocket, |_| {
2039 Separation::new(Trigger::Time { time_s: 3_000.0 }, 0)
2040 })
2041 .run(&mut ())
2042 .unwrap();
2043 assert!(carried.bodies.is_empty());
2044 let apogee = |result: &FlightResult| {
2045 result
2046 .event(EventKind::Apogee)
2047 .unwrap()
2048 .sample
2049 .height_above_ground_m
2050 };
2051 assert!(
2052 apogee(&result) > apogee(&carried),
2053 "{} against {}",
2054 apogee(&result),
2055 apogee(&carried)
2056 );
2057 }
2058
2059 #[test]
2063 fn a_drag_override_near_a_parallel_stage_is_refused() {
2064 let aero = |rocket: &Rocket| {
2065 let assembly = rocket.assemble(CONFIGURATION).unwrap();
2066 hpr_aero::AeroModel::new(&assembly.layout).map(|_| ())
2067 };
2068 let stated = |include_children| hpr_design::DragOverride {
2069 coefficient: 0.5,
2070 include_children,
2071 };
2072 for (stage, include_children, refused) in [
2073 (1, false, Some("a drag override on a parallel stage")),
2074 (1, true, Some("a drag override on a parallel stage")),
2075 (0, true, Some("covering a stage a parallel stage hangs on")),
2076 (0, false, None),
2077 ] {
2078 let mut rocket = strapped(2);
2079 rocket.stages[stage].drag_override = Some(stated(include_children));
2080 match (aero(&rocket), refused) {
2081 (Ok(()), None) => {}
2082 (Err(error), Some(want)) => {
2083 assert!(error.to_string().contains(want), "{error}");
2084 }
2085 (got, want) => panic!("stage {stage}, {include_children}: {got:?}, {want:?}"),
2086 }
2087 }
2088 }
2089
2090 #[test]
2094 fn a_separation_drops_only_what_hangs_together() {
2095 fn rename(component: &mut hpr_design::Component) {
2096 component.id = component.id.replace("booster", "strap");
2097 for child in &mut component.children {
2098 rename(child);
2099 }
2100 }
2101 let mut rocket = two_stage(Ignition::Launch);
2103 let mut pods = strapped(2).stages[1].clone();
2104 pods.id = "straps".to_owned();
2105 pods.components.iter_mut().for_each(rename);
2106 rocket.stages.insert(1, pods);
2107 let simulation = || {
2108 Simulation::new(
2109 &rocket,
2110 CONFIGURATION,
2111 Environment::standard(site()).unwrap(),
2112 Rail::vertical(6.0),
2113 FlightSettings::default(),
2114 )
2115 .unwrap()
2116 };
2117 let booster = motor_index(&simulation(), BOOSTER_MOUNT);
2118 let at_burnout = |after_stage| {
2119 Separation::new(
2120 Trigger::Burnout {
2121 motor: booster,
2122 delay_s: 0.0,
2123 },
2124 after_stage,
2125 )
2126 };
2127 match simulation().with_separation(at_burnout(0)) {
2128 Err(SimError::Domain { what, value }) => {
2129 assert!(what.contains("must hang together"), "{what}");
2130 assert_eq!(value, 0.0);
2131 }
2132 other => panic!("expected the hang-together refusal, got {other:?}"),
2133 }
2134 simulation().with_separation(at_burnout(1)).unwrap();
2136 simulation()
2137 .with_separations(vec![
2138 at_burnout(1),
2139 Separation::new(Trigger::Time { time_s: 5.0 }, 0),
2140 ])
2141 .unwrap();
2142 }
2143
2144 #[test]
2149 fn a_powered_separation_drops_a_burning_booster_only_when_told() {
2150 let rocket = two_stage(Ignition::Separation { delay_s: 0.0 });
2151 let flown = Simulation::new(
2152 &rocket,
2153 CONFIGURATION,
2154 Environment::standard(site()).unwrap(),
2155 Rail::vertical(6.0),
2156 FlightSettings::default(),
2157 )
2158 .unwrap();
2159 let split_s = 0.5 * booster_burnout_s(&flown);
2160 let at_split = |_: &Simulation| Separation::new(Trigger::Time { time_s: split_s }, 0);
2161 let burning = |error: &SimError| {
2162 matches!(error, SimError::Domain { what, .. }
2163 if what.contains("the aft body's motors must have burned out"))
2164 };
2165 let refused = |rocket: &Rocket, separation: &dyn Fn(&Simulation) -> Separation| {
2166 staged_with(
2167 rocket,
2168 Rail::vertical(6.0),
2169 BOOSTER_AT_SEPARATION,
2170 separation,
2171 )
2172 .expect_err("refused")
2173 };
2174 let error = refused(&rocket, &at_split);
2175 assert!(burning(&error), "{error:?}");
2176
2177 let result = staged(&rocket, |sim| at_split(sim).dropping_burning())
2178 .run(&mut ())
2179 .unwrap();
2180 assert!((time_of(&result, EventKind::Separation) - split_s).abs() < 1e-12);
2181 let curve = flown.assembly().motors[motor_index(&flown, BOOSTER_MOUNT)]
2182 .mounted
2183 .motor
2184 .curve();
2185 let left_n_s = curve.total_impulse_ns() - curve.impulse_ns(split_s);
2186 assert!(left_n_s > 0.1 * curve.total_impulse_ns(), "{left_n_s}");
2187 let booster = result
2188 .bodies
2189 .iter()
2190 .find(|body| body.body == 1)
2191 .expect("the booster's descent");
2192 assert!(
2193 (booster.impulse_left_n_s - left_n_s).abs() <= 1e-12 * left_n_s,
2194 "{} against {left_n_s}",
2195 booster.impulse_left_n_s
2196 );
2197 for body in result.bodies.iter().filter(|body| body.body != 1) {
2198 assert_eq!(body.impulse_left_n_s, 0.0, "body {}", body.body);
2199 }
2200
2201 let error = refused(&two_stage(Ignition::Never), &|sim| {
2203 at_split(sim).dropping_burning()
2204 });
2205 assert!(burning(&error), "{error:?}");
2206
2207 let mut late = two_stage(Ignition::Launch);
2209 late.configurations
2210 .iter_mut()
2211 .find(|c| c.id == CONFIGURATION)
2212 .unwrap()
2213 .motors
2214 .iter_mut()
2215 .find(|m| m.mount == BOOSTER_MOUNT)
2216 .unwrap()
2217 .ignition = Ignition::Time {
2218 time_s: split_s + 1.0,
2219 };
2220 let error = refused(&late, &|sim| at_split(sim).dropping_burning());
2221 assert!(burning(&error), "{error:?}");
2222 }
2223}