1use crate::atmosphere::{
3 AtmosphereError, KernelAtmosphere, PressureReferenceMode, RelativeHumidity, StationAir,
4 StationAtmospherePresence, StationOrigin, StationPressureOrigin, DEFAULT_HUMIDITY_PERCENT,
5};
6use crate::cluster_bc::ClusterBCDegradation;
7use crate::gravity::Gravity;
8use crate::mc_stats::{wilson_interval, BernoulliConfidenceSequence, ConfidenceLevel, Welford};
9use crate::pitch_damping::{calculate_pitch_damping_coefficient, PitchDampingCoefficients};
10use crate::precession_nutation::{
11 calculate_combined_angular_motion, projectile_moments_of_inertia, AngularState,
12 PrecessionNutationParams,
13};
14use crate::trajectory_observation::{bracket_param, Bracket, TrajectoryTermination};
15use crate::trajectory_sampling::{
16 projected_sample_count, sample_trajectory, TrajectoryData, TrajectoryOutputs, TrajectorySample,
17};
18use crate::wind_shear::WindShearModel;
19use crate::DragModel;
20use nalgebra::{Vector3, Vector6};
21use std::error::Error;
22use std::fmt;
23
24#[derive(Debug, Clone, Copy, PartialEq)]
34#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
35pub enum UnitSystem {
36 Metric,
38 Imperial,
40}
41
42#[derive(Debug, Clone, Copy, PartialEq)]
44pub enum OutputFormat {
45 Table,
46 Json,
47 Csv,
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
71#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
72pub enum BcReferenceStandard {
73 #[default]
76 Icao,
77 ArmyStandardMetro,
80}
81
82pub const BC_REFERENCE_STANDARD_INERT_WARNING: &str =
86 "warning: --bc-reference army-standard-metro has no effect together with a custom drag \
87 table (--drag-table): the deck's Cd is divided by sectional density, not a BC value, so \
88 no BC-reference conversion applies";
89
90#[derive(Debug)]
92pub struct BallisticsError {
93 message: String,
94 atmosphere: Option<crate::atmosphere::AtmosphereError>,
95}
96
97impl BallisticsError {
98 pub fn atmosphere_error(&self) -> Option<&crate::atmosphere::AtmosphereError> {
103 self.atmosphere.as_ref()
104 }
105
106 pub fn in_terminal_words(mut self, units: UnitSystem, temperature_label: &str) -> Self {
121 if let Some(error) = &self.atmosphere {
122 if error.reason() == crate::AtmosphereErrorReason::AirAloftBelowAbsoluteZero
123 && self.message == error.to_string()
124 {
125 self.message = format!(
126 "{temperature_label} = {}: {}",
127 terminal_temperature_text(error.value(), units),
128 error.explanation_in(terminal_altitude_unit(units))
129 );
130 }
131 }
132 self
133 }
134}
135
136impl fmt::Display for BallisticsError {
137 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
138 write!(f, "{}", self.message)
139 }
140}
141
142impl Error for BallisticsError {
143 fn source(&self) -> Option<&(dyn Error + 'static)> {
144 self.atmosphere
145 .as_ref()
146 .map(|error| error as &(dyn Error + 'static))
147 }
148}
149
150impl From<String> for BallisticsError {
151 fn from(msg: String) -> Self {
152 BallisticsError {
153 message: msg,
154 atmosphere: None,
155 }
156 }
157}
158
159impl From<&str> for BallisticsError {
160 fn from(msg: &str) -> Self {
161 BallisticsError {
162 message: msg.to_string(),
163 atmosphere: None,
164 }
165 }
166}
167
168impl From<crate::atmosphere::AtmosphereError> for BallisticsError {
169 fn from(error: crate::atmosphere::AtmosphereError) -> Self {
170 BallisticsError {
171 message: error.to_string(),
172 atmosphere: Some(error),
173 }
174 }
175}
176
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
185pub enum DropsReference {
186 #[default]
188 Los,
189 Target,
192}
193
194#[derive(Debug, Clone)]
198pub struct BallisticInputs {
199 pub bc_value: f64, pub bc_type: DragModel, pub bc_reference_standard: BcReferenceStandard,
207 pub bullet_mass: f64, pub muzzle_velocity: f64, pub bullet_diameter: f64, pub bullet_length: f64, pub muzzle_angle: f64, pub target_distance: f64, pub azimuth_angle: f64, pub shot_azimuth: f64,
221 pub shooting_angle: f64, pub cant_angle: f64,
231 pub sight_height: f64, pub sight_offset_lateral_m: f64,
243 pub muzzle_height: f64, pub target_height: f64, pub zero_poi_vertical_m: f64,
254 pub zero_poi_horizontal_m: f64,
260 pub ground_threshold: f64, pub altitude: f64, pub temperature: f64, pub pressure: f64, pub humidity_percent: f64,
280 pub latitude: Option<f64>, pub wind_speed: f64, pub wind_angle: f64, pub twist_rate: f64, pub is_twist_right: bool, pub caliber_inches: f64, pub weight_grains: f64, pub manufacturer: Option<String>, pub bullet_model: Option<String>, pub bullet_id: Option<String>, pub bullet_cluster: Option<usize>, pub use_rk4: bool, pub use_adaptive_rk45: bool, pub enable_advanced_effects: bool,
302 pub enable_magnus: bool, pub enable_coriolis: bool, pub use_powder_sensitivity: bool,
305 pub powder_temp_sensitivity: f64, pub powder_temp: f64, pub powder_temp_curve: Option<Vec<(f64, f64)>>,
314 pub powder_curve_temp_c: Option<f64>,
318 pub tipoff_yaw: f64, pub tipoff_decay_distance: f64, pub cd_delta2: f64,
326 pub use_bc_segments: bool,
336 pub bc_segments: Option<Vec<(f64, f64)>>, pub bc_segments_data: Option<Vec<crate::BCSegmentData>>, pub use_enhanced_spin_drift: bool,
339 pub use_form_factor: bool,
342 pub enable_wind_shear: bool,
343 pub wind_shear_model: String,
344 pub enable_trajectory_sampling: bool,
345 pub sample_interval: f64, pub drops_reference: DropsReference,
355 pub enable_pitch_damping: bool,
356 pub enable_precession_nutation: bool,
357 pub enable_aerodynamic_jump: bool,
360 pub use_cluster_bc: bool, pub custom_drag_table: Option<crate::drag::DragTable>,
377 pub cd_scale: f64,
391 pub custom_drag_reference: bool,
411
412 pub bc_type_str: Option<String>,
414}
415
416impl BallisticInputs {
417 #[deprecated(
426 since = "0.50.0",
427 note = "read the `humidity_percent` field, which is the percent itself since 0.50.0"
428 )]
429 pub fn humidity_percent(&self) -> f64 {
430 self.humidity_percent
431 }
432
433 pub fn windage_zero_bias_rad(&self, zero_distance_m: f64) -> f64 {
448 if zero_distance_m > 0.0 {
449 (self.zero_poi_horizontal_m + self.sight_offset_lateral_m) / zero_distance_m
450 } else {
451 0.0
452 }
453 }
454
455 pub fn sectional_density_lb_in2(&self) -> Option<f64> {
461 let weight_gr = if self.weight_grains > 0.0 {
462 self.weight_grains
463 } else {
464 self.bullet_mass / crate::constants::GRAINS_TO_KG };
466 let diameter_in = if self.caliber_inches > 0.0 {
467 self.caliber_inches
468 } else {
469 self.bullet_diameter / 0.0254 };
471 if weight_gr > 0.0 && diameter_in > 0.0 {
472 Some(weight_gr / 7000.0 / (diameter_in * diameter_in))
473 } else {
474 None
475 }
476 }
477
478 pub fn custom_drag_denominator(&self, resolved_bc: f64) -> f64 {
496 if self.custom_drag_reference {
497 return resolved_bc;
498 }
499 match self.sectional_density_lb_in2() {
500 Some(sd) => sd,
501 None => {
502 static WARN_ONCE: std::sync::Once = std::sync::Once::new();
503 WARN_ONCE.call_once(|| {
504 eprintln!(
505 "Warning: custom drag table active but bullet mass/diameter are \
506 unavailable; falling back to bc_value for the retardation denominator"
507 );
508 });
509 resolved_bc
510 }
511 }
512 }
513
514 pub fn bc_reference_standard_inert_warning(&self) -> Option<&'static str> {
527 if self.custom_drag_table.is_some()
528 && !self.custom_drag_reference
529 && matches!(
530 self.bc_reference_standard,
531 BcReferenceStandard::ArmyStandardMetro
532 )
533 {
534 Some(BC_REFERENCE_STANDARD_INERT_WARNING)
535 } else {
536 None
537 }
538 }
539
540 pub fn normalize_for_solve(&mut self) {
559 if matches!(
572 self.bc_reference_standard,
573 BcReferenceStandard::ArmyStandardMetro
574 ) {
575 self.bc_value *= crate::constants::ASM_TO_ICAO_BC;
576 if let Some(segments) = self.bc_segments.as_mut() {
577 for (_mach, bc) in segments.iter_mut() {
578 *bc *= crate::constants::ASM_TO_ICAO_BC;
579 }
580 }
581 if let Some(segments) = self.bc_segments_data.as_mut() {
582 for segment in segments.iter_mut() {
583 segment.bc_value *= crate::constants::ASM_TO_ICAO_BC;
584 }
585 }
586 self.bc_reference_standard = BcReferenceStandard::Icao;
589 }
590
591 self.caliber_inches = self.bullet_diameter / 0.0254;
596 self.weight_grains = self.bullet_mass / crate::constants::GRAINS_TO_KG;
597
598 self.muzzle_velocity = resolve_powder_adjusted_velocity(
609 self.muzzle_velocity,
610 self.temperature,
611 self.use_powder_sensitivity,
612 self.powder_temp_sensitivity,
613 self.powder_temp,
614 self.powder_temp_curve.as_deref(),
615 self.powder_curve_temp_c,
616 );
617 }
618}
619
620impl Default for BallisticInputs {
621 fn default() -> Self {
622 let mass_kg = 0.01;
623 let diameter_m = 0.00762;
624 let bc = 0.5;
625 let muzzle_angle_rad = 0.0;
626 let bc_type = DragModel::G1;
627
628 Self {
629 bc_value: bc,
631 bc_type,
632 bc_reference_standard: BcReferenceStandard::Icao,
633 bullet_mass: mass_kg,
634 muzzle_velocity: 800.0,
635 bullet_diameter: diameter_m,
636 bullet_length: crate::stability::estimate_bullet_length_m(diameter_m, mass_kg),
640
641 muzzle_angle: muzzle_angle_rad,
643 target_distance: 100.0,
644 azimuth_angle: 0.0,
645 shot_azimuth: 0.0,
646 shooting_angle: 0.0,
647 cant_angle: 0.0,
648 sight_height: 0.05,
649 sight_offset_lateral_m: 0.0, muzzle_height: 0.0, target_height: 0.0, zero_poi_vertical_m: 0.0, zero_poi_horizontal_m: 0.0,
654 ground_threshold: -100.0, altitude: 0.0,
658 temperature: 15.0,
659 pressure: 1013.25, humidity_percent: DEFAULT_HUMIDITY_PERCENT,
661 latitude: None,
662
663 wind_speed: 0.0,
665 wind_angle: 0.0,
666
667 twist_rate: 12.0, is_twist_right: true,
670 caliber_inches: diameter_m / 0.0254, weight_grains: mass_kg / crate::constants::GRAINS_TO_KG, manufacturer: None,
673 bullet_model: None,
674 bullet_id: None,
675 bullet_cluster: None,
676
677 use_rk4: true, use_adaptive_rk45: true, enable_advanced_effects: false,
683 enable_magnus: false,
684 enable_coriolis: false,
685 use_powder_sensitivity: false,
686 powder_temp_sensitivity: 0.0,
687 powder_temp: 15.0,
688 powder_temp_curve: None,
689 powder_curve_temp_c: None,
690 tipoff_yaw: 0.0,
691 tipoff_decay_distance: 50.0,
692 cd_delta2: 7.5,
693 use_bc_segments: false,
694 bc_segments: None,
695 bc_segments_data: None,
696 use_enhanced_spin_drift: false,
697 use_form_factor: false,
698 enable_wind_shear: false,
699 wind_shear_model: "none".to_string(),
700 enable_trajectory_sampling: false,
701 sample_interval: 10.0, drops_reference: DropsReference::Los, enable_pitch_damping: false,
704 enable_precession_nutation: false,
705 enable_aerodynamic_jump: false,
706 use_cluster_bc: false, custom_drag_table: None,
710 cd_scale: 1.0,
711 custom_drag_reference: false,
712
713 bc_type_str: None,
715 }
716 }
717}
718
719pub fn interpolate_powder_temp_curve(curve: &[(f64, f64)], temp_c: f64) -> f64 {
725 debug_assert!(!curve.is_empty());
726 if curve.is_empty() {
727 return 0.0;
728 }
729 let mut sorted;
732 let pts: &[(f64, f64)] = if curve.windows(2).all(|w| w[0].0 <= w[1].0) {
733 curve
734 } else {
735 sorted = curve.to_vec();
736 sorted.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
737 &sorted
738 };
739 let n = pts.len();
740 if temp_c <= pts[0].0 {
741 return pts[0].1; }
743 if temp_c >= pts[n - 1].0 {
744 return pts[n - 1].1; }
746 for i in 1..n {
747 let (t0, v0) = pts[i - 1];
748 let (t1, v1) = pts[i];
749 if temp_c <= t1 {
750 let span = t1 - t0;
751 if span.abs() < f64::EPSILON {
752 return v1; }
754 let f = (temp_c - t0) / span;
755 return v0 + f * (v1 - v0);
756 }
757 }
758 pts[n - 1].1
759}
760
761pub fn parse_powder_sweep(s: &str) -> Result<Vec<f64>, String> {
767 const MAX_SWEEP_ROWS: usize = 500;
768 let parts: Vec<&str> = s.split(':').collect();
769 if parts.len() != 3 {
770 return Err(format!(
771 "Invalid --sweep '{}': expected START:END:STEP (e.g. \"20:110:10\")",
772 s
773 ));
774 }
775 let parse = |p: &str, name: &str| -> Result<f64, String> {
776 p.trim()
777 .parse::<f64>()
778 .map_err(|_| format!("Invalid --sweep {}: '{}' is not a number", name, p.trim()))
779 };
780 let start = parse(parts[0], "START")?;
781 let end = parse(parts[1], "END")?;
782 let step = parse(parts[2], "STEP")?;
783 if !step.is_finite() || step <= 0.0 {
784 return Err(format!("Invalid --sweep STEP {}: must be positive", step));
785 }
786 if !start.is_finite() || !end.is_finite() || end < start {
787 return Err(format!(
788 "Invalid --sweep range {}:{}: END must be >= START",
789 start, end
790 ));
791 }
792 let n_f = ((end - start) / step + 1e-9).floor();
798 if !n_f.is_finite() || n_f + 1.0 > MAX_SWEEP_ROWS as f64 {
799 return Err(format!(
800 "--sweep would produce more than {} rows; use a larger STEP",
801 MAX_SWEEP_ROWS
802 ));
803 }
804 let n = n_f as usize + 1;
805 Ok((0..n).map(|i| start + step * i as f64).collect())
807}
808
809pub fn resolve_powder_adjusted_velocity(
818 nominal_velocity_mps: f64,
819 ambient_temperature_c: f64,
820 use_powder_sensitivity: bool,
821 powder_temp_sensitivity_mps_per_c: f64,
822 powder_reference_temp_c: f64,
823 powder_temp_curve: Option<&[(f64, f64)]>,
824 powder_curve_temp_c: Option<f64>,
825) -> f64 {
826 if let Some(curve) = powder_temp_curve {
827 if !curve.is_empty() {
828 let lookup_c = powder_curve_temp_c.unwrap_or(ambient_temperature_c);
829 return interpolate_powder_temp_curve(curve, lookup_c);
830 }
831 return nominal_velocity_mps;
834 }
835 if use_powder_sensitivity {
836 let temp_delta_c = ambient_temperature_c - powder_reference_temp_c;
837 return nominal_velocity_mps + powder_temp_sensitivity_mps_per_c * temp_delta_c;
838 }
839 nominal_velocity_mps
840}
841
842#[derive(Debug, Clone)]
844pub struct WindConditions {
845 pub speed: f64, pub direction: f64,
849 pub vertical_speed: f64,
857}
858
859impl Default for WindConditions {
860 fn default() -> Self {
861 Self {
862 speed: 0.0,
863 direction: 0.0,
864 vertical_speed: 0.0,
865 }
866 }
867}
868
869#[derive(Debug, Clone)]
871pub struct AtmosphericConditions {
872 pub temperature: f64, pub pressure: f64, pub humidity: f64,
879 pub altitude: f64, }
881
882impl AtmosphericConditions {
883 pub fn resolved_station(&self, presence: StationAtmospherePresence) -> (f64, f64) {
887 crate::atmosphere::resolve_station_conditions_with_presence(
888 self.temperature,
889 self.pressure,
890 self.altitude,
891 PressureReferenceMode::Absolute,
892 presence,
893 )
894 }
895
896 pub fn station_air(
905 &self,
906 presence: StationAtmospherePresence,
907 ) -> Result<StationAir, AtmosphereError> {
908 let humidity = RelativeHumidity::try_percent(self.humidity)?;
909 let (temperature_c, pressure_hpa) = self.resolved_station(presence);
910 StationAir::new(self.altitude, temperature_c, pressure_hpa, humidity)
911 }
912
913 pub fn station_origin(&self, presence: StationAtmospherePresence) -> StationOrigin {
921 StationOrigin::resolving(
922 self.pressure,
923 self.altitude,
924 PressureReferenceMode::Absolute,
925 presence,
926 )
927 }
928
929 pub fn air_refusal_named(
938 &self,
939 presence: StationAtmospherePresence,
940 units: UnitSystem,
941 labels: [&str; 4],
942 ) -> Option<crate::atmosphere::AirRefusal> {
943 self.air_refusal_named_from(presence, self.station_origin(presence), units, labels)
944 }
945
946 pub fn air_refusal_named_from(
952 &self,
953 presence: StationAtmospherePresence,
954 origin: StationOrigin,
955 units: UnitSystem,
956 labels: [&str; 4],
957 ) -> Option<crate::atmosphere::AirRefusal> {
958 self.air_refusal_from(
959 presence,
960 origin,
961 labels.map(crate::atmosphere::AirField::named),
962 self.humidity,
963 terminal_air_units(units),
964 )
965 }
966
967 pub fn for_density_altitude_named(
977 density_altitude_m: f64,
978 explicit_temperature_c: Option<f64>,
979 humidity: f64,
980 units: UnitSystem,
981 labels: [&str; 4],
982 ) -> Result<Self, crate::atmosphere::AirRefusal> {
983 match crate::atmosphere::station_for_density_altitude(
984 density_altitude_m,
985 explicit_temperature_c,
986 ) {
987 Ok((altitude, temperature, pressure)) => Ok(Self {
988 temperature,
989 pressure,
990 humidity,
991 altitude,
992 }),
993 Err(error) => {
994 let units = terminal_air_units(units);
995 let [humidity_field, temperature, pressure, altitude] =
996 labels.map(crate::atmosphere::AirField::named);
997 let temperature_c = explicit_temperature_c.unwrap_or(f64::NAN);
998 Err(error.refusal_in(
999 &crate::atmosphere::AirSpelling {
1000 humidity: humidity_field,
1001 temperature,
1002 pressure,
1003 altitude,
1004 humidity_sent: humidity,
1005 temperature_text: units.temperature.text(temperature_c),
1006 temperature_unit: units.temperature,
1007 temperature_origin: StationOrigin::density_altitude(
1008 explicit_temperature_c.is_some(),
1009 )
1010 .temperature,
1011 pressure_text: String::new(),
1012 pressure_origin: StationPressureOrigin::DensityAltitude,
1013 qnh_text: None,
1014 altitude_unit: units.altitude,
1015 },
1016 density_altitude_m,
1017 temperature_c,
1018 f64::NAN,
1019 ))
1020 }
1021 }
1022 }
1023
1024 pub fn air_refusal(
1034 &self,
1035 presence: StationAtmospherePresence,
1036 fields: [crate::atmosphere::AirField<'_>; 4],
1037 humidity_sent: f64,
1038 units: crate::atmosphere::AirUnits,
1039 ) -> Option<crate::atmosphere::AirRefusal> {
1040 self.air_refusal_from(
1041 presence,
1042 self.station_origin(presence),
1043 fields,
1044 humidity_sent,
1045 units,
1046 )
1047 }
1048
1049 pub fn air_refusal_from(
1059 &self,
1060 presence: StationAtmospherePresence,
1061 origin: StationOrigin,
1062 fields: [crate::atmosphere::AirField<'_>; 4],
1063 humidity_sent: f64,
1064 units: crate::atmosphere::AirUnits,
1065 ) -> Option<crate::atmosphere::AirRefusal> {
1066 let error = self.station_air(presence).err()?;
1067 let (temperature_c, pressure_hpa) = self.resolved_station(presence);
1068 let [humidity, temperature, pressure, altitude] = fields;
1069 let spelling = crate::atmosphere::AirSpelling {
1070 humidity,
1071 temperature,
1072 pressure,
1073 altitude,
1074 humidity_sent,
1075 temperature_text: units.temperature.text(temperature_c),
1076 temperature_unit: units.temperature,
1077 temperature_origin: origin.temperature,
1078 pressure_text: units.pressure.text(pressure_hpa),
1079 pressure_origin: origin.pressure,
1080 qnh_text: origin.qnh_hpa.map(|qnh_hpa| units.pressure.text(qnh_hpa)),
1081 altitude_unit: units.altitude,
1082 };
1083 if let (Some(qnh_hpa), "pressure_hpa") = (origin.qnh_hpa, error.field()) {
1086 if let Err(qnh_error) = crate::atmosphere::check_station_pressure_hpa(qnh_hpa) {
1087 return Some(qnh_error.refusal_in(
1088 &crate::atmosphere::AirSpelling {
1089 pressure_text: units.pressure.text(qnh_hpa),
1090 pressure_origin: StationPressureOrigin::Reading,
1091 qnh_text: None,
1092 ..spelling
1093 },
1094 self.altitude,
1095 temperature_c,
1096 qnh_hpa,
1097 ));
1098 }
1099 }
1100 Some(error.refusal_in(&spelling, self.altitude, temperature_c, pressure_hpa))
1101 }
1102}
1103
1104fn terminal_air_units(units: UnitSystem) -> crate::atmosphere::AirUnits {
1107 match units {
1108 UnitSystem::Imperial => crate::atmosphere::AirUnits::IMPERIAL,
1109 UnitSystem::Metric => crate::atmosphere::AirUnits::METRIC,
1110 }
1111}
1112
1113fn terminal_temperature_text(temperature_c: f64, units: UnitSystem) -> String {
1116 match units {
1117 UnitSystem::Imperial => {
1118 crate::atmosphere::reading_text(temperature_c * 9.0 / 5.0 + 32.0, "°F")
1119 }
1120 UnitSystem::Metric => crate::atmosphere::reading_text(temperature_c, "°C"),
1121 }
1122}
1123
1124fn terminal_altitude_unit(units: UnitSystem) -> crate::atmosphere::AltitudeUnit {
1126 match units {
1127 UnitSystem::Imperial => crate::atmosphere::AltitudeUnit::Feet,
1128 UnitSystem::Metric => crate::atmosphere::AltitudeUnit::Meters,
1129 }
1130}
1131
1132impl Default for AtmosphericConditions {
1133 fn default() -> Self {
1134 Self {
1135 temperature: 15.0,
1136 pressure: 1013.25,
1137 humidity: DEFAULT_HUMIDITY_PERCENT,
1138 altitude: 0.0,
1139 }
1140 }
1141}
1142
1143#[derive(Debug, Clone)]
1145pub struct TrajectoryPoint {
1146 pub time: f64,
1147 pub position: Vector3<f64>,
1148 pub velocity_magnitude: f64,
1149 pub kinetic_energy: f64,
1150 pub drag_coefficient: Option<f64>,
1157}
1158
1159impl TrajectoryPoint {
1160 pub fn drag_coefficient_json_value(&self, with_drag_coefficient: bool) -> Option<f64> {
1168 if with_drag_coefficient {
1169 self.drag_coefficient
1170 } else {
1171 None
1172 }
1173 }
1174}
1175
1176#[derive(Debug, Clone)]
1178pub struct TrajectoryResult {
1179 pub max_range: f64,
1180 pub max_height: f64,
1181 pub time_of_flight: f64,
1182 pub impact_velocity: f64,
1183 pub impact_energy: f64,
1184 pub projectile_mass_kg: f64,
1186 pub line_of_sight_height_m: f64,
1188 pub station_speed_of_sound_mps: f64,
1190 pub termination: TrajectoryTermination,
1192 pub points: Vec<TrajectoryPoint>,
1193 pub sampled_points: Option<Vec<TrajectorySample>>, pub min_pitch_damping: Option<f64>, pub transonic_mach: Option<f64>, pub angular_state: Option<AngularState>, pub max_yaw_angle: Option<f64>, pub max_precession_angle: Option<f64>, pub aerodynamic_jump: Option<crate::aerodynamic_jump::AerodynamicJumpComponents>,
1202 pub mach_1_2_distance_m: Option<f64>,
1207 pub mach_1_0_distance_m: Option<f64>,
1211 pub mach_0_9_distance_m: Option<f64>,
1219}
1220
1221const RK45_TOLERANCE: f64 = 1e-6;
1222const RK45_SAFETY_FACTOR: f64 = 0.9;
1223const RK45_MAX_DT: f64 = 0.01;
1224const RK45_MIN_DT: f64 = 1e-6;
1225const TRAJECTORY_TIME_LIMIT_S: f64 = 100.0;
1226
1227pub const MAX_TRAJECTORY_POINTS: usize = 250_000;
1233
1234fn cli_rk45_error_norm(
1236 position: &Vector3<f64>,
1237 velocity: &Vector3<f64>,
1238 fifth_position: &Vector3<f64>,
1239 fifth_velocity: &Vector3<f64>,
1240 fourth_position: &Vector3<f64>,
1241 fourth_velocity: &Vector3<f64>,
1242) -> f64 {
1243 let pack_state = |position: &Vector3<f64>, velocity: &Vector3<f64>| {
1244 Vector6::new(
1245 position.x, position.y, position.z, velocity.x, velocity.y, velocity.z,
1246 )
1247 };
1248 let state = pack_state(position, velocity);
1249 let fifth_order = pack_state(fifth_position, fifth_velocity);
1250 let fourth_order = pack_state(fourth_position, fourth_velocity);
1251
1252 crate::trajectory_integration::rk45_error_norm(&state, &fifth_order, &fourth_order)
1253}
1254
1255struct Rk45Trial {
1256 position: Vector3<f64>,
1257 velocity: Vector3<f64>,
1258 suggested_dt: f64,
1259 error: f64,
1260}
1261
1262struct Rk45AcceptedStep {
1263 position: Vector3<f64>,
1264 velocity: Vector3<f64>,
1265 used_dt: f64,
1266 next_dt: f64,
1267 error: f64,
1268}
1269
1270#[derive(Default)]
1284struct MachTransitionTracker {
1285 previous_mach: Option<f64>,
1286 crossed_transonic: bool,
1287 crossed_subsonic: bool,
1288 crossed_narrow: bool,
1289 mach_1_2_distance_m: Option<f64>,
1292 mach_1_0_distance_m: Option<f64>,
1295 mach_0_9_distance_m: Option<f64>,
1298}
1299
1300impl MachTransitionTracker {
1301 fn record_downward_crossings(&mut self, mach: f64, downrange_m: f64, distances: &mut Vec<f64>) {
1302 if !mach.is_finite() {
1303 self.previous_mach = None;
1304 return;
1305 }
1306
1307 if let Some(previous_mach) = self.previous_mach {
1308 if !self.crossed_transonic && previous_mach >= 1.2 && mach < 1.2 {
1309 self.crossed_transonic = true;
1310 distances.push(downrange_m);
1311 self.mach_1_2_distance_m = Some(downrange_m);
1312 }
1313 if !self.crossed_subsonic && previous_mach >= 1.0 && mach < 1.0 {
1314 self.crossed_subsonic = true;
1315 distances.push(downrange_m);
1316 self.mach_1_0_distance_m = Some(downrange_m);
1317 }
1318 if !self.crossed_narrow && previous_mach >= 0.9 && mach < 0.9 {
1319 self.crossed_narrow = true;
1320 self.mach_0_9_distance_m = Some(downrange_m);
1322 }
1323 }
1324 self.previous_mach = Some(mach);
1325 }
1326}
1327
1328impl TrajectoryResult {
1329 pub fn position_at_range(&self, target_range: f64) -> Option<Vector3<f64>> {
1333 if self.points.is_empty() {
1334 return None;
1335 }
1336
1337 for i in 0..self.points.len() - 1 {
1339 let p1 = &self.points[i];
1340 let p2 = &self.points[i + 1];
1341
1342 if p1.position.x <= target_range && p2.position.x >= target_range {
1344 let dx = p2.position.x - p1.position.x;
1346 if dx.abs() < 1e-10 {
1347 return Some(p1.position);
1348 }
1349 let t = (target_range - p1.position.x) / dx;
1350
1351 return Some(Vector3::new(
1353 target_range,
1354 p1.position.y + t * (p2.position.y - p1.position.y),
1355 p1.position.z + t * (p2.position.z - p1.position.z),
1356 ));
1357 }
1358 }
1359
1360 self.points.last().map(|p| p.position)
1362 }
1363}
1364
1365#[derive(Clone)]
1367pub struct TrajectorySolver {
1368 gravity: Gravity,
1369 inputs: BallisticInputs,
1370 wind: WindConditions,
1371 atmosphere: AtmosphericConditions,
1372 station_presence: StationAtmospherePresence,
1376 max_range: f64,
1377 time_step: f64,
1378 max_trajectory_points: usize,
1379 cluster_bc: Option<ClusterBCDegradation>,
1380 precession_nutation_inertias: (f64, f64),
1382 wind_sock: Option<crate::wind::WindSock>,
1387 atmo_sock: Option<crate::atmosphere::AtmoSock>,
1394}
1395
1396#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1408pub(crate) enum ZeroTargetFrame {
1409 SightLine,
1410 WorldVertical,
1411}
1412
1413#[derive(Debug, Clone, Copy, PartialEq)]
1426pub struct ZeroCrossings {
1427 pub near_m: Option<f64>,
1430 pub far_m: Option<f64>,
1433}
1434
1435impl TrajectorySolver {
1436 pub fn new(
1444 inputs: BallisticInputs,
1445 wind: WindConditions,
1446 atmosphere: AtmosphericConditions,
1447 ) -> Self {
1448 Self::new_with_station_presence(
1449 inputs,
1450 wind,
1451 atmosphere,
1452 StationAtmospherePresence::NEITHER,
1453 )
1454 }
1455
1456 pub fn new_with_station_presence(
1467 inputs: BallisticInputs,
1468 wind: WindConditions,
1469 atmosphere: AtmosphericConditions,
1470 station_presence: StationAtmospherePresence,
1471 ) -> Self {
1472 Self::new_with_station_presence_and_gravity(
1473 inputs,
1474 wind,
1475 atmosphere,
1476 station_presence,
1477 Gravity::EARTH,
1478 )
1479 }
1480
1481 pub fn new_with_resolved_station_atmosphere(
1492 inputs: BallisticInputs,
1493 wind: WindConditions,
1494 atmosphere: AtmosphericConditions,
1495 ) -> Self {
1496 Self::new_with_station_presence(inputs, wind, atmosphere, StationAtmospherePresence::BOTH)
1497 }
1498
1499 fn new_with_station_presence_and_gravity(
1500 mut inputs: BallisticInputs,
1501 wind: WindConditions,
1502 atmosphere: AtmosphericConditions,
1503 station_presence: StationAtmospherePresence,
1504 gravity: Gravity,
1505 ) -> Self {
1506 inputs.normalize_for_solve();
1511 inputs.humidity_percent = atmosphere.humidity;
1514
1515 let cluster_bc = if inputs.use_cluster_bc {
1517 Some(ClusterBCDegradation::new())
1518 } else {
1519 None
1520 };
1521 let precession_nutation_inertias = projectile_moments_of_inertia(
1522 inputs.bullet_mass,
1523 inputs.bullet_diameter,
1524 inputs.bullet_length,
1525 );
1526
1527 Self {
1528 gravity,
1529 inputs,
1530 wind,
1531 atmosphere,
1532 station_presence,
1533 max_range: 1000.0,
1534 time_step: 0.001,
1535 max_trajectory_points: MAX_TRAJECTORY_POINTS,
1536 cluster_bc,
1537 precession_nutation_inertias,
1538 wind_sock: None,
1539 atmo_sock: None,
1540 }
1541 }
1542
1543 pub fn set_max_range(&mut self, range: f64) {
1544 self.max_range = range;
1545 }
1546
1547 pub fn set_time_step(&mut self, step: f64) {
1548 self.time_step = step;
1549 }
1550
1551 pub(crate) fn calculate_and_set_zero_angle(
1555 &mut self,
1556 target_distance_m: f64,
1557 target_height_m: f64,
1558 frame: ZeroTargetFrame,
1559 ) -> Result<f64, BallisticsError> {
1560 let angle = self.find_zero_angle(target_distance_m, target_height_m, frame)?;
1561 let angle = if target_distance_m > 0.0 {
1570 angle + self.inputs.zero_poi_vertical_m / target_distance_m
1571 } else {
1572 angle
1573 };
1574 self.inputs.muzzle_angle = angle;
1575 self.apply_windage_zero_bias(target_distance_m);
1576 Ok(angle)
1577 }
1578
1579 pub(crate) fn apply_windage_zero_bias(&mut self, target_distance_m: f64) {
1593 self.inputs.azimuth_angle += self.inputs.windage_zero_bias_rad(target_distance_m);
1594 }
1595
1596 fn find_zero_angle(
1597 &self,
1598 target_distance_m: f64,
1599 target_height_m: f64,
1600 frame: ZeroTargetFrame,
1601 ) -> Result<f64, BallisticsError> {
1602 let mut low_angle = 0.0;
1606 let mut high_angle = 0.2; let tolerance = 1e-7;
1608 let max_iterations = 60;
1609
1610 let low_height = self.zero_trial_height_at(low_angle, target_distance_m, frame)?;
1612 let high_height = self.zero_trial_height_at(high_angle, target_distance_m, frame)?;
1613
1614 match (low_height, high_height) {
1615 (Some(low_height), Some(high_height)) => {
1616 let low_error = low_height - target_height_m;
1617 let high_error = high_height - target_height_m;
1618
1619 if low_error > 0.0 && high_error > 0.0 {
1620 let mut expanded = false;
1631 for multiplier in [1.0, 2.0, 3.0, 4.0] {
1632 let new_low = (-0.2_f64 * multiplier).max(-0.785);
1633 match self.zero_trial_height_at(new_low, target_distance_m, frame) {
1634 Ok(Some(height)) if height - target_height_m > 0.0 => {}
1635 Ok(_) => {
1636 high_angle = low_angle;
1637 low_angle = new_low;
1638 expanded = true;
1639 break;
1640 }
1641 Err(error) if error.atmosphere_error().is_some() => return Err(error),
1642 Err(_) => {}
1643 }
1644 }
1645 if !expanded {
1646 return Err("Cannot find zero angle: target is below the trajectory even at the steepest downward angle".into());
1647 }
1648 } else if low_error < 0.0 && high_error < 0.0 {
1649 let mut expanded = false;
1653 for multiplier in [2.0, 3.0, 4.0] {
1654 let new_high = (high_angle * multiplier).min(0.785);
1655 match self.zero_trial_height_at(new_high, target_distance_m, frame) {
1656 Ok(Some(height)) if height - target_height_m > 0.0 => {
1657 high_angle = new_high;
1658 expanded = true;
1659 break;
1660 }
1661 Err(error) if error.atmosphere_error().is_some() => return Err(error),
1662 _ => {}
1663 }
1664 if new_high >= 0.785 {
1665 break;
1666 }
1667 }
1668 if !expanded {
1669 return Err("Cannot find zero angle: target beyond effective range even at maximum angle".into());
1670 }
1671 }
1672 }
1673 (None, Some(_)) => {
1674 }
1677 (Some(_), None) => {
1678 return Err(
1679 "Cannot find zero angle: high angle trajectory doesn't reach target distance"
1680 .into(),
1681 );
1682 }
1683 (None, None) => {
1684 return Err(
1685 "Cannot find zero angle: trajectory cannot reach target distance at any angle"
1686 .into(),
1687 );
1688 }
1689 }
1690
1691 for _ in 0..max_iterations {
1692 let mid_angle = (low_angle + high_angle) / 2.0;
1693 match self.zero_trial_height_at(mid_angle, target_distance_m, frame)? {
1694 Some(height) => {
1695 let error = height - target_height_m;
1696 if error.abs() < 0.0001 {
1699 return Ok(mid_angle);
1700 }
1701
1702 if (high_angle - low_angle).abs() < tolerance {
1705 if error.abs() < 0.01 {
1706 return Ok(mid_angle);
1707 }
1708 return Err("Zero angle did not converge: residual height error too large (target not reachable / not bracketed)".into());
1709 }
1710
1711 if error > 0.0 {
1712 high_angle = mid_angle;
1713 } else {
1714 low_angle = mid_angle;
1715 }
1716 }
1717 None => {
1718 low_angle = mid_angle;
1719 if (high_angle - low_angle).abs() < tolerance {
1720 return Err("Trajectory cannot reach target distance - angle converged without valid solution".into());
1721 }
1722 }
1723 }
1724 }
1725
1726 Err("Failed to find zero angle".into())
1727 }
1728
1729 fn zero_trial_height_at(
1732 &self,
1733 angle_rad: f64,
1734 target_distance_m: f64,
1735 frame: ZeroTargetFrame,
1736 ) -> Result<Option<f64>, BallisticsError> {
1737 let mut trial = self.clone();
1738 trial.inputs.muzzle_angle = angle_rad;
1739 trial.inputs.enable_aerodynamic_jump = false;
1742 trial.inputs.cant_angle = 0.0;
1745 if frame == ZeroTargetFrame::SightLine {
1752 trial.inputs.shooting_angle = 0.0;
1753 }
1754 trial.set_max_range(target_distance_m * 2.0);
1755 let result = trial.solve()?;
1756
1757 for (index, point) in result.points.iter().enumerate() {
1758 if point.position.x >= target_distance_m {
1759 let shot_y_m = if index == 0 {
1760 point.position.y
1761 } else {
1762 let previous = &result.points[index - 1];
1763 let span = point.position.x - previous.position.x;
1764 let fraction = (target_distance_m - previous.position.x) / span;
1765 previous.position.y + fraction * (point.position.y - previous.position.y)
1766 };
1767 return Ok(Some(crate::atmosphere::shot_frame_altitude(
1768 0.0,
1769 target_distance_m,
1770 shot_y_m,
1771 trial.inputs.shooting_angle,
1772 )));
1773 }
1774 }
1775 Ok(None)
1776 }
1777
1778 fn find_zero_range(
1805 &self,
1806 angle_rad: f64,
1807 target_height_m: f64,
1808 frame: ZeroTargetFrame,
1809 ) -> Result<ZeroCrossings, BallisticsError> {
1810 let mut trial = self.clone();
1811 trial.inputs.muzzle_angle = angle_rad;
1812 trial.inputs.enable_aerodynamic_jump = false;
1815 trial.inputs.cant_angle = 0.0;
1816 if frame == ZeroTargetFrame::SightLine {
1817 trial.inputs.shooting_angle = 0.0;
1818 }
1819 let result = trial.solve()?;
1820
1821 let mut near_crossing: Option<f64> = None;
1829 let mut far_crossing: Option<f64> = None;
1830 let mut previous: Option<(f64, f64)> = None; for point in &result.points {
1832 let height = crate::atmosphere::shot_frame_altitude(
1833 0.0,
1834 point.position.x,
1835 point.position.y,
1836 trial.inputs.shooting_angle,
1837 );
1838 let error = height - target_height_m;
1839 if let Some((prev_x, prev_error)) = previous {
1840 if prev_error == 0.0 {
1841 if near_crossing.is_none() {
1844 near_crossing = Some(prev_x);
1845 } else {
1846 far_crossing = Some(prev_x);
1847 }
1848 }
1849 if prev_error * error < 0.0 {
1850 let fraction = prev_error / (prev_error - error);
1851 let crossing = prev_x + fraction * (point.position.x - prev_x);
1852 if prev_error < 0.0 && error > 0.0 {
1853 if near_crossing.is_none() {
1855 near_crossing = Some(crossing);
1856 }
1857 } else {
1858 far_crossing = Some(crossing);
1860 }
1861 }
1862 }
1863 previous = Some((point.position.x, error));
1864 }
1865 if let Some((last_x, last_error)) = previous {
1868 if last_error == 0.0 {
1869 if near_crossing.is_none() {
1870 near_crossing = Some(last_x);
1871 } else {
1872 far_crossing = Some(last_x);
1873 }
1874 }
1875 }
1876
1877 if near_crossing.is_none() && far_crossing.is_none() {
1878 return Err(BallisticsError::from(
1879 "Cannot find zero range: this angle never crosses the target height within the \
1880 solved range (angle too shallow to reach it, or both crossings lie beyond \
1881 the solver's max range)."
1882 .to_string(),
1883 ));
1884 }
1885
1886 Ok(ZeroCrossings {
1887 near_m: near_crossing,
1888 far_m: far_crossing,
1889 })
1890 }
1891
1892 pub fn equivalent_horizontal_range(
1916 &self,
1917 target_range_m: f64,
1918 zero_distance_m: f64,
1919 ) -> Option<f64> {
1920 if !target_range_m.is_finite() || !zero_distance_m.is_finite() {
1921 return None;
1922 }
1923 if target_range_m <= zero_distance_m || target_range_m <= 0.0 {
1924 return None;
1925 }
1926
1927 fn path_y_at(points: &[TrajectoryPoint], distance_m: f64) -> Option<f64> {
1932 match bracket_param(points.len(), |i| points[i].position.x, distance_m) {
1933 Bracket::Below => Some(points[0].position.y),
1938 Bracket::Above | Bracket::Degenerate => None,
1939 Bracket::Inside { lo, t } => {
1940 let hi = lo + 1;
1941 Some(
1942 points[lo].position.y + t * (points[hi].position.y - points[lo].position.y),
1943 )
1944 }
1945 }
1946 }
1947
1948 let mut inclined = self.clone();
1952 inclined.inputs.enable_trajectory_sampling = false;
1953 let inclined_result = inclined.solve().ok()?;
1954 let los_height = inclined_result.line_of_sight_height_m;
1955 let inclined_drop = los_height - path_y_at(&inclined_result.points, target_range_m)?;
1956 let correction = inclined_drop / target_range_m;
1957 if correction <= 0.0 {
1958 return None;
1959 }
1960
1961 let mut flat = self.clone();
1963 flat.inputs.enable_trajectory_sampling = false;
1964 flat.inputs.shooting_angle = 0.0;
1965 let flat_result = flat.solve().ok()?;
1966 let flat_correction_at = |range_m: f64| -> Option<f64> {
1967 Some((los_height - path_y_at(&flat_result.points, range_m)?) / range_m)
1968 };
1969
1970 let flat_terminal_m = flat_result.points.last().map(|p| p.position.x)?;
1978 let mut low = zero_distance_m.max(1.0);
1979 let mut high = target_range_m.min(flat_terminal_m);
1980 if high <= low {
1981 return None;
1982 }
1983 if flat_correction_at(low)? - correction > 0.0 {
1984 return None; }
1986 if flat_correction_at(high)? - correction < 0.0 {
1987 return None; }
1989 for _ in 0..60 {
1990 let mid = 0.5 * (low + high);
1991 let error = flat_correction_at(mid)? - correction;
1992 if error.abs() == 0.0 {
1993 return Some(mid);
1994 }
1995 if error < 0.0 {
1996 low = mid;
1997 } else {
1998 high = mid;
1999 }
2000 if high - low < 0.01 {
2001 break;
2002 }
2003 }
2004 Some(0.5 * (low + high))
2005 }
2006
2007 fn validate_for_solve(&self) -> Result<(), BallisticsError> {
2013 let require_finite = |name: &str, value: f64| {
2014 if value.is_finite() {
2015 Ok(())
2016 } else {
2017 Err(BallisticsError::from(format!("{name} must be finite")))
2018 }
2019 };
2020 let require_positive = |name: &str, value: f64| {
2021 if value.is_finite() && value > 0.0 {
2022 Ok(())
2023 } else {
2024 Err(BallisticsError::from(format!(
2025 "{name} must be finite and greater than zero"
2026 )))
2027 }
2028 };
2029
2030 if self.inputs.custom_drag_table.is_none() || self.inputs.custom_drag_reference {
2039 require_positive("bc_value", self.inputs.bc_value)?;
2040 }
2041 require_positive("bullet_mass", self.inputs.bullet_mass)?;
2042 require_positive("bullet_diameter", self.inputs.bullet_diameter)?;
2043 require_positive("muzzle_velocity", self.inputs.muzzle_velocity)?;
2044 require_positive("cd_scale", self.inputs.cd_scale)?;
2050
2051 require_finite("muzzle_angle", self.inputs.muzzle_angle)?;
2052 require_finite("azimuth_angle", self.inputs.azimuth_angle)?;
2053 require_finite("shooting_angle", self.inputs.shooting_angle)?;
2054 require_finite("cant_angle", self.inputs.cant_angle)?;
2055 require_finite("muzzle_height", self.inputs.muzzle_height)?;
2056
2057 for (name, value) in [
2061 ("zero_poi_vertical_m", self.inputs.zero_poi_vertical_m),
2062 ("zero_poi_horizontal_m", self.inputs.zero_poi_horizontal_m),
2063 ] {
2064 require_finite(name, value)?;
2065 if value.abs() >= 1.0 {
2066 return Err(BallisticsError::from(format!(
2067 "{name} must be smaller than 1.0 m in magnitude (it is a linear POI \
2068 offset at the zero range, in meters)"
2069 )));
2070 }
2071 }
2072
2073 require_finite("sight_offset_lateral_m", self.inputs.sight_offset_lateral_m)?;
2077 if self.inputs.sight_offset_lateral_m.abs() >= 0.5 {
2078 return Err(BallisticsError::from(
2079 "sight_offset_lateral_m must be smaller than 0.5 m in magnitude (it is \
2080 the lateral sight-to-bore mount offset, in meters)",
2081 ));
2082 }
2083
2084 if !(self.inputs.ground_threshold.is_finite()
2087 || self.inputs.ground_threshold == f64::NEG_INFINITY)
2088 {
2089 return Err(BallisticsError::from(
2090 "ground_threshold must be finite or negative infinity",
2091 ));
2092 }
2093
2094 match &self.wind_sock {
2095 Some(wind_sock) => wind_sock
2096 .validate_segments()
2097 .map_err(BallisticsError::from)?,
2098 None => {
2099 require_finite("wind.speed", self.wind.speed)?;
2100 require_finite("wind.direction", self.wind.direction)?;
2101 require_finite("wind.vertical_speed", self.wind.vertical_speed)?;
2102 }
2103 }
2104
2105 require_finite("atmosphere.temperature", self.atmosphere.temperature)?;
2106 require_finite("atmosphere.pressure", self.atmosphere.pressure)?;
2107 require_finite("atmosphere.altitude", self.atmosphere.altitude)?;
2108 self.station_air()?;
2115 if let Some(sock) = &self.atmo_sock {
2116 sock.validate()
2117 .map_err(|error| BallisticsError::from(error.to_string()))?;
2118 }
2119
2120 require_positive("max_range", self.max_range)?;
2121 if !self.inputs.use_rk4 || !self.inputs.use_adaptive_rk45 {
2124 require_positive("time_step", self.time_step)?;
2125 }
2126
2127 if self.inputs.enable_trajectory_sampling {
2128 require_finite("sight_height", self.inputs.sight_height)?;
2129 require_positive("sample_interval", self.inputs.sample_interval)?;
2130 projected_sample_count(self.max_range, self.inputs.sample_interval)?;
2131 }
2132
2133 if self.inputs.drops_reference == DropsReference::Target {
2137 require_finite("target_height", self.inputs.target_height)?;
2138 if self.inputs.shooting_angle.cos() <= 1e-9 {
2139 return Err(BallisticsError::from(
2140 "drops reference 'target' is undefined for shooting angles at or beyond 90 degrees",
2141 ));
2142 }
2143 }
2144
2145 if self.inputs.enable_coriolis {
2146 require_finite("shot_azimuth", self.inputs.shot_azimuth)?;
2147 if let Some(latitude) = self.inputs.latitude {
2148 require_finite("latitude", latitude)?;
2149 }
2150 }
2151
2152 Ok(())
2153 }
2154
2155 fn validate_result_sanity(&self, result: &TrajectoryResult) -> Result<(), BallisticsError> {
2162 let require_finite = |name: &str, value: f64| {
2163 if value.is_finite() {
2164 Ok(())
2165 } else {
2166 Err(BallisticsError::from(format!(
2167 "trajectory result contains non-finite {name}"
2168 )))
2169 }
2170 };
2171 let require_non_negative = |name: &str, value: f64| {
2172 if value >= 0.0 {
2173 Ok(())
2174 } else {
2175 Err(BallisticsError::from(format!(
2176 "trajectory result contains non-physical negative {name} ({value})"
2177 )))
2178 }
2179 };
2180 let require_indexed_finite = |collection: &str, index: usize, field: &str, value: f64| {
2181 if value.is_finite() {
2182 Ok(())
2183 } else {
2184 Err(BallisticsError::from(format!(
2185 "trajectory result contains non-finite {collection}[{index}].{field}"
2186 )))
2187 }
2188 };
2189 let require_indexed_non_negative = |collection: &str,
2190 index: usize,
2191 field: &str,
2192 value: f64| {
2193 if value >= 0.0 {
2194 Ok(())
2195 } else {
2196 Err(BallisticsError::from(format!(
2197 "trajectory result contains non-physical negative {collection}[{index}].{field} ({value})"
2198 )))
2199 }
2200 };
2201
2202 require_finite("max_range", result.max_range)?;
2203 require_finite("max_height", result.max_height)?;
2204 require_finite("time_of_flight", result.time_of_flight)?;
2205 require_finite("impact_velocity", result.impact_velocity)?;
2206 require_finite("impact_energy", result.impact_energy)?;
2207 require_finite("projectile_mass_kg", result.projectile_mass_kg)?;
2208 require_finite("line_of_sight_height_m", result.line_of_sight_height_m)?;
2209 require_finite(
2210 "station_speed_of_sound_mps",
2211 result.station_speed_of_sound_mps,
2212 )?;
2213
2214 require_non_negative("max_range", result.max_range)?;
2218 require_non_negative("time_of_flight", result.time_of_flight)?;
2219 require_non_negative("impact_velocity", result.impact_velocity)?;
2220 require_non_negative("impact_energy", result.impact_energy)?;
2221 require_non_negative("projectile_mass_kg", result.projectile_mass_kg)?;
2222 require_non_negative(
2223 "station_speed_of_sound_mps",
2224 result.station_speed_of_sound_mps,
2225 )?;
2226
2227 for (index, point) in result.points.iter().enumerate() {
2228 require_indexed_finite("points", index, "time", point.time)?;
2229 require_indexed_finite("points", index, "position.x", point.position.x)?;
2230 require_indexed_finite("points", index, "position.y", point.position.y)?;
2231 require_indexed_finite("points", index, "position.z", point.position.z)?;
2232 require_indexed_finite(
2233 "points",
2234 index,
2235 "velocity_magnitude",
2236 point.velocity_magnitude,
2237 )?;
2238 require_indexed_finite("points", index, "kinetic_energy", point.kinetic_energy)?;
2239 require_indexed_non_negative("points", index, "time", point.time)?;
2240 require_indexed_non_negative(
2241 "points",
2242 index,
2243 "velocity_magnitude",
2244 point.velocity_magnitude,
2245 )?;
2246 require_indexed_non_negative("points", index, "kinetic_energy", point.kinetic_energy)?;
2247 }
2248
2249 if let Some(samples) = &result.sampled_points {
2250 for (index, sample) in samples.iter().enumerate() {
2251 require_indexed_finite("sampled_points", index, "distance_m", sample.distance_m)?;
2252 require_indexed_finite("sampled_points", index, "drop_m", sample.drop_m)?;
2253 require_indexed_finite(
2254 "sampled_points",
2255 index,
2256 "wind_drift_m",
2257 sample.wind_drift_m,
2258 )?;
2259 require_indexed_finite(
2260 "sampled_points",
2261 index,
2262 "velocity_mps",
2263 sample.velocity_mps,
2264 )?;
2265 require_indexed_finite("sampled_points", index, "energy_j", sample.energy_j)?;
2266 require_indexed_finite("sampled_points", index, "time_s", sample.time_s)?;
2267 }
2268 }
2269
2270 for (name, value) in [
2271 ("min_pitch_damping", result.min_pitch_damping),
2272 ("transonic_mach", result.transonic_mach),
2273 ("max_yaw_angle", result.max_yaw_angle),
2274 ("max_precession_angle", result.max_precession_angle),
2275 ] {
2276 if let Some(value) = value {
2277 require_finite(name, value)?;
2278 }
2279 }
2280
2281 if let Some(state) = result.angular_state {
2282 for (name, value) in [
2283 ("angular_state.pitch_angle", state.pitch_angle),
2284 ("angular_state.yaw_angle", state.yaw_angle),
2285 ("angular_state.pitch_rate", state.pitch_rate),
2286 ("angular_state.yaw_rate", state.yaw_rate),
2287 ("angular_state.precession_angle", state.precession_angle),
2288 ("angular_state.nutation_phase", state.nutation_phase),
2289 ] {
2290 require_finite(name, value)?;
2291 }
2292 }
2293
2294 if let Some(jump) = result.aerodynamic_jump {
2295 for (name, value) in [
2296 ("aerodynamic_jump.vertical_jump_moa", jump.vertical_jump_moa),
2297 (
2298 "aerodynamic_jump.horizontal_jump_moa",
2299 jump.horizontal_jump_moa,
2300 ),
2301 ("aerodynamic_jump.jump_angle_rad", jump.jump_angle_rad),
2302 (
2303 "aerodynamic_jump.magnus_component_moa",
2304 jump.magnus_component_moa,
2305 ),
2306 ("aerodynamic_jump.yaw_component_moa", jump.yaw_component_moa),
2307 (
2308 "aerodynamic_jump.stabilization_factor",
2309 jump.stabilization_factor,
2310 ),
2311 ] {
2312 require_finite(name, value)?;
2313 }
2314 }
2315
2316 Ok(())
2317 }
2318
2319 fn validate_integration_state(
2332 &self,
2333 position: &Vector3<f64>,
2334 velocity: &Vector3<f64>,
2335 time: f64,
2336 ) -> Result<(), BallisticsError> {
2337 if !(position.iter().all(|value| value.is_finite())
2338 && velocity.iter().all(|value| value.is_finite())
2339 && time.is_finite())
2340 {
2341 return Err(BallisticsError::from(
2342 "trajectory integration produced a non-finite state (often from physically \
2343 extreme inputs — e.g. an absurd bore/muzzle height placing the launch far \
2344 from sea level, or a degenerate atmosphere; check those inputs, or set \
2345 --altitude explicitly)",
2346 ));
2347 }
2348
2349 let speed = velocity.magnitude();
2350 let budget = self.speed_budget(time);
2351 if speed > budget {
2352 return Err(BallisticsError::from(format!(
2353 "trajectory integration diverged: speed {speed:.3e} m/s at t={time:.6}s exceeds \
2354 the physical budget of {budget:.3e} m/s"
2355 )));
2356 }
2357 Ok(())
2358 }
2359
2360 #[allow(clippy::too_many_arguments)]
2370 fn refusal_of_failed_step(
2371 &self,
2372 error: BallisticsError,
2373 station: &StationAir,
2374 step_start: &Vector3<f64>,
2375 position: &Vector3<f64>,
2376 velocity: &Vector3<f64>,
2377 step_s: f64,
2378 end_time: f64,
2379 ) -> BallisticsError {
2380 if position
2381 .iter()
2382 .chain(velocity.iter())
2383 .all(|value| value.is_finite())
2384 {
2385 return error;
2386 }
2387 let altitude_m = crate::atmosphere::shot_frame_altitude(
2388 self.atmosphere.altitude,
2389 step_start.x,
2390 step_start.y,
2391 self.inputs.shooting_angle,
2392 );
2393 crate::atmosphere::air_aloft_refusal(
2394 &KernelAtmosphere::Station(*station),
2395 self.atmo_sock.as_ref(),
2396 step_start.x,
2397 altitude_m,
2398 step_s * self.speed_budget(end_time),
2399 )
2400 .map_or(error, BallisticsError::from)
2401 }
2402
2403 fn speed_budget(&self, time: f64) -> f64 {
2408 let scalar_wind = self.wind.speed.abs() + self.wind.vertical_speed.abs();
2409 let wind_bound = match &self.wind_sock {
2410 Some(sock) => scalar_wind.max(sock.max_speed_mps()),
2411 None => scalar_wind,
2412 };
2413 2.0 * (self.inputs.muzzle_velocity + wind_bound + 10.0) + self.gravity.magnitude() * time
2414 }
2415
2416 fn push_trajectory_point(
2420 &self,
2421 points: &mut Vec<TrajectoryPoint>,
2422 point: TrajectoryPoint,
2423 collapsed_steps: &mut usize,
2424 ) -> Result<(), BallisticsError> {
2425 if points.len() + *collapsed_steps >= self.max_trajectory_points {
2430 return Err(BallisticsError::from(format!(
2431 "trajectory point limit of {} exceeded",
2432 self.max_trajectory_points
2433 )));
2434 }
2435 if let Some(last) = points.last_mut() {
2446 if point.position.x == last.position.x {
2447 *last = point;
2448 *collapsed_steps += 1;
2449 return Ok(());
2450 }
2451 }
2452 points.push(point);
2453 Ok(())
2454 }
2455
2456 pub fn set_wind_segments(&mut self, segments: Vec<crate::wind::WindSegment>) {
2463 self.wind_sock = if segments.is_empty() {
2464 None
2465 } else {
2466 Some(crate::wind::WindSock::new(segments))
2467 };
2468 }
2469
2470 pub fn set_atmo_segments(&mut self, segments: Vec<crate::atmosphere::AtmoSegment>) {
2479 self.atmo_sock = if segments.is_empty() {
2480 None
2481 } else {
2482 Some(crate::atmosphere::AtmoSock::new(segments))
2483 };
2484 }
2485
2486 fn launch_angles_from(
2495 &self,
2496 aj: Option<&crate::aerodynamic_jump::AerodynamicJumpComponents>,
2497 ) -> (f64, f64) {
2498 let (mut elev, mut azim) = (self.inputs.muzzle_angle, self.inputs.azimuth_angle);
2499 if self.inputs.cant_angle != 0.0 {
2506 let (sin_c, cos_c) = self.inputs.cant_angle.sin_cos();
2507 let (e0, a0) = (elev, azim);
2508 elev = e0 * cos_c - a0 * sin_c;
2509 azim = a0 * cos_c + e0 * sin_c;
2510 }
2511 match aj {
2512 Some(c) => {
2513 const MOA_PER_RAD: f64 = 3437.7467707849;
2515 (
2516 elev + c.vertical_jump_moa / MOA_PER_RAD,
2517 azim + c.horizontal_jump_moa / MOA_PER_RAD,
2518 )
2519 }
2520 None => (elev, azim),
2521 }
2522 }
2523
2524 fn aerodynamic_jump_components(
2532 &self,
2533 ) -> Option<crate::aerodynamic_jump::AerodynamicJumpComponents> {
2534 if !self.inputs.enable_aerodynamic_jump {
2535 return None;
2536 }
2537 let diameter_m = self.inputs.bullet_diameter;
2541 if !(self.inputs.twist_rate.is_finite()
2542 && self.inputs.twist_rate != 0.0
2543 && diameter_m.is_finite()
2544 && diameter_m > 0.0
2545 && self.inputs.bullet_length.is_finite()
2546 && self.inputs.bullet_length > 0.0
2547 && self.inputs.muzzle_velocity.is_finite())
2548 {
2549 return None;
2550 }
2551
2552 let (temp_c, pressure_hpa) = self.resolved_station_conditions();
2554 let sg = crate::stability::compute_stability_coefficient(
2555 &self.inputs,
2556 (self.atmosphere.altitude, temp_c, pressure_hpa, 0.0),
2557 );
2558 if !(sg.is_finite() && sg > 0.0) {
2559 return None;
2560 }
2561 let length_calibers = self.inputs.bullet_length / diameter_m;
2562
2563 const MS_TO_MPH: f64 = 2.236_936_292_054_4;
2569 let crosswind_from_right_mps = if let Some(sock) = &self.wind_sock {
2570 -sock.vector_for_range_stateless(0.0)[2]
2571 } else {
2572 self.wind.speed * self.wind.direction.sin()
2573 };
2574 let crosswind_from_right_mph = crosswind_from_right_mps * MS_TO_MPH;
2575
2576 let vertical_jump_moa = crate::aerodynamic_jump::litz_crosswind_jump_moa(
2577 sg,
2578 length_calibers,
2579 crosswind_from_right_mph,
2580 self.inputs.is_twist_right,
2581 );
2582 if !vertical_jump_moa.is_finite() {
2583 return None;
2584 }
2585
2586 const MOA_PER_RAD: f64 = 3437.7467707849;
2587 Some(crate::aerodynamic_jump::AerodynamicJumpComponents {
2588 vertical_jump_moa,
2589 horizontal_jump_moa: 0.0,
2591 jump_angle_rad: vertical_jump_moa.abs() / MOA_PER_RAD,
2592 magnus_component_moa: 0.0,
2593 yaw_component_moa: 0.0,
2594 stabilization_factor: (sg / 1.5).clamp(0.0, 1.0),
2595 })
2596 }
2597
2598 fn resolved_station_conditions(&self) -> (f64, f64) {
2600 self.atmosphere.resolved_station(self.station_presence)
2602 }
2603
2604 fn station_air(&self) -> Result<StationAir, BallisticsError> {
2617 self.atmosphere
2618 .station_air(self.station_presence)
2619 .map_err(|_| {
2620 let refusal = self
2621 .atmosphere
2622 .air_refusal(
2623 self.station_presence,
2624 [
2625 crate::atmosphere::AirField::named("atmosphere.humidity"),
2626 crate::atmosphere::AirField::named("atmosphere.temperature"),
2627 crate::atmosphere::AirField::named("atmosphere.pressure"),
2628 crate::atmosphere::AirField::named("atmosphere.altitude"),
2629 ],
2630 self.atmosphere.humidity,
2631 crate::atmosphere::AirUnits::METRIC,
2632 )
2633 .expect("the station refused this air");
2634 BallisticsError::from(refusal.message().to_string())
2635 })
2636 }
2637
2638 #[cfg(test)]
2641 fn resolved_atmosphere(&self) -> (f64, f64, f64, f64) {
2642 let station = self.station_air().expect("test atmospheres are valid");
2643 (
2644 station.density_kg_m3(),
2645 station.speed_of_sound_mps(),
2646 station.temperature_c(),
2647 station.pressure_hpa(),
2648 )
2649 }
2650
2651 fn precession_nutation_params(
2652 &self,
2653 velocity_mps: f64,
2654 air_density_kg_m3: f64,
2655 speed_of_sound_mps: f64,
2656 ) -> PrecessionNutationParams {
2657 let (spin_inertia, transverse_inertia) = self.precession_nutation_inertias;
2658 let spin_rate_rad_s = if self.inputs.twist_rate > 0.0 {
2659 let velocity_fps = velocity_mps * 3.28084;
2660 let twist_rate_ft = self.inputs.twist_rate / 12.0;
2661 (velocity_fps / twist_rate_ft) * 2.0 * std::f64::consts::PI
2662 } else {
2663 0.0
2664 };
2665
2666 PrecessionNutationParams {
2667 mass_kg: self.inputs.bullet_mass,
2668 caliber_m: self.inputs.bullet_diameter,
2669 length_m: self.inputs.bullet_length,
2670 spin_rate_rad_s,
2671 spin_inertia,
2672 transverse_inertia,
2673 velocity_mps,
2674 air_density_kg_m3,
2675 mach: velocity_mps / speed_of_sound_mps,
2676 pitch_damping_coeff: PitchDampingCoefficients::default().subsonic,
2677 nutation_damping_factor: 0.05,
2678 }
2679 }
2680
2681 fn append_terminal_endpoint(
2690 &self,
2691 points: &mut Vec<TrajectoryPoint>,
2692 post_position: Vector3<f64>,
2693 post_velocity: Vector3<f64>,
2694 post_time: f64,
2695 max_height: &mut f64,
2696 collapsed_steps: &mut usize,
2697 ) -> Result<TrajectoryTermination, BallisticsError> {
2698 let previous = points
2699 .last()
2700 .cloned()
2701 .ok_or_else(|| BallisticsError::from("No trajectory points generated"))?;
2702
2703 let mut crossings = Vec::with_capacity(3);
2704 if previous.position.x < self.max_range && post_position.x >= self.max_range {
2705 let span = post_position.x - previous.position.x;
2706 if span.is_finite() && span > 0.0 {
2707 crossings.push((
2708 (self.max_range - previous.position.x) / span,
2709 TrajectoryTermination::MaxRange,
2710 ));
2711 }
2712 }
2713 if self.inputs.ground_threshold.is_finite()
2714 && previous.position.y > self.inputs.ground_threshold
2715 && post_position.y <= self.inputs.ground_threshold
2716 {
2717 let span = post_position.y - previous.position.y;
2718 if span.is_finite() && span < 0.0 {
2719 crossings.push((
2720 (self.inputs.ground_threshold - previous.position.y) / span,
2721 TrajectoryTermination::GroundThreshold,
2722 ));
2723 }
2724 }
2725 if previous.time < TRAJECTORY_TIME_LIMIT_S && post_time >= TRAJECTORY_TIME_LIMIT_S {
2726 let span = post_time - previous.time;
2727 if span.is_finite() && span > 0.0 {
2728 crossings.push((
2729 (TRAJECTORY_TIME_LIMIT_S - previous.time) / span,
2730 TrajectoryTermination::TimeLimit,
2731 ));
2732 }
2733 }
2734
2735 let (fraction, termination) = crossings
2736 .into_iter()
2737 .filter(|(fraction, _)| fraction.is_finite() && (0.0..=1.0).contains(fraction))
2738 .min_by(|left, right| {
2739 let priority = |termination: TrajectoryTermination| match termination {
2740 TrajectoryTermination::GroundThreshold => 0,
2741 TrajectoryTermination::MaxRange => 1,
2742 TrajectoryTermination::TimeLimit => 2,
2743 TrajectoryTermination::VelocityFloor => 3,
2744 };
2745 left.0
2746 .total_cmp(&right.0)
2747 .then_with(|| priority(left.1).cmp(&priority(right.1)))
2748 })
2749 .ok_or_else(|| {
2750 BallisticsError::from(
2751 "trajectory integration stopped without crossing a supported boundary",
2752 )
2753 })?;
2754
2755 let mut position = previous.position + (post_position - previous.position) * fraction;
2756 match termination {
2757 TrajectoryTermination::MaxRange => position.x = self.max_range,
2758 TrajectoryTermination::GroundThreshold => {
2759 position.y = self.inputs.ground_threshold;
2760 }
2761 TrajectoryTermination::TimeLimit | TrajectoryTermination::VelocityFloor => {}
2762 }
2763 let velocity_magnitude = previous.velocity_magnitude
2764 + (post_velocity.magnitude() - previous.velocity_magnitude) * fraction;
2765 let mut time = previous.time + (post_time - previous.time) * fraction;
2766 if termination == TrajectoryTermination::TimeLimit {
2767 time = TRAJECTORY_TIME_LIMIT_S;
2768 }
2769 let kinetic_energy =
2770 0.5 * self.inputs.bullet_mass * velocity_magnitude * velocity_magnitude;
2771
2772 if position.y > *max_height {
2773 *max_height = position.y;
2774 }
2775 let terminal_point = TrajectoryPoint {
2776 time,
2777 position,
2778 velocity_magnitude,
2779 kinetic_energy,
2780 drag_coefficient: None,
2781 };
2782 if terminal_point.position.x < previous.position.x {
2783 return Err(BallisticsError::from(
2784 "trajectory terminal state reversed downrange before the crossed boundary",
2785 ));
2786 }
2787 if terminal_point.position.x == previous.position.x {
2788 let last = points.last_mut().ok_or_else(|| {
2793 BallisticsError::from("trajectory points disappeared during terminal finalization")
2794 })?;
2795 *last = terminal_point;
2796 } else {
2797 self.push_trajectory_point(points, terminal_point, collapsed_steps)?;
2798 }
2799 Ok(termination)
2800 }
2801
2802 fn gravity_acceleration(&self) -> Vector3<f64> {
2803 self.gravity.in_frame(self.inputs.shooting_angle)
2804 }
2805
2806 fn boundary_layer_shear_model(&self) -> Option<WindShearModel> {
2816 if !self.inputs.enable_wind_shear {
2817 return None;
2818 }
2819 match self.inputs.wind_shear_model.as_str() {
2820 "none" => None,
2821 "logarithmic" => Some(WindShearModel::Logarithmic),
2822 "power_law" | "powerlaw" | "exponential" => Some(WindShearModel::PowerLaw),
2823 "ekman_spiral" | "ekman" => Some(WindShearModel::EkmanSpiral),
2824 "custom_layers" | "custom" => Some(WindShearModel::CustomLayers),
2825 _ => Some(WindShearModel::PowerLaw),
2826 }
2827 }
2828
2829 fn get_wind_at_altitude(&self, height_agl_m: f64, model: WindShearModel) -> Vector3<f64> {
2830 let speed_ratio = crate::wind_shear::boundary_layer_speed_ratio_agl(height_agl_m, model);
2845
2846 crate::wind::wind_vector(self.wind.speed, self.wind.direction, 0.0) * speed_ratio
2853 + Vector3::new(0.0, self.wind.vertical_speed, 0.0)
2854 }
2855
2856 pub fn solve(&self) -> Result<TrajectoryResult, BallisticsError> {
2857 self.validate_for_solve()?;
2858 let mut result = if self.inputs.use_rk4 {
2859 if self.inputs.use_adaptive_rk45 {
2860 self.solve_rk45()?
2861 } else {
2862 self.solve_rk4()?
2863 }
2864 } else {
2865 self.solve_euler()?
2866 };
2867 self.apply_spin_drift(&mut result);
2868 self.validate_result_sanity(&result)?;
2869 Ok(result)
2870 }
2871
2872 fn apply_spin_drift(&self, result: &mut TrajectoryResult) {
2878 if !self.inputs.use_enhanced_spin_drift {
2879 return;
2880 }
2881 let d_in = self.inputs.bullet_diameter / 0.0254; let m_gr = self.inputs.bullet_mass / crate::constants::GRAINS_TO_KG; let twist_in = self.inputs.twist_rate; if d_in <= 0.0 || m_gr <= 0.0 || twist_in <= 0.0 {
2885 return;
2886 }
2887
2888 let sg = self.effective_spin_drift_sg();
2895
2896 for p in result.points.iter_mut() {
2897 if p.time <= 0.0 {
2898 continue;
2899 }
2900 p.position.z +=
2902 crate::spin_drift::litz_drift_meters(sg, p.time, self.inputs.is_twist_right);
2903 }
2904
2905 if let Some(samples) = result.sampled_points.as_mut() {
2909 for s in samples.iter_mut() {
2910 if s.time_s <= 0.0 {
2911 continue;
2912 }
2913 s.wind_drift_m +=
2914 crate::spin_drift::litz_drift_meters(sg, s.time_s, self.inputs.is_twist_right);
2915 }
2916 }
2917 }
2918
2919 fn effective_spin_drift_sg(&self) -> f64 {
2924 let (temp_c, press_hpa) = self.resolved_station_conditions();
2925 crate::spin_drift::effective_sg_from_inputs(&self.inputs, temp_c, press_hpa)
2926 }
2927
2928 fn initial_position(&self) -> Vector3<f64> {
2946 if self.inputs.cant_angle == 0.0 && self.inputs.sight_offset_lateral_m == 0.0 {
2947 return Vector3::new(0.0, self.inputs.muzzle_height, 0.0);
2948 }
2949 let (sin_c, cos_c) = self.inputs.cant_angle.sin_cos();
2950 let sh = self.inputs.sight_height;
2951 let off = self.inputs.sight_offset_lateral_m;
2952 Vector3::new(
2953 0.0,
2954 self.inputs.muzzle_height + sh * (1.0 - cos_c) + off * sin_c,
2955 -sh * sin_c - off * cos_c,
2956 )
2957 }
2958
2959 fn build_sampled_points(
2966 &self,
2967 points: &[TrajectoryPoint],
2968 max_height: f64,
2969 transonic_distances: Vec<f64>,
2970 mach_transitions: &MachTransitionTracker,
2971 ) -> Result<Option<Vec<TrajectorySample>>, BallisticsError> {
2972 if !self.inputs.enable_trajectory_sampling {
2973 return Ok(None);
2974 }
2975
2976 let last_point = points.last().ok_or("No trajectory points generated")?;
2977 let trajectory_data = TrajectoryData {
2978 times: points.iter().map(|p| p.time).collect(),
2979 positions: points.iter().map(|p| p.position).collect(),
2980 velocities: points
2981 .iter()
2982 .map(|p| {
2983 Vector3::new(0.0, 0.0, p.velocity_magnitude)
2985 })
2986 .collect(),
2987 transonic_distances, mach_1_2_distance_m: mach_transitions.mach_1_2_distance_m,
2989 mach_1_0_distance_m: mach_transitions.mach_1_0_distance_m,
2990 mach_0_9_distance_m: mach_transitions.mach_0_9_distance_m,
2991 };
2992
2993 let sight_position_m = self.inputs.muzzle_height + self.inputs.sight_height;
2998 let target_reference = self.inputs.drops_reference == DropsReference::Target;
2999 let target_vertical_height_m = if target_reference && self.inputs.target_height != 0.0 {
3006 self.inputs.target_height
3007 } else {
3008 sight_position_m
3009 };
3010 let outputs = TrajectoryOutputs {
3011 target_distance_horiz_m: last_point.position.x, target_vertical_height_m,
3013 time_of_flight_s: last_point.time,
3014 max_ord_dist_horiz_m: max_height,
3015 sight_height_m: sight_position_m,
3016 };
3017
3018 let mut samples = sample_trajectory(
3020 &trajectory_data,
3021 &outputs,
3022 self.inputs.sample_interval,
3023 self.inputs.bullet_mass,
3024 )?;
3025
3026 if target_reference {
3033 let cos_theta = self.inputs.shooting_angle.cos();
3034 for sample in &mut samples {
3035 sample.drop_m /= cos_theta;
3036 }
3037 }
3038 Ok(Some(samples))
3039 }
3040
3041 fn solve_euler(&self) -> Result<TrajectoryResult, BallisticsError> {
3042 let mut time = 0.0;
3044 let mut position = self.initial_position();
3048 let aj_components = self.aerodynamic_jump_components();
3054 let (launch_elev, launch_azim) = self.launch_angles_from(aj_components.as_ref());
3055 let horizontal_velocity = self.inputs.muzzle_velocity * launch_elev.cos();
3056 let mut velocity = Vector3::new(
3057 horizontal_velocity * launch_azim.cos(), self.inputs.muzzle_velocity * launch_elev.sin(), horizontal_velocity * launch_azim.sin(), );
3061
3062 let mut points = Vec::new();
3063 let mut collapsed_steps = 0;
3066 let mut max_height = position.y;
3067 let mut min_pitch_damping = f64::INFINITY; let mut transonic_mach = None; let mut transonic_distances: Vec<f64> = Vec::new();
3073 let mut mach_transitions = MachTransitionTracker::default();
3074
3075 let mut angular_state = if self.inputs.enable_precession_nutation {
3077 Some(AngularState {
3078 pitch_angle: 0.001, yaw_angle: 0.001,
3080 pitch_rate: 0.0,
3081 yaw_rate: 0.0,
3082 precession_angle: 0.0,
3083 nutation_phase: 0.0,
3084 })
3085 } else {
3086 None
3087 };
3088 let mut max_yaw_angle = 0.0;
3089 let mut max_precession_angle = 0.0;
3090
3091 let station = self.station_air()?;
3097 let air_density = station.density_kg_m3();
3098 let speed_of_sound = station.speed_of_sound_mps();
3099
3100 let wind_vector = crate::wind::wind_vector(
3106 self.wind.speed,
3107 self.wind.direction,
3108 self.wind.vertical_speed,
3109 );
3110
3111 let pitch_coeffs = PitchDampingCoefficients::from_bullet_type(
3114 self.inputs.bullet_model.as_deref().unwrap_or("default"),
3115 );
3116
3117 while position.x < self.max_range
3119 && position.y > self.inputs.ground_threshold
3120 && time < TRAJECTORY_TIME_LIMIT_S
3121 {
3122 let velocity_magnitude = velocity.magnitude();
3124 let kinetic_energy =
3125 0.5 * self.inputs.bullet_mass * velocity_magnitude * velocity_magnitude;
3126
3127 self.push_trajectory_point(
3128 &mut points,
3129 TrajectoryPoint {
3130 time,
3131 position,
3132 velocity_magnitude,
3133 kinetic_energy,
3134 drag_coefficient: None,
3135 },
3136 &mut collapsed_steps,
3137 )?;
3138
3139 {
3142 let mach_here = if speed_of_sound > 0.0 {
3143 velocity_magnitude / speed_of_sound
3144 } else {
3145 0.0
3146 };
3147 mach_transitions.record_downward_crossings(
3148 mach_here,
3149 position.x,
3150 &mut transonic_distances,
3151 );
3152 }
3153
3154 if position.y > max_height {
3156 max_height = position.y;
3157 }
3158
3159 if self.inputs.enable_pitch_damping {
3161 let mach = velocity_magnitude / speed_of_sound;
3162
3163 if transonic_mach.is_none() && mach < 1.2 && mach > 0.8 {
3165 transonic_mach = Some(mach);
3166 }
3167
3168 let pitch_damping = calculate_pitch_damping_coefficient(mach, &pitch_coeffs);
3170
3171 if pitch_damping < min_pitch_damping {
3173 min_pitch_damping = pitch_damping;
3174 }
3175 }
3176
3177 if self.inputs.enable_precession_nutation {
3179 if let Some(ref mut state) = angular_state {
3180 let velocity_magnitude = velocity.magnitude();
3181 let params = self.precession_nutation_params(
3182 velocity_magnitude,
3183 air_density,
3184 speed_of_sound,
3185 );
3186
3187 *state = calculate_combined_angular_motion(
3189 ¶ms,
3190 state,
3191 time,
3192 self.time_step,
3193 0.001, );
3195
3196 if state.yaw_angle.abs() > max_yaw_angle {
3198 max_yaw_angle = state.yaw_angle.abs();
3199 }
3200 if state.precession_angle.abs() > max_precession_angle {
3201 max_precession_angle = state.precession_angle.abs();
3202 }
3203 }
3204 }
3205
3206 let acceleration =
3213 self.calculate_acceleration(&position, &velocity, &wind_vector, &station);
3214
3215 let step_start = position;
3217 velocity += acceleration * self.time_step;
3218 position += velocity * self.time_step;
3219 time += self.time_step;
3220 self.validate_integration_state(&position, &velocity, time)
3221 .map_err(|error| {
3222 self.refusal_of_failed_step(
3223 error,
3224 &station,
3225 &step_start,
3226 &position,
3227 &velocity,
3228 self.time_step,
3229 time,
3230 )
3231 })?;
3232 }
3233
3234 let termination = self.append_terminal_endpoint(
3235 &mut points,
3236 position,
3237 velocity,
3238 time,
3239 &mut max_height,
3240 &mut collapsed_steps,
3241 )?;
3242
3243 self.annotate_drag_coefficients(&mut points, speed_of_sound);
3248
3249 let last_point = points.last().ok_or("No trajectory points generated")?;
3250
3251 let sampled_points =
3253 self.build_sampled_points(&points, max_height, transonic_distances, &mach_transitions)?;
3254
3255 Ok(TrajectoryResult {
3256 max_range: last_point.position.x, max_height,
3258 time_of_flight: last_point.time,
3259 impact_velocity: last_point.velocity_magnitude,
3260 impact_energy: last_point.kinetic_energy,
3261 projectile_mass_kg: self.inputs.bullet_mass,
3262 line_of_sight_height_m: self.inputs.muzzle_height + self.inputs.sight_height,
3263 station_speed_of_sound_mps: speed_of_sound,
3264 termination,
3265 points,
3266 sampled_points,
3267 min_pitch_damping: if self.inputs.enable_pitch_damping {
3268 Some(min_pitch_damping)
3269 } else {
3270 None
3271 },
3272 transonic_mach,
3273 angular_state,
3274 max_yaw_angle: if self.inputs.enable_precession_nutation {
3275 Some(max_yaw_angle)
3276 } else {
3277 None
3278 },
3279 max_precession_angle: if self.inputs.enable_precession_nutation {
3280 Some(max_precession_angle)
3281 } else {
3282 None
3283 },
3284 aerodynamic_jump: aj_components,
3285 mach_1_2_distance_m: mach_transitions.mach_1_2_distance_m,
3286 mach_1_0_distance_m: mach_transitions.mach_1_0_distance_m,
3287 mach_0_9_distance_m: mach_transitions.mach_0_9_distance_m,
3288 })
3289 }
3290
3291 fn solve_rk4(&self) -> Result<TrajectoryResult, BallisticsError> {
3292 let mut time = 0.0;
3294 let mut position = self.initial_position();
3299
3300 let aj_components = self.aerodynamic_jump_components();
3306 let (launch_elev, launch_azim) = self.launch_angles_from(aj_components.as_ref());
3307 let horizontal_velocity = self.inputs.muzzle_velocity * launch_elev.cos();
3308 let mut velocity = Vector3::new(
3309 horizontal_velocity * launch_azim.cos(), self.inputs.muzzle_velocity * launch_elev.sin(), horizontal_velocity * launch_azim.sin(), );
3313
3314 let mut points = Vec::new();
3315 let mut collapsed_steps = 0;
3318 let mut max_height = position.y;
3319 let mut min_pitch_damping = f64::INFINITY; let mut transonic_mach = None; let mut transonic_distances: Vec<f64> = Vec::new();
3325 let mut mach_transitions = MachTransitionTracker::default();
3326
3327 let mut angular_state = if self.inputs.enable_precession_nutation {
3329 Some(AngularState {
3330 pitch_angle: 0.001, yaw_angle: 0.001,
3332 pitch_rate: 0.0,
3333 yaw_rate: 0.0,
3334 precession_angle: 0.0,
3335 nutation_phase: 0.0,
3336 })
3337 } else {
3338 None
3339 };
3340 let mut max_yaw_angle = 0.0;
3341 let mut max_precession_angle = 0.0;
3342
3343 let station = self.station_air()?;
3349 let air_density = station.density_kg_m3();
3350 let speed_of_sound = station.speed_of_sound_mps();
3351
3352 let wind_vector = crate::wind::wind_vector(
3358 self.wind.speed,
3359 self.wind.direction,
3360 self.wind.vertical_speed,
3361 );
3362
3363 let pitch_coeffs = PitchDampingCoefficients::from_bullet_type(
3366 self.inputs.bullet_model.as_deref().unwrap_or("default"),
3367 );
3368
3369 while position.x < self.max_range
3371 && position.y > self.inputs.ground_threshold
3372 && time < TRAJECTORY_TIME_LIMIT_S
3373 {
3374 let velocity_magnitude = velocity.magnitude();
3376 let kinetic_energy =
3377 0.5 * self.inputs.bullet_mass * velocity_magnitude * velocity_magnitude;
3378
3379 self.push_trajectory_point(
3380 &mut points,
3381 TrajectoryPoint {
3382 time,
3383 position,
3384 velocity_magnitude,
3385 kinetic_energy,
3386 drag_coefficient: None,
3387 },
3388 &mut collapsed_steps,
3389 )?;
3390
3391 {
3394 let mach_here = if speed_of_sound > 0.0 {
3395 velocity_magnitude / speed_of_sound
3396 } else {
3397 0.0
3398 };
3399 mach_transitions.record_downward_crossings(
3400 mach_here,
3401 position.x,
3402 &mut transonic_distances,
3403 );
3404 }
3405
3406 if position.y > max_height {
3407 max_height = position.y;
3408 }
3409
3410 if self.inputs.enable_pitch_damping {
3412 let mach = velocity_magnitude / speed_of_sound;
3413
3414 if transonic_mach.is_none() && mach < 1.2 && mach > 0.8 {
3416 transonic_mach = Some(mach);
3417 }
3418
3419 let pitch_damping = calculate_pitch_damping_coefficient(mach, &pitch_coeffs);
3421
3422 if pitch_damping < min_pitch_damping {
3424 min_pitch_damping = pitch_damping;
3425 }
3426 }
3427
3428 if self.inputs.enable_precession_nutation {
3430 if let Some(ref mut state) = angular_state {
3431 let velocity_magnitude = velocity.magnitude();
3432 let params = self.precession_nutation_params(
3433 velocity_magnitude,
3434 air_density,
3435 speed_of_sound,
3436 );
3437
3438 *state = calculate_combined_angular_motion(
3440 ¶ms,
3441 state,
3442 time,
3443 self.time_step,
3444 0.001, );
3446
3447 if state.yaw_angle.abs() > max_yaw_angle {
3449 max_yaw_angle = state.yaw_angle.abs();
3450 }
3451 if state.precession_angle.abs() > max_precession_angle {
3452 max_precession_angle = state.precession_angle.abs();
3453 }
3454 }
3455 }
3456
3457 let dt = self.time_step;
3459
3460 let acc1 = self.calculate_acceleration(&position, &velocity, &wind_vector, &station);
3462
3463 let pos2 = position + velocity * (dt * 0.5);
3465 let vel2 = velocity + acc1 * (dt * 0.5);
3466 let acc2 = self.calculate_acceleration(&pos2, &vel2, &wind_vector, &station);
3467
3468 let pos3 = position + vel2 * (dt * 0.5);
3470 let vel3 = velocity + acc2 * (dt * 0.5);
3471 let acc3 = self.calculate_acceleration(&pos3, &vel3, &wind_vector, &station);
3472
3473 let pos4 = position + vel3 * dt;
3475 let vel4 = velocity + acc3 * dt;
3476 let acc4 = self.calculate_acceleration(&pos4, &vel4, &wind_vector, &station);
3477
3478 let step_start = position;
3480 position += (velocity + vel2 * 2.0 + vel3 * 2.0 + vel4) * (dt / 6.0);
3481 velocity += (acc1 + acc2 * 2.0 + acc3 * 2.0 + acc4) * (dt / 6.0);
3482 time += dt;
3483 self.validate_integration_state(&position, &velocity, time)
3484 .map_err(|error| {
3485 self.refusal_of_failed_step(
3486 error,
3487 &station,
3488 &step_start,
3489 &position,
3490 &velocity,
3491 dt,
3492 time,
3493 )
3494 })?;
3495 }
3496
3497 let termination = self.append_terminal_endpoint(
3498 &mut points,
3499 position,
3500 velocity,
3501 time,
3502 &mut max_height,
3503 &mut collapsed_steps,
3504 )?;
3505
3506 self.annotate_drag_coefficients(&mut points, speed_of_sound);
3511
3512 let last_point = points.last().ok_or("No trajectory points generated")?;
3513
3514 let sampled_points =
3516 self.build_sampled_points(&points, max_height, transonic_distances, &mach_transitions)?;
3517
3518 Ok(TrajectoryResult {
3519 max_range: last_point.position.x, max_height,
3521 time_of_flight: last_point.time,
3522 impact_velocity: last_point.velocity_magnitude,
3523 impact_energy: last_point.kinetic_energy,
3524 projectile_mass_kg: self.inputs.bullet_mass,
3525 line_of_sight_height_m: self.inputs.muzzle_height + self.inputs.sight_height,
3526 station_speed_of_sound_mps: speed_of_sound,
3527 termination,
3528 points,
3529 sampled_points,
3530 min_pitch_damping: if self.inputs.enable_pitch_damping {
3531 Some(min_pitch_damping)
3532 } else {
3533 None
3534 },
3535 transonic_mach,
3536 angular_state,
3537 max_yaw_angle: if self.inputs.enable_precession_nutation {
3538 Some(max_yaw_angle)
3539 } else {
3540 None
3541 },
3542 max_precession_angle: if self.inputs.enable_precession_nutation {
3543 Some(max_precession_angle)
3544 } else {
3545 None
3546 },
3547 aerodynamic_jump: aj_components,
3548 mach_1_2_distance_m: mach_transitions.mach_1_2_distance_m,
3549 mach_1_0_distance_m: mach_transitions.mach_1_0_distance_m,
3550 mach_0_9_distance_m: mach_transitions.mach_0_9_distance_m,
3551 })
3552 }
3553
3554 fn solve_rk45(&self) -> Result<TrajectoryResult, BallisticsError> {
3555 let mut time = 0.0;
3557 let mut position = self.initial_position();
3561
3562 let aj_components = self.aerodynamic_jump_components();
3568 let (launch_elev, launch_azim) = self.launch_angles_from(aj_components.as_ref());
3569 let horizontal_velocity = self.inputs.muzzle_velocity * launch_elev.cos();
3570 let mut velocity = Vector3::new(
3571 horizontal_velocity * launch_azim.cos(), self.inputs.muzzle_velocity * launch_elev.sin(), horizontal_velocity * launch_azim.sin(), );
3575
3576 let mut points = Vec::new();
3577 let mut collapsed_steps = 0;
3580 let mut max_height = position.y;
3581 let mut dt = 0.001; let station = self.station_air()?;
3590 let air_density = station.density_kg_m3();
3591 let speed_of_sound = station.speed_of_sound_mps();
3592 let wind_vector = crate::wind::wind_vector(
3597 self.wind.speed,
3598 self.wind.direction,
3599 self.wind.vertical_speed,
3600 );
3601
3602 let mut transonic_distances: Vec<f64> = Vec::new();
3604 let mut mach_transitions = MachTransitionTracker::default();
3605
3606 let mut min_pitch_damping = f64::INFINITY;
3611 let mut transonic_mach: Option<f64> = None;
3612 let pitch_coeffs = PitchDampingCoefficients::from_bullet_type(
3613 self.inputs.bullet_model.as_deref().unwrap_or("default"),
3614 );
3615 let mut angular_state = if self.inputs.enable_precession_nutation {
3616 Some(AngularState {
3617 pitch_angle: 0.001,
3618 yaw_angle: 0.001,
3619 pitch_rate: 0.0,
3620 yaw_rate: 0.0,
3621 precession_angle: 0.0,
3622 nutation_phase: 0.0,
3623 })
3624 } else {
3625 None
3626 };
3627 let mut max_yaw_angle = 0.0;
3628 let mut max_precession_angle = 0.0;
3629
3630 while position.x < self.max_range
3631 && position.y > self.inputs.ground_threshold
3632 && time < TRAJECTORY_TIME_LIMIT_S
3633 {
3634 let velocity_magnitude = velocity.magnitude();
3636 let kinetic_energy = 0.5 * self.inputs.bullet_mass * velocity_magnitude.powi(2);
3637
3638 self.push_trajectory_point(
3639 &mut points,
3640 TrajectoryPoint {
3641 time,
3642 position,
3643 velocity_magnitude,
3644 kinetic_energy,
3645 drag_coefficient: None,
3646 },
3647 &mut collapsed_steps,
3648 )?;
3649
3650 {
3653 let mach_here = if speed_of_sound > 0.0 {
3654 velocity_magnitude / speed_of_sound
3655 } else {
3656 0.0
3657 };
3658 mach_transitions.record_downward_crossings(
3659 mach_here,
3660 position.x,
3661 &mut transonic_distances,
3662 );
3663 }
3664
3665 if position.y > max_height {
3666 max_height = position.y;
3667 }
3668
3669 if self.inputs.enable_pitch_damping {
3672 let mach = velocity_magnitude / speed_of_sound;
3673 if transonic_mach.is_none() && mach < 1.2 && mach > 0.8 {
3674 transonic_mach = Some(mach);
3675 }
3676 let pitch_damping = calculate_pitch_damping_coefficient(mach, &pitch_coeffs);
3677 if pitch_damping < min_pitch_damping {
3678 min_pitch_damping = pitch_damping;
3679 }
3680 }
3681
3682 let accepted_step =
3685 self.adaptive_rk45_step(&position, &velocity, dt, &wind_vector, &station);
3686 debug_assert!(
3687 accepted_step.error <= RK45_TOLERANCE || accepted_step.used_dt <= RK45_MIN_DT
3688 );
3689
3690 if self.inputs.enable_precession_nutation {
3694 if let Some(ref mut state) = angular_state {
3695 let params = self.precession_nutation_params(
3696 velocity_magnitude,
3697 air_density,
3698 speed_of_sound,
3699 );
3700
3701 *state = calculate_combined_angular_motion(
3702 ¶ms,
3703 state,
3704 time,
3705 accepted_step.used_dt,
3706 0.001,
3707 );
3708
3709 if state.yaw_angle.abs() > max_yaw_angle {
3710 max_yaw_angle = state.yaw_angle.abs();
3711 }
3712 if state.precession_angle.abs() > max_precession_angle {
3713 max_precession_angle = state.precession_angle.abs();
3714 }
3715 }
3716 }
3717
3718 let step_start = position;
3719 position = accepted_step.position;
3720 velocity = accepted_step.velocity;
3721 time += accepted_step.used_dt;
3722 self.validate_integration_state(&position, &velocity, time)
3723 .map_err(|error| {
3724 self.refusal_of_failed_step(
3725 error,
3726 &station,
3727 &step_start,
3728 &position,
3729 &velocity,
3730 accepted_step.used_dt,
3731 time,
3732 )
3733 })?;
3734
3735 dt = accepted_step.next_dt;
3737 }
3738
3739 if points.is_empty() {
3741 return Err(BallisticsError::from("No trajectory points calculated"));
3742 }
3743
3744 let termination = self.append_terminal_endpoint(
3746 &mut points,
3747 position,
3748 velocity,
3749 time,
3750 &mut max_height,
3751 &mut collapsed_steps,
3752 )?;
3753
3754 self.annotate_drag_coefficients(&mut points, speed_of_sound);
3756
3757 let last_point = points.last().unwrap();
3758
3759 let sampled_points =
3761 self.build_sampled_points(&points, max_height, transonic_distances, &mach_transitions)?;
3762
3763 Ok(TrajectoryResult {
3764 max_range: last_point.position.x, max_height,
3766 time_of_flight: last_point.time,
3767 impact_velocity: last_point.velocity_magnitude,
3768 impact_energy: last_point.kinetic_energy,
3769 projectile_mass_kg: self.inputs.bullet_mass,
3770 line_of_sight_height_m: self.inputs.muzzle_height + self.inputs.sight_height,
3771 station_speed_of_sound_mps: speed_of_sound,
3772 termination,
3773 points,
3774 sampled_points,
3775 min_pitch_damping: if self.inputs.enable_pitch_damping {
3776 Some(min_pitch_damping)
3777 } else {
3778 None
3779 },
3780 transonic_mach,
3781 angular_state,
3782 max_yaw_angle: if self.inputs.enable_precession_nutation {
3783 Some(max_yaw_angle)
3784 } else {
3785 None
3786 },
3787 max_precession_angle: if self.inputs.enable_precession_nutation {
3788 Some(max_precession_angle)
3789 } else {
3790 None
3791 },
3792 aerodynamic_jump: aj_components,
3793 mach_1_2_distance_m: mach_transitions.mach_1_2_distance_m,
3794 mach_1_0_distance_m: mach_transitions.mach_1_0_distance_m,
3795 mach_0_9_distance_m: mach_transitions.mach_0_9_distance_m,
3796 })
3797 }
3798
3799 fn adaptive_rk45_step(
3800 &self,
3801 position: &Vector3<f64>,
3802 velocity: &Vector3<f64>,
3803 initial_dt: f64,
3804 wind_vector: &Vector3<f64>,
3805 station: &StationAir,
3806 ) -> Rk45AcceptedStep {
3807 let mut trial_dt = initial_dt;
3808
3809 loop {
3810 let trial = self.rk45_step(
3811 position,
3812 velocity,
3813 trial_dt,
3814 wind_vector,
3815 RK45_TOLERANCE,
3816 station,
3817 );
3818 let next_dt = if trial.suggested_dt.is_finite() {
3823 (RK45_SAFETY_FACTOR * trial.suggested_dt).clamp(RK45_MIN_DT, RK45_MAX_DT)
3824 } else {
3825 RK45_MIN_DT
3826 };
3827
3828 if trial.error <= RK45_TOLERANCE || trial_dt <= RK45_MIN_DT {
3829 return Rk45AcceptedStep {
3830 position: trial.position,
3831 velocity: trial.velocity,
3832 used_dt: trial_dt,
3833 next_dt,
3834 error: trial.error,
3835 };
3836 }
3837
3838 trial_dt = next_dt;
3839 }
3840 }
3841
3842 fn rk45_step(
3843 &self,
3844 position: &Vector3<f64>,
3845 velocity: &Vector3<f64>,
3846 dt: f64,
3847 wind_vector: &Vector3<f64>,
3848 tolerance: f64,
3849 station: &StationAir,
3850 ) -> Rk45Trial {
3851 const A21: f64 = 1.0 / 5.0;
3853 const A31: f64 = 3.0 / 40.0;
3854 const A32: f64 = 9.0 / 40.0;
3855 const A41: f64 = 44.0 / 45.0;
3856 const A42: f64 = -56.0 / 15.0;
3857 const A43: f64 = 32.0 / 9.0;
3858 const A51: f64 = 19372.0 / 6561.0;
3859 const A52: f64 = -25360.0 / 2187.0;
3860 const A53: f64 = 64448.0 / 6561.0;
3861 const A54: f64 = -212.0 / 729.0;
3862 const A61: f64 = 9017.0 / 3168.0;
3863 const A62: f64 = -355.0 / 33.0;
3864 const A63: f64 = 46732.0 / 5247.0;
3865 const A64: f64 = 49.0 / 176.0;
3866 const A65: f64 = -5103.0 / 18656.0;
3867 const A71: f64 = 35.0 / 384.0;
3868 const A73: f64 = 500.0 / 1113.0;
3869 const A74: f64 = 125.0 / 192.0;
3870 const A75: f64 = -2187.0 / 6784.0;
3871 const A76: f64 = 11.0 / 84.0;
3872
3873 const B1: f64 = 35.0 / 384.0;
3875 const B3: f64 = 500.0 / 1113.0;
3876 const B4: f64 = 125.0 / 192.0;
3877 const B5: f64 = -2187.0 / 6784.0;
3878 const B6: f64 = 11.0 / 84.0;
3879
3880 const B1_ERR: f64 = 5179.0 / 57600.0;
3882 const B3_ERR: f64 = 7571.0 / 16695.0;
3883 const B4_ERR: f64 = 393.0 / 640.0;
3884 const B5_ERR: f64 = -92097.0 / 339200.0;
3885 const B6_ERR: f64 = 187.0 / 2100.0;
3886 const B7_ERR: f64 = 1.0 / 40.0;
3887
3888 let k1_v = self.calculate_acceleration(position, velocity, wind_vector, station);
3890 let k1_p = *velocity;
3891
3892 let p2 = position + dt * A21 * k1_p;
3893 let v2 = velocity + dt * A21 * k1_v;
3894 let k2_v = self.calculate_acceleration(&p2, &v2, wind_vector, station);
3895 let k2_p = v2;
3896
3897 let p3 = position + dt * (A31 * k1_p + A32 * k2_p);
3898 let v3 = velocity + dt * (A31 * k1_v + A32 * k2_v);
3899 let k3_v = self.calculate_acceleration(&p3, &v3, wind_vector, station);
3900 let k3_p = v3;
3901
3902 let p4 = position + dt * (A41 * k1_p + A42 * k2_p + A43 * k3_p);
3903 let v4 = velocity + dt * (A41 * k1_v + A42 * k2_v + A43 * k3_v);
3904 let k4_v = self.calculate_acceleration(&p4, &v4, wind_vector, station);
3905 let k4_p = v4;
3906
3907 let p5 = position + dt * (A51 * k1_p + A52 * k2_p + A53 * k3_p + A54 * k4_p);
3908 let v5 = velocity + dt * (A51 * k1_v + A52 * k2_v + A53 * k3_v + A54 * k4_v);
3909 let k5_v = self.calculate_acceleration(&p5, &v5, wind_vector, station);
3910 let k5_p = v5;
3911
3912 let p6 = position + dt * (A61 * k1_p + A62 * k2_p + A63 * k3_p + A64 * k4_p + A65 * k5_p);
3913 let v6 = velocity + dt * (A61 * k1_v + A62 * k2_v + A63 * k3_v + A64 * k4_v + A65 * k5_v);
3914 let k6_v = self.calculate_acceleration(&p6, &v6, wind_vector, station);
3915 let k6_p = v6;
3916
3917 let p7 = position + dt * (A71 * k1_p + A73 * k3_p + A74 * k4_p + A75 * k5_p + A76 * k6_p);
3918 let v7 = velocity + dt * (A71 * k1_v + A73 * k3_v + A74 * k4_v + A75 * k5_v + A76 * k6_v);
3919 let k7_v = self.calculate_acceleration(&p7, &v7, wind_vector, station);
3920 let k7_p = v7;
3921
3922 let new_pos = position + dt * (B1 * k1_p + B3 * k3_p + B4 * k4_p + B5 * k5_p + B6 * k6_p);
3924 let new_vel = velocity + dt * (B1 * k1_v + B3 * k3_v + B4 * k4_v + B5 * k5_v + B6 * k6_v);
3925
3926 let pos_err = position
3928 + dt * (B1_ERR * k1_p
3929 + B3_ERR * k3_p
3930 + B4_ERR * k4_p
3931 + B5_ERR * k5_p
3932 + B6_ERR * k6_p
3933 + B7_ERR * k7_p);
3934 let vel_err = velocity
3935 + dt * (B1_ERR * k1_v
3936 + B3_ERR * k3_v
3937 + B4_ERR * k4_v
3938 + B5_ERR * k5_v
3939 + B6_ERR * k6_v
3940 + B7_ERR * k7_v);
3941
3942 let error = cli_rk45_error_norm(position, velocity, &new_pos, &new_vel, &pos_err, &vel_err);
3944
3945 let dt_new = if error < tolerance {
3947 dt * (tolerance / error).powf(0.2).min(2.0)
3948 } else {
3949 dt * (tolerance / error).powf(0.25).max(0.1)
3950 };
3951
3952 Rk45Trial {
3953 position: new_pos,
3954 velocity: new_vel,
3955 suggested_dt: dt_new,
3956 error,
3957 }
3958 }
3959
3960 fn apply_cluster_bc_correction(&self, base_bc: f64, velocity_fps: f64) -> f64 {
3961 if let Some(ref cluster_bc) = self.cluster_bc {
3962 cluster_bc.apply_correction_for_drag_model(
3963 base_bc,
3964 self.inputs.caliber_inches,
3965 self.inputs.weight_grains,
3966 velocity_fps,
3967 self.inputs.bc_type,
3968 )
3969 } else {
3970 base_bc
3971 }
3972 }
3973
3974 fn calculate_acceleration(
3975 &self,
3976 position: &Vector3<f64>,
3977 velocity: &Vector3<f64>,
3978 wind_vector: &Vector3<f64>,
3979 station: &StationAir,
3980 ) -> Vector3<f64> {
3981 let actual_wind = if let Some(ref sock) = self.wind_sock {
3987 sock.vector_for_range_stateless(position.x)
3988 } else if let Some(model) = self.boundary_layer_shear_model() {
3989 self.get_wind_at_altitude(
3990 crate::wind_shear::shear_height_agl_m(position.y, self.inputs.muzzle_height),
3991 model,
3992 )
3993 } else {
3994 *wind_vector
3995 };
3996 let actual_wind =
3997 crate::derivatives::level_vector_to_shot_frame(actual_wind, self.inputs.shooting_angle);
3998
3999 let relative_velocity = velocity - actual_wind;
4000 let velocity_magnitude = relative_velocity.magnitude();
4001
4002 if velocity_magnitude < 0.001 {
4003 return self.gravity_acceleration();
4004 }
4005
4006 let local_alt = crate::atmosphere::shot_frame_altitude(
4021 self.atmosphere.altitude,
4022 position.x,
4023 position.y,
4024 self.inputs.shooting_angle,
4025 );
4026 let local_air = crate::atmosphere::air_at_with_gravity(
4027 &KernelAtmosphere::Station(*station),
4028 self.atmo_sock.as_ref(),
4029 position.x,
4030 local_alt,
4031 self.gravity,
4032 );
4033 let (air_density, speed_of_sound) = (local_air.density_kg_m3, local_air.speed_of_sound_mps);
4034 #[cfg(test)]
4037 crate::atmosphere::air_trace::record_consumed(
4038 air_density,
4039 velocity_magnitude,
4040 velocity_magnitude / speed_of_sound,
4041 );
4042
4043 let (cd, retard_denom) = self.drag_terms(velocity_magnitude, speed_of_sound);
4048
4049 let velocity_fps = velocity_magnitude * 3.28084;
4051
4052 let cd_to_retard = crate::constants::CD_TO_RETARD;
4057 let standard_factor = cd * cd_to_retard;
4058 let density_scale = air_density / 1.225; let a_drag_ft_s2 =
4062 (velocity_fps * velocity_fps) * standard_factor * density_scale / retard_denom;
4063 let a_drag_m_s2 = a_drag_ft_s2 * 0.3048; let drag_acceleration = -a_drag_m_s2 * (relative_velocity / velocity_magnitude);
4067
4068 let mut accel = drag_acceleration + self.gravity_acceleration();
4071
4072 if self.inputs.enable_coriolis {
4075 if let Some(lat_deg) = self.inputs.latitude {
4076 let omega_earth = 7.2921159e-5_f64; let lat = lat_deg.to_radians();
4078 let az = self.inputs.shot_azimuth; let omega = Vector3::new(
4085 omega_earth * lat.cos() * az.cos(), omega_earth * lat.sin(), -omega_earth * lat.cos() * az.sin(), );
4089 let omega = crate::derivatives::level_vector_to_shot_frame(
4090 omega,
4091 self.inputs.shooting_angle,
4092 );
4093 accel += -2.0 * omega.cross(velocity);
4098 }
4099 }
4100
4101 if self.inputs.enable_magnus
4108 && !self.inputs.use_enhanced_spin_drift
4109 && self.inputs.bullet_diameter > 0.0
4110 && self.inputs.twist_rate > 0.0
4111 {
4112 let diameter_m = self.inputs.bullet_diameter;
4113 let (spin_rad_s, spin_param) = crate::spin_drift::calculate_magnus_spin_state(
4114 self.inputs.muzzle_velocity,
4115 velocity_magnitude,
4116 self.inputs.twist_rate,
4117 diameter_m,
4118 );
4119 let mach = velocity_magnitude / speed_of_sound;
4121
4122 let d_in = self.inputs.bullet_diameter / 0.0254;
4124 let m_gr = self.inputs.bullet_mass / crate::constants::GRAINS_TO_KG;
4125 let l_in = if self.inputs.bullet_length > 0.0 {
4126 self.inputs.bullet_length / 0.0254
4127 } else {
4128 let est_m = crate::stability::estimate_bullet_length_m(
4130 self.inputs.bullet_diameter,
4131 self.inputs.bullet_mass,
4132 );
4133 if est_m > 0.0 {
4134 est_m / 0.0254
4135 } else {
4136 4.5 * d_in
4137 }
4138 };
4139 let sg = crate::spin_drift::calculate_dynamic_stability(
4143 m_gr,
4144 velocity_magnitude,
4145 spin_rad_s,
4146 d_in,
4147 l_in,
4148 air_density,
4149 );
4150
4151 let (yaw_rad, _) = crate::spin_drift::calculate_yaw_of_repose_with_gravity(
4153 sg,
4154 velocity_magnitude,
4155 spin_rad_s,
4156 0.0, 0.0, air_density,
4159 d_in,
4160 l_in,
4161 m_gr,
4162 mach,
4163 "match",
4164 false,
4165 self.gravity,
4166 );
4167
4168 let c_np = crate::derivatives::calculate_magnus_moment_coefficient(mach);
4170 let area = std::f64::consts::PI * (diameter_m / 2.0).powi(2);
4171 let magnus_force = 0.5
4172 * air_density
4173 * velocity_magnitude.powi(2)
4174 * area
4175 * c_np
4176 * spin_param
4177 * yaw_rad.sin();
4178
4179 if magnus_force.abs() > 1e-12 {
4183 if let Some(dir) = crate::derivatives::yaw_of_repose_magnus_direction(
4184 relative_velocity,
4185 self.gravity_acceleration(),
4186 self.inputs.is_twist_right,
4187 ) {
4188 accel += (magnus_force / self.inputs.bullet_mass) * dir;
4189 }
4190 }
4191 }
4192
4193 accel
4194 }
4195
4196 fn drag_terms(&self, velocity_magnitude: f64, speed_of_sound: f64) -> (f64, f64) {
4210 let cd = self.calculate_drag_coefficient(velocity_magnitude, speed_of_sound);
4211
4212 let velocity_fps = velocity_magnitude * 3.28084;
4213
4214 let (base_bc, bc_from_segments) = if let Some(segments) = self
4219 .inputs
4220 .bc_segments_data
4221 .as_ref()
4222 .filter(|segments| self.inputs.use_bc_segments && !segments.is_empty())
4223 {
4224 (
4226 crate::bc_estimation::velocity_segment_bc(
4227 velocity_fps,
4228 segments,
4229 self.inputs.bc_value,
4230 ),
4231 true,
4232 )
4233 } else if let Some(segments) = self
4234 .inputs
4235 .bc_segments
4236 .as_ref()
4237 .filter(|segments| !segments.is_empty())
4238 {
4239 (
4240 crate::derivatives::interpolated_bc(
4241 velocity_magnitude / speed_of_sound,
4242 segments,
4243 Some(&self.inputs),
4244 ),
4245 true,
4246 )
4247 } else {
4248 (self.inputs.bc_value, false)
4249 };
4250
4251 let effective_bc = if bc_from_segments {
4256 base_bc
4257 } else {
4258 self.apply_cluster_bc_correction(base_bc, velocity_fps)
4259 };
4260 let effective_bc = effective_bc.max(1e-6);
4263
4264 let retard_denom = if self.inputs.custom_drag_table.is_some() {
4270 self.inputs.custom_drag_denominator(effective_bc)
4271 } else {
4272 effective_bc
4273 };
4274
4275 (cd, retard_denom)
4276 }
4277
4278 pub fn effective_drag_coefficient(
4301 &self,
4302 velocity_magnitude: f64,
4303 speed_of_sound: f64,
4304 ) -> Option<f64> {
4305 if !velocity_magnitude.is_finite() || speed_of_sound <= 1e-9 {
4306 return None;
4307 }
4308 let sectional_density = self.inputs.sectional_density_lb_in2()?;
4309 let (cd, retard_denom) = self.drag_terms(velocity_magnitude, speed_of_sound);
4310 if retard_denom <= 0.0 {
4311 return None;
4312 }
4313 let effective = cd * sectional_density / retard_denom;
4314 effective.is_finite().then_some(effective)
4315 }
4316
4317 fn annotate_drag_coefficients(&self, points: &mut [TrajectoryPoint], speed_of_sound: f64) {
4327 for point in points.iter_mut() {
4328 point.drag_coefficient =
4329 self.effective_drag_coefficient(point.velocity_magnitude, speed_of_sound);
4330 }
4331 }
4332
4333 fn calculate_drag_coefficient(&self, velocity: f64, speed_of_sound: f64) -> f64 {
4334 let mach = velocity / speed_of_sound;
4335
4336 if let Some(ref table) = self.inputs.custom_drag_table {
4340 return table.interpolate(mach) * self.inputs.cd_scale;
4345 }
4346
4347 crate::drag::get_drag_coefficient(mach, &self.inputs.bc_type)
4350 }
4351}
4352
4353#[derive(Debug, Clone)]
4355pub struct MonteCarloParams {
4356 pub num_simulations: usize,
4357 pub velocity_std_dev: f64,
4358 pub angle_std_dev: f64,
4359 pub bc_std_dev: f64,
4360 pub wind_speed_std_dev: f64,
4361 pub target_distance: Option<f64>,
4362 pub base_wind_speed: f64,
4363 pub base_wind_direction: f64,
4364 pub azimuth_std_dev: f64, }
4366
4367impl Default for MonteCarloParams {
4368 fn default() -> Self {
4369 Self {
4370 num_simulations: 1000,
4371 velocity_std_dev: 1.0,
4372 angle_std_dev: 0.001,
4373 bc_std_dev: 0.01,
4374 wind_speed_std_dev: 1.0,
4375 target_distance: None,
4376 base_wind_speed: 0.0,
4377 base_wind_direction: 0.0,
4378 azimuth_std_dev: 0.001, }
4380 }
4381}
4382
4383#[derive(Debug, Clone)]
4385pub struct MonteCarloResults {
4386 pub ranges: Vec<f64>,
4387 pub impact_velocities: Vec<f64>,
4388 pub impact_positions: Vec<Vector3<f64>>,
4394}
4395
4396pub const DEFAULT_HIT_RADIUS_M: f64 = 0.3;
4399
4400pub const TARGET_NOT_REACHED_SENTINEL_M: f64 = -1.0e9;
4406
4407impl MonteCarloResults {
4408 pub fn position_reached_target(position: &Vector3<f64>) -> bool {
4410 position.iter().all(|component| component.is_finite())
4411 && position.y != TARGET_NOT_REACHED_SENTINEL_M
4412 }
4413
4414 pub fn target_arrival_count(&self) -> usize {
4416 self.impact_positions
4417 .iter()
4418 .filter(|position| Self::position_reached_target(position))
4419 .count()
4420 }
4421
4422 pub fn target_shortfall_fraction(&self) -> f64 {
4425 if self.impact_positions.is_empty() {
4426 return 0.0;
4427 }
4428 (self.impact_positions.len() - self.target_arrival_count()) as f64
4429 / self.impact_positions.len() as f64
4430 }
4431
4432 pub fn target_plane_cep(&self) -> Option<f64> {
4438 let mut radial_misses: Vec<f64> = self
4439 .impact_positions
4440 .iter()
4441 .filter(|position| Self::position_reached_target(position))
4442 .map(Vector3::norm)
4443 .filter(|miss| miss.is_finite())
4444 .collect();
4445 radial_misses.sort_by(f64::total_cmp);
4446 if radial_misses.is_empty() {
4447 None
4448 } else {
4449 Some(radial_misses[radial_misses.len() / 2])
4450 }
4451 }
4452
4453 pub fn hit_probability(&self, hit_radius_m: f64) -> f64 {
4462 if self.impact_positions.is_empty() {
4463 return 0.0;
4464 }
4465 let hits = self
4466 .impact_positions
4467 .iter()
4468 .filter(|position| Self::position_is_hit(position, hit_radius_m))
4469 .count();
4470 hits as f64 / self.impact_positions.len() as f64
4471 }
4472
4473 pub fn position_is_hit(position: &Vector3<f64>, hit_radius_m: f64) -> bool {
4485 Self::position_reached_target(position) && position.norm() < hit_radius_m
4486 }
4487
4488 pub fn hit_probability_wilson(
4510 &self,
4511 hit_radius_m: f64,
4512 level: ConfidenceLevel,
4513 ) -> (f64, (f64, f64), u64) {
4514 let trials = self.impact_positions.len() as u64;
4515 let hits = self
4516 .impact_positions
4517 .iter()
4518 .filter(|position| Self::position_is_hit(position, hit_radius_m))
4519 .count() as u64;
4520 (
4521 self.hit_probability(hit_radius_m),
4522 wilson_interval(hits, trials, level),
4523 trials,
4524 )
4525 }
4526
4527 pub fn rect_hit_probability(&self, width_m: f64, height_m: f64) -> f64 {
4539 let dimensions_invalid =
4540 width_m.is_nan() || width_m <= 0.0 || height_m.is_nan() || height_m <= 0.0;
4541 if self.impact_positions.is_empty() || dimensions_invalid {
4542 return 0.0;
4543 }
4544 let half_width = width_m / 2.0;
4545 let half_height = height_m / 2.0;
4546 let hits = self
4547 .impact_positions
4548 .iter()
4549 .filter(|position| {
4550 Self::position_reached_target(position)
4551 && position.z.abs() <= half_width
4552 && position.y.abs() <= half_height
4553 })
4554 .count();
4555 hits as f64 / self.impact_positions.len() as f64
4556 }
4557}
4558
4559fn wind_from_signed_speed_sample(
4560 signed_speed: f64,
4561 sampled_direction: f64,
4562 vertical_speed: f64,
4563) -> WindConditions {
4564 if signed_speed < 0.0 {
4569 WindConditions {
4570 speed: -signed_speed,
4571 direction: sampled_direction + std::f64::consts::PI,
4572 vertical_speed,
4573 }
4574 } else {
4575 WindConditions {
4576 speed: signed_speed,
4577 direction: sampled_direction,
4578 vertical_speed,
4579 }
4580 }
4581}
4582
4583struct MonteCarloWindSampler {
4584 speed: rand_distr::Normal<f64>,
4585 direction: rand_distr::Normal<f64>,
4586 vertical_speed: f64,
4588}
4589
4590impl MonteCarloWindSampler {
4591 fn new(
4592 base_wind: &WindConditions,
4593 wind_speed_std_dev: f64,
4594 wind_direction_std_dev: f64,
4595 ) -> Result<Self, BallisticsError> {
4596 use rand_distr::Normal;
4597
4598 if !wind_direction_std_dev.is_finite() || wind_direction_std_dev < 0.0 {
4599 return Err("Wind direction standard deviation must be finite and non-negative".into());
4600 }
4601
4602 let speed = Normal::new(base_wind.speed, wind_speed_std_dev)
4603 .map_err(|e| format!("Invalid wind speed distribution: {e}"))?;
4604 let direction = Normal::new(base_wind.direction, wind_direction_std_dev)
4605 .map_err(|e| format!("Invalid wind direction distribution: {e}"))?;
4606 Ok(Self {
4607 speed,
4608 direction,
4609 vertical_speed: base_wind.vertical_speed,
4610 })
4611 }
4612
4613 fn sample<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> WindConditions {
4614 use rand_distr::Distribution;
4615
4616 wind_from_signed_speed_sample(
4617 self.speed.sample(rng),
4618 self.direction.sample(rng),
4619 self.vertical_speed,
4620 )
4621 }
4622}
4623
4624#[derive(Debug, Clone, Copy)]
4627struct TrialOutcome {
4628 range: f64,
4631 impact_velocity: f64,
4633 impact_position: Vector3<f64>,
4636}
4637
4638struct MonteCarloTrialSampler {
4658 base_inputs: BallisticInputs,
4659 atmosphere: AtmosphericConditions,
4660 station_presence: StationAtmospherePresence,
4662 solver_max_range: f64,
4663 target_distance: f64,
4666 baseline_at_target: Vector3<f64>,
4669 velocity_delta_dist: rand_distr::Normal<f64>,
4670 angle_dist: rand_distr::Normal<f64>,
4671 bc_dist: rand_distr::Normal<f64>,
4672 wind_sampler: MonteCarloWindSampler,
4673 azimuth_dist: rand_distr::Normal<f64>,
4674}
4675
4676impl MonteCarloTrialSampler {
4677 fn new(
4681 base_inputs: BallisticInputs,
4682 base_wind: &WindConditions,
4683 params: &MonteCarloParams,
4684 wind_direction_std_dev: f64,
4685 station_presence: StationAtmospherePresence,
4686 ) -> Result<Self, BallisticsError> {
4687 use rand_distr::Normal;
4688
4689 let atmosphere = AtmosphericConditions {
4690 temperature: base_inputs.temperature,
4691 pressure: base_inputs.pressure,
4692 humidity: base_inputs.humidity_percent,
4693 altitude: base_inputs.altitude,
4694 };
4695 let target_hint = params
4696 .target_distance
4697 .unwrap_or(base_inputs.target_distance);
4698 let solver_max_range = target_hint.max(1000.0) * 2.0;
4699
4700 let mut baseline_solver = TrajectorySolver::new_with_station_presence(
4702 base_inputs.clone(),
4703 base_wind.clone(),
4704 atmosphere.clone(),
4705 station_presence,
4706 );
4707 baseline_solver.set_max_range(solver_max_range);
4708 let baseline_result = baseline_solver.solve()?;
4709
4710 let target_distance = params.target_distance.unwrap_or(baseline_result.max_range);
4712
4713 let baseline_at_target = baseline_result
4715 .position_at_range(target_distance)
4716 .ok_or("Could not interpolate baseline at target distance")?;
4717
4718 let velocity_delta_dist = Normal::new(0.0, params.velocity_std_dev)
4723 .map_err(|e| format!("Invalid velocity distribution: {}", e))?;
4724 let angle_dist = Normal::new(base_inputs.muzzle_angle, params.angle_std_dev)
4725 .map_err(|e| format!("Invalid angle distribution: {}", e))?;
4726 let bc_dist = Normal::new(base_inputs.bc_value, params.bc_std_dev)
4727 .map_err(|e| format!("Invalid BC distribution: {}", e))?;
4728 let wind_sampler = MonteCarloWindSampler::new(
4731 base_wind,
4732 params.wind_speed_std_dev,
4733 wind_direction_std_dev,
4734 )?;
4735 let azimuth_dist = Normal::new(base_inputs.azimuth_angle, params.azimuth_std_dev)
4736 .map_err(|e| format!("Invalid azimuth distribution: {}", e))?;
4737
4738 Ok(Self {
4739 base_inputs,
4740 atmosphere,
4741 station_presence,
4742 solver_max_range,
4743 target_distance,
4744 baseline_at_target,
4745 velocity_delta_dist,
4746 angle_dist,
4747 bc_dist,
4748 wind_sampler,
4749 azimuth_dist,
4750 })
4751 }
4752
4753 fn sample_one_trial<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> Option<TrialOutcome> {
4763 use rand_distr::Distribution;
4764
4765 let mut inputs = self.base_inputs.clone();
4767 let muzzle_velocity_delta = self.velocity_delta_dist.sample(&mut *rng);
4768 inputs.muzzle_angle = self.angle_dist.sample(&mut *rng);
4769 inputs.bc_value = self.bc_dist.sample(&mut *rng).max(0.01);
4770 inputs.azimuth_angle = self.azimuth_dist.sample(&mut *rng); let wind = self.wind_sampler.sample(&mut *rng);
4774
4775 let mut solver = TrajectorySolver::new_with_station_presence(
4779 inputs,
4780 wind,
4781 self.atmosphere.clone(),
4782 self.station_presence,
4783 );
4784 solver.inputs.muzzle_velocity =
4785 (solver.inputs.muzzle_velocity + muzzle_velocity_delta).max(0.0);
4786 solver.set_max_range(self.solver_max_range);
4787 let result = solver.solve().ok()?;
4789
4790 let impact_position = if result.max_range < self.target_distance {
4796 Vector3::new(0.0, TARGET_NOT_REACHED_SENTINEL_M, 0.0)
4799 } else {
4800 let pos_at_target = result.position_at_range(self.target_distance)?;
4802 Vector3::new(
4807 0.0,
4808 pos_at_target.y - self.baseline_at_target.y,
4809 pos_at_target.z - self.baseline_at_target.z,
4810 )
4811 };
4812
4813 Some(TrialOutcome {
4814 range: result.max_range,
4815 impact_velocity: result.impact_velocity,
4816 impact_position,
4817 })
4818 }
4819}
4820
4821pub fn run_monte_carlo(
4827 base_inputs: BallisticInputs,
4828 params: MonteCarloParams,
4829) -> Result<MonteCarloResults, BallisticsError> {
4830 run_monte_carlo_with_direction_std_dev(base_inputs, params, 0.0)
4831}
4832
4833pub fn run_monte_carlo_with_direction_std_dev(
4840 base_inputs: BallisticInputs,
4841 params: MonteCarloParams,
4842 wind_direction_std_dev: f64,
4843) -> Result<MonteCarloResults, BallisticsError> {
4844 let base_wind = WindConditions {
4845 speed: params.base_wind_speed,
4846 direction: params.base_wind_direction,
4847 vertical_speed: 0.0,
4848 };
4849 run_monte_carlo_with_wind_and_direction_std_dev(
4850 base_inputs,
4851 base_wind,
4852 params,
4853 wind_direction_std_dev,
4854 )
4855}
4856
4857pub fn run_monte_carlo_with_wind(
4861 base_inputs: BallisticInputs,
4862 base_wind: WindConditions,
4863 params: MonteCarloParams,
4864) -> Result<MonteCarloResults, BallisticsError> {
4865 run_monte_carlo_with_wind_and_direction_std_dev(base_inputs, base_wind, params, 0.0)
4866}
4867
4868pub fn run_monte_carlo_with_wind_and_direction_std_dev(
4875 base_inputs: BallisticInputs,
4876 base_wind: WindConditions,
4877 params: MonteCarloParams,
4878 wind_direction_std_dev: f64,
4879) -> Result<MonteCarloResults, BallisticsError> {
4880 run_monte_carlo_with_station_presence(
4881 base_inputs,
4882 base_wind,
4883 params,
4884 wind_direction_std_dev,
4885 None,
4886 StationAtmospherePresence::NEITHER,
4887 )
4888}
4889
4890pub fn run_monte_carlo_with_station_presence(
4901 base_inputs: BallisticInputs,
4902 base_wind: WindConditions,
4903 params: MonteCarloParams,
4904 wind_direction_std_dev: f64,
4905 seed: Option<u64>,
4906 station_presence: StationAtmospherePresence,
4907) -> Result<MonteCarloResults, BallisticsError> {
4908 match seed {
4909 None => {
4910 let mut rng = rand::rng();
4911 run_monte_carlo_with_wind_and_direction_std_dev_using_rng(
4912 base_inputs,
4913 base_wind,
4914 params,
4915 wind_direction_std_dev,
4916 station_presence,
4917 &mut rng,
4918 )
4919 }
4920 Some(seed) => {
4921 use rand::{rngs::StdRng, SeedableRng};
4922 let mut rng = StdRng::seed_from_u64(seed);
4923 run_monte_carlo_with_wind_and_direction_std_dev_using_rng(
4924 base_inputs,
4925 base_wind,
4926 params,
4927 wind_direction_std_dev,
4928 station_presence,
4929 &mut rng,
4930 )
4931 }
4932 }
4933}
4934
4935pub fn run_monte_carlo_with_wind_and_direction_std_dev_seeded(
4944 base_inputs: BallisticInputs,
4945 base_wind: WindConditions,
4946 params: MonteCarloParams,
4947 wind_direction_std_dev: f64,
4948 seed: u64,
4949) -> Result<MonteCarloResults, BallisticsError> {
4950 run_monte_carlo_with_station_presence(
4951 base_inputs,
4952 base_wind,
4953 params,
4954 wind_direction_std_dev,
4955 Some(seed),
4956 StationAtmospherePresence::NEITHER,
4957 )
4958}
4959
4960fn run_monte_carlo_with_wind_and_direction_std_dev_using_rng<R: rand::Rng + ?Sized>(
4961 base_inputs: BallisticInputs,
4962 base_wind: WindConditions,
4963 params: MonteCarloParams,
4964 wind_direction_std_dev: f64,
4965 station_presence: StationAtmospherePresence,
4966 rng: &mut R,
4967) -> Result<MonteCarloResults, BallisticsError> {
4968 let mut ranges = Vec::new();
4969 let mut impact_velocities = Vec::new();
4970 let mut impact_positions = Vec::new();
4971
4972 let sampler = MonteCarloTrialSampler::new(
4973 base_inputs,
4974 &base_wind,
4975 ¶ms,
4976 wind_direction_std_dev,
4977 station_presence,
4978 )?;
4979
4980 for _ in 0..params.num_simulations {
4981 if let Some(outcome) = sampler.sample_one_trial(rng) {
4985 ranges.push(outcome.range);
4986 impact_velocities.push(outcome.impact_velocity);
4987 impact_positions.push(outcome.impact_position);
4988 }
4989 }
4990
4991 if ranges.is_empty() {
4992 return Err("No successful simulations".into());
4993 }
4994
4995 Ok(MonteCarloResults {
4996 ranges,
4997 impact_velocities,
4998 impact_positions,
4999 })
5000}
5001
5002pub const MC_ADAPTIVE_SCHEMA_VERSION_V1: u32 = 1;
5004
5005pub const MC_ADAPTIVE_METHOD_V1: &str = "anytime_beta_binomial_mixture_cs_v1";
5012
5013pub const MC_ADAPTIVE_ASSUMPTIONS_V1: [&str; 4] = [
5027 "Sampling uncertainty only: intervals cover Monte Carlo sampling error, not model error in the trajectory solver or its inputs.",
5028 "Anytime-valid stopping: the beta-binomial mixture confidence sequence keeps its coverage guarantee despite stopping the moment the target half-width is met.",
5029 "Input dispersions are the independent normal distributions declared in MonteCarloParams; correlations between inputs are not modeled.",
5030 "Continuous statistics are streaming Welford moments over trials that reached the target plane, reported with sample (n-1) standard deviations; hit probability's denominator includes all trials.",
5031];
5032
5033#[derive(Debug, Clone)]
5040pub struct McConvergence {
5041 pub level: ConfidenceLevel,
5043 pub target_half_width: f64,
5046 pub min_samples: u64,
5050 pub max_samples: u64,
5053 pub batch_size: u64,
5056}
5057
5058impl Default for McConvergence {
5059 fn default() -> Self {
5060 Self {
5061 level: ConfidenceLevel::P95,
5062 target_half_width: 0.02,
5063 min_samples: 1_000,
5064 max_samples: 100_000,
5065 batch_size: 500,
5066 }
5067 }
5068}
5069
5070impl McConvergence {
5071 pub fn validate(&self) -> Result<(), String> {
5080 if !self.target_half_width.is_finite() || self.target_half_width <= 0.0 {
5081 return Err(format!(
5082 "McConvergence.target_half_width must be a finite value greater than zero (got {})",
5083 self.target_half_width
5084 ));
5085 }
5086 if self.batch_size == 0 {
5087 return Err("McConvergence.batch_size must be greater than zero".to_string());
5088 }
5089 if self.max_samples == 0 {
5090 return Err("McConvergence.max_samples must be greater than zero".to_string());
5091 }
5092 if self.max_samples < self.min_samples {
5093 return Err(format!(
5094 "McConvergence.max_samples ({}) must be at least McConvergence.min_samples ({})",
5095 self.max_samples, self.min_samples
5096 ));
5097 }
5098 Ok(())
5099 }
5100}
5101
5102#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
5104#[serde(rename_all = "snake_case")]
5105pub enum McStopReason {
5106 TargetHalfWidthMet,
5109 MaxSamplesReached,
5112}
5113
5114#[derive(Debug, Clone, serde::Serialize)]
5121pub struct AdaptiveMcReportV1 {
5122 pub schema_version: u32,
5124 pub method: String,
5126 pub assumptions: Vec<String>,
5128 pub confidence_percent: u32,
5130 pub hit_probability: f64,
5133 pub ci_low: f64,
5135 pub ci_high: f64,
5137 pub samples: u64,
5139 pub attempts: u64,
5150 pub arrivals: u64,
5165 pub stop_reason: McStopReason,
5167 pub hit_radius_m: f64,
5169 pub target_distance_m: f64,
5171 pub mean_impact_velocity_mps: f64,
5176 pub std_impact_velocity_mps: f64,
5178 pub mean_drop_at_target_m: f64,
5186 pub std_drop_at_target_m: f64,
5189 pub mean_wind_drift_at_target_m: f64,
5192 pub std_wind_drift_at_target_m: f64,
5195}
5196
5197pub fn run_monte_carlo_adaptive_seeded(
5275 base_inputs: &BallisticInputs,
5276 base_wind: &WindConditions,
5277 params: &MonteCarloParams,
5278 convergence: &McConvergence,
5279 hit_radius_m: f64,
5280 seed: u64,
5281) -> Result<AdaptiveMcReportV1, String> {
5282 run_monte_carlo_adaptive_seeded_with_station_presence(
5283 base_inputs,
5284 base_wind,
5285 params,
5286 convergence,
5287 hit_radius_m,
5288 seed,
5289 StationAtmospherePresence::NEITHER,
5290 )
5291}
5292
5293pub fn run_monte_carlo_adaptive_seeded_with_station_presence(
5298 base_inputs: &BallisticInputs,
5299 base_wind: &WindConditions,
5300 params: &MonteCarloParams,
5301 convergence: &McConvergence,
5302 hit_radius_m: f64,
5303 seed: u64,
5304 station_presence: StationAtmospherePresence,
5305) -> Result<AdaptiveMcReportV1, String> {
5306 use rand::{rngs::StdRng, SeedableRng};
5307
5308 convergence.validate()?;
5309
5310 let sampler = MonteCarloTrialSampler::new(
5313 base_inputs.clone(),
5314 base_wind,
5315 params,
5316 0.0,
5317 station_presence,
5318 )
5319 .map_err(|e| e.to_string())?;
5320
5321 let mut rng = StdRng::seed_from_u64(seed);
5322 let mut hits_cs = BernoulliConfidenceSequence::new(convergence.level);
5323 let mut impact_velocity = Welford::new();
5324 let mut drop_at_target = Welford::new();
5325 let mut drift_at_target = Welford::new();
5326
5327 let mut attempts: u64 = 0;
5328 let mut stop_reason = McStopReason::MaxSamplesReached;
5329
5330 while attempts < convergence.max_samples {
5331 let batch = convergence
5334 .batch_size
5335 .min(convergence.max_samples - attempts);
5336 let mut batch_hits: u64 = 0;
5337 let mut batch_trials: u64 = 0;
5338
5339 for _ in 0..batch {
5340 attempts += 1;
5341 let Some(outcome) = sampler.sample_one_trial(&mut rng) else {
5342 continue; };
5344 batch_trials += 1;
5345 if MonteCarloResults::position_is_hit(&outcome.impact_position, hit_radius_m) {
5346 batch_hits += 1;
5347 }
5348 if MonteCarloResults::position_reached_target(&outcome.impact_position) {
5352 impact_velocity.push(outcome.impact_velocity);
5353 drop_at_target.push(outcome.impact_position.y);
5354 drift_at_target.push(outcome.impact_position.z);
5355 }
5356 }
5357
5358 hits_cs.update_batch(batch_hits, batch_trials);
5359
5360 if hits_cs.trials() >= convergence.min_samples
5361 && hits_cs.half_width() <= convergence.target_half_width
5362 {
5363 stop_reason = McStopReason::TargetHalfWidthMet;
5364 break;
5365 }
5366 }
5367
5368 let samples = hits_cs.trials();
5369 if samples == 0 {
5370 return Err("No successful simulations".to_string());
5371 }
5372 let (ci_low, ci_high) = hits_cs.bounds();
5373
5374 Ok(AdaptiveMcReportV1 {
5375 schema_version: MC_ADAPTIVE_SCHEMA_VERSION_V1,
5376 method: MC_ADAPTIVE_METHOD_V1.to_string(),
5377 assumptions: MC_ADAPTIVE_ASSUMPTIONS_V1
5378 .iter()
5379 .map(|s| s.to_string())
5380 .collect(),
5381 confidence_percent: convergence.level.as_percent(),
5382 hit_probability: hits_cs.successes() as f64 / samples as f64,
5383 ci_low,
5384 ci_high,
5385 samples,
5386 attempts,
5387 arrivals: drop_at_target.count(),
5391 stop_reason,
5392 hit_radius_m,
5393 target_distance_m: sampler.target_distance,
5394 mean_impact_velocity_mps: impact_velocity.mean(),
5395 std_impact_velocity_mps: impact_velocity.sample_std(),
5396 mean_drop_at_target_m: drop_at_target.mean(),
5397 std_drop_at_target_m: drop_at_target.sample_std(),
5398 mean_wind_drift_at_target_m: drift_at_target.mean(),
5399 std_wind_drift_at_target_m: drift_at_target.sample_std(),
5400 })
5401}
5402
5403pub fn calculate_zero_angle(
5405 inputs: BallisticInputs,
5406 target_distance: f64,
5407 target_height: f64,
5408) -> Result<f64, BallisticsError> {
5409 calculate_zero_angle_with_conditions(
5410 inputs,
5411 target_distance,
5412 target_height,
5413 WindConditions::default(),
5414 AtmosphericConditions::default(),
5415 )
5416}
5417
5418pub fn calculate_zero_angle_with_conditions(
5423 inputs: BallisticInputs,
5424 target_distance: f64,
5425 target_height: f64,
5426 wind: WindConditions,
5427 atmosphere: AtmosphericConditions,
5428) -> Result<f64, BallisticsError> {
5429 calculate_zero_angle_with_station_presence(
5430 inputs,
5431 target_distance,
5432 target_height,
5433 wind,
5434 atmosphere,
5435 StationAtmospherePresence::NEITHER,
5436 )
5437}
5438
5439pub fn calculate_zero_angle_with_station_presence(
5444 inputs: BallisticInputs,
5445 target_distance: f64,
5446 target_height: f64,
5447 wind: WindConditions,
5448 atmosphere: AtmosphericConditions,
5449 station_presence: StationAtmospherePresence,
5450) -> Result<f64, BallisticsError> {
5451 let mut solver =
5452 TrajectorySolver::new_with_station_presence(inputs, wind, atmosphere, station_presence);
5453 solver.calculate_and_set_zero_angle(target_distance, target_height, ZeroTargetFrame::SightLine)
5454}
5455
5456pub fn calculate_zero_angle_with_resolved_conditions(
5462 inputs: BallisticInputs,
5463 target_distance: f64,
5464 target_height: f64,
5465 wind: WindConditions,
5466 atmosphere: AtmosphericConditions,
5467) -> Result<f64, BallisticsError> {
5468 let mut solver =
5469 TrajectorySolver::new_with_resolved_station_atmosphere(inputs, wind, atmosphere);
5470 solver.calculate_and_set_zero_angle(target_distance, target_height, ZeroTargetFrame::SightLine)
5471}
5472
5473pub const ZERO_RANGE_FROM_ANGLE_MAX_RANGE_M: f64 = 2000.0;
5481
5482pub fn calculate_zero_range_from_angle_with_conditions(
5500 inputs: BallisticInputs,
5501 zero_angle_rad: f64,
5502 target_height: f64,
5503 wind: WindConditions,
5504 atmosphere: AtmosphericConditions,
5505) -> Result<ZeroCrossings, BallisticsError> {
5506 calculate_zero_range_from_angle_with_station_presence(
5507 inputs,
5508 zero_angle_rad,
5509 target_height,
5510 wind,
5511 atmosphere,
5512 StationAtmospherePresence::NEITHER,
5513 )
5514}
5515
5516pub fn calculate_zero_range_from_angle_with_station_presence(
5521 inputs: BallisticInputs,
5522 zero_angle_rad: f64,
5523 target_height: f64,
5524 wind: WindConditions,
5525 atmosphere: AtmosphericConditions,
5526 station_presence: StationAtmospherePresence,
5527) -> Result<ZeroCrossings, BallisticsError> {
5528 let mut solver =
5529 TrajectorySolver::new_with_station_presence(inputs, wind, atmosphere, station_presence);
5530 solver.set_max_range(ZERO_RANGE_FROM_ANGLE_MAX_RANGE_M);
5531 solver.find_zero_range(zero_angle_rad, target_height, ZeroTargetFrame::SightLine)
5532}
5533
5534pub fn calculate_zero_range_from_angle_with_resolved_conditions(
5540 inputs: BallisticInputs,
5541 zero_angle_rad: f64,
5542 target_height: f64,
5543 wind: WindConditions,
5544 atmosphere: AtmosphericConditions,
5545) -> Result<ZeroCrossings, BallisticsError> {
5546 let mut solver =
5547 TrajectorySolver::new_with_resolved_station_atmosphere(inputs, wind, atmosphere);
5548 solver.set_max_range(ZERO_RANGE_FROM_ANGLE_MAX_RANGE_M);
5549 solver.find_zero_range(zero_angle_rad, target_height, ZeroTargetFrame::SightLine)
5550}
5551
5552#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5554pub enum BcFitMode {
5555 Drop,
5557 Velocity,
5560}
5561
5562#[derive(Debug, Clone, Copy)]
5564pub struct BcEstimate {
5565 pub bc: f64,
5567 pub rms_error: f64,
5569 pub drag_model: DragModel,
5571 pub mode: BcFitMode,
5573 pub at_bound: bool,
5577}
5578
5579fn fit_value_at(
5587 points: &[TrajectoryPoint],
5588 target_dist: f64,
5589 mode: BcFitMode,
5590 drop_offset: f64,
5591) -> Option<f64> {
5592 let val = |p: &TrajectoryPoint| match mode {
5593 BcFitMode::Drop => drop_offset - p.position.y,
5594 BcFitMode::Velocity => p.velocity_magnitude,
5595 };
5596 for i in 0..points.len() {
5597 if points[i].position.x >= target_dist {
5598 if i == 0 {
5599 return Some(val(&points[0]));
5600 }
5601 let p1 = &points[i - 1];
5602 let p2 = &points[i];
5603 let dx = p2.position.x - p1.position.x;
5604 if dx.abs() < 1e-9 {
5605 return Some(val(p2));
5606 }
5607 let t = (target_dist - p1.position.x) / dx;
5608 return Some(val(p1) + t * (val(p2) - val(p1)));
5609 }
5610 }
5611 None
5612}
5613
5614fn fit_residual_sse(
5615 trajectory: &[TrajectoryPoint],
5616 observations: &[(f64, f64)],
5617 mode: BcFitMode,
5618 drop_offset: f64,
5619) -> Option<f64> {
5620 if observations.is_empty() {
5621 return None;
5622 }
5623 let mut total = 0.0;
5624 for (target_dist, target_val) in observations {
5625 let value = fit_value_at(trajectory, *target_dist, mode, drop_offset)?;
5628 let error = value - target_val;
5629 total += error * error;
5630 }
5631 Some(total)
5632}
5633
5634#[allow(clippy::too_many_arguments)] pub fn estimate_bc_fit(
5655 velocity: f64,
5656 mass: f64,
5657 diameter: f64,
5658 points: &[(f64, f64)],
5659 drag_model: DragModel,
5660 mode: BcFitMode,
5661 atmosphere: AtmosphericConditions,
5662 zero_range: Option<f64>,
5663 sight_height: f64,
5664) -> Result<BcEstimate, BallisticsError> {
5665 estimate_bc_fit_with_station_presence(
5666 velocity,
5667 mass,
5668 diameter,
5669 points,
5670 drag_model,
5671 mode,
5672 atmosphere,
5673 zero_range,
5674 sight_height,
5675 StationAtmospherePresence::NEITHER,
5676 )
5677}
5678
5679#[allow(clippy::too_many_arguments)] pub fn estimate_bc_fit_with_station_presence(
5687 velocity: f64,
5688 mass: f64,
5689 diameter: f64,
5690 points: &[(f64, f64)],
5691 drag_model: DragModel,
5692 mode: BcFitMode,
5693 atmosphere: AtmosphericConditions,
5694 zero_range: Option<f64>,
5695 sight_height: f64,
5696 station_presence: StationAtmospherePresence,
5697) -> Result<BcEstimate, BallisticsError> {
5698 if points.is_empty() {
5699 return Err(BallisticsError::from(
5700 "No data points provided for BC estimation.".to_string(),
5701 ));
5702 }
5703 TrajectorySolver::new_with_station_presence(
5708 BallisticInputs::default(),
5709 WindConditions::default(),
5710 atmosphere.clone(),
5711 station_presence,
5712 )
5713 .station_air()?;
5714 let max_dist = points.iter().map(|(d, _)| *d).fold(0.0_f64, f64::max);
5715 let drop_offset = if zero_range.is_some() {
5718 sight_height
5719 } else {
5720 0.0
5721 };
5722
5723 let sse = |bc_value: f64| -> Result<Option<f64>, BallisticsError> {
5725 let mut inputs = BallisticInputs {
5726 muzzle_velocity: velocity,
5727 bc_value,
5728 bc_type: drag_model,
5729 bullet_mass: mass,
5730 bullet_diameter: diameter,
5731 sight_height,
5732 ..Default::default()
5733 };
5734 if let Some(zr) = zero_range {
5737 let za = calculate_zero_angle_with_station_presence(
5743 inputs.clone(),
5744 zr,
5745 sight_height,
5746 WindConditions::default(),
5747 atmosphere.clone(),
5748 station_presence,
5749 )?;
5750 inputs.muzzle_angle = za;
5751 }
5752 let mut solver = TrajectorySolver::new_with_station_presence(
5753 inputs,
5754 WindConditions::default(),
5755 atmosphere.clone(),
5756 station_presence,
5757 );
5758 solver.set_max_range(max_dist * 1.5);
5759 let result = solver.solve()?;
5760 Ok(fit_residual_sse(&result.points, points, mode, drop_offset))
5761 };
5762
5763 let (bc_min, bc_max) = match drag_model {
5767 DragModel::G7 => (0.05, 0.70),
5768 _ => (0.10, 1.20),
5769 };
5770
5771 let mut best_bc = f64::NAN;
5773 let mut best_sse = f64::MAX;
5774 let mut air_refusal = None;
5775 let mut bc = bc_min;
5776 while bc <= bc_max + 1e-9 {
5777 match sse(bc) {
5778 Ok(Some(s)) if s < best_sse => {
5779 best_sse = s;
5780 best_bc = bc;
5781 }
5782 Err(error) if error.atmosphere_error().is_some() => {
5783 air_refusal.get_or_insert(error);
5784 }
5785 _ => {}
5786 }
5787 bc += 0.01;
5788 }
5789 if !best_bc.is_finite() {
5790 if let Some(error) = air_refusal {
5793 return Err(error);
5794 }
5795 return Err(BallisticsError::from(
5796 "Unable to estimate BC from provided data. Check that the values and units are correct."
5797 .to_string(),
5798 ));
5799 }
5800
5801 let lo = (best_bc - 0.01).max(bc_min);
5803 let hi = (best_bc + 0.01).min(bc_max);
5804 let mut bc = lo;
5805 while bc <= hi + 1e-9 {
5806 if let Ok(Some(s)) = sse(bc) {
5807 if s < best_sse {
5808 best_sse = s;
5809 best_bc = bc;
5810 }
5811 }
5812 bc += 0.001;
5813 }
5814
5815 let at_bound = best_bc <= bc_min + 0.011 || best_bc >= bc_max - 0.011;
5818 let rms_error = (best_sse / points.len() as f64).sqrt();
5821 Ok(BcEstimate {
5822 bc: best_bc,
5823 rms_error,
5824 drag_model,
5825 mode,
5826 at_bound,
5827 })
5828}
5829
5830pub fn estimate_bc_from_trajectory(
5833 velocity: f64,
5834 mass: f64,
5835 diameter: f64,
5836 points: &[(f64, f64)], ) -> Result<f64, BallisticsError> {
5838 estimate_bc_fit(
5839 velocity,
5840 mass,
5841 diameter,
5842 points,
5843 DragModel::G1,
5844 BcFitMode::Drop,
5845 AtmosphericConditions::default(),
5846 None,
5847 0.05,
5848 )
5849 .map(|e| e.bc)
5850}
5851
5852use rand;
5854use rand_distr;
5855
5856#[cfg(test)]
5857mod mba737_powder_resolution_tests {
5858 use super::*;
5859
5860 #[test]
5861 fn linear_model_cold_powder_subtracts() {
5862 let v = resolve_powder_adjusted_velocity(823.0, 11.1, true, 0.5486, 21.1, None, None);
5864 assert!((v - (823.0 + 0.5486 * (11.1 - 21.1))).abs() < 1e-12);
5865 assert!(v < 823.0);
5866 }
5867
5868 #[test]
5869 fn linear_model_hot_powder_adds() {
5870 let v = resolve_powder_adjusted_velocity(823.0, 31.1, true, 0.5486, 21.1, None, None);
5871 assert!((v - (823.0 + 0.5486 * 10.0)).abs() < 1e-12);
5872 }
5873
5874 #[test]
5875 fn disabled_flag_is_passthrough() {
5876 let v = resolve_powder_adjusted_velocity(823.0, 40.0, false, 0.5486, 21.1, None, None);
5877 assert_eq!(v, 823.0);
5878 }
5879
5880 #[test]
5881 fn curve_overrides_linear_and_interpolates_at_powder_temp() {
5882 let curve = [(4.4, 798.6), (21.1, 823.0), (37.8, 841.2)];
5883 let v = resolve_powder_adjusted_velocity(
5885 823.0,
5886 30.0,
5887 true,
5888 99.0,
5889 21.1,
5890 Some(&curve),
5891 Some(4.4),
5892 );
5893 assert!((v - 798.6).abs() < 1e-9);
5894 }
5895
5896 #[test]
5897 fn curve_falls_back_to_ambient_and_clamps() {
5898 let curve = [(4.4, 798.6), (37.8, 841.2)];
5899 let v = resolve_powder_adjusted_velocity(823.0, -40.0, true, 1.0, 21.1, Some(&curve), None);
5901 assert!((v - 798.6).abs() < 1e-9);
5902 let v_hot =
5903 resolve_powder_adjusted_velocity(823.0, 60.0, true, 1.0, 21.1, Some(&curve), None);
5904 assert!((v_hot - 841.2).abs() < 1e-9);
5905 }
5906
5907 #[test]
5908 fn empty_curve_suppresses_linear_fallback() {
5909 let v = resolve_powder_adjusted_velocity(823.0, 40.0, true, 0.5486, 21.1, Some(&[]), None);
5911 assert_eq!(v, 823.0);
5912 }
5913
5914 #[test]
5915 fn sweep_huge_range_errors_instead_of_overflowing() {
5916 assert!(parse_powder_sweep("0:1e20:1").is_err());
5919 assert!(parse_powder_sweep("0:1e308:1e-3").is_err());
5920 }
5921
5922 #[test]
5923 fn sweep_fractional_step_keeps_end_row() {
5924 let rows = parse_powder_sweep("0:0.3:0.1").unwrap();
5926 assert_eq!(rows.len(), 4);
5927 assert!((rows[3] - 0.3).abs() < 1e-9);
5928 }
5929
5930 #[test]
5931 fn solver_and_helper_agree_on_linear_model() {
5932 let inputs = BallisticInputs {
5934 use_powder_sensitivity: true,
5935 powder_temp_sensitivity: 0.5486,
5936 powder_temp: 21.1,
5937 temperature: 4.4,
5938 ..Default::default()
5939 };
5940 let expected = resolve_powder_adjusted_velocity(
5941 inputs.muzzle_velocity,
5942 inputs.temperature,
5943 true,
5944 0.5486,
5945 21.1,
5946 None,
5947 None,
5948 );
5949 let solver = TrajectorySolver::new(
5950 inputs,
5951 WindConditions::default(),
5952 AtmosphericConditions::default(),
5953 );
5954 assert!((solver.inputs.muzzle_velocity - expected).abs() < 1e-12);
5955 }
5956}
5957
5958#[cfg(test)]
5959mod mba1302_solver_seam_tests {
5960 use super::*;
5961 use crate::wind::WindSegment;
5962
5963 #[test]
5964 fn authoritative_station_atmosphere_preserves_explicit_standard_values_at_altitude() {
5965 let atmosphere = AtmosphericConditions {
5966 temperature: 15.0,
5967 pressure: 1013.25,
5968 humidity: 50.0,
5969 altitude: 2_000.0,
5970 };
5971 let legacy = TrajectorySolver::new(
5972 BallisticInputs::default(),
5973 WindConditions::default(),
5974 atmosphere.clone(),
5975 );
5976 let authoritative = TrajectorySolver::new_with_resolved_station_atmosphere(
5977 BallisticInputs::default(),
5978 WindConditions::default(),
5979 atmosphere,
5980 );
5981
5982 let (legacy_density, _, legacy_temp_c, legacy_pressure_hpa) = legacy.resolved_atmosphere();
5983 let (authoritative_density, _, authoritative_temp_c, authoritative_pressure_hpa) =
5984 authoritative.resolved_atmosphere();
5985 let (icao_temp_k, icao_pressure_pa) =
5986 crate::atmosphere::calculate_icao_standard_atmosphere(2_000.0);
5987 let (expected_authoritative_density, _) =
5988 crate::atmosphere::calculate_atmosphere(2_000.0, Some(15.0), Some(1013.25), 50.0);
5989
5990 assert!((legacy_temp_c - (icao_temp_k - 273.15)).abs() < 1e-12);
5991 assert!((legacy_pressure_hpa - icao_pressure_pa / 100.0).abs() < 1e-12);
5992 assert_eq!(authoritative_temp_c.to_bits(), 15.0_f64.to_bits());
5993 assert_eq!(authoritative_pressure_hpa.to_bits(), 1013.25_f64.to_bits());
5994 assert_eq!(
5995 authoritative_density.to_bits(),
5996 expected_authoritative_density.to_bits()
5997 );
5998 assert!(
5999 (authoritative_density - legacy_density).abs() > 0.1,
6000 "explicit standard values at altitude must differ from ICAO-at-altitude: explicit={authoritative_density}, ICAO={legacy_density}"
6001 );
6002 }
6003
6004 #[test]
6013 fn precomputed_absolute_resolution_via_authoritative_matches_legacy_new() {
6014 for (temperature, pressure, altitude) in [
6015 (15.0, 1013.25, 0.0), (15.0, 1013.25, 2000.0), (-5.0, 850.0, 2000.0), (22.0, 950.0, 500.0),
6019 ] {
6020 let atmosphere = AtmosphericConditions {
6021 temperature,
6022 pressure,
6023 humidity: 50.0,
6024 altitude,
6025 };
6026 let legacy = TrajectorySolver::new(
6027 BallisticInputs::default(),
6028 WindConditions::default(),
6029 atmosphere.clone(),
6030 );
6031
6032 let (resolved_temp_c, resolved_pressure_hpa) =
6033 crate::atmosphere::resolve_station_conditions_with_pressure_mode(
6034 temperature,
6035 pressure,
6036 altitude,
6037 crate::atmosphere::PressureReferenceMode::Absolute,
6038 );
6039 let precomputed_atmosphere = AtmosphericConditions {
6040 temperature: resolved_temp_c,
6041 pressure: resolved_pressure_hpa,
6042 humidity: 50.0,
6043 altitude,
6044 };
6045 let precomputed = TrajectorySolver::new_with_resolved_station_atmosphere(
6046 BallisticInputs::default(),
6047 WindConditions::default(),
6048 precomputed_atmosphere,
6049 );
6050
6051 let (legacy_density, legacy_sos, legacy_temp_c, legacy_pressure_hpa) =
6052 legacy.resolved_atmosphere();
6053 let (pre_density, pre_sos, pre_temp_c, pre_pressure_hpa) =
6054 precomputed.resolved_atmosphere();
6055
6056 assert_eq!(
6057 legacy_temp_c.to_bits(),
6058 pre_temp_c.to_bits(),
6059 "temperature=({temperature}, {pressure}, {altitude})"
6060 );
6061 assert_eq!(
6062 legacy_pressure_hpa.to_bits(),
6063 pre_pressure_hpa.to_bits(),
6064 "pressure=({temperature}, {pressure}, {altitude})"
6065 );
6066 assert_eq!(legacy_density.to_bits(), pre_density.to_bits());
6067 assert_eq!(legacy_sos.to_bits(), pre_sos.to_bits());
6068 }
6069
6070 for (altitude, pinned) in [
6075 (
6076 150.0,
6077 [
6079 f64::from_bits(0x3ff344d9d9fd1ea1),
6080 f64::from_bits(0x40754269eee53ba5),
6081 f64::from_bits(0x402c0ccfd0c49b20),
6082 f64::from_bits(0x408f1ae13f434f1f),
6083 ],
6084 ),
6085 (
6086 1500.0,
6087 [
6089 f64::from_bits(0x3ff0e75c08c70bc0),
6090 f64::from_bits(0x4074ec457a661d16),
6091 f64::from_bits(0x4015025af8d136c0),
6092 f64::from_bits(0x408a6cc6358cefbd),
6093 ],
6094 ),
6095 ] {
6096 let atmosphere = AtmosphericConditions {
6097 temperature: 15.05,
6098 pressure: 1013.0,
6099 humidity: 50.0,
6100 altitude,
6101 };
6102 let bits = |r: (f64, f64, f64, f64)| [r.0, r.1, r.2, r.3].map(f64::to_bits);
6103 let pinned = pinned.map(f64::to_bits);
6104 let legacy = TrajectorySolver::new(
6105 BallisticInputs::default(),
6106 WindConditions::default(),
6107 atmosphere.clone(),
6108 );
6109 assert_eq!(
6110 bits(legacy.resolved_atmosphere()),
6111 pinned,
6112 "new at {altitude} m"
6113 );
6114 let neither = TrajectorySolver::new_with_station_presence(
6115 BallisticInputs::default(),
6116 WindConditions::default(),
6117 atmosphere.clone(),
6118 StationAtmospherePresence::NEITHER,
6119 );
6120 assert_eq!(
6121 bits(neither.resolved_atmosphere()),
6122 pinned,
6123 "NEITHER at {altitude} m"
6124 );
6125
6126 let both = TrajectorySolver::new_with_station_presence(
6127 BallisticInputs::default(),
6128 WindConditions::default(),
6129 atmosphere.clone(),
6130 StationAtmospherePresence::BOTH,
6131 );
6132 let authoritative = TrajectorySolver::new_with_resolved_station_atmosphere(
6133 BallisticInputs::default(),
6134 WindConditions::default(),
6135 atmosphere,
6136 );
6137 let both_resolved = both.resolved_atmosphere();
6138 assert_eq!(
6139 bits(both_resolved),
6140 bits(authoritative.resolved_atmosphere())
6141 );
6142 assert_eq!(both_resolved.2.to_bits(), 15.05_f64.to_bits());
6143 assert_eq!(both_resolved.3.to_bits(), 1013.0_f64.to_bits());
6144 assert_ne!(
6145 bits(both_resolved),
6146 pinned,
6147 "BOTH must not swap at {altitude} m"
6148 );
6149 }
6150 }
6151
6152 fn configured_euler_zero(vertical_wind_mps: f64, time_step_s: f64) -> TrajectorySolver {
6153 let inputs = BallisticInputs {
6154 muzzle_velocity: 800.0,
6155 bc_value: 0.5,
6156 bc_type: DragModel::G7,
6157 bullet_mass: 0.0109,
6158 bullet_diameter: 0.00782,
6159 bullet_length: 0.0309,
6160 sight_height: 0.05,
6161 ground_threshold: -100.0,
6162 use_rk4: false,
6163 use_adaptive_rk45: false,
6164 ..BallisticInputs::default()
6165 };
6166 let mut solver = TrajectorySolver::new_with_resolved_station_atmosphere(
6167 inputs,
6168 WindConditions::default(),
6169 AtmosphericConditions::default(),
6170 );
6171 solver.set_max_range(300.0);
6172 solver.set_time_step(time_step_s);
6173 if vertical_wind_mps != 0.0 {
6174 solver.set_wind_segments(vec![WindSegment {
6175 speed_kmh: 0.0,
6176 angle_deg: 0.0,
6177 until_m: 400.0,
6178 vertical_mps: vertical_wind_mps,
6179 }]);
6180 }
6181 solver
6182 }
6183
6184 #[test]
6185 fn inclined_shot_zeroes_like_a_level_rifle() {
6186 const ZERO_DISTANCE_M: f64 = 91.44; const SIGHT_HEIGHT_M: f64 = 0.0381; let inputs = BallisticInputs {
6195 bc_value: 0.5,
6196 bullet_mass: 150.0 * 0.06479891 / 1000.0,
6197 muzzle_velocity: 2700.0 * 0.3048,
6198 sight_height: SIGHT_HEIGHT_M,
6199 ..Default::default()
6200 };
6201
6202 let mut level = inputs.clone();
6203 level.shooting_angle = 0.0;
6204 let level_angle = TrajectorySolver::new(level, Default::default(), Default::default())
6205 .find_zero_angle(ZERO_DISTANCE_M, SIGHT_HEIGHT_M, ZeroTargetFrame::SightLine)
6206 .expect("level zero must solve");
6207
6208 let mut inclined = inputs;
6209 inclined.shooting_angle = 5.71_f64.to_radians();
6210 let inclined_angle =
6211 TrajectorySolver::new(inclined, Default::default(), Default::default())
6212 .find_zero_angle(ZERO_DISTANCE_M, SIGHT_HEIGHT_M, ZeroTargetFrame::SightLine)
6213 .expect("MBA-1412: a 5.71 deg incline at a 100 yd zero must be solvable");
6214
6215 assert!(
6216 (inclined_angle - level_angle).abs() < 1e-9,
6217 "zeroing is level-rifle sight geometry; incline must not move the solved zero: \
6218 level={level_angle}, inclined={inclined_angle}"
6219 );
6220 }
6221
6222 #[test]
6223 fn target_below_the_level_bore_impact_zeroes_with_a_downward_bore() {
6224 const TARGET_DISTANCE_M: f64 = 457.2; let inputs = BallisticInputs {
6229 bc_value: 0.462,
6230 bullet_mass: 168.0 * 0.06479891 / 1000.0,
6231 bullet_diameter: 0.308 * 0.0254,
6232 muzzle_velocity: 2700.0 * 0.3048,
6233 sight_height: 0.05,
6234 ..Default::default()
6235 };
6236 let solver = TrajectorySolver::new(inputs, Default::default(), Default::default());
6237 let level_impact_m = solver
6238 .zero_trial_height_at(0.0, TARGET_DISTANCE_M, ZeroTargetFrame::SightLine)
6239 .expect("level trial")
6240 .expect("level trial reaches the target distance");
6241
6242 for depth_m in [0.005, 1.0, 4.572, 91.44] {
6245 let target_m = level_impact_m - depth_m;
6246 let angle = solver
6247 .find_zero_angle(TARGET_DISTANCE_M, target_m, ZeroTargetFrame::SightLine)
6248 .unwrap_or_else(|e| panic!("target {depth_m} m below the level impact: {e}"));
6249 assert!(
6250 angle < 0.0,
6251 "a target below the level impact needs a downward bore: depth={depth_m} m angle={angle}"
6252 );
6253 let hit_m = solver
6254 .zero_trial_height_at(angle, TARGET_DISTANCE_M, ZeroTargetFrame::SightLine)
6255 .expect("verify trial")
6256 .expect("zeroed trial reaches the target distance");
6257 assert!(
6258 (hit_m - target_m).abs() < 0.0001,
6259 "zero missed a target {depth_m} m below the level impact: hit={hit_m} target={target_m}"
6260 );
6261 }
6262 }
6263
6264 #[test]
6265 fn configured_zero_keeps_segments_method_and_time_step_then_sets_base_angle() {
6266 const TARGET_DISTANCE_M: f64 = 150.0;
6267 const TARGET_HEIGHT_M: f64 = 0.05;
6268
6269 let mut segmented = configured_euler_zero(-10.0, 0.02);
6272 let coarse_height = segmented
6273 .zero_trial_height_at(0.0, TARGET_DISTANCE_M, ZeroTargetFrame::SightLine)
6274 .expect("coarse configured trial")
6275 .expect("coarse trial reaches target");
6276 let mut fine = segmented.clone();
6277 fine.set_time_step(0.001);
6278 let fine_height = fine
6279 .zero_trial_height_at(0.0, TARGET_DISTANCE_M, ZeroTargetFrame::SightLine)
6280 .expect("fine configured trial")
6281 .expect("fine trial reaches target");
6282 assert!(
6283 (coarse_height - fine_height).abs() > 1e-5,
6284 "configured Euler step must affect zero trials: coarse={coarse_height}, fine={fine_height}"
6285 );
6286
6287 let segmented_angle = segmented
6288 .calculate_and_set_zero_angle(
6289 TARGET_DISTANCE_M,
6290 TARGET_HEIGHT_M,
6291 ZeroTargetFrame::SightLine,
6292 )
6293 .expect("segmented zero");
6294 assert_eq!(
6295 segmented.inputs.muzzle_angle.to_bits(),
6296 segmented_angle.to_bits(),
6297 "successful zero must install its angle on the configured solver"
6298 );
6299 assert_eq!(segmented.time_step.to_bits(), 0.02_f64.to_bits());
6300 assert_eq!(segmented.max_range.to_bits(), 300.0_f64.to_bits());
6301 assert!(segmented.wind_sock.is_some());
6302 assert_eq!(segmented.station_presence, StationAtmospherePresence::BOTH);
6303 let zero_height = segmented
6304 .zero_trial_height_at(
6305 segmented_angle,
6306 TARGET_DISTANCE_M,
6307 ZeroTargetFrame::SightLine,
6308 )
6309 .expect("verify segmented zero")
6310 .expect("zeroed trial reaches target");
6311 assert!(
6312 (zero_height - TARGET_HEIGHT_M).abs() < 0.0001,
6313 "configured zero missed target: height={zero_height}"
6314 );
6315
6316 let mut calm = configured_euler_zero(0.0, 0.02);
6317 let calm_angle = calm
6318 .calculate_and_set_zero_angle(
6319 TARGET_DISTANCE_M,
6320 TARGET_HEIGHT_M,
6321 ZeroTargetFrame::SightLine,
6322 )
6323 .expect("calm zero");
6324 assert!(
6325 (segmented_angle - calm_angle).abs() > 1e-5,
6326 "segmented vertical wind must participate in zero trials: segmented={segmented_angle}, calm={calm_angle}"
6327 );
6328 }
6329}
6330
6331#[cfg(test)]
6332mod uniform_gravity_tests {
6333 use super::*;
6334
6335 #[test]
6336 fn uniform_gravity_is_per_solver_and_survives_cloning() {
6337 for (use_rk4, use_adaptive_rk45) in [(false, false), (true, false), (true, true)] {
6338 let inputs = BallisticInputs {
6340 bullet_mass: 0.0459,
6341 bullet_diameter: 0.0427,
6342 bullet_length: 0.0427,
6343 muzzle_velocity: 10.0,
6344 muzzle_height: 10.0,
6345 muzzle_angle: 0.0,
6346 bc_type: DragModel::GS,
6347 custom_drag_table: Some(crate::drag::DragTable::new(
6348 vec![0.0, 5.0],
6349 vec![1e-20, 1e-20],
6350 )),
6351 use_rk4,
6352 use_adaptive_rk45,
6353 ..BallisticInputs::default()
6354 };
6355 let public = TrajectorySolver::new(
6356 inputs.clone(),
6357 WindConditions::default(),
6358 AtmosphericConditions::default(),
6359 );
6360 for magnitude in [0.0, 1.62, 9.80665, 20.0] {
6361 let mut solver = TrajectorySolver::new_with_station_presence_and_gravity(
6362 inputs.clone(),
6363 WindConditions::default(),
6364 AtmosphericConditions::default(),
6365 StationAtmospherePresence::NEITHER,
6366 Gravity::new(magnitude).unwrap(),
6367 )
6368 .clone();
6369 solver.set_max_range(10.0);
6370 let result = solver.solve().unwrap();
6371 let end = result.points.last().unwrap();
6372 assert!((end.time - 1.0).abs() < 1e-8);
6373 let step = if use_adaptive_rk45 {
6376 RK45_MAX_DT
6377 } else {
6378 solver.time_step
6379 };
6380 let tolerance = magnitude * step * step / 8.0
6381 + if use_rk4 { 0.0 } else { magnitude * step / 2.0 }
6382 + 1e-8;
6383 assert!(
6384 (end.position.y - (10.0 - 0.5 * magnitude)).abs() < tolerance,
6385 "g={magnitude}, rk4={use_rk4}, adaptive={use_adaptive_rk45}, y={}, time={}",
6386 end.position.y,
6387 end.time
6388 );
6389 assert!(
6390 (solver.speed_budget(1.0) - solver.speed_budget(0.0) - magnitude).abs() < 1e-12
6391 );
6392 assert_eq!(public.gravity, Gravity::EARTH);
6393 if magnitude == 9.80665 {
6394 let mut earth = public.clone();
6395 earth.set_max_range(10.0);
6396 let reference = earth.solve().unwrap();
6397 assert_eq!(result.points.len(), reference.points.len());
6398 for (actual, expected) in result.points.iter().zip(&reference.points) {
6399 assert_eq!(actual.time.to_bits(), expected.time.to_bits());
6400 assert_eq!(actual.position, expected.position);
6401 assert_eq!(
6402 actual.velocity_magnitude.to_bits(),
6403 expected.velocity_magnitude.to_bits()
6404 );
6405 }
6406 }
6407 }
6408 }
6409 }
6410
6411 fn match_308_inputs() -> BallisticInputs {
6412 BallisticInputs {
6413 muzzle_velocity: 800.0,
6414 bullet_mass: 168.0 * crate::constants::GRAINS_TO_KG,
6415 bullet_diameter: 0.308 * 0.0254,
6416 bullet_length: 1.215 * 0.0254,
6417 twist_rate: 10.0,
6418 ..BallisticInputs::default()
6419 }
6420 }
6421
6422 fn station_1000_m() -> AtmosphericConditions {
6423 AtmosphericConditions {
6424 temperature: 15.0,
6425 pressure: 1013.25,
6426 humidity: 0.0,
6427 altitude: 1000.0,
6428 }
6429 }
6430
6431 fn aerodynamic_acceleration_with_gravity(
6435 inputs: &BallisticInputs,
6436 gravity: Gravity,
6437 position: Vector3<f64>,
6438 velocity: Vector3<f64>,
6439 ) -> Vector3<f64> {
6440 let solver = TrajectorySolver::new_with_station_presence_and_gravity(
6441 inputs.clone(),
6442 WindConditions::default(),
6443 station_1000_m(),
6444 StationAtmospherePresence::BOTH,
6445 gravity,
6446 );
6447 let station = solver.station_air().unwrap();
6448 solver.calculate_acceleration(&position, &velocity, &Vector3::zeros(), &station)
6449 - solver.gravity_acceleration()
6450 }
6451
6452 #[test]
6453 fn local_atmosphere_uses_the_simulation_gravity() {
6454 let inputs = match_308_inputs(); let velocity = Vector3::new(600.0, 0.0, 0.0);
6456 let low_gravity = Gravity::new(3.71).unwrap();
6457 let aerodynamic = |position, gravity| {
6458 aerodynamic_acceleration_with_gravity(&inputs, gravity, position, velocity)
6459 };
6460
6461 let earth = aerodynamic(Vector3::zeros(), Gravity::EARTH);
6464 let low = aerodynamic(Vector3::zeros(), low_gravity);
6465 assert!(
6466 (earth - low).norm() < 1e-12,
6467 "station-altitude drag must not depend on gravity: earth={earth:?}, low={low:?}"
6468 );
6469
6470 let aloft = Vector3::new(0.0, 2_000.0, 0.0);
6473 let earth = aerodynamic(aloft, Gravity::EARTH);
6474 let low = aerodynamic(aloft, low_gravity);
6475 let ratio = low.x / earth.x;
6476 assert!(earth.x < 0.0, "drag must oppose flight: {earth:?}");
6477 assert!(
6478 (ratio - 1.162_702).abs() < 1e-4,
6479 "drag aloft must follow the simulation's hydrostatic density: low/earth={ratio}, \
6480 expected 1.162702 (standard lapse rate, 1000 m station, 2000 m above it)"
6481 );
6482 }
6483
6484 #[test]
6485 fn magnus_yaw_of_repose_uses_the_simulation_gravity() {
6486 let velocity = Vector3::new(800.0, 0.0, 0.0);
6487 let low_gravity = Gravity::new(3.71).unwrap();
6488 let aerodynamic = |enable_magnus, gravity| {
6490 let inputs = BallisticInputs {
6491 enable_magnus,
6492 ..match_308_inputs()
6493 };
6494 aerodynamic_acceleration_with_gravity(&inputs, gravity, Vector3::zeros(), velocity)
6495 };
6496
6497 let earth = aerodynamic(false, Gravity::EARTH);
6499 let low = aerodynamic(false, low_gravity);
6500 assert!(
6501 (earth - low).norm() < 1e-12,
6502 "Magnus-off drag must not depend on gravity: earth={earth:?}, low={low:?}"
6503 );
6504
6505 let earth = aerodynamic(true, Gravity::EARTH) - earth;
6507 let low = aerodynamic(true, low_gravity) - low;
6508 let ratio = low.y / earth.y;
6509 let expected = low_gravity.magnitude() / Gravity::EARTH.magnitude();
6510 assert!(
6511 earth.y < 0.0,
6512 "right-hand Magnus must point down: {earth:?}"
6513 );
6514 assert!(
6515 (ratio - expected).abs() < 1e-6,
6516 "Magnus must scale with the simulation's gravity: low/earth={ratio}, expected={expected}"
6517 );
6518 }
6519}
6520
6521#[cfg(test)]
6522mod result_sanity_tests {
6523 use super::*;
6524
6525 fn default_solver() -> TrajectorySolver {
6526 TrajectorySolver::new(
6527 BallisticInputs::default(),
6528 WindConditions::default(),
6529 AtmosphericConditions::default(),
6530 )
6531 }
6532
6533 fn minimal_result() -> TrajectoryResult {
6534 TrajectoryResult {
6535 max_range: 100.0,
6536 max_height: 1.0,
6537 time_of_flight: 0.5,
6538 impact_velocity: 700.0,
6539 impact_energy: 2450.0,
6540 projectile_mass_kg: 0.01,
6541 line_of_sight_height_m: 1.5,
6542 station_speed_of_sound_mps: 340.0,
6543 termination: TrajectoryTermination::MaxRange,
6544 points: vec![],
6545 sampled_points: None,
6546 min_pitch_damping: None,
6547 transonic_mach: None,
6548 angular_state: None,
6549 max_yaw_angle: None,
6550 max_precession_angle: None,
6551 aerodynamic_jump: None,
6552 mach_1_2_distance_m: None,
6553 mach_1_0_distance_m: None,
6554 mach_0_9_distance_m: None,
6555 }
6556 }
6557
6558 #[test]
6559 fn mba1293_negative_scalars_fail_the_result_postcondition() {
6560 let solver = default_solver();
6561 solver
6562 .validate_result_sanity(&minimal_result())
6563 .expect("a sane result must pass");
6564
6565 for (name, mutate) in [
6566 (
6567 "max_range",
6568 (|r| r.max_range = -50.588) as fn(&mut TrajectoryResult),
6569 ),
6570 ("time_of_flight", |r| r.time_of_flight = -1.0),
6571 ("impact_velocity", |r| r.impact_velocity = -700.0),
6572 ("impact_energy", |r| r.impact_energy = -1.0),
6573 ] {
6574 let mut result = minimal_result();
6575 mutate(&mut result);
6576 let error = solver
6577 .validate_result_sanity(&result)
6578 .expect_err("negative scalar must fail");
6579 assert!(
6580 error.to_string().contains(name),
6581 "error for {name} did not name the field: {error}"
6582 );
6583 }
6584 }
6585
6586 #[test]
6587 fn mba1293_speed_budget_bounds_legitimate_states_and_rejects_divergence() {
6588 let solver = default_solver();
6589 let mv = solver.inputs.muzzle_velocity;
6590
6591 let position = Vector3::new(10.0, 0.0, 0.0);
6593 solver
6594 .validate_integration_state(&position, &Vector3::new(mv, 0.0, 0.0), 0.01)
6595 .expect("muzzle-speed state must pass");
6596
6597 let error = solver
6599 .validate_integration_state(&position, &Vector3::new(-13.0 * mv, 0.0, 0.0), 0.01)
6600 .expect_err("13x muzzle speed must fail the budget");
6601 assert!(error.to_string().contains("diverged"), "{error}");
6602
6603 let after_fall = mv + crate::constants::G_ACCEL_MPS2 * 60.0;
6605 solver
6606 .validate_integration_state(&position, &Vector3::new(0.0, -after_fall, 0.0), 60.0)
6607 .expect("gravity-accelerated speed within g*t must pass");
6608 }
6609}
6610
6611#[cfg(test)]
6612mod trajectory_point_budget_tests {
6613 use super::*;
6614 use crate::MAX_TRAJECTORY_SAMPLES;
6615
6616 fn solver_with_budget(
6617 use_rk4: bool,
6618 use_adaptive_rk45: bool,
6619 point_budget: usize,
6620 max_range: f64,
6621 ) -> TrajectorySolver {
6622 let inputs = BallisticInputs {
6623 use_rk4,
6624 use_adaptive_rk45,
6625 ground_threshold: f64::NEG_INFINITY,
6626 ..BallisticInputs::default()
6627 };
6628 let mut solver = TrajectorySolver::new(
6629 inputs,
6630 WindConditions::default(),
6631 AtmosphericConditions::default(),
6632 );
6633 solver.max_trajectory_points = point_budget;
6634 solver.set_max_range(max_range);
6635 solver.set_time_step(0.001);
6636 solver
6637 }
6638
6639 #[test]
6640 fn mba1283_every_solver_errors_instead_of_exceeding_point_budget() {
6641 for (mode, use_rk4, use_adaptive_rk45) in [
6642 ("Euler", false, false),
6643 ("RK4", true, false),
6644 ("RK45", true, true),
6645 ] {
6646 let error = solver_with_budget(use_rk4, use_adaptive_rk45, 3, 10.0)
6647 .solve()
6648 .expect_err("a solve requiring more than three points must fail");
6649 assert!(
6650 error.to_string().contains("point limit of 3"),
6651 "unexpected {mode} point-budget error: {error}"
6652 );
6653 }
6654 }
6655
6656 #[test]
6657 fn mba1283_interpolated_endpoint_counts_toward_point_budget() {
6658 for (mode, use_rk4, use_adaptive_rk45) in [
6659 ("Euler", false, false),
6660 ("RK4", true, false),
6661 ("RK45", true, true),
6662 ] {
6663 let result = solver_with_budget(use_rk4, use_adaptive_rk45, 2, 0.1)
6664 .solve()
6665 .expect("the initial point plus exact endpoint fit a two-point budget");
6666 assert_eq!(result.points.len(), 2, "unexpected {mode} point count");
6667
6668 let error = solver_with_budget(use_rk4, use_adaptive_rk45, 1, 0.1)
6669 .solve()
6670 .expect_err("the exact endpoint must not exceed a one-point budget");
6671 assert!(
6672 error.to_string().contains("point limit of 1"),
6673 "unexpected {mode} endpoint-budget error: {error}"
6674 );
6675 }
6676 }
6677
6678 #[test]
6686 fn mba1599_collapsed_stall_steps_count_toward_point_budget() {
6687 for (mode, use_rk4, use_adaptive_rk45, bc_value) in [
6688 ("Euler", false, false, 2.0e-4),
6689 ("RK4", true, false, 1.0e-4),
6690 ("RK45", true, true, 1.0e-4),
6691 ] {
6692 let stalled = |point_budget: usize| {
6693 let inputs = BallisticInputs {
6694 bc_value,
6695 bc_type: DragModel::G7,
6696 bullet_mass: 0.01134,
6697 bullet_diameter: 0.00782,
6698 muzzle_velocity: 823.0,
6699 use_rk4,
6700 use_adaptive_rk45,
6701 ground_threshold: -100.0,
6702 ..BallisticInputs::default()
6703 };
6704 let mut solver = TrajectorySolver::new(
6705 inputs,
6706 WindConditions::default(),
6707 AtmosphericConditions::default(),
6708 );
6709 solver.max_trajectory_points = point_budget;
6710 solver.set_max_range(300.0);
6711 solver.set_time_step(0.001);
6712 solver.solve()
6713 };
6714
6715 let flown = stalled(MAX_TRAJECTORY_POINTS)
6716 .unwrap_or_else(|error| panic!("{mode}: the stall ends inside the cap: {error}"));
6717 assert_eq!(
6718 flown.termination,
6719 TrajectoryTermination::GroundThreshold,
6720 "{mode}"
6721 );
6722 let stored = flown.points.len();
6723 let budget = stored + 1;
6724 let Err(error) = stalled(budget) else {
6725 panic!("{mode}: the flight fit a {budget}-point budget with {stored} stored points, so the collapsed steps were not counted");
6726 };
6727 assert!(
6728 error
6729 .to_string()
6730 .contains(&format!("trajectory point limit of {budget} exceeded")),
6731 "unexpected {mode} stall-budget error: {error}"
6732 );
6733 }
6734 }
6735
6736 #[test]
6740 fn mba1599_point_budget_fails_on_the_same_call_with_or_without_collapsing() {
6741 let solver = solver_with_budget(true, false, 4, 10.0);
6742 let point = |x: f64| TrajectoryPoint {
6743 time: x,
6744 position: Vector3::new(x, 0.0, 0.0),
6745 velocity_magnitude: 1.0,
6746 kinetic_energy: 0.0,
6747 drag_coefficient: None,
6748 };
6749 let assert_over_budget = |error: BallisticsError| {
6750 assert!(
6751 error
6752 .to_string()
6753 .contains("trajectory point limit of 4 exceeded"),
6754 "unexpected point-budget error: {error}"
6755 );
6756 };
6757 for distances in [
6758 [0.0, 1.0, 2.0, 3.0],
6759 [0.0, 1.0, 1.0, 2.0],
6760 [0.0, 0.0, 0.0, 0.0],
6761 ] {
6762 let mut points = Vec::new();
6763 let mut collapsed_steps = 0;
6764 for x in distances {
6765 solver
6766 .push_trajectory_point(&mut points, point(x), &mut collapsed_steps)
6767 .expect("four calls fit a four-point budget");
6768 }
6769 assert_eq!(points.len() + collapsed_steps, 4, "{distances:?}");
6770
6771 for x in [distances[3], 5.0] {
6773 let error = solver
6774 .push_trajectory_point(
6775 &mut points.clone(),
6776 point(x),
6777 &mut collapsed_steps.clone(),
6778 )
6779 .expect_err("a fifth call exceeds a four-point budget");
6780 assert_over_budget(error);
6781 }
6782 let error = solver
6784 .append_terminal_endpoint(
6785 &mut points.clone(),
6786 Vector3::new(20.0, 0.0, 0.0),
6787 Vector3::new(1.0, 0.0, 0.0),
6788 10.0,
6789 &mut 0.0,
6790 &mut collapsed_steps.clone(),
6791 )
6792 .expect_err("the terminal point is a fifth call");
6793 assert_over_budget(error);
6794 }
6795 }
6796
6797 #[test]
6798 fn mba1299_every_solver_preflights_the_sample_budget() {
6799 for (mode, use_rk4, use_adaptive_rk45) in [
6800 ("Euler", false, false),
6801 ("RK4", true, false),
6802 ("RK45", true, true),
6803 ] {
6804 let inputs = BallisticInputs {
6805 use_rk4,
6806 use_adaptive_rk45,
6807 enable_trajectory_sampling: true,
6808 sample_interval: 1.0,
6809 ground_threshold: f64::NEG_INFINITY,
6810 ..BallisticInputs::default()
6811 };
6812 let mut solver = TrajectorySolver::new(
6813 inputs,
6814 WindConditions::default(),
6815 AtmosphericConditions::default(),
6816 );
6817 solver.set_max_range(MAX_TRAJECTORY_SAMPLES as f64);
6818 solver.max_trajectory_points = 0;
6821
6822 let error = solver
6823 .solve()
6824 .expect_err("an over-limit sample grid must fail before integration");
6825 assert!(
6826 error
6827 .to_string()
6828 .contains("trajectory sample limit of 250000 exceeded"),
6829 "unexpected {mode} sample-budget error: {error}"
6830 );
6831 }
6832 }
6833
6834 #[test]
6835 fn mba1299_normal_sampling_does_not_change_solver_results() {
6836 for (mode, use_rk4, use_adaptive_rk45) in [
6837 ("Euler", false, false),
6838 ("RK4", true, false),
6839 ("RK45", true, true),
6840 ] {
6841 let solve = |enable_trajectory_sampling| {
6842 let inputs = BallisticInputs {
6843 use_rk4,
6844 use_adaptive_rk45,
6845 enable_trajectory_sampling,
6846 sample_interval: 0.5,
6847 ground_threshold: f64::NEG_INFINITY,
6848 ..BallisticInputs::default()
6849 };
6850 let mut solver = TrajectorySolver::new(
6851 inputs,
6852 WindConditions::default(),
6853 AtmosphericConditions::default(),
6854 );
6855 solver.set_max_range(2.0);
6856 solver.solve().expect("normal short-range solve")
6857 };
6858
6859 let baseline = solve(false);
6860 let sampled = solve(true);
6861 for (field, left, right) in [
6862 ("max_range", baseline.max_range, sampled.max_range),
6863 ("max_height", baseline.max_height, sampled.max_height),
6864 (
6865 "time_of_flight",
6866 baseline.time_of_flight,
6867 sampled.time_of_flight,
6868 ),
6869 (
6870 "impact_velocity",
6871 baseline.impact_velocity,
6872 sampled.impact_velocity,
6873 ),
6874 (
6875 "impact_energy",
6876 baseline.impact_energy,
6877 sampled.impact_energy,
6878 ),
6879 ] {
6880 assert_eq!(
6881 left.to_bits(),
6882 right.to_bits(),
6883 "{mode} sampling changed {field}"
6884 );
6885 }
6886 assert_eq!(baseline.points.len(), sampled.points.len());
6887 for (index, (left, right)) in baseline.points.iter().zip(&sampled.points).enumerate() {
6888 assert_eq!(
6889 left.time.to_bits(),
6890 right.time.to_bits(),
6891 "{mode} point {index}"
6892 );
6893 assert_eq!(
6894 left.position.map(f64::to_bits),
6895 right.position.map(f64::to_bits),
6896 "{mode} point {index} position"
6897 );
6898 assert_eq!(
6899 left.velocity_magnitude.to_bits(),
6900 right.velocity_magnitude.to_bits(),
6901 "{mode} point {index} velocity"
6902 );
6903 assert_eq!(
6904 left.kinetic_energy.to_bits(),
6905 right.kinetic_energy.to_bits(),
6906 "{mode} point {index} energy"
6907 );
6908 }
6909 assert!(baseline.sampled_points.is_none());
6910 let samples = sampled
6911 .sampled_points
6912 .expect("sampling-enabled solve should return observations");
6913 assert_eq!(
6914 samples
6915 .iter()
6916 .map(|sample| sample.distance_m)
6917 .collect::<Vec<_>>(),
6918 vec![0.0, 0.5, 1.0, 1.5, 2.0],
6919 "{mode} normal sampling grid changed"
6920 );
6921 }
6922 }
6923}
6924
6925#[cfg(test)]
6926mod monte_carlo_result_tests {
6927 use super::*;
6928
6929 fn make_results(impact_positions: Vec<Vector3<f64>>) -> MonteCarloResults {
6930 let count = impact_positions.len();
6931 MonteCarloResults {
6932 ranges: vec![500.0; count],
6933 impact_velocities: vec![300.0; count],
6934 impact_positions,
6935 }
6936 }
6937
6938 #[test]
6939 fn target_plane_cep_excludes_shortfall_markers() {
6940 let mut positions: Vec<Vector3<f64>> = (1..=5)
6941 .map(|radius| Vector3::new(0.0, radius as f64, 0.0))
6942 .collect();
6943 positions.extend((0..5).map(|_| Vector3::new(0.0, TARGET_NOT_REACHED_SENTINEL_M, 0.0)));
6944 let results = make_results(positions);
6945
6946 assert_eq!(results.target_arrival_count(), 5);
6947 assert_eq!(results.target_shortfall_fraction(), 0.5);
6948 assert_eq!(results.target_plane_cep(), Some(3.0));
6949
6950 let one_shortfall = make_results(vec![
6951 Vector3::new(0.0, 1.0, 0.0),
6952 Vector3::new(0.0, 2.0, 0.0),
6953 Vector3::new(0.0, 3.0, 0.0),
6954 Vector3::new(0.0, 4.0, 0.0),
6955 Vector3::new(0.0, 5.0, 0.0),
6956 Vector3::new(0.0, TARGET_NOT_REACHED_SENTINEL_M, 0.0),
6957 ]);
6958 assert_eq!(one_shortfall.target_plane_cep(), Some(3.0));
6959 }
6960
6961 #[test]
6962 fn all_shortfalls_have_no_cep_but_still_count_as_misses() {
6963 let all_shortfalls = make_results(vec![
6964 Vector3::new(0.0, TARGET_NOT_REACHED_SENTINEL_M, 0.0),
6965 Vector3::new(0.0, TARGET_NOT_REACHED_SENTINEL_M, 0.0),
6966 ]);
6967 assert_eq!(all_shortfalls.target_arrival_count(), 0);
6968 assert_eq!(all_shortfalls.target_shortfall_fraction(), 1.0);
6969 assert_eq!(all_shortfalls.target_plane_cep(), None);
6970 assert_eq!(all_shortfalls.hit_probability(0.3), 0.0);
6971
6972 let one_hit_one_shortfall = make_results(vec![
6973 Vector3::new(0.0, 0.1, 0.0),
6974 Vector3::new(0.0, TARGET_NOT_REACHED_SENTINEL_M, 0.0),
6975 ]);
6976 assert_eq!(one_hit_one_shortfall.hit_probability(0.3), 0.5);
6977 }
6978
6979 #[test]
6981 fn rect_hit_probability_checks_independent_axis_halves() {
6982 let results = make_results(vec![
6983 Vector3::new(0.0, 0.1, 0.1),
6985 Vector3::new(0.0, 0.0, 0.2),
6987 Vector3::new(0.0, 0.0, 0.201),
6989 Vector3::new(0.0, 0.301, 0.0),
6991 Vector3::new(0.0, TARGET_NOT_REACHED_SENTINEL_M, 0.0),
6993 ]);
6994 assert!((results.rect_hit_probability(0.4, 0.6) - 0.4).abs() < 1e-12);
6996 }
6997
6998 #[test]
6999 fn rect_hit_probability_matches_circular_hit_probability_for_a_centered_hit() {
7000 let results = make_results(vec![Vector3::new(0.0, 0.0, 0.0)]);
7001 assert_eq!(results.rect_hit_probability(0.5, 0.5), 1.0);
7002 assert_eq!(results.hit_probability(0.3), 1.0);
7003 }
7004
7005 #[test]
7006 fn rect_hit_probability_is_zero_for_empty_or_nonpositive_dimensions() {
7007 let empty = make_results(vec![]);
7008 assert_eq!(empty.rect_hit_probability(1.0, 1.0), 0.0);
7009
7010 let results = make_results(vec![Vector3::new(0.0, 0.0, 0.0)]);
7011 assert_eq!(results.rect_hit_probability(0.0, 1.0), 0.0);
7012 assert_eq!(results.rect_hit_probability(1.0, 0.0), 0.0);
7013 assert_eq!(results.rect_hit_probability(-1.0, 1.0), 0.0);
7014 }
7015}
7016
7017#[cfg(test)]
7021mod station_presence_twin_tests {
7022 use super::*;
7023
7024 fn rifle() -> BallisticInputs {
7025 BallisticInputs {
7026 muzzle_velocity: 823.0,
7027 bc_value: 0.475,
7028 bc_type: DragModel::G1,
7029 bullet_mass: 0.0109,
7030 bullet_diameter: 0.00782,
7031 sight_height: 0.0381,
7032 ..Default::default()
7033 }
7034 }
7035
7036 fn air(temperature: f64, pressure: f64, altitude: f64) -> AtmosphericConditions {
7037 AtmosphericConditions {
7038 temperature,
7039 pressure,
7040 humidity: 50.0,
7041 altitude,
7042 }
7043 }
7044
7045 #[test]
7046 fn zero_twins_reproduce_ab4eb0c_with_neither_and_fly_a_supplied_reading() {
7047 let cases = [
7056 (
7057 20.0,
7058 1013.0,
7059 150.0,
7060 f64::from_bits(0x3f65f73333333333),
7061 f64::from_bits(0x4034aaf57020aad0),
7062 f64::from_bits(0x406c0aa310c17a28),
7063 ),
7064 (
7065 15.0,
7066 850.0,
7067 1500.0,
7068 f64::from_bits(0x3f6594ccccccccce),
7069 f64::from_bits(0x4034aa5d88f6063f),
7070 f64::from_bits(0x406c6ab977f9df7a),
7071 ),
7072 ];
7073 for (t, p, alt, zero, near, far) in cases {
7074 let calm = WindConditions::default;
7075 let legacy = calculate_zero_angle_with_conditions(
7076 rifle(),
7077 300.0,
7078 0.0381,
7079 calm(),
7080 air(t, p, alt),
7081 )
7082 .unwrap();
7083 let neither = calculate_zero_angle_with_station_presence(
7084 rifle(),
7085 300.0,
7086 0.0381,
7087 calm(),
7088 air(t, p, alt),
7089 StationAtmospherePresence::NEITHER,
7090 )
7091 .unwrap();
7092 assert_eq!(
7093 legacy.to_bits(),
7094 zero.to_bits(),
7095 "legacy zero ({t}, {p}, {alt})"
7096 );
7097 assert_eq!(
7098 neither.to_bits(),
7099 zero.to_bits(),
7100 "NEITHER zero ({t}, {p}, {alt})"
7101 );
7102
7103 let legacy_range = calculate_zero_range_from_angle_with_conditions(
7104 rifle(),
7105 0.002,
7106 0.0381,
7107 calm(),
7108 air(t, p, alt),
7109 )
7110 .unwrap();
7111 let neither_range = calculate_zero_range_from_angle_with_station_presence(
7112 rifle(),
7113 0.002,
7114 0.0381,
7115 calm(),
7116 air(t, p, alt),
7117 StationAtmospherePresence::NEITHER,
7118 )
7119 .unwrap();
7120 for crossings in [legacy_range, neither_range] {
7121 assert_eq!(crossings.near_m.unwrap().to_bits(), near.to_bits());
7122 assert_eq!(crossings.far_m.unwrap().to_bits(), far.to_bits());
7123 }
7124
7125 let both = calculate_zero_angle_with_station_presence(
7128 rifle(),
7129 300.0,
7130 0.0381,
7131 calm(),
7132 air(t, p, alt),
7133 StationAtmospherePresence::BOTH,
7134 )
7135 .unwrap();
7136 let authoritative = calculate_zero_angle_with_resolved_conditions(
7137 rifle(),
7138 300.0,
7139 0.0381,
7140 calm(),
7141 air(t, p, alt),
7142 )
7143 .unwrap();
7144 assert_eq!(both.to_bits(), authoritative.to_bits());
7145 assert_ne!(
7146 both.to_bits(),
7147 zero.to_bits(),
7148 "BOTH must not swap ({t}, {p}, {alt})"
7149 );
7150
7151 let both_range = calculate_zero_range_from_angle_with_station_presence(
7152 rifle(),
7153 0.002,
7154 0.0381,
7155 calm(),
7156 air(t, p, alt),
7157 StationAtmospherePresence::BOTH,
7158 )
7159 .unwrap();
7160 let authoritative_range = calculate_zero_range_from_angle_with_resolved_conditions(
7161 rifle(),
7162 0.002,
7163 0.0381,
7164 calm(),
7165 air(t, p, alt),
7166 )
7167 .unwrap();
7168 assert_eq!(both_range, authoritative_range);
7169 assert_ne!(both_range.far_m.unwrap().to_bits(), far.to_bits());
7170 }
7171 }
7172
7173 #[test]
7174 fn solver_twin_with_both_lies_between_out_of_band_neighbours() {
7175 let impact = |p: f64, presence| {
7176 let mut solver = TrajectorySolver::new_with_station_presence(
7177 rifle(),
7178 WindConditions::default(),
7179 air(20.0, p, 150.0),
7180 presence,
7181 );
7182 solver.set_max_range(600.0);
7183 solver.solve().unwrap().impact_velocity
7184 };
7185 let low = impact(1012.0, StationAtmospherePresence::NEITHER);
7186 let high = impact(1014.0, StationAtmospherePresence::NEITHER);
7187 let both = impact(1013.0, StationAtmospherePresence::BOTH);
7188 let neither = impact(1013.0, StationAtmospherePresence::NEITHER);
7189 assert!(high < both && both < low, "{high} < {both} < {low}");
7191 assert_ne!(both.to_bits(), neither.to_bits());
7192
7193 let temperature = |t: f64, presence| {
7194 let mut solver = TrajectorySolver::new_with_station_presence(
7195 rifle(),
7196 WindConditions::default(),
7197 air(t, 850.0, 1500.0),
7198 presence,
7199 );
7200 solver.set_max_range(600.0);
7201 solver.solve().unwrap().impact_velocity
7202 };
7203 let cold = temperature(14.8, StationAtmospherePresence::NEITHER);
7204 let warm = temperature(15.2, StationAtmospherePresence::NEITHER);
7205 let both = temperature(15.0, StationAtmospherePresence::BOTH);
7206 assert!(cold < both && both < warm, "{cold} < {both} < {warm}");
7208 assert_ne!(
7209 both.to_bits(),
7210 temperature(15.0, StationAtmospherePresence::NEITHER).to_bits()
7211 );
7212 }
7213
7214 #[test]
7216 fn monte_carlo_twin_with_neither_reproduces_the_legacy_seeded_pins() {
7217 let inputs = BallisticInputs {
7218 muzzle_velocity: 800.0,
7219 ..BallisticInputs::default()
7220 };
7221 let params = MonteCarloParams {
7222 num_simulations: 200,
7223 target_distance: Some(500.0),
7224 ..MonteCarloParams::default()
7225 };
7226 let results = run_monte_carlo_with_station_presence(
7227 inputs,
7228 WindConditions::default(),
7229 params,
7230 0.01,
7231 Some(0x1352_5EED),
7232 StationAtmospherePresence::NEITHER,
7233 )
7234 .unwrap();
7235 assert_eq!(results.ranges.len(), 200);
7236 assert_eq!(
7237 results.hit_probability(DEFAULT_HIT_RADIUS_M).to_bits(),
7238 0.14_f64.to_bits()
7239 );
7240 let expected_ranges: [f64; 3] = [1907.9716332174821, 1936.4071333440454, 1912.81384414182];
7243 let expected_velocities: [f64; 3] =
7244 [238.6179931921287, 239.9185187950357, 243.14025219104838];
7245 let expected_positions: [(f64, f64); 3] = [
7246 (-0.06435559190712015, 0.7344970251956466),
7247 (0.5769422272471794, 0.2722720177468328),
7248 (-0.7440424901848259, 0.15418044529361857),
7249 ];
7250 for i in 0..3 {
7251 assert_eq!(results.ranges[i].to_bits(), expected_ranges[i].to_bits());
7252 assert_eq!(
7253 results.impact_velocities[i].to_bits(),
7254 expected_velocities[i].to_bits()
7255 );
7256 assert_eq!(
7257 results.impact_positions[i].y.to_bits(),
7258 expected_positions[i].0.to_bits()
7259 );
7260 assert_eq!(
7261 results.impact_positions[i].z.to_bits(),
7262 expected_positions[i].1.to_bits()
7263 );
7264 }
7265 }
7266
7267 fn in_band_mc_inputs() -> BallisticInputs {
7268 BallisticInputs {
7269 muzzle_velocity: 800.0,
7270 temperature: 20.0,
7271 pressure: 1013.0,
7272 altitude: 150.0,
7273 ..BallisticInputs::default()
7274 }
7275 }
7276
7277 #[test]
7278 fn monte_carlo_in_band_seeded_case_is_pinned_and_both_differs() {
7279 let params = MonteCarloParams {
7280 num_simulations: 50,
7281 target_distance: Some(500.0),
7282 ..MonteCarloParams::default()
7283 };
7284 let pinned = [
7292 (
7293 f64::from_bits(0x409e36cd7bbf5e66),
7294 f64::from_bits(0x406e61096bd7c6b4),
7295 ),
7296 (
7297 f64::from_bits(0x409eaa62062b31d5),
7298 f64::from_bits(0x406e8a32ed528026),
7299 ),
7300 (
7301 f64::from_bits(0x409e4836fe30807a),
7302 f64::from_bits(0x406ef312a9a45523),
7303 ),
7304 ];
7305 let seeded = run_monte_carlo_with_wind_and_direction_std_dev_seeded(
7306 in_band_mc_inputs(),
7307 WindConditions::default(),
7308 params.clone(),
7309 0.01,
7310 0x1352_5EED,
7311 )
7312 .unwrap();
7313 let neither = run_monte_carlo_with_station_presence(
7314 in_band_mc_inputs(),
7315 WindConditions::default(),
7316 params.clone(),
7317 0.01,
7318 Some(0x1352_5EED),
7319 StationAtmospherePresence::NEITHER,
7320 )
7321 .unwrap();
7322 for results in [&seeded, &neither] {
7323 assert_eq!(results.ranges.len(), 50);
7324 for (i, (range, velocity)) in pinned.iter().enumerate() {
7325 assert_eq!(results.ranges[i].to_bits(), range.to_bits(), "range[{i}]");
7326 assert_eq!(
7327 results.impact_velocities[i].to_bits(),
7328 velocity.to_bits(),
7329 "velocity[{i}]"
7330 );
7331 }
7332 }
7333 let both = run_monte_carlo_with_station_presence(
7334 in_band_mc_inputs(),
7335 WindConditions::default(),
7336 params,
7337 0.01,
7338 Some(0x1352_5EED),
7339 StationAtmospherePresence::BOTH,
7340 )
7341 .unwrap();
7342 assert_ne!(both.ranges[0].to_bits(), pinned[0].0.to_bits());
7343 assert!(both.ranges[0] < pinned[0].0);
7345 }
7346
7347 #[test]
7348 fn adaptive_monte_carlo_twin_is_pinned_and_both_differs() {
7349 let params = MonteCarloParams {
7350 num_simulations: 1,
7351 velocity_std_dev: 3.0,
7352 angle_std_dev: 3.5e-4,
7353 bc_std_dev: 0.01,
7354 wind_speed_std_dev: 1.0,
7355 target_distance: Some(300.0),
7356 base_wind_speed: 0.0,
7357 base_wind_direction: 0.0,
7358 azimuth_std_dev: 3.5e-4,
7359 };
7360 let convergence = McConvergence {
7361 min_samples: 40,
7362 max_samples: 80,
7363 batch_size: 40,
7364 ..McConvergence::default()
7365 };
7366 let legacy = run_monte_carlo_adaptive_seeded(
7367 &in_band_mc_inputs(),
7368 &WindConditions::default(),
7369 ¶ms,
7370 &convergence,
7371 DEFAULT_HIT_RADIUS_M,
7372 7,
7373 )
7374 .unwrap();
7375 let neither = run_monte_carlo_adaptive_seeded_with_station_presence(
7376 &in_band_mc_inputs(),
7377 &WindConditions::default(),
7378 ¶ms,
7379 &convergence,
7380 DEFAULT_HIT_RADIUS_M,
7381 7,
7382 StationAtmospherePresence::NEITHER,
7383 )
7384 .unwrap();
7385 for report in [&legacy, &neither] {
7386 assert_eq!(report.samples, 80);
7387 assert_eq!(report.attempts, 80);
7388 assert_eq!(
7395 report.hit_probability.to_bits(),
7396 f64::from_bits(0x3fef99999999999a).to_bits()
7397 );
7398 assert_eq!(
7399 report.mean_impact_velocity_mps.to_bits(),
7400 0x406e99b50b1cadd6
7401 );
7402 assert_eq!(report.mean_drop_at_target_m.to_bits(), 0x3f63de4982c26e62);
7403 }
7404 let both = run_monte_carlo_adaptive_seeded_with_station_presence(
7405 &in_band_mc_inputs(),
7406 &WindConditions::default(),
7407 ¶ms,
7408 &convergence,
7409 DEFAULT_HIT_RADIUS_M,
7410 7,
7411 StationAtmospherePresence::BOTH,
7412 )
7413 .unwrap();
7414 assert_ne!(both.mean_impact_velocity_mps.to_bits(), 0x406e99b50b1cadd6);
7415 }
7416
7417 #[test]
7421 fn monte_carlo_baseline_flies_the_trials_air() {
7422 let params = MonteCarloParams {
7423 num_simulations: 3,
7424 velocity_std_dev: 0.0,
7425 angle_std_dev: 0.0,
7426 bc_std_dev: 0.0,
7427 wind_speed_std_dev: 0.0,
7428 target_distance: Some(500.0),
7429 base_wind_speed: 0.0,
7430 base_wind_direction: 0.0,
7431 azimuth_std_dev: 0.0,
7432 };
7433 let inputs = BallisticInputs {
7434 temperature: 15.0,
7435 ..in_band_mc_inputs()
7436 };
7437 for presence in [
7438 StationAtmospherePresence::NEITHER,
7439 StationAtmospherePresence::new(true, false),
7440 StationAtmospherePresence::new(false, true),
7441 StationAtmospherePresence::BOTH,
7442 ] {
7443 let results = run_monte_carlo_with_station_presence(
7444 inputs.clone(),
7445 WindConditions::default(),
7446 params.clone(),
7447 0.0,
7448 Some(7),
7449 presence,
7450 )
7451 .unwrap();
7452 assert_eq!(results.impact_positions.len(), 3);
7453 for position in &results.impact_positions {
7454 assert_eq!(position.y.to_bits(), 0.0_f64.to_bits(), "{presence:?}");
7455 assert_eq!(position.z.to_bits(), 0.0_f64.to_bits(), "{presence:?}");
7456 }
7457 }
7458 }
7459
7460 #[test]
7464 fn estimate_bc_fit_twin_zeroes_in_the_supplied_air() {
7465 let atmosphere = air(15.0, 1013.0, 150.0);
7466 let presence = StationAtmospherePresence::BOTH;
7467 let mut inputs = BallisticInputs {
7468 muzzle_velocity: 823.0,
7469 bc_value: 0.475,
7470 bc_type: DragModel::G1,
7471 bullet_mass: 0.0109,
7472 bullet_diameter: 0.00782,
7473 sight_height: 0.0381,
7474 ..Default::default()
7475 };
7476 inputs.muzzle_angle = calculate_zero_angle_with_station_presence(
7477 inputs.clone(),
7478 100.0,
7479 0.0381,
7480 WindConditions::default(),
7481 atmosphere.clone(),
7482 presence,
7483 )
7484 .unwrap();
7485 let mut solver = TrajectorySolver::new_with_station_presence(
7486 inputs,
7487 WindConditions::default(),
7488 atmosphere.clone(),
7489 presence,
7490 );
7491 solver.set_max_range(750.0);
7492 let flight = solver.solve().unwrap();
7493 let points: Vec<(f64, f64)> = [300.0, 500.0]
7494 .iter()
7495 .map(|&d| {
7496 (
7497 d,
7498 fit_value_at(&flight.points, d, BcFitMode::Drop, 0.0381).unwrap(),
7499 )
7500 })
7501 .collect();
7502 let fit = estimate_bc_fit_with_station_presence(
7503 823.0,
7504 0.0109,
7505 0.00782,
7506 &points,
7507 DragModel::G1,
7508 BcFitMode::Drop,
7509 atmosphere,
7510 Some(100.0),
7511 0.0381,
7512 presence,
7513 )
7514 .unwrap();
7515 assert!((fit.bc - 0.475).abs() < 1e-9, "{fit:?}");
7516 assert!(fit.rms_error < 1e-9, "{fit:?}");
7517 }
7518
7519 #[test]
7520 fn estimate_bc_fit_twin_is_pinned_and_both_fits_the_supplied_air() {
7521 let points = [(300.0, 650.0), (500.0, 560.0)];
7522 let fit = |p: f64, presence| {
7523 estimate_bc_fit_with_station_presence(
7524 823.0,
7525 0.0109,
7526 0.00782,
7527 &points,
7528 DragModel::G1,
7529 BcFitMode::Velocity,
7530 air(20.0, p, 150.0),
7531 None,
7532 0.0381,
7533 presence,
7534 )
7535 .unwrap()
7536 .bc
7537 };
7538 let legacy = estimate_bc_fit(
7539 823.0,
7540 0.0109,
7541 0.00782,
7542 &points,
7543 DragModel::G1,
7544 BcFitMode::Velocity,
7545 air(20.0, 1013.0, 150.0),
7546 None,
7547 0.0381,
7548 )
7549 .unwrap()
7550 .bc;
7551 let pinned = f64::from_bits(0x3fe0000000000003);
7553 assert_eq!(legacy.to_bits(), pinned.to_bits());
7554 assert_eq!(
7555 fit(1013.0, StationAtmospherePresence::NEITHER).to_bits(),
7556 pinned.to_bits()
7557 );
7558 let low = fit(1010.0, StationAtmospherePresence::NEITHER);
7562 let high = fit(1016.0, StationAtmospherePresence::NEITHER);
7563 let both = fit(1013.0, StationAtmospherePresence::BOTH);
7564 assert!(low < both && both < high, "{low} < {both} < {high}");
7565 }
7566
7567 #[test]
7568 fn monte_carlo_kernel_twin_is_pinned_and_both_lies_between_neighbours() {
7569 let kernel_inputs = |p: f64| BallisticInputs {
7570 muzzle_velocity: 823.0,
7571 bc_value: 0.475,
7572 bullet_mass: 0.0109,
7573 bullet_diameter: 0.00782,
7574 target_distance: 500.0,
7575 temperature: 20.0,
7576 pressure: p,
7577 altitude: 150.0,
7578 ..Default::default()
7579 };
7580 let solve = |p: f64, presence| {
7581 crate::monte_carlo::solve_trajectory_for_monte_carlo_with_station_presence(
7582 &kernel_inputs(p),
7583 presence,
7584 )
7585 .unwrap()
7586 };
7587 let legacy =
7588 crate::monte_carlo::solve_trajectory_for_monte_carlo(&kernel_inputs(1013.0)).unwrap();
7589 let neither = solve(1013.0, StationAtmospherePresence::NEITHER);
7590 for output in [&legacy, &neither] {
7591 assert_eq!(output.drop.to_bits(), 0x4003a01e93c0dd30);
7601 assert_eq!(output.velocity.to_bits(), 0x4080fcf394753ebe);
7602 }
7603 let low = solve(1012.0, StationAtmospherePresence::NEITHER).velocity;
7604 let high = solve(1014.0, StationAtmospherePresence::NEITHER).velocity;
7605 let both = solve(1013.0, StationAtmospherePresence::BOTH).velocity;
7606 assert!(high < both && both < low, "{high} < {both} < {low}");
7607 }
7608}
7609
7610#[cfg(test)]
7611mod monte_carlo_seeded_tests {
7612 use super::*;
7613
7614 fn seeded_test_fixture() -> (BallisticInputs, WindConditions) {
7623 (
7624 BallisticInputs {
7625 muzzle_velocity: 800.0,
7626 ..BallisticInputs::default()
7627 },
7628 WindConditions::default(),
7629 )
7630 }
7631
7632 fn loose_params() -> MonteCarloParams {
7642 MonteCarloParams {
7643 num_simulations: 1, velocity_std_dev: 3.0,
7645 angle_std_dev: 3.5e-4,
7646 bc_std_dev: 0.01,
7647 wind_speed_std_dev: 1.0,
7648 target_distance: Some(300.0),
7649 base_wind_speed: 0.0,
7650 base_wind_direction: 0.0,
7651 azimuth_std_dev: 3.5e-4,
7652 }
7653 }
7654
7655 fn mixed_arrival_params() -> MonteCarloParams {
7663 MonteCarloParams {
7664 num_simulations: 1,
7665 target_distance: Some(1920.0),
7666 ..MonteCarloParams::default()
7667 }
7668 }
7669
7670 #[test]
7686 fn legacy_seeded_estimates_are_pinned_bit_for_bit() {
7687 let (inputs, wind) = seeded_test_fixture();
7688 let params = MonteCarloParams {
7689 num_simulations: 200,
7690 target_distance: Some(500.0),
7691 ..MonteCarloParams::default()
7692 };
7693
7694 let results = run_monte_carlo_with_wind_and_direction_std_dev_seeded(
7695 inputs,
7696 wind,
7697 params,
7698 0.01,
7699 0x1352_5EED,
7700 )
7701 .expect("seeded legacy run");
7702
7703 assert_eq!(results.ranges.len(), 200, "ranges length");
7708 assert_eq!(
7709 results.impact_velocities.len(),
7710 200,
7711 "impact_velocities length"
7712 );
7713 assert_eq!(
7714 results.impact_positions.len(),
7715 200,
7716 "impact_positions length"
7717 );
7718
7719 assert_eq!(
7721 results.hit_probability(DEFAULT_HIT_RADIUS_M).to_bits(),
7722 0.14_f64.to_bits(),
7723 "hit_probability = {:?}",
7724 results.hit_probability(DEFAULT_HIT_RADIUS_M)
7725 );
7726
7727 let expected_ranges: [f64; 3] = [1907.9716332174821, 1936.4071333440454, 1912.81384414182];
7739 let expected_velocities: [f64; 3] =
7740 [238.6179931921287, 239.9185187950357, 243.14025219104838];
7741 let expected_positions: [(f64, f64, f64); 3] = [
7742 (0.0, -0.06435559190712015, 0.7344970251956466),
7743 (0.0, 0.5769422272471794, 0.2722720177468328),
7744 (0.0, -0.7440424901848259, 0.15418044529361857),
7745 ];
7746
7747 for (i, expected) in expected_ranges.iter().enumerate() {
7748 assert_eq!(
7749 results.ranges[i].to_bits(),
7750 expected.to_bits(),
7751 "ranges[{i}] = {:?}, pinned {expected:?}",
7752 results.ranges[i]
7753 );
7754 }
7755 for (i, expected) in expected_velocities.iter().enumerate() {
7756 assert_eq!(
7757 results.impact_velocities[i].to_bits(),
7758 expected.to_bits(),
7759 "impact_velocities[{i}] = {:?}, pinned {expected:?}",
7760 results.impact_velocities[i]
7761 );
7762 }
7763 for (i, (x, y, z)) in expected_positions.iter().enumerate() {
7764 let actual = results.impact_positions[i];
7765 assert_eq!(
7766 actual.x.to_bits(),
7767 x.to_bits(),
7768 "impact_positions[{i}].x = {:?}",
7769 actual.x
7770 );
7771 assert_eq!(
7772 actual.y.to_bits(),
7773 y.to_bits(),
7774 "impact_positions[{i}].y = {:?}",
7775 actual.y
7776 );
7777 assert_eq!(
7778 actual.z.to_bits(),
7779 z.to_bits(),
7780 "impact_positions[{i}].z = {:?}",
7781 actual.z
7782 );
7783 }
7784 }
7785
7786 #[test]
7787 fn seeded_runs_are_deterministic_and_match_the_using_rng_path() {
7788 let inputs = BallisticInputs {
7789 muzzle_velocity: 800.0,
7790 ..BallisticInputs::default()
7791 };
7792 let params = MonteCarloParams {
7793 num_simulations: 64,
7794 target_distance: Some(200.0),
7795 ..MonteCarloParams::default()
7796 };
7797
7798 let a = run_monte_carlo_with_wind_and_direction_std_dev_seeded(
7799 inputs.clone(),
7800 WindConditions::default(),
7801 params.clone(),
7802 0.01,
7803 42,
7804 )
7805 .expect("seeded run a");
7806 let b = run_monte_carlo_with_wind_and_direction_std_dev_seeded(
7807 inputs,
7808 WindConditions::default(),
7809 params,
7810 0.01,
7811 42,
7812 )
7813 .expect("seeded run b");
7814
7815 assert_eq!(a.ranges.len(), b.ranges.len());
7816 for (ra, rb) in a.ranges.iter().zip(b.ranges.iter()) {
7817 assert_eq!(ra.to_bits(), rb.to_bits());
7818 }
7819 for (pa, pb) in a.impact_positions.iter().zip(b.impact_positions.iter()) {
7820 assert_eq!(pa.x.to_bits(), pb.x.to_bits());
7821 assert_eq!(pa.y.to_bits(), pb.y.to_bits());
7822 assert_eq!(pa.z.to_bits(), pb.z.to_bits());
7823 }
7824 }
7825
7826 #[test]
7827 fn different_seeds_generally_produce_different_draws() {
7828 let inputs = BallisticInputs {
7829 muzzle_velocity: 800.0,
7830 ..BallisticInputs::default()
7831 };
7832 let params = MonteCarloParams {
7833 num_simulations: 32,
7834 velocity_std_dev: 5.0,
7835 target_distance: Some(200.0),
7836 ..MonteCarloParams::default()
7837 };
7838
7839 let a = run_monte_carlo_with_wind_and_direction_std_dev_seeded(
7840 inputs.clone(),
7841 WindConditions::default(),
7842 params.clone(),
7843 0.0,
7844 1,
7845 )
7846 .expect("seeded run a");
7847 let b = run_monte_carlo_with_wind_and_direction_std_dev_seeded(
7848 inputs,
7849 WindConditions::default(),
7850 params,
7851 0.0,
7852 2,
7853 )
7854 .expect("seeded run b");
7855
7856 assert_ne!(a.impact_velocities, b.impact_velocities);
7857 }
7858
7859 #[test]
7860 fn adaptive_stops_at_target_half_width_on_an_easy_case() {
7861 let (inputs, wind) = seeded_test_fixture();
7862 let conv = McConvergence {
7863 target_half_width: 0.05,
7864 ..Default::default()
7865 };
7866 let r = run_monte_carlo_adaptive_seeded(
7867 &inputs,
7868 &wind,
7869 &loose_params(),
7870 &conv,
7871 DEFAULT_HIT_RADIUS_M,
7872 0x1352_ADA9,
7873 )
7874 .unwrap();
7875
7876 assert_eq!(r.stop_reason, McStopReason::TargetHalfWidthMet);
7877 assert!(
7878 (r.ci_high - r.ci_low) / 2.0 <= 0.05 + 1e-12,
7879 "half-width {} exceeds the requested 0.05",
7880 (r.ci_high - r.ci_low) / 2.0
7881 );
7882 assert!(r.samples >= conv.min_samples, "stopped below min_samples");
7883 assert!(r.samples < conv.max_samples, "did not actually stop early");
7884 assert!(r.samples.is_multiple_of(conv.batch_size) || r.samples == conv.min_samples);
7885 assert!(r.ci_low <= r.hit_probability && r.hit_probability <= r.ci_high);
7886
7887 assert_eq!(r.hit_radius_m, DEFAULT_HIT_RADIUS_M);
7889 assert_eq!(r.target_distance_m, 300.0);
7890 assert_eq!(r.confidence_percent, 95);
7891 assert!(
7893 r.samples > 1,
7894 "params.num_simulations must be ignored by the adaptive driver"
7895 );
7896 assert!(
7899 r.mean_impact_velocity_mps > 0.0,
7900 "no impact velocity accumulated"
7901 );
7902 assert!(
7903 r.std_drop_at_target_m > 0.0 && r.std_wind_drift_at_target_m > 0.0,
7904 "dispersion collapsed: drop sd {} drift sd {}",
7905 r.std_drop_at_target_m,
7906 r.std_wind_drift_at_target_m
7907 );
7908 }
7909
7910 #[test]
7911 fn adaptive_caps_at_max_samples_on_an_impossible_target() {
7912 let (inputs, wind) = seeded_test_fixture();
7913 let conv = McConvergence {
7914 target_half_width: 1e-6,
7915 max_samples: 3_000,
7916 batch_size: 500,
7917 min_samples: 1_000,
7918 level: ConfidenceLevel::P95,
7919 };
7920 let r = run_monte_carlo_adaptive_seeded(
7921 &inputs,
7922 &wind,
7923 &loose_params(),
7924 &conv,
7925 DEFAULT_HIT_RADIUS_M,
7926 7,
7927 )
7928 .unwrap();
7929
7930 assert_eq!(r.stop_reason, McStopReason::MaxSamplesReached);
7931 assert_eq!(r.samples, 3_000);
7932 }
7933
7934 #[test]
7943 fn adaptive_stops_between_the_floor_and_the_ceiling() {
7944 let (inputs, wind) = seeded_test_fixture();
7945 let conv = McConvergence {
7946 level: ConfidenceLevel::P95,
7947 target_half_width: 0.03,
7948 min_samples: 0,
7949 max_samples: 10_000,
7950 batch_size: 100,
7951 };
7952 let r = run_monte_carlo_adaptive_seeded(
7953 &inputs,
7954 &wind,
7955 &loose_params(),
7956 &conv,
7957 DEFAULT_HIT_RADIUS_M,
7958 0x1352_5A1D,
7959 )
7960 .unwrap();
7961
7962 assert_eq!(r.stop_reason, McStopReason::TargetHalfWidthMet);
7963 assert!(r.samples > 0);
7964 assert!(
7965 r.samples.is_multiple_of(conv.batch_size),
7966 "samples {} is not a whole number of batches",
7967 r.samples
7968 );
7969 assert!(
7970 r.samples > conv.min_samples,
7971 "stopped on the floor, not on the data"
7972 );
7973 assert!(
7974 r.samples < conv.max_samples,
7975 "ran to the ceiling, so nothing adaptive was exercised"
7976 );
7977 assert!(
7978 r.samples > conv.batch_size,
7979 "stopped on the very first look ({} samples); the multi-batch path is untested",
7980 r.samples
7981 );
7982 assert!((r.ci_high - r.ci_low) / 2.0 <= 0.03 + 1e-12);
7983 assert!(r.ci_low <= r.hit_probability && r.hit_probability <= r.ci_high);
7984 assert_eq!(r.attempts, r.samples, "no trial should have been dropped");
7985 }
7986
7987 #[test]
7995 fn adaptive_runs_a_truncated_final_batch_up_to_max_samples() {
7996 let (inputs, wind) = seeded_test_fixture();
7997 let conv = McConvergence {
7998 level: ConfidenceLevel::P95,
7999 target_half_width: 1e-6,
8000 min_samples: 0,
8001 max_samples: 750,
8002 batch_size: 500,
8003 };
8004 let r = run_monte_carlo_adaptive_seeded(
8005 &inputs,
8006 &wind,
8007 &loose_params(),
8008 &conv,
8009 DEFAULT_HIT_RADIUS_M,
8010 0x1352_7B10,
8011 )
8012 .unwrap();
8013
8014 assert_eq!(r.stop_reason, McStopReason::MaxSamplesReached);
8015 assert_eq!(
8016 r.samples, 750,
8017 "the 250-trial final batch did not run, or was not truncated"
8018 );
8019 assert_eq!(r.attempts, 750);
8020 assert!(!r.samples.is_multiple_of(conv.batch_size));
8021 }
8022
8023 #[test]
8024 fn adaptive_is_deterministic_for_a_seed() {
8025 let (inputs, wind) = seeded_test_fixture();
8026 let conv = McConvergence::default();
8027 let a = run_monte_carlo_adaptive_seeded(
8028 &inputs,
8029 &wind,
8030 &loose_params(),
8031 &conv,
8032 DEFAULT_HIT_RADIUS_M,
8033 99,
8034 )
8035 .unwrap();
8036 let b = run_monte_carlo_adaptive_seeded(
8037 &inputs,
8038 &wind,
8039 &loose_params(),
8040 &conv,
8041 DEFAULT_HIT_RADIUS_M,
8042 99,
8043 )
8044 .unwrap();
8045
8046 assert_eq!(a.hit_probability.to_bits(), b.hit_probability.to_bits());
8047 assert_eq!(a.samples, b.samples);
8048 assert_eq!(a.ci_low.to_bits(), b.ci_low.to_bits());
8049 assert_eq!(a.ci_high.to_bits(), b.ci_high.to_bits());
8050 assert_eq!(
8053 a.mean_impact_velocity_mps.to_bits(),
8054 b.mean_impact_velocity_mps.to_bits()
8055 );
8056 assert_eq!(
8057 a.std_drop_at_target_m.to_bits(),
8058 b.std_drop_at_target_m.to_bits()
8059 );
8060 }
8061
8062 #[test]
8063 fn adaptive_report_carries_schema_method_and_all_four_assumptions() {
8064 let (inputs, wind) = seeded_test_fixture();
8065 let conv = McConvergence {
8069 min_samples: 0,
8070 max_samples: 50,
8071 batch_size: 50,
8072 target_half_width: 1.0,
8073 level: ConfidenceLevel::P90,
8074 };
8075 let r = run_monte_carlo_adaptive_seeded(
8076 &inputs,
8077 &wind,
8078 &mixed_arrival_params(),
8079 &conv,
8080 DEFAULT_HIT_RADIUS_M,
8081 0x1352_D0C5,
8082 )
8083 .unwrap();
8084
8085 assert_eq!(r.schema_version, MC_ADAPTIVE_SCHEMA_VERSION_V1);
8086 assert_eq!(r.schema_version, 1);
8087 assert_eq!(r.method, "anytime_beta_binomial_mixture_cs_v1");
8088 assert_eq!(r.confidence_percent, 90);
8089
8090 assert_eq!(r.attempts, 50, "one full batch was drawn");
8096 assert_eq!(r.samples, 50, "no trial was dropped by the solver");
8097 assert!(
8098 r.arrivals > 0 && r.arrivals < r.samples,
8099 "fixture must split the run: arrivals {} of samples {}",
8100 r.arrivals,
8101 r.samples
8102 );
8103 assert!(
8106 r.arrivals >= 2,
8107 "arrivals {} too few for a sample sd",
8108 r.arrivals
8109 );
8110 assert!(r.std_drop_at_target_m > 0.0 && r.std_impact_velocity_mps > 0.0);
8111 assert!(r.attempts >= r.samples && r.samples >= r.arrivals);
8113
8114 assert_eq!(r.assumptions.len(), 4, "exactly four assumptions expected");
8120 assert_eq!(
8121 r.assumptions[0],
8122 "Sampling uncertainty only: intervals cover Monte Carlo sampling error, not model error in the trajectory solver or its inputs."
8123 );
8124 assert_eq!(
8125 r.assumptions[1],
8126 "Anytime-valid stopping: the beta-binomial mixture confidence sequence keeps its coverage guarantee despite stopping the moment the target half-width is met."
8127 );
8128 assert_eq!(
8129 r.assumptions[2],
8130 "Input dispersions are the independent normal distributions declared in MonteCarloParams; correlations between inputs are not modeled."
8131 );
8132 assert_eq!(
8133 r.assumptions[3],
8134 "Continuous statistics are streaming Welford moments over trials that reached the target plane, reported with sample (n-1) standard deviations; hit probability's denominator includes all trials."
8135 );
8136
8137 assert_eq!(
8139 serde_json::to_string(&McStopReason::TargetHalfWidthMet).unwrap(),
8140 "\"target_half_width_met\""
8141 );
8142 assert_eq!(
8143 serde_json::to_string(&McStopReason::MaxSamplesReached).unwrap(),
8144 "\"max_samples_reached\""
8145 );
8146 }
8147
8148 #[test]
8149 fn adaptive_rejects_nonsense_convergence() {
8150 let (inputs, wind) = seeded_test_fixture();
8151 let run = |conv: McConvergence| {
8152 run_monte_carlo_adaptive_seeded(
8153 &inputs,
8154 &wind,
8155 &loose_params(),
8156 &conv,
8157 DEFAULT_HIT_RADIUS_M,
8158 1,
8159 )
8160 .unwrap_err()
8161 };
8162
8163 for bad_width in [0.0, -0.01, f64::NAN] {
8164 let err = run(McConvergence {
8165 target_half_width: bad_width,
8166 ..Default::default()
8167 });
8168 assert!(
8169 err.contains("target_half_width"),
8170 "error must name the field, got: {err}"
8171 );
8172 }
8173
8174 let err = run(McConvergence {
8175 batch_size: 0,
8176 ..Default::default()
8177 });
8178 assert!(err.contains("batch_size"), "got: {err}");
8179
8180 let err = run(McConvergence {
8181 min_samples: 5_000,
8182 max_samples: 1_000,
8183 ..Default::default()
8184 });
8185 assert!(err.contains("max_samples"), "got: {err}");
8186 assert!(err.contains("min_samples"), "got: {err}");
8187
8188 let err = run(McConvergence {
8189 max_samples: 0,
8190 min_samples: 0,
8191 ..Default::default()
8192 });
8193 assert!(err.contains("max_samples"), "got: {err}");
8194
8195 let err = McConvergence {
8197 batch_size: 0,
8198 ..Default::default()
8199 }
8200 .validate()
8201 .unwrap_err();
8202 assert!(err.contains("batch_size"));
8203 }
8204
8205 #[test]
8206 fn wilson_companion_matches_hit_probability_and_wilson_interval() {
8207 let (inputs, wind) = seeded_test_fixture();
8208 let params = MonteCarloParams {
8209 num_simulations: 128,
8210 target_distance: Some(500.0),
8211 ..MonteCarloParams::default()
8212 };
8213 let results = run_monte_carlo_with_wind_and_direction_std_dev_seeded(
8214 inputs,
8215 wind,
8216 params,
8217 0.01,
8218 0x1352_C0DE,
8219 )
8220 .expect("seeded legacy run");
8221
8222 for level in [
8223 ConfidenceLevel::P90,
8224 ConfidenceLevel::P95,
8225 ConfidenceLevel::P99,
8226 ] {
8227 let (p_hat, (lo, hi), n) = results.hit_probability_wilson(DEFAULT_HIT_RADIUS_M, level);
8228
8229 assert_eq!(
8232 p_hat.to_bits(),
8233 results.hit_probability(DEFAULT_HIT_RADIUS_M).to_bits()
8234 );
8235 assert_eq!(n, results.impact_positions.len() as u64);
8236
8237 let hits = results
8241 .impact_positions
8242 .iter()
8243 .filter(|p| MonteCarloResults::position_is_hit(p, DEFAULT_HIT_RADIUS_M))
8244 .count() as u64;
8245 let (want_lo, want_hi) = wilson_interval(hits, n, level);
8246 assert_eq!(lo.to_bits(), want_lo.to_bits());
8247 assert_eq!(hi.to_bits(), want_hi.to_bits());
8248 assert!(lo <= p_hat && p_hat <= hi, "interval excludes p_hat");
8249 }
8250
8251 let empty = MonteCarloResults {
8253 ranges: Vec::new(),
8254 impact_velocities: Vec::new(),
8255 impact_positions: Vec::new(),
8256 };
8257 assert_eq!(
8258 empty.hit_probability_wilson(DEFAULT_HIT_RADIUS_M, ConfidenceLevel::P95),
8259 (0.0, (0.0, 1.0), 0)
8260 );
8261 }
8262}
8263
8264#[cfg(test)]
8265mod monte_carlo_powder_curve_tests {
8266 use super::*;
8267 use rand::{rngs::StdRng, SeedableRng};
8268
8269 #[test]
8270 fn powder_curve_preserves_sampled_muzzle_velocity_dispersion() {
8271 let inputs = BallisticInputs {
8272 muzzle_velocity: 700.0,
8273 powder_temp_curve: Some(vec![(15.0, 800.0)]),
8274 powder_curve_temp_c: Some(15.0),
8275 ..BallisticInputs::default()
8276 };
8277 let params = MonteCarloParams {
8278 num_simulations: 16,
8279 velocity_std_dev: 20.0,
8280 angle_std_dev: 1e-12,
8281 bc_std_dev: 1e-12,
8282 wind_speed_std_dev: 1e-12,
8283 target_distance: Some(100.0),
8284 azimuth_std_dev: 1e-12,
8285 ..MonteCarloParams::default()
8286 };
8287
8288 let mut rng = StdRng::seed_from_u64(0x5EED_1176);
8289 let results = run_monte_carlo_with_wind_and_direction_std_dev_using_rng(
8290 inputs,
8291 WindConditions::default(),
8292 params,
8293 0.0,
8294 StationAtmospherePresence::NEITHER,
8295 &mut rng,
8296 )
8297 .expect("Monte Carlo solve");
8298 let min_velocity = results
8299 .impact_velocities
8300 .iter()
8301 .copied()
8302 .fold(f64::INFINITY, f64::min);
8303 let max_velocity = results
8304 .impact_velocities
8305 .iter()
8306 .copied()
8307 .fold(f64::NEG_INFINITY, f64::max);
8308
8309 assert!(
8310 max_velocity - min_velocity > 1.0,
8311 "20 m/s muzzle spread collapsed after curve resolution: impact-velocity span={} m/s",
8312 max_velocity - min_velocity
8313 );
8314 }
8315}
8316
8317#[cfg(test)]
8318mod monte_carlo_wind_sampling_tests {
8319 use super::*;
8320 use rand::{rngs::StdRng, SeedableRng};
8321
8322 #[test]
8323 fn wind_speed_sigma_does_not_change_seeded_direction_draws() {
8324 let base_wind = WindConditions {
8325 speed: 100.0,
8326 direction: 0.37,
8327 vertical_speed: 0.0,
8328 };
8329 let narrow_speed = MonteCarloWindSampler::new(&base_wind, 0.5, 0.2).unwrap();
8330 let wide_speed = MonteCarloWindSampler::new(&base_wind, 4.0, 0.2).unwrap();
8331 let mut narrow_rng = StdRng::seed_from_u64(0x5EED_1223);
8332 let mut wide_rng = StdRng::seed_from_u64(0x5EED_1223);
8333 let mut speed_changed = false;
8334
8335 for _ in 0..32 {
8336 let narrow = narrow_speed.sample(&mut narrow_rng);
8337 let wide = wide_speed.sample(&mut wide_rng);
8338 assert!(narrow.speed > 0.0 && wide.speed > 0.0);
8339 assert_eq!(narrow.direction.to_bits(), wide.direction.to_bits());
8340 speed_changed |= narrow.speed.to_bits() != wide.speed.to_bits();
8341 }
8342 assert!(
8343 speed_changed,
8344 "different speed sigmas must still vary speed draws"
8345 );
8346 }
8347
8348 #[test]
8349 fn zero_direction_sigma_has_no_angular_jitter() {
8350 let base_wind = WindConditions {
8351 speed: 100.0,
8352 direction: 0.37,
8353 vertical_speed: 0.0,
8354 };
8355 let sampler = MonteCarloWindSampler::new(&base_wind, 4.0, 0.0).unwrap();
8356 let mut rng = StdRng::seed_from_u64(0x5EED_1223);
8357 let mut speed_changed = false;
8358
8359 for _ in 0..32 {
8360 let wind = sampler.sample(&mut rng);
8361 speed_changed |= wind.speed.to_bits() != base_wind.speed.to_bits();
8362 assert_eq!(wind.direction.to_bits(), base_wind.direction.to_bits());
8363 }
8364 assert!(speed_changed, "speed uncertainty should remain active");
8365 }
8366
8367 #[test]
8368 fn direction_sigma_controls_seeded_angular_spread_in_radians() {
8369 let base_wind = WindConditions {
8370 speed: 100.0,
8371 direction: 0.37,
8372 vertical_speed: 0.0,
8373 };
8374 let narrow = MonteCarloWindSampler::new(&base_wind, 4.0, 0.1).unwrap();
8375 let wide = MonteCarloWindSampler::new(&base_wind, 4.0, 0.2).unwrap();
8376 let mut narrow_rng = StdRng::seed_from_u64(0x5EED_1223);
8377 let mut wide_rng = StdRng::seed_from_u64(0x5EED_1223);
8378 let mut nonzero_direction_draw = false;
8379
8380 for _ in 0..32 {
8381 let narrow_wind = narrow.sample(&mut narrow_rng);
8382 let wide_wind = wide.sample(&mut wide_rng);
8383 assert_eq!(narrow_wind.speed.to_bits(), wide_wind.speed.to_bits());
8384
8385 let narrow_delta = narrow_wind.direction - base_wind.direction;
8386 let wide_delta = wide_wind.direction - base_wind.direction;
8387 assert!((wide_delta - 2.0 * narrow_delta).abs() < 1e-12);
8388 nonzero_direction_draw |= narrow_delta.abs() > 1e-6;
8389 }
8390 assert!(
8391 nonzero_direction_draw,
8392 "positive radians sigma must vary direction"
8393 );
8394 }
8395
8396 #[test]
8397 fn direction_sigma_rejects_negative_or_nonfinite_values() {
8398 let base_wind = WindConditions::default();
8399 for sigma in [-0.1, f64::NAN, f64::INFINITY] {
8400 assert!(MonteCarloWindSampler::new(&base_wind, 1.0, sigma).is_err());
8401 }
8402 }
8403
8404 #[test]
8405 fn base_vertical_wind_rides_into_every_mc_sample() {
8406 use rand::SeedableRng;
8410 let base_wind = WindConditions {
8411 vertical_speed: 4.2,
8412 ..Default::default()
8413 };
8414 let sampler = MonteCarloWindSampler::new(&base_wind, 1.0, 0.2).unwrap();
8415 let mut rng = rand::rngs::StdRng::seed_from_u64(7);
8416 for _ in 0..32 {
8417 let w = sampler.sample(&mut rng);
8418 assert_eq!(w.vertical_speed, 4.2);
8419 }
8420 }
8421
8422 #[test]
8423 fn negative_speed_sample_reverses_wind_direction() {
8424 let direction = 0.25;
8425 let signed_speed = -2.5;
8426 let wind = wind_from_signed_speed_sample(signed_speed, direction, 0.0);
8427 let positive_wind = wind_from_signed_speed_sample(2.5, direction, 0.0);
8428
8429 assert_eq!(wind.speed, 2.5);
8430 assert!(
8431 (wind.direction - (direction + std::f64::consts::PI)).abs() < f64::EPSILON,
8432 "negative speed must reverse direction by pi: got {}",
8433 wind.direction
8434 );
8435 assert_eq!(positive_wind.speed, 2.5);
8436 assert_eq!(positive_wind.direction, direction);
8437
8438 let normalized_x = -wind.speed * wind.direction.cos();
8439 let normalized_z = -wind.speed * wind.direction.sin();
8440 let signed_x = -signed_speed * direction.cos();
8441 let signed_z = -signed_speed * direction.sin();
8442 assert!((normalized_x - signed_x).abs() < 1e-12);
8443 assert!((normalized_z - signed_z).abs() < 1e-12);
8444 }
8445}
8446
8447#[cfg(test)]
8448mod bc_fit_objective_tests {
8449 use super::*;
8450
8451 #[test]
8452 fn all_trials_refused_in_flight_preserve_the_atmosphere_cause() {
8453 let temperature = -273.1435;
8454 let error = estimate_bc_fit_with_station_presence(
8455 823.0,
8456 0.0109,
8457 0.00782,
8458 &[(800.0, 0.1), (900.0, 0.3)],
8459 DragModel::G7,
8460 BcFitMode::Drop,
8461 AtmosphericConditions {
8462 temperature,
8463 pressure: 0.0187,
8464 humidity: 0.0,
8465 ..Default::default()
8466 },
8467 Some(600.0),
8468 0.05,
8469 StationAtmospherePresence::BOTH,
8470 )
8471 .unwrap_err();
8472 let cause = error
8473 .atmosphere_error()
8474 .expect("the refused flight's cause");
8475 assert_eq!(cause.field(), "temperature_c");
8476 assert_eq!(cause.value().to_bits(), temperature.to_bits());
8477 assert_eq!(
8478 cause.reason(),
8479 crate::AtmosphereErrorReason::AirAloftBelowAbsoluteZero
8480 );
8481 }
8482
8483 fn velocity_point(range_m: f64, velocity_mps: f64) -> TrajectoryPoint {
8484 TrajectoryPoint {
8485 time: 0.0,
8486 position: Vector3::new(range_m, 0.0, 0.0),
8487 velocity_magnitude: velocity_mps,
8488 kinetic_energy: 0.0,
8489 drag_coefficient: None,
8490 }
8491 }
8492
8493 #[test]
8494 fn candidate_that_misses_an_observation_has_no_score() {
8495 let trajectory = vec![velocity_point(0.0, 800.0), velocity_point(100.0, 700.0)];
8496 let observations = vec![(50.0, 750.0), (150.0, 600.0)];
8497
8498 assert!(
8499 fit_residual_sse(&trajectory, &observations, BcFitMode::Velocity, 0.0).is_none(),
8500 "a candidate that reaches only one of two observations must not compete on partial SSE"
8501 );
8502
8503 let complete_observations = vec![(50.0, 740.0), (100.0, 680.0)];
8504 assert_eq!(
8505 fit_residual_sse(
8506 &trajectory,
8507 &complete_observations,
8508 BcFitMode::Velocity,
8509 0.0,
8510 ),
8511 Some(500.0)
8512 );
8513 }
8514}
8515
8516#[cfg(test)]
8517mod cluster_bc_reference_space_tests {
8518 use super::*;
8519
8520 fn acceleration_at_1100_fps(inputs: BallisticInputs) -> Vector3<f64> {
8521 let solver = TrajectorySolver::new(
8522 inputs,
8523 WindConditions::default(),
8524 AtmosphericConditions::default(),
8525 );
8526 let position = Vector3::zeros();
8527 let velocity = Vector3::new(1100.0 / 3.28084, 0.0, 0.0);
8528 let station = solver.station_air().unwrap();
8529 solver.calculate_acceleration(&position, &velocity, &Vector3::zeros(), &station)
8530 }
8531
8532 #[test]
8533 fn solver_passes_g7_reference_model_to_cluster_classifier() {
8534 let inputs = BallisticInputs {
8535 bc_value: 0.190,
8536 bc_type: DragModel::G7,
8537 bullet_mass: 77.0 * crate::constants::GRAINS_TO_KG,
8538 bullet_diameter: 0.224 * 0.0254,
8539 use_cluster_bc: true,
8540 ..BallisticInputs::default()
8541 };
8542
8543 let solver = TrajectorySolver::new(
8544 inputs,
8545 WindConditions::default(),
8546 AtmosphericConditions::default(),
8547 );
8548 let corrected = solver.apply_cluster_bc_correction(0.190, 2800.0);
8549
8550 assert!(
8551 (corrected / 0.190 - 1.004).abs() < 1e-12,
8552 "solver selected the wrong G7 cluster multiplier: {}",
8553 corrected / 0.190
8554 );
8555 }
8556
8557 #[test]
8558 fn velocity_bc_segments_are_not_cluster_corrected_twice() {
8559 let segmented_clustered = BallisticInputs {
8560 bc_value: 0.5,
8561 bc_type: DragModel::G7,
8562 use_bc_segments: true,
8563 bc_segments_data: Some(vec![
8564 crate::BCSegmentData {
8565 velocity_min: 0.0,
8566 velocity_max: 1_600.0,
8567 bc_value: 0.4,
8568 },
8569 crate::BCSegmentData {
8570 velocity_min: 1_600.0,
8571 velocity_max: 5_000.0,
8572 bc_value: 0.45,
8573 },
8574 ]),
8575 use_cluster_bc: true,
8576 ..BallisticInputs::default()
8577 };
8578 let mut segmented_only = segmented_clustered.clone();
8579 segmented_only.use_cluster_bc = false;
8580 let mut constant_clustered = segmented_clustered.clone();
8581 constant_clustered.bc_value = 0.4;
8582 constant_clustered.bc_segments_data = None;
8583
8584 let stacked = acceleration_at_1100_fps(segmented_clustered);
8585 let segment_only = acceleration_at_1100_fps(segmented_only);
8586 let cluster_only = acceleration_at_1100_fps(constant_clustered);
8587
8588 assert!(
8589 (stacked.x - segment_only.x).abs() < 1e-12,
8590 "segment BC already owns the velocity shape: stacked ax={} segment-only ax={}",
8591 stacked.x,
8592 segment_only.x
8593 );
8594 assert!(
8595 (cluster_only.x - segment_only.x).abs() > 1e-6,
8596 "cluster correction must remain active for a constant BC"
8597 );
8598 }
8599
8600 #[test]
8601 fn mach_bc_segments_are_not_cluster_corrected_twice() {
8602 let mach_segmented_clustered = BallisticInputs {
8603 bc_value: 0.5,
8604 bc_type: DragModel::G7,
8605 use_bc_segments: false,
8606 bc_segments: Some(vec![(0.5, 0.3), (1.5, 0.5)]),
8607 use_cluster_bc: true,
8608 ..BallisticInputs::default()
8609 };
8610 let mut mach_segmented_only = mach_segmented_clustered.clone();
8611 mach_segmented_only.use_cluster_bc = false;
8612
8613 let stacked = acceleration_at_1100_fps(mach_segmented_clustered);
8614 let segment_only = acceleration_at_1100_fps(mach_segmented_only);
8615
8616 assert!(
8617 (stacked.x - segment_only.x).abs() < 1e-12,
8618 "Mach segment BC already owns the velocity shape: stacked ax={} segment-only ax={}",
8619 stacked.x,
8620 segment_only.x
8621 );
8622 }
8623}
8624
8625#[cfg(test)]
8626mod velocity_bc_flag_tests {
8627 use super::*;
8628
8629 fn acceleration_at_600_mps(inputs: BallisticInputs) -> Vector3<f64> {
8630 let solver = TrajectorySolver::new(
8631 inputs,
8632 WindConditions::default(),
8633 AtmosphericConditions::default(),
8634 );
8635 let station = solver.station_air().unwrap();
8636 solver.calculate_acceleration(
8637 &Vector3::zeros(),
8638 &Vector3::new(600.0, 0.0, 0.0),
8639 &Vector3::zeros(),
8640 &station,
8641 )
8642 }
8643
8644 #[test]
8645 fn velocity_bc_data_requires_opt_in_in_trajectory_solver() {
8646 let scalar_inputs = BallisticInputs {
8647 bc_value: 0.5,
8648 bc_type: DragModel::G7,
8649 ..BallisticInputs::default()
8650 };
8651 let mut disabled_inputs = scalar_inputs.clone();
8652 disabled_inputs.bc_segments_data = Some(vec![crate::BCSegmentData {
8653 velocity_min: 0.0,
8654 velocity_max: 4_000.0,
8655 bc_value: 0.46,
8656 }]);
8657 disabled_inputs.use_bc_segments = false;
8658 let mut enabled_inputs = disabled_inputs.clone();
8659 enabled_inputs.use_bc_segments = true;
8660 let mut mach_only_inputs = scalar_inputs.clone();
8661 mach_only_inputs.bc_segments = Some(vec![(0.0, 0.4), (3.0, 0.4)]);
8662 let mut disabled_with_both = mach_only_inputs.clone();
8663 disabled_with_both.bc_segments_data = disabled_inputs.bc_segments_data.clone();
8664
8665 let scalar = acceleration_at_600_mps(scalar_inputs);
8666 let disabled = acceleration_at_600_mps(disabled_inputs);
8667 let enabled = acceleration_at_600_mps(enabled_inputs);
8668 let mach_only = acceleration_at_600_mps(mach_only_inputs);
8669 let disabled_with_both = acceleration_at_600_mps(disabled_with_both);
8670
8671 assert_eq!(
8672 disabled.x.to_bits(),
8673 scalar.x.to_bits(),
8674 "a populated velocity table must not change drag while use_bc_segments is false"
8675 );
8676 assert!(
8677 enabled.x < disabled.x - 1.0,
8678 "enabling the lower BC table must increase drag: disabled ax={} enabled ax={}",
8679 disabled.x,
8680 enabled.x
8681 );
8682 assert_eq!(
8683 disabled_with_both.x.to_bits(),
8684 mach_only.x.to_bits(),
8685 "disabling velocity data must fall through to an explicit Mach table"
8686 );
8687 }
8688}
8689
8690#[cfg(test)]
8691mod mach_bc_segment_tests {
8692 use super::*;
8693
8694 #[test]
8695 fn trajectory_solver_interpolates_explicit_mach_bc_segments() {
8696 let segmented_inputs = BallisticInputs {
8697 bc_value: 0.8,
8698 use_bc_segments: false,
8699 bc_segments: Some(vec![(1.0, 0.2), (2.0, 0.4)]),
8700 bc_segments_data: None,
8701 ..BallisticInputs::default()
8702 };
8703
8704 let mut expected_inputs = segmented_inputs.clone();
8705 expected_inputs.bc_value = 0.3;
8706 expected_inputs.bc_segments = None;
8707
8708 let atmosphere = AtmosphericConditions::default();
8709 let segmented_solver = TrajectorySolver::new(
8710 segmented_inputs,
8711 WindConditions::default(),
8712 atmosphere.clone(),
8713 );
8714 let expected_solver =
8715 TrajectorySolver::new(expected_inputs, WindConditions::default(), atmosphere);
8716 let position = Vector3::zeros();
8717 let (density, _, temp_c, pressure_hpa) = segmented_solver.resolved_atmosphere();
8718 let (_, local_speed_of_sound) = crate::atmosphere::get_local_atmosphere_humid(
8719 segmented_solver.atmosphere.altitude,
8720 segmented_solver.atmosphere.altitude,
8721 temp_c,
8722 pressure_hpa,
8723 density / 1.225,
8724 segmented_solver.atmosphere.humidity,
8725 );
8726 let velocity = Vector3::new(1.5 * local_speed_of_sound, 0.0, 0.0);
8727 let station = segmented_solver.station_air().unwrap();
8729
8730 let segmented_acceleration = segmented_solver.calculate_acceleration(
8731 &position,
8732 &velocity,
8733 &Vector3::zeros(),
8734 &station,
8735 );
8736 let expected_acceleration = expected_solver.calculate_acceleration(
8737 &position,
8738 &velocity,
8739 &Vector3::zeros(),
8740 &station,
8741 );
8742
8743 assert!(
8744 (segmented_acceleration.x - expected_acceleration.x).abs() < 1e-12,
8745 "Mach 1.5 must interpolate BC 0.3: segmented ax={} expected ax={}",
8746 segmented_acceleration.x,
8747 expected_acceleration.x
8748 );
8749 }
8750}
8751
8752#[cfg(test)]
8753mod custom_drag_table_validation_tests {
8754 use super::*;
8755
8756 #[test]
8757 fn solve_accepts_zero_bc_when_custom_table_present() {
8758 let inputs = BallisticInputs {
8759 bc_value: 0.0, bullet_mass: 0.0106,
8761 bullet_diameter: 0.00782,
8762 muzzle_velocity: 850.0,
8763 custom_drag_table: Some(crate::drag::DragTable::new(
8764 vec![0.5, 1.0, 2.0, 3.0],
8765 vec![0.23, 0.40, 0.30, 0.26],
8766 )),
8767 ..BallisticInputs::default()
8768 };
8769 let solver = TrajectorySolver::new(
8770 inputs,
8771 WindConditions::default(),
8772 AtmosphericConditions::default(),
8773 );
8774 assert!(solver.solve().is_ok());
8776 }
8777
8778 #[test]
8779 fn solve_still_requires_bc_without_table() {
8780 let inputs = BallisticInputs {
8781 bc_value: 0.0,
8782 bullet_mass: 0.0106,
8783 bullet_diameter: 0.00782,
8784 muzzle_velocity: 850.0,
8785 ..BallisticInputs::default()
8786 };
8787 let solver = TrajectorySolver::new(
8788 inputs,
8789 WindConditions::default(),
8790 AtmosphericConditions::default(),
8791 );
8792 assert!(solver.solve().is_err());
8793 }
8794}
8795
8796#[cfg(test)]
8798mod cd_scale_tests {
8799 use super::*;
8800
8801 fn deck() -> crate::drag::DragTable {
8802 crate::drag::DragTable::new(vec![0.5, 1.0, 2.0, 3.0], vec![0.23, 0.40, 0.30, 0.26])
8803 }
8804
8805 fn deck_inputs(cd_scale: f64) -> BallisticInputs {
8806 BallisticInputs {
8807 bullet_mass: 0.0106,
8808 bullet_diameter: 0.00782,
8809 muzzle_velocity: 850.0,
8810 custom_drag_table: Some(deck()),
8811 cd_scale,
8812 ..BallisticInputs::default()
8813 }
8814 }
8815
8816 #[test]
8817 fn default_cd_scale_is_one() {
8818 assert_eq!(BallisticInputs::default().cd_scale, 1.0);
8819 }
8820
8821 #[test]
8824 fn cd_scale_absent_is_byte_identical_to_explicit_one() {
8825 let omitted = BallisticInputs {
8826 bullet_mass: 0.0106,
8827 bullet_diameter: 0.00782,
8828 muzzle_velocity: 850.0,
8829 custom_drag_table: Some(deck()),
8830 ..BallisticInputs::default()
8831 };
8832 let explicit = BallisticInputs {
8833 cd_scale: 1.0,
8834 ..omitted.clone()
8835 };
8836
8837 let solver_omitted = TrajectorySolver::new(
8838 omitted,
8839 WindConditions::default(),
8840 AtmosphericConditions::default(),
8841 );
8842 let solver_explicit = TrajectorySolver::new(
8843 explicit,
8844 WindConditions::default(),
8845 AtmosphericConditions::default(),
8846 );
8847
8848 let cd_omitted = solver_omitted.calculate_drag_coefficient(700.0, 340.0);
8849 let cd_explicit = solver_explicit.calculate_drag_coefficient(700.0, 340.0);
8850 assert_eq!(
8851 cd_omitted.to_bits(),
8852 cd_explicit.to_bits(),
8853 "default cd_scale must be bit-identical to an explicit 1.0"
8854 );
8855
8856 let result = solver_omitted.solve();
8859 assert!(
8860 result.is_ok(),
8861 "existing custom-deck solves must pass unchanged"
8862 );
8863 }
8864
8865 #[test]
8867 fn cd_scale_multiplies_the_interpolated_cd_exactly() {
8868 let velocity = 700.0;
8869 let speed_of_sound = 340.0;
8870 let mach = velocity / speed_of_sound;
8871 let expected_unscaled = deck().interpolate(mach);
8872
8873 for &scale in &[0.90, 1.0, 1.10, 1.5] {
8874 let solver = TrajectorySolver::new(
8875 deck_inputs(scale),
8876 WindConditions::default(),
8877 AtmosphericConditions::default(),
8878 );
8879 let cd = solver.calculate_drag_coefficient(velocity, speed_of_sound);
8880 assert!(
8881 (cd - expected_unscaled * scale).abs() < 1e-12,
8882 "scale={scale}: cd={cd} expected={}",
8883 expected_unscaled * scale
8884 );
8885 }
8886 }
8887
8888 #[test]
8892 fn cd_scale_direction_on_cli_api_solver() {
8893 let solve = |scale: f64| {
8894 TrajectorySolver::new(
8895 deck_inputs(scale),
8896 WindConditions::default(),
8897 AtmosphericConditions::default(),
8898 )
8899 .solve()
8900 .expect("custom-deck solve should succeed")
8901 };
8902
8903 let baseline = solve(1.0);
8904 let scaled_up = solve(1.10);
8905 let scaled_down = solve(0.90);
8906
8907 assert!(
8908 scaled_up.impact_velocity < baseline.impact_velocity,
8909 "cd_scale=1.10 must increase drag -> lower impact velocity: base={} up={}",
8910 baseline.impact_velocity,
8911 scaled_up.impact_velocity
8912 );
8913 assert!(
8914 scaled_down.impact_velocity > baseline.impact_velocity,
8915 "cd_scale=0.90 must decrease drag -> higher impact velocity: base={} down={}",
8916 baseline.impact_velocity,
8917 scaled_down.impact_velocity
8918 );
8919 }
8920
8921 #[test]
8923 fn validate_for_solve_rejects_invalid_cd_scale() {
8924 for bad in [0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
8925 let solver = TrajectorySolver::new(
8926 deck_inputs(bad),
8927 WindConditions::default(),
8928 AtmosphericConditions::default(),
8929 );
8930 assert!(
8931 solver.solve().is_err(),
8932 "cd_scale={bad} must be rejected by validate_for_solve"
8933 );
8934 }
8935 }
8936
8937 #[test]
8944 fn validate_for_solve_rejects_invalid_cd_scale_without_a_custom_drag_table() {
8945 for bad in [0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
8946 let inputs = BallisticInputs {
8947 bc_value: 0.5,
8948 bc_type: crate::DragModel::G1,
8949 bullet_mass: 0.0106,
8950 bullet_diameter: 0.00782,
8951 muzzle_velocity: 850.0,
8952 cd_scale: bad,
8953 ..BallisticInputs::default()
8954 };
8955 assert!(
8956 inputs.custom_drag_table.is_none(),
8957 "precondition: no custom deck"
8958 );
8959 let solver = TrajectorySolver::new(
8960 inputs,
8961 WindConditions::default(),
8962 AtmosphericConditions::default(),
8963 );
8964 assert!(
8965 solver.solve().is_err(),
8966 "cd_scale={bad} must be rejected by validate_for_solve even without a custom \
8967 drag table"
8968 );
8969 }
8970 }
8971
8972 #[test]
8976 fn cd_scale_is_inert_without_a_custom_drag_table() {
8977 let make = |cd_scale: f64| BallisticInputs {
8978 bc_value: 0.5,
8979 bc_type: crate::DragModel::G1,
8980 bullet_mass: 0.0106,
8981 bullet_diameter: 0.00782,
8982 muzzle_velocity: 850.0,
8983 cd_scale,
8984 ..BallisticInputs::default()
8985 };
8986 let solver_neutral = TrajectorySolver::new(
8987 make(1.0),
8988 WindConditions::default(),
8989 AtmosphericConditions::default(),
8990 );
8991 let solver_far = TrajectorySolver::new(
8992 make(1.5),
8993 WindConditions::default(),
8994 AtmosphericConditions::default(),
8995 );
8996 let cd_neutral = solver_neutral.calculate_drag_coefficient(700.0, 340.0);
8997 let cd_far = solver_far.calculate_drag_coefficient(700.0, 340.0);
8998 assert_eq!(
8999 cd_neutral.to_bits(),
9000 cd_far.to_bits(),
9001 "cd_scale must not affect the G-model/BC drag path"
9002 );
9003 }
9004
9005 #[test]
9008 fn cd_scale_shifts_all_three_solver_paths_in_the_same_direction() {
9009 let cli_solve = |scale: f64| {
9011 TrajectorySolver::new(
9012 deck_inputs(scale),
9013 WindConditions::default(),
9014 AtmosphericConditions::default(),
9015 )
9016 .solve()
9017 .expect("cli_api custom-deck solve should succeed")
9018 };
9019 let cli_baseline = cli_solve(1.0);
9020 let cli_scaled = cli_solve(1.10);
9021 assert!(
9022 cli_scaled.impact_velocity < cli_baseline.impact_velocity,
9023 "cli_api: cd_scale=1.10 must lower impact velocity"
9024 );
9025
9026 let derivatives_accel_x = |scale: f64| {
9028 let inputs = deck_inputs(scale);
9029 crate::derivatives::compute_derivatives(
9030 nalgebra::Vector3::zeros(),
9031 nalgebra::Vector3::new(700.0, 0.0, 0.0),
9032 &inputs,
9033 nalgebra::Vector3::zeros(),
9034 &KernelAtmosphere::uniform(1.225, 340.0).unwrap(),
9035 inputs.bc_value,
9036 None,
9037 0.0,
9038 None,
9039 )[3]
9040 };
9041 let deriv_baseline = derivatives_accel_x(1.0);
9042 let deriv_scaled = derivatives_accel_x(1.10);
9043 assert!(
9044 deriv_scaled < deriv_baseline,
9045 "derivatives: cd_scale=1.10 must make x-acceleration more negative (more drag): \
9046 base={deriv_baseline} scaled={deriv_scaled}"
9047 );
9048
9049 let fast_final_speed = |scale: f64| {
9051 let inputs = deck_inputs(scale);
9052 let wind_sock = crate::wind::WindSock::new(vec![]);
9053 let params = crate::fast_trajectory::FastIntegrationParams {
9054 horiz: 500.0,
9055 vert: 0.0,
9056 initial_state: [0.0, 0.0, 0.0, 850.0, 0.0, 0.0],
9057 t_span: (0.0, 5.0),
9058 atmosphere: KernelAtmosphere::from_legacy_params(
9059 (0.0, 15.0, 1013.25, 1.0),
9060 crate::atmosphere::RelativeHumidity::DRY,
9061 )
9062 .unwrap(),
9063 atmo_sock: None,
9064 };
9065 let solution = crate::fast_trajectory::fast_integrate(&inputs, &wind_sock, params);
9066 assert!(
9067 solution.success,
9068 "fast_integrate must succeed for scale={scale}"
9069 );
9070 let last = solution.t.len() - 1;
9071 let (vx, vy, vz) = (
9072 solution.y[3][last],
9073 solution.y[4][last],
9074 solution.y[5][last],
9075 );
9076 (vx * vx + vy * vy + vz * vz).sqrt()
9077 };
9078 let fast_baseline = fast_final_speed(1.0);
9079 let fast_scaled = fast_final_speed(1.10);
9080 assert!(
9081 fast_scaled < fast_baseline,
9082 "fast_trajectory: cd_scale=1.10 must lower final speed: base={fast_baseline} scaled={fast_scaled}"
9083 );
9084 }
9085}
9086
9087#[cfg(test)]
9091mod custom_drag_reference_tests {
9092 use super::*;
9093
9094 fn g7_table() -> crate::drag::DragTable {
9096 crate::drag::DragTable::from_csv_str(include_str!("../data/g7.csv"))
9097 .expect("bundled table parses")
9098 }
9099
9100 fn g1_table() -> crate::drag::DragTable {
9102 crate::drag::DragTable::from_csv_str(include_str!("../data/g1.csv"))
9103 .expect("bundled table parses")
9104 }
9105
9106 fn laddered_inputs() -> BallisticInputs {
9110 BallisticInputs {
9111 bc_value: 0.243,
9112 bc_type: DragModel::G7,
9113 bullet_mass: 175.0 * crate::constants::GRAINS_TO_KG,
9114 bullet_diameter: 0.308 * 0.0254,
9115 weight_grains: 175.0,
9116 caliber_inches: 0.308,
9117 muzzle_velocity: 823.0,
9118 use_bc_segments: true,
9119 bc_segments_data: Some(vec![
9120 crate::BCSegmentData {
9121 velocity_min: 2400.0,
9122 velocity_max: 4000.0,
9123 bc_value: 0.260,
9124 },
9125 crate::BCSegmentData {
9126 velocity_min: 0.0,
9127 velocity_max: 2400.0,
9128 bc_value: 0.220,
9129 },
9130 ]),
9131 ..BallisticInputs::default()
9132 }
9133 }
9134
9135 fn reference(inputs: BallisticInputs) -> BallisticInputs {
9136 BallisticInputs {
9137 custom_drag_table: Some(g7_table()),
9138 custom_drag_reference: true,
9139 ..inputs
9140 }
9141 }
9142
9143 fn solve(inputs: BallisticInputs) -> TrajectoryResult {
9144 let mut solver = TrajectorySolver::new(
9145 inputs,
9146 WindConditions::default(),
9147 AtmosphericConditions::default(),
9148 );
9149 solver.set_max_range(800.0);
9150 solver.solve().expect("solve")
9151 }
9152
9153 #[test]
9154 fn default_is_the_projectiles_own_curve() {
9155 assert!(!BallisticInputs::default().custom_drag_reference);
9156 }
9157
9158 #[test]
9159 fn the_denominator_is_the_resolved_bc_for_a_reference_curve() {
9160 let own = BallisticInputs {
9161 custom_drag_table: Some(g7_table()),
9162 ..laddered_inputs()
9163 };
9164 let sd = own.sectional_density_lb_in2().expect("SD");
9165 assert_eq!(own.custom_drag_denominator(0.220), sd);
9166 let reference = reference(laddered_inputs());
9167 assert_eq!(reference.custom_drag_denominator(0.220), 0.220);
9168 assert_eq!(reference.custom_drag_denominator(0.260), 0.260);
9169 }
9170
9171 #[test]
9175 fn a_reference_curve_flies_a_ladder_exactly_as_the_builtin_model() {
9176 let builtin = solve(laddered_inputs());
9177 let table = solve(reference(laddered_inputs()));
9178 assert_eq!(table.points.len(), builtin.points.len());
9179 for (t, b) in table.points.iter().zip(&builtin.points) {
9180 assert_eq!(t.position, b.position);
9181 assert_eq!(
9182 t.velocity_magnitude.to_bits(),
9183 b.velocity_magnitude.to_bits()
9184 );
9185 }
9186
9187 let own_curve = solve(BallisticInputs {
9188 custom_drag_reference: false,
9189 ..reference(laddered_inputs())
9190 });
9191 assert!(
9192 (own_curve.impact_velocity - builtin.impact_velocity).abs() > 10.0,
9193 "the fixture must tell the readings apart: {} vs {}",
9194 own_curve.impact_velocity,
9195 builtin.impact_velocity
9196 );
9197 }
9198
9199 #[test]
9204 fn a_reference_curve_flies_the_table_not_bc_types_curve() {
9205 let table = solve(BallisticInputs {
9206 custom_drag_table: Some(g1_table()),
9207 custom_drag_reference: true,
9208 bc_type: DragModel::G7,
9209 ..laddered_inputs()
9210 });
9211 let builtin_g1 = solve(BallisticInputs {
9212 bc_type: DragModel::G1,
9213 ..laddered_inputs()
9214 });
9215 assert_eq!(table.points.len(), builtin_g1.points.len());
9216 for (t, b) in table.points.iter().zip(&builtin_g1.points) {
9217 assert_eq!(t.position, b.position);
9218 assert_eq!(
9219 t.velocity_magnitude.to_bits(),
9220 b.velocity_magnitude.to_bits()
9221 );
9222 }
9223
9224 let builtin_g7 = solve(laddered_inputs());
9225 assert!(
9226 (builtin_g1.impact_velocity - builtin_g7.impact_velocity).abs() > 50.0,
9227 "the fixture must tell the curves apart: G1 {} vs G7 {}",
9228 builtin_g1.impact_velocity,
9229 builtin_g7.impact_velocity
9230 );
9231 }
9232
9233 #[test]
9236 fn validate_for_solve_requires_a_bc_for_a_reference_curve() {
9237 for bad in [0.0, -0.1, f64::NAN, f64::INFINITY] {
9238 let inputs = BallisticInputs {
9239 bc_value: bad,
9240 ..reference(laddered_inputs())
9241 };
9242 let error = TrajectorySolver::new(
9243 inputs.clone(),
9244 WindConditions::default(),
9245 AtmosphericConditions::default(),
9246 )
9247 .solve()
9248 .expect_err("a reference curve needs a finite positive BC");
9249 assert!(error.to_string().contains("bc_value"), "{error}");
9250
9251 let own_curve = BallisticInputs {
9252 custom_drag_reference: false,
9253 use_bc_segments: false,
9254 bc_segments_data: None,
9255 ..inputs
9256 };
9257 assert!(
9258 TrajectorySolver::new(
9259 own_curve,
9260 WindConditions::default(),
9261 AtmosphericConditions::default(),
9262 )
9263 .solve()
9264 .is_ok(),
9265 "bc_value={bad} is still ignored by the own-curve reading"
9266 );
9267 }
9268 }
9269
9270 #[test]
9274 fn army_standard_metro_converts_a_reference_curves_bcs() {
9275 let asm = BallisticInputs {
9276 bc_reference_standard: BcReferenceStandard::ArmyStandardMetro,
9277 ..reference(laddered_inputs())
9278 };
9279 assert!(asm.bc_reference_standard_inert_warning().is_none());
9280 assert!(BallisticInputs {
9281 custom_drag_reference: false,
9282 ..asm.clone()
9283 }
9284 .bc_reference_standard_inert_warning()
9285 .is_some());
9286
9287 let converted = solve(asm);
9288 let builtin_asm = solve(BallisticInputs {
9289 bc_reference_standard: BcReferenceStandard::ArmyStandardMetro,
9290 ..laddered_inputs()
9291 });
9292 let icao = solve(reference(laddered_inputs()));
9293 assert_eq!(
9294 converted.impact_velocity.to_bits(),
9295 builtin_asm.impact_velocity.to_bits()
9296 );
9297 assert!(
9298 converted.impact_velocity < icao.impact_velocity,
9299 "the ASM BCs are smaller once converted, so the bullet must slow more: {} vs {}",
9300 converted.impact_velocity,
9301 icao.impact_velocity
9302 );
9303 }
9304
9305 #[test]
9308 fn the_reported_cd_is_the_projectiles_own() {
9309 let inputs = reference(laddered_inputs());
9310 let sd = inputs.sectional_density_lb_in2().expect("SD");
9311 let solver = TrajectorySolver::new(
9312 inputs,
9313 WindConditions::default(),
9314 AtmosphericConditions::default(),
9315 );
9316 let sos = 340.0;
9317 for (fps, band_bc) in [(2600.0, 0.260), (2200.0, 0.220)] {
9318 let velocity = fps / 3.28084;
9319 let expected = g7_table().interpolate(velocity / sos) * sd / band_bc;
9320 let reported = solver
9321 .effective_drag_coefficient(velocity, sos)
9322 .expect("mass and diameter are set");
9323 assert!(
9324 (reported - expected).abs() < 1e-12,
9325 "{fps} fps: reported {reported}, expected {expected}"
9326 );
9327 }
9328 }
9329}
9330
9331#[cfg(test)]
9332mod humid_local_mach_tests {
9333 use super::*;
9334
9335 fn solver_with_station_humidity(humidity_percent: f64) -> TrajectorySolver {
9336 let inputs = BallisticInputs {
9337 custom_drag_table: Some(crate::drag::DragTable::new(vec![0.5, 1.5], vec![0.1, 1.1])),
9338 ..BallisticInputs::default()
9339 };
9340 TrajectorySolver::new(
9341 inputs,
9342 WindConditions::default(),
9343 AtmosphericConditions {
9344 temperature: 30.0,
9345 pressure: 1013.25,
9346 humidity: humidity_percent,
9347 altitude: 0.0,
9348 },
9349 )
9350 }
9351
9352 fn acceleration(solver: &TrajectorySolver, base_ratio: f64) -> Vector3<f64> {
9353 let humidity =
9356 crate::atmosphere::RelativeHumidity::try_percent(solver.atmosphere.humidity).unwrap();
9357 let station = StationAir::with_density_ratio(
9358 solver.atmosphere.altitude,
9359 30.0,
9360 1013.25,
9361 base_ratio,
9362 humidity,
9363 )
9364 .unwrap();
9365 solver.calculate_acceleration(
9366 &Vector3::zeros(),
9367 &Vector3::new(350.0, 0.0, 0.0),
9368 &Vector3::zeros(),
9369 &station,
9370 )
9371 }
9372
9373 #[test]
9374 fn local_mach_uses_station_humidity_when_density_is_held_constant() {
9375 let dry = acceleration(&solver_with_station_humidity(0.0), 1.0);
9376 let humid = acceleration(&solver_with_station_humidity(100.0), 1.0);
9377
9378 assert!(
9379 humid.x > dry.x,
9380 "humid sound speed should lower Mach and drag on the rising test curve: dry ax={} humid ax={}",
9381 dry.x,
9382 humid.x
9383 );
9384 }
9385
9386 #[test]
9387 fn active_atmosphere_zone_uses_zone_humidity_instead_of_station_humidity() {
9388 let zone_humidity = 80.0;
9389 let zone_ratio =
9390 crate::atmosphere::calculate_air_density_cimp(30.0, 1013.25, zone_humidity) / 1.225;
9391 let station_solver = solver_with_station_humidity(zone_humidity);
9392 let mut zoned_solver = solver_with_station_humidity(0.0);
9393 zoned_solver.set_atmo_segments(vec![(30.0, 1013.25, zone_humidity, 1_000.0)]);
9394
9395 let station = acceleration(&station_solver, zone_ratio);
9396 let zoned = acceleration(&zoned_solver, zone_ratio);
9397
9398 assert!(
9399 (zoned - station).norm() < 1e-12,
9400 "active zone T/P/RH should override the station atmosphere: station={station:?} zoned={zoned:?}"
9401 );
9402 }
9403}
9404
9405#[cfg(test)]
9406mod inclined_atmosphere_frame_tests {
9407 use super::*;
9408
9409 fn expected_shot_frame_vector(level: Vector3<f64>, angle: f64) -> Vector3<f64> {
9410 let (sin_angle, cos_angle) = angle.sin_cos();
9411 Vector3::new(
9412 level.x * cos_angle + level.y * sin_angle,
9413 -level.x * sin_angle + level.y * cos_angle,
9414 level.z,
9415 )
9416 }
9417
9418 #[test]
9419 fn inclined_positions_at_same_world_altitude_have_same_solver_acceleration() {
9420 let angle = std::f64::consts::FRAC_PI_6;
9421 let inputs = BallisticInputs {
9422 shooting_angle: angle,
9423 ..BallisticInputs::default()
9424 };
9425 let atmosphere = AtmosphericConditions {
9426 altitude: 100.0,
9427 ..AtmosphericConditions::default()
9428 };
9429 let solver = TrajectorySolver::new(inputs, WindConditions::default(), atmosphere);
9430 let station = solver.station_air().unwrap();
9431 let velocity = Vector3::new(600.0, 0.0, 0.0);
9432 let along_slant = Vector3::new(1_000.0, 0.0, 0.0);
9433 let across_slant = Vector3::new(0.0, 500.0 / angle.cos(), 0.0);
9434
9435 let a = solver.calculate_acceleration(&along_slant, &velocity, &Vector3::zeros(), &station);
9436 let b =
9437 solver.calculate_acceleration(&across_slant, &velocity, &Vector3::zeros(), &station);
9438
9439 assert!(
9440 (a - b).norm() < 1e-10,
9441 "solver acceleration differs at equal world altitude: {a:?} vs {b:?}"
9442 );
9443 }
9444
9445 #[test]
9446 fn inclined_headwind_is_rotated_into_solver_frame() {
9447 let angle = std::f64::consts::FRAC_PI_6;
9448 let inputs = BallisticInputs {
9449 shooting_angle: angle,
9450 ..BallisticInputs::default()
9451 };
9452 let solver = TrajectorySolver::new(
9453 inputs,
9454 WindConditions::default(),
9455 AtmosphericConditions::default(),
9456 );
9457 let level_headwind = Vector3::new(-100.0, 0.0, 0.0);
9458 let velocity = expected_shot_frame_vector(level_headwind, angle);
9459 let station = solver.station_air().unwrap();
9460 let actual =
9461 solver.calculate_acceleration(&Vector3::zeros(), &velocity, &level_headwind, &station);
9462
9463 assert!(
9464 (actual - solver.gravity_acceleration()).norm() < 1e-12,
9465 "co-moving horizontal wind must leave only shot-frame gravity: {actual:?}"
9466 );
9467 }
9468
9469 #[test]
9470 fn inclined_coriolis_is_rotated_into_solver_frame() {
9471 let angle = std::f64::consts::FRAC_PI_6;
9472 let latitude_deg = 45.0_f64;
9473 let shot_azimuth = 0.4_f64;
9474 let velocity = Vector3::new(600.0, 20.0, 5.0);
9475 let base_inputs = BallisticInputs {
9476 shooting_angle: angle,
9477 latitude: Some(latitude_deg),
9478 shot_azimuth,
9479 ..BallisticInputs::default()
9480 };
9481 let acceleration = |enable_coriolis| {
9482 let mut inputs = base_inputs.clone();
9483 inputs.enable_coriolis = enable_coriolis;
9484 let solver = TrajectorySolver::new(
9485 inputs,
9486 WindConditions::default(),
9487 AtmosphericConditions::default(),
9488 );
9489 let station = solver.station_air().unwrap();
9490 solver.calculate_acceleration(&Vector3::zeros(), &velocity, &Vector3::zeros(), &station)
9491 };
9492
9493 let omega_earth = 7.2921159e-5_f64;
9494 let latitude = latitude_deg.to_radians();
9495 let level_omega = Vector3::new(
9496 omega_earth * latitude.cos() * shot_azimuth.cos(),
9497 omega_earth * latitude.sin(),
9498 -omega_earth * latitude.cos() * shot_azimuth.sin(),
9499 );
9500 let expected = -2.0 * expected_shot_frame_vector(level_omega, angle).cross(&velocity);
9501 let actual = acceleration(true) - acceleration(false);
9502
9503 assert!(
9504 (actual - expected).norm() < 1e-12,
9505 "inclined Coriolis mismatch: actual={actual:?}, expected={expected:?}"
9506 );
9507 }
9508}
9509
9510#[cfg(test)]
9511mod terminal_range_interpolation_tests {
9512 use super::*;
9513
9514 #[test]
9515 fn terminal_finalizer_selects_the_earliest_crossed_boundary() {
9516 let inputs = BallisticInputs {
9517 ground_threshold: 0.0,
9518 ..BallisticInputs::default()
9519 };
9520 let mut solver = TrajectorySolver::new(
9521 inputs,
9522 WindConditions::default(),
9523 AtmosphericConditions::default(),
9524 );
9525 solver.set_max_range(120.0);
9526
9527 let previous_speed = 700.0;
9528 let mut points = vec![TrajectoryPoint {
9529 time: 99.0,
9530 position: Vector3::new(90.0, 1.0, -1.0),
9531 velocity_magnitude: previous_speed,
9532 kinetic_energy: 0.5 * solver.inputs.bullet_mass * previous_speed.powi(2),
9533 drag_coefficient: None,
9534 }];
9535 let mut max_height = 1.0;
9536 let termination = solver
9537 .append_terminal_endpoint(
9538 &mut points,
9539 Vector3::new(130.0, -3.0, 3.0),
9540 Vector3::new(600.0, 0.0, 0.0),
9541 101.0,
9542 &mut max_height,
9543 &mut 0,
9544 )
9545 .expect("the final step brackets supported boundaries");
9546
9547 assert_eq!(termination, TrajectoryTermination::GroundThreshold);
9548 assert_eq!(points.len(), 2);
9549 let terminal = points.last().expect("terminal point");
9550 assert_eq!(terminal.time, 99.5);
9551 assert_eq!(terminal.position, Vector3::new(100.0, 0.0, 0.0));
9552 assert_eq!(terminal.velocity_magnitude, 675.0);
9553 assert_eq!(
9554 terminal.kinetic_energy,
9555 0.5 * solver.inputs.bullet_mass * 675.0_f64.powi(2)
9556 );
9557
9558 solver.set_max_range(100.0);
9560 let mut tied_points = vec![points[0].clone()];
9561 assert_eq!(
9562 solver
9563 .append_terminal_endpoint(
9564 &mut tied_points,
9565 Vector3::new(130.0, -3.0, 3.0),
9566 Vector3::new(600.0, 0.0, 0.0),
9567 101.0,
9568 &mut max_height,
9569 &mut 0,
9570 )
9571 .expect("tied boundaries remain a valid terminal"),
9572 TrajectoryTermination::GroundThreshold
9573 );
9574 }
9575
9576 #[test]
9577 fn sub_ulp_terminal_crossing_replaces_instead_of_duplicating_range() {
9578 let ground_threshold = f64::from_bits(1.0_f64.to_bits() - 1);
9579 let inputs = BallisticInputs {
9580 ground_threshold,
9581 ..BallisticInputs::default()
9582 };
9583 let mut solver = TrajectorySolver::new(
9584 inputs,
9585 WindConditions::default(),
9586 AtmosphericConditions::default(),
9587 );
9588 solver.set_max_range(1_000.0);
9589
9590 let speed = 700.0;
9591 let mut points = vec![TrajectoryPoint {
9592 time: 0.0,
9593 position: Vector3::new(100.0, 1.0, 0.0),
9594 velocity_magnitude: speed,
9595 kinetic_energy: 0.5 * solver.inputs.bullet_mass * speed.powi(2),
9596 drag_coefficient: None,
9597 }];
9598 let mut max_height = 1.0;
9599 let termination = solver
9600 .append_terminal_endpoint(
9601 &mut points,
9602 Vector3::new(101.0, 0.0, 0.0),
9603 Vector3::new(699.0, 0.0, 0.0),
9604 1.0,
9605 &mut max_height,
9606 &mut 0,
9607 )
9608 .expect("sub-ULP ground crossing remains representable as one terminal state");
9609
9610 assert_eq!(termination, TrajectoryTermination::GroundThreshold);
9611 assert_eq!(points.len(), 1);
9612 assert_eq!(points[0].position.x, 100.0);
9613 assert_eq!(points[0].position.y.to_bits(), ground_threshold.to_bits());
9614 assert!(points[0].time > 0.0);
9615 }
9616
9617 #[test]
9623 fn downrange_stall_replaces_instead_of_duplicating_range() {
9624 for (name, use_rk4, use_adaptive_rk45, bc_value) in [
9625 ("Euler", false, false, 2.0e-4),
9626 ("RK4", true, false, 1.0e-4),
9627 ("RK45", true, true, 1.0e-4),
9628 ] {
9629 let inputs = BallisticInputs {
9630 bc_value,
9631 bc_type: DragModel::G7,
9632 bullet_mass: 0.01134,
9633 bullet_diameter: 0.00782,
9634 muzzle_velocity: 823.0,
9635 use_rk4,
9636 use_adaptive_rk45,
9637 ground_threshold: -100.0,
9638 ..BallisticInputs::default()
9639 };
9640 let mut solver = TrajectorySolver::new(
9641 inputs,
9642 WindConditions::default(),
9643 AtmosphericConditions::default(),
9644 );
9645 solver.set_max_range(300.0);
9646 solver.set_time_step(0.001);
9647
9648 let result = solver
9649 .solve()
9650 .unwrap_or_else(|error| panic!("{name}: a stalled flight still solves: {error}"));
9651 assert!(
9652 result
9653 .points
9654 .windows(2)
9655 .all(|pair| pair[1].position.x > pair[0].position.x),
9656 "{name}: stored downrange distances must strictly increase"
9657 );
9658 assert_eq!(
9659 result.termination,
9660 TrajectoryTermination::GroundThreshold,
9661 "{name}"
9662 );
9663 assert!(
9664 result.max_range > 0.0 && result.max_range < 300.0,
9665 "{name}: the stall ends short of max_range, got {} m",
9666 result.max_range
9667 );
9668 let terminal = result.points.last().expect("terminal point");
9669 assert_eq!(terminal.position.y, -100.0, "{name}");
9670 result
9671 .sample_observations(50.0, 100)
9672 .unwrap_or_else(|error| panic!("{name}: checked sampling refused: {error}"));
9673 }
9674 }
9675
9676 #[test]
9677 fn every_solver_appends_an_exact_max_range_endpoint() {
9678 let target_range = 0.1;
9679 let modes = [
9680 ("Euler", false, false),
9681 ("RK4", true, false),
9682 ("RK45", true, true),
9683 ];
9684
9685 for (name, use_rk4, use_adaptive_rk45) in modes {
9686 let inputs = BallisticInputs {
9687 use_rk4,
9688 use_adaptive_rk45,
9689 ground_threshold: f64::NEG_INFINITY,
9690 enable_trajectory_sampling: true,
9691 sample_interval: target_range,
9692 ..BallisticInputs::default()
9693 };
9694 let mut solver = TrajectorySolver::new(
9695 inputs,
9696 WindConditions::default(),
9697 AtmosphericConditions::default(),
9698 );
9699 solver.set_max_range(target_range);
9700
9701 let result = solver.solve().expect("short-range solve should succeed");
9702 let terminal = result.points.last().expect("terminal point is missing");
9703 let muzzle = result.points.first().expect("muzzle point is missing");
9704
9705 assert_eq!(result.termination, TrajectoryTermination::MaxRange);
9706 assert_eq!(
9707 terminal.position.x.to_bits(),
9708 target_range.to_bits(),
9709 "{name} did not terminate exactly at max_range"
9710 );
9711 assert_eq!(result.max_range.to_bits(), target_range.to_bits());
9712 assert!(
9713 result.time_of_flight > 0.0 && result.time_of_flight < solver.time_step,
9714 "{name} terminal time was not interpolated within the crossing step: {}",
9715 result.time_of_flight
9716 );
9717 assert_eq!(result.time_of_flight.to_bits(), terminal.time.to_bits());
9718 assert_eq!(
9719 result.impact_velocity.to_bits(),
9720 terminal.velocity_magnitude.to_bits()
9721 );
9722 assert_eq!(
9723 result.impact_energy.to_bits(),
9724 terminal.kinetic_energy.to_bits()
9725 );
9726 let expected_energy = 0.5 * solver.inputs.bullet_mass * result.impact_velocity.powi(2);
9727 assert!((result.impact_energy - expected_energy).abs() < 1e-12);
9728 assert!(terminal.velocity_magnitude < muzzle.velocity_magnitude);
9729 assert!(terminal.kinetic_energy < muzzle.kinetic_energy);
9730
9731 let terminal_sample = result
9732 .sampled_points
9733 .as_ref()
9734 .and_then(|samples| samples.last())
9735 .expect("terminal trajectory sample is missing");
9736 assert_eq!(
9737 terminal_sample.distance_m.to_bits(),
9738 target_range.to_bits(),
9739 "{name} sampling did not include max_range"
9740 );
9741 assert_eq!(
9742 terminal_sample.time_s.to_bits(),
9743 result.time_of_flight.to_bits()
9744 );
9745 assert_eq!(
9746 terminal_sample.velocity_mps.to_bits(),
9747 result.impact_velocity.to_bits()
9748 );
9749 assert!((terminal_sample.energy_j - result.impact_energy).abs() < 1e-12);
9750 }
9751 }
9752}
9753
9754#[cfg(test)]
9755mod precession_inertia_wiring_tests {
9756 use super::*;
9757
9758 #[test]
9759 fn solver_uses_projectile_specific_moments_of_inertia() {
9760 let mass_kg = 55.0 * crate::constants::GRAINS_TO_KG;
9761 let caliber_m = 0.224 * 0.0254;
9762 let length_m = 0.75 * 0.0254;
9763 let inputs = BallisticInputs {
9764 bullet_mass: mass_kg,
9765 bullet_diameter: caliber_m,
9766 bullet_length: length_m,
9767 muzzle_velocity: 800.0,
9768 twist_rate: 7.0,
9769 enable_precession_nutation: true,
9770 use_rk4: false,
9771 use_adaptive_rk45: false,
9772 ..BallisticInputs::default()
9773 };
9774 let mut solver = TrajectorySolver::new(
9775 inputs,
9776 WindConditions::default(),
9777 AtmosphericConditions::default(),
9778 );
9779 solver.set_max_range(0.1);
9780
9781 let (air_density, speed_of_sound, _, _) = solver.resolved_atmosphere();
9782 let velocity_mps = solver.inputs.muzzle_velocity;
9783 let velocity_fps = velocity_mps * 3.28084;
9784 let twist_rate_ft = solver.inputs.twist_rate / 12.0;
9785 let spin_rate_rad_s = (velocity_fps / twist_rate_ft) * 2.0 * std::f64::consts::PI;
9786 let initial_state = AngularState {
9787 pitch_angle: 0.001,
9788 yaw_angle: 0.001,
9789 pitch_rate: 0.0,
9790 yaw_rate: 0.0,
9791 precession_angle: 0.0,
9792 nutation_phase: 0.0,
9793 };
9794 let params = PrecessionNutationParams {
9795 mass_kg,
9796 caliber_m,
9797 length_m,
9798 spin_rate_rad_s,
9799 spin_inertia: crate::spin_decay::calculate_moment_of_inertia(
9800 mass_kg, caliber_m, length_m, "ogive",
9801 ),
9802 transverse_inertia: crate::pitch_damping::calculate_transverse_moment_of_inertia(
9803 mass_kg, caliber_m, length_m, "ogive",
9804 ),
9805 velocity_mps,
9806 air_density_kg_m3: air_density,
9807 mach: velocity_mps / speed_of_sound,
9808 pitch_damping_coeff: PitchDampingCoefficients::default().subsonic,
9809 nutation_damping_factor: 0.05,
9810 };
9811 let expected = calculate_combined_angular_motion(
9812 ¶ms,
9813 &initial_state,
9814 0.0,
9815 solver.time_step,
9816 0.001,
9817 );
9818 let actual = solver
9819 .solve()
9820 .expect("one-step solve should succeed")
9821 .angular_state
9822 .expect("precession/nutation was enabled");
9823
9824 assert!(
9825 (actual.precession_angle - expected.precession_angle).abs() < 1e-15,
9826 "precession phase used the wrong inertia: actual={}, expected={}",
9827 actual.precession_angle,
9828 expected.precession_angle
9829 );
9830 assert!(
9831 (actual.nutation_phase - expected.nutation_phase).abs() < 1e-15,
9832 "nutation phase used the wrong inertia: actual={}, expected={}",
9833 actual.nutation_phase,
9834 expected.nutation_phase
9835 );
9836 }
9837}
9838
9839#[cfg(test)]
9840mod form_factor_drag_tests {
9841 use super::*;
9842
9843 fn acceleration_with_form_factor_flag(enabled: bool) -> Vector3<f64> {
9844 let inputs = BallisticInputs {
9845 bc_value: 0.462,
9846 bc_type: DragModel::G1,
9847 bullet_model: Some("168gr SMK Match".to_string()),
9848 use_form_factor: enabled,
9849 ..BallisticInputs::default()
9850 };
9851 let solver = TrajectorySolver::new(
9852 inputs,
9853 WindConditions::default(),
9854 AtmosphericConditions::default(),
9855 );
9856 let station = solver.station_air().unwrap();
9857 solver.calculate_acceleration(
9858 &Vector3::zeros(),
9859 &Vector3::new(600.0, 0.0, 0.0),
9860 &Vector3::zeros(),
9861 &station,
9862 )
9863 }
9864
9865 #[test]
9866 fn measured_bc_drag_does_not_apply_name_based_form_factor_again() {
9867 let baseline = acceleration_with_form_factor_flag(false);
9868 let flagged = acceleration_with_form_factor_flag(true);
9869
9870 assert!(
9871 (flagged - baseline).norm() < 1e-12,
9872 "published BC already encodes form factor: baseline={baseline:?} flagged={flagged:?}"
9873 );
9874 }
9875}
9876
9877#[cfg(test)]
9878mod rk45_adaptivity_tests {
9879 use super::*;
9880
9881 #[test]
9882 fn cli_rk45_error_norm_scales_components_independently() {
9883 let position = Vector3::new(1.0e9, 0.0, 0.0);
9884 let velocity = Vector3::new(800.0, 0.0, 0.0);
9885 let fifth_position = position;
9886 let fifth_velocity = velocity;
9887 let fourth_position = position;
9888 let fourth_velocity = Vector3::new(800.0, 1.0e-3, 0.0);
9889
9890 let error = cli_rk45_error_norm(
9891 &position,
9892 &velocity,
9893 &fifth_position,
9894 &fifth_velocity,
9895 &fourth_position,
9896 &fourth_velocity,
9897 );
9898 let expected = 1.0e-3 / 6.0_f64.sqrt();
9899
9900 assert!(
9901 (error - expected).abs() <= 1e-15,
9902 "large downrange position masked a velocity-component error: {error}"
9903 );
9904 }
9905
9906 fn discontinuous_wind_solver() -> TrajectorySolver {
9907 let inputs = BallisticInputs::default();
9908 let mut solver = TrajectorySolver::new(
9909 inputs,
9910 WindConditions::default(),
9911 AtmosphericConditions::default(),
9912 );
9913 solver.set_wind_segments(vec![
9914 crate::wind::WindSegment::new(0.0, 90.0, 4.0),
9915 crate::wind::WindSegment::new(1_000.0, 90.0, 10_000.0),
9916 ]);
9917 solver
9918 }
9919
9920 #[test]
9921 fn rk45_retries_discontinuous_trial_before_advancing() {
9922 let solver = discontinuous_wind_solver();
9923 let position = Vector3::new(0.0, solver.inputs.muzzle_height, 0.0);
9924 let velocity = Vector3::new(solver.inputs.muzzle_velocity, 0.0, 0.0);
9925 let station = solver.station_air().unwrap();
9926 let dt = 0.01;
9927
9928 let rejected_trial = solver.rk45_step(
9929 &position,
9930 &velocity,
9931 dt,
9932 &Vector3::zeros(),
9933 RK45_TOLERANCE,
9934 &station,
9935 );
9936 assert!(
9937 rejected_trial.error > RK45_TOLERANCE,
9938 "discontinuous full step must exceed tolerance, got {}",
9939 rejected_trial.error
9940 );
9941
9942 let accepted =
9943 solver.adaptive_rk45_step(&position, &velocity, dt, &Vector3::zeros(), &station);
9944 assert!(accepted.used_dt < dt, "oversized trial was not retried");
9945 assert!(
9946 accepted.error <= RK45_TOLERANCE || accepted.used_dt <= RK45_MIN_DT,
9947 "accepted error {} exceeds tolerance at dt {}",
9948 accepted.error,
9949 accepted.used_dt
9950 );
9951
9952 let accepted_trial = solver.rk45_step(
9953 &position,
9954 &velocity,
9955 accepted.used_dt,
9956 &Vector3::zeros(),
9957 RK45_TOLERANCE,
9958 &station,
9959 );
9960 assert_eq!(accepted.position, accepted_trial.position);
9961 assert_eq!(accepted.velocity, accepted_trial.velocity);
9962 assert!((RK45_MIN_DT..=RK45_MAX_DT).contains(&accepted.next_dt));
9963 }
9964}
9965
9966#[cfg(test)]
9967mod ground_termination_tests {
9968 use super::*;
9969 use crate::trajectory_observation::TrajectoryObservationFlag;
9970
9971 #[test]
9972 fn every_solver_reports_one_exact_early_ground_endpoint() {
9973 for (name, use_rk4, use_adaptive_rk45) in [
9974 ("Euler", false, false),
9975 ("RK4", true, false),
9976 ("RK45", true, true),
9977 ] {
9978 let inputs = BallisticInputs {
9979 muzzle_height: 1.0,
9980 muzzle_angle: -0.2,
9981 ground_threshold: 0.0,
9982 use_rk4,
9983 use_adaptive_rk45,
9984 ..BallisticInputs::default()
9985 };
9986 let mut solver = TrajectorySolver::new(
9987 inputs,
9988 WindConditions::default(),
9989 AtmosphericConditions::default(),
9990 );
9991 solver.set_max_range(1_000.0);
9992
9993 let result = solver.solve().expect("early-ground solve should succeed");
9994 let terminal = result.points.last().expect("terminal point is missing");
9995
9996 assert_eq!(result.termination, TrajectoryTermination::GroundThreshold);
9997 assert_eq!(terminal.position.y.to_bits(), 0.0_f64.to_bits());
9998 assert!(
9999 terminal.position.x < 1_000.0,
10000 "{name} incorrectly reached max range"
10001 );
10002 assert_eq!(result.max_range.to_bits(), terminal.position.x.to_bits());
10003 assert_eq!(
10004 result
10005 .points
10006 .iter()
10007 .filter(|point| point.position.y == 0.0)
10008 .count(),
10009 1,
10010 "{name} did not retain exactly one ground endpoint"
10011 );
10012
10013 let observations = result
10014 .sample_observations(1.0, 100)
10015 .expect("checked early-ground sampling should succeed");
10016 assert!(observations[..observations.len() - 1]
10017 .iter()
10018 .all(|observation| observation.distance_m < terminal.position.x));
10019 let terminal_observation = observations.last().expect("terminal observation");
10020 assert_eq!(
10021 terminal_observation.distance_m.to_bits(),
10022 terminal.position.x.to_bits()
10023 );
10024 assert!(terminal_observation
10025 .flags
10026 .contains(&TrajectoryObservationFlag::Terminal));
10027 assert!(terminal_observation
10028 .flags
10029 .contains(&TrajectoryObservationFlag::GroundThreshold));
10030 assert_eq!(
10031 observations
10032 .iter()
10033 .filter(|observation| observation
10034 .flags
10035 .contains(&TrajectoryObservationFlag::Terminal))
10036 .count(),
10037 1,
10038 "{name} repeated the terminal observation"
10039 );
10040 }
10041 }
10042
10043 #[test]
10048 fn rk4_and_rk45_descend_to_ground_threshold() {
10049 for adaptive in [false, true] {
10050 let inputs = BallisticInputs {
10051 muzzle_angle: 0.1, use_rk4: true,
10053 use_adaptive_rk45: adaptive,
10054 ..BallisticInputs::default()
10055 };
10056 assert_eq!(
10057 inputs.ground_threshold, -100.0,
10058 "default ground_threshold is -100 m"
10059 );
10060
10061 let mut solver = TrajectorySolver::new(
10062 inputs,
10063 WindConditions::default(),
10064 AtmosphericConditions::default(),
10065 );
10066 solver.set_max_range(1.0e7);
10068
10069 let result = solver.solve().expect("solve should succeed");
10070 let final_y = result
10071 .points
10072 .last()
10073 .expect("trajectory has points")
10074 .position
10075 .y;
10076 assert!(
10077 final_y < -1.0,
10078 "adaptive_rk45={adaptive}: final y = {final_y} m; a lofted shot should descend \
10079 past launch level toward the ground_threshold floor, not stop at y = 0"
10080 );
10081 }
10082 }
10083}
10084
10085#[cfg(test)]
10086mod magnus_stability_tests {
10087 use super::*;
10088
10089 #[test]
10090 fn yaw_of_repose_magnus_force_is_vertical_and_twist_signed() {
10091 let acceleration = |enable_magnus, is_twist_right| {
10092 let inputs = BallisticInputs {
10093 muzzle_velocity: 822.96,
10094 bullet_mass: 168.0 * crate::constants::GRAINS_TO_KG,
10095 bullet_diameter: 0.308 * 0.0254,
10096 bullet_length: 1.215 * 0.0254,
10097 twist_rate: 10.0,
10098 is_twist_right,
10099 enable_magnus,
10100 ..BallisticInputs::default()
10101 };
10102 let solver = TrajectorySolver::new(
10103 inputs,
10104 WindConditions::default(),
10105 AtmosphericConditions::default(),
10106 );
10107 let station = solver.station_air().unwrap();
10108 solver.calculate_acceleration(
10109 &Vector3::zeros(),
10110 &Vector3::new(822.96, 0.0, 0.0),
10111 &Vector3::zeros(),
10112 &station,
10113 )
10114 };
10115
10116 let baseline = acceleration(false, true);
10117 let right_twist = acceleration(true, true) - baseline;
10118 let left_twist = acceleration(true, false) - baseline;
10119
10120 assert!(
10121 right_twist.y < 0.0,
10122 "right-hand Magnus must point down, got {right_twist:?}"
10123 );
10124 assert!(
10125 left_twist.y > 0.0,
10126 "left-hand Magnus must point up, got {left_twist:?}"
10127 );
10128 assert!((right_twist.y + left_twist.y).abs() < 1e-12);
10129 assert!(right_twist.x.abs() < 1e-12 && right_twist.z.abs() < 1e-12);
10130 assert!(left_twist.x.abs() < 1e-12 && left_twist.z.abs() < 1e-12);
10131 }
10132
10133 #[test]
10134 fn magnus_uses_velocity_corrected_muzzle_stability_gate() {
10135 let muzzle_velocity = 1_400.0 / 3.28084;
10136 let inputs = BallisticInputs {
10137 muzzle_velocity,
10138 bullet_mass: 168.0 * crate::constants::GRAINS_TO_KG,
10139 bullet_diameter: 0.308 * 0.0254,
10140 bullet_length: 1.215 * 0.0254,
10141 twist_rate: 15.0,
10142 enable_magnus: true,
10143 ..BallisticInputs::default()
10144 };
10145 let solver = TrajectorySolver::new(
10146 inputs.clone(),
10147 WindConditions::default(),
10148 AtmosphericConditions::default(),
10149 );
10150
10151 let bare_sg = crate::spin_drift::miller_stability(0.308, 168.0, 15.0, 1.215);
10152 let canonical_sg = solver.effective_spin_drift_sg();
10153 assert!(bare_sg > 1.0, "test requires bare Sg above the Magnus gate");
10154 assert!(
10155 canonical_sg < 1.0,
10156 "velocity-corrected Sg must be below the gate, got {canonical_sg}"
10157 );
10158
10159 let station = solver.station_air().unwrap();
10160 let acceleration = solver.calculate_acceleration(
10161 &Vector3::zeros(),
10162 &Vector3::new(muzzle_velocity, 0.0, 0.0),
10163 &Vector3::zeros(),
10164 &station,
10165 );
10166 let mut baseline_inputs = inputs;
10167 baseline_inputs.enable_magnus = false;
10168 let baseline_solver = TrajectorySolver::new(
10169 baseline_inputs,
10170 WindConditions::default(),
10171 AtmosphericConditions::default(),
10172 );
10173 let baseline = baseline_solver.calculate_acceleration(
10174 &Vector3::zeros(),
10175 &Vector3::new(muzzle_velocity, 0.0, 0.0),
10176 &Vector3::zeros(),
10177 &station,
10178 );
10179
10180 assert_eq!(
10181 acceleration, baseline,
10182 "canonical Sg below 1 must suppress every Magnus acceleration component"
10183 );
10184 }
10185
10186 #[test]
10187 fn magnus_force_grows_as_fixed_spin_projectile_slows() {
10188 let inputs = BallisticInputs {
10189 muzzle_velocity: 800.0,
10190 bullet_mass: 168.0 * crate::constants::GRAINS_TO_KG,
10191 bullet_diameter: 0.308 * 0.0254,
10192 bullet_length: 1.215 * 0.0254,
10193 twist_rate: 12.0,
10194 enable_magnus: true,
10195 ..BallisticInputs::default()
10196 };
10197
10198 let magnus_acceleration = |speed_mps| {
10199 let evaluate = |enable_magnus| {
10200 let mut run_inputs = inputs.clone();
10201 run_inputs.enable_magnus = enable_magnus;
10202 let solver = TrajectorySolver::new(
10203 run_inputs,
10204 WindConditions::default(),
10205 AtmosphericConditions::default(),
10206 );
10207 let station = solver.station_air().unwrap();
10208 solver
10209 .calculate_acceleration(
10210 &Vector3::zeros(),
10211 &Vector3::new(speed_mps, 0.0, 0.0),
10212 &Vector3::zeros(),
10213 &station,
10214 )
10215 .y
10216 };
10217 (evaluate(true) - evaluate(false)).abs()
10218 };
10219
10220 let fast = magnus_acceleration(200.0);
10221 let slow = magnus_acceleration(100.0);
10222 let ratio = slow / fast;
10223 let expected_ratio = 2.0_f64.powf(5.0 / 3.0);
10224
10225 assert!(fast > 0.0 && slow > 0.0, "fast={fast}, slow={slow}");
10226 assert!(
10227 (ratio - expected_ratio).abs() < 1e-3,
10228 "fixed-spin Magnus acceleration must grow downrange; slow/fast={ratio}, \
10229 expected={expected_ratio}"
10230 );
10231 }
10232}
10233
10234#[cfg(test)]
10235mod coriolis_direction_tests {
10236 use super::*;
10237 use std::f64::consts::FRAC_PI_2;
10238
10239 #[test]
10240 fn supersonic_crossing_flags_a_positive_range_sample() {
10241 use crate::trajectory_sampling::TrajectoryFlag;
10245
10246 for (solver_name, use_rk4, use_adaptive_rk45) in [
10247 ("Euler", false, false),
10248 ("RK4", true, false),
10249 ("RK45", true, true),
10250 ] {
10251 let inputs = BallisticInputs {
10252 muzzle_velocity: 850.0,
10253 bc_value: 0.2,
10254 bc_type: DragModel::G7,
10255 muzzle_angle: 0.03,
10256 enable_trajectory_sampling: true,
10257 sample_interval: 50.0,
10258 use_rk4,
10259 use_adaptive_rk45,
10260 ..BallisticInputs::default()
10261 };
10262 let mut solver = TrajectorySolver::new(
10263 inputs,
10264 WindConditions::default(),
10265 AtmosphericConditions::default(),
10266 );
10267 solver.set_max_range(2000.0);
10268 let samples = solver
10269 .solve()
10270 .expect("supersonic solve should succeed")
10271 .sampled_points
10272 .expect("sampling was enabled");
10273 let flagged_distances: Vec<_> = samples
10274 .iter()
10275 .filter(|sample| sample.flags.contains(&TrajectoryFlag::MachTransition))
10276 .map(|sample| sample.distance_m)
10277 .collect();
10278
10279 assert!(
10280 !flagged_distances.is_empty()
10281 && flagged_distances.iter().all(|distance| *distance > 0.0),
10282 "{solver_name} must flag genuine crossings only at positive range: {flagged_distances:?}"
10283 );
10284 }
10285 }
10286
10287 #[test]
10288 fn subsonic_launch_does_not_flag_a_muzzle_transition() {
10289 use crate::trajectory_sampling::TrajectoryFlag;
10290
10291 for (solver_name, use_rk4, use_adaptive_rk45) in [
10292 ("Euler", false, false),
10293 ("RK4", true, false),
10294 ("RK45", true, true),
10295 ] {
10296 let inputs = BallisticInputs {
10297 muzzle_velocity: 250.0,
10298 muzzle_angle: 0.02,
10299 enable_trajectory_sampling: true,
10300 sample_interval: 25.0,
10301 use_rk4,
10302 use_adaptive_rk45,
10303 ..BallisticInputs::default()
10304 };
10305 let mut solver = TrajectorySolver::new(
10306 inputs,
10307 WindConditions::default(),
10308 AtmosphericConditions::default(),
10309 );
10310 solver.set_max_range(300.0);
10311 let samples = solver
10312 .solve()
10313 .expect("subsonic solve should succeed")
10314 .sampled_points
10315 .expect("sampling was enabled");
10316
10317 assert!(
10318 samples
10319 .iter()
10320 .all(|sample| !sample.flags.contains(&TrajectoryFlag::MachTransition)),
10321 "{solver_name} marked a Mach transition for a launch already below Mach 1"
10322 );
10323 }
10324 }
10325
10326 #[test]
10327 fn mach_transition_tracker_requires_a_downward_crossing() {
10328 fn record(mach_values: &[f64]) -> Vec<f64> {
10329 let mut tracker = MachTransitionTracker::default();
10330 let mut distances = Vec::new();
10331 for (index, mach) in mach_values.iter().copied().enumerate() {
10332 tracker.record_downward_crossings(mach, index as f64 * 10.0, &mut distances);
10333 }
10334 distances
10335 }
10336
10337 assert!(record(&[0.9, 0.8, 0.7]).is_empty());
10338 assert_eq!(record(&[1.1, 1.05, 0.99]), vec![20.0]);
10339 assert_eq!(record(&[1.2, 1.19, 1.0, 0.99]), vec![10.0, 30.0]);
10340 assert_eq!(record(&[0.9, 1.3, 1.1, 0.9, 1.3, 0.8]), vec![20.0, 30.0]);
10341 assert!(record(&[1.3, f64::NAN, 1.1]).is_empty());
10342 }
10343
10344 #[test]
10345 fn mach_transition_tracker_labels_0_9_without_touching_the_flat_vec() {
10346 fn record(mach_values: &[f64]) -> (Vec<f64>, MachTransitionTracker) {
10352 let mut tracker = MachTransitionTracker::default();
10353 let mut distances = Vec::new();
10354 for (index, mach) in mach_values.iter().copied().enumerate() {
10355 tracker.record_downward_crossings(mach, index as f64 * 10.0, &mut distances);
10356 }
10357 (distances, tracker)
10358 }
10359
10360 let (distances, tracker) = record(&[0.9, 0.8, 0.7]);
10363 assert!(distances.is_empty()); assert_eq!(tracker.mach_1_2_distance_m, None);
10365 assert_eq!(tracker.mach_1_0_distance_m, None);
10366 assert_eq!(tracker.mach_0_9_distance_m, Some(10.0));
10367
10368 let (distances, tracker) = record(&[1.1, 1.05, 0.99]);
10370 assert_eq!(distances, vec![20.0]);
10371 assert_eq!(tracker.mach_1_2_distance_m, None);
10372 assert_eq!(tracker.mach_1_0_distance_m, Some(20.0));
10373 assert_eq!(tracker.mach_0_9_distance_m, None);
10374
10375 let (distances, tracker) = record(&[1.2, 1.19, 1.0, 0.99]);
10377 assert_eq!(distances, vec![10.0, 30.0]); assert_eq!(tracker.mach_1_2_distance_m, Some(10.0));
10379 assert_eq!(tracker.mach_1_0_distance_m, Some(30.0));
10380 assert_eq!(tracker.mach_0_9_distance_m, None);
10381
10382 let (distances, tracker) = record(&[0.9, 1.3, 1.1, 0.9, 1.3, 0.8]);
10385 assert_eq!(distances, vec![20.0, 30.0]); assert_eq!(tracker.mach_1_2_distance_m, Some(20.0));
10387 assert_eq!(tracker.mach_1_0_distance_m, Some(30.0));
10388 assert_eq!(tracker.mach_0_9_distance_m, Some(50.0));
10389 assert!(
10390 tracker.mach_1_2_distance_m < tracker.mach_1_0_distance_m
10391 && tracker.mach_1_0_distance_m < tracker.mach_0_9_distance_m,
10392 "labeled crossings must be strictly increasing downrange"
10393 );
10394
10395 let (distances, tracker) = record(&[1.3, f64::NAN, 1.1]);
10397 assert!(distances.is_empty());
10398 assert_eq!(tracker.mach_1_2_distance_m, None);
10399 assert_eq!(tracker.mach_1_0_distance_m, None);
10400 assert_eq!(tracker.mach_0_9_distance_m, None);
10401 }
10402
10403 #[test]
10404 fn humidity_percent_is_a_percent_field_that_relative_humidity_validates_never_clamps() {
10405 let inputs = BallisticInputs::default();
10410 assert_eq!(
10411 inputs.humidity_percent.to_bits(),
10412 DEFAULT_HUMIDITY_PERCENT.to_bits()
10413 );
10414 assert_eq!(
10415 inputs.humidity_percent.to_bits(),
10416 AtmosphericConditions::default().humidity.to_bits()
10417 );
10418 for percent in [0.0, 7.0, 50.0, 55.0, 100.0] {
10419 let validated = crate::RelativeHumidity::try_percent(percent).expect("in range");
10420 assert_eq!(validated.percent().to_bits(), percent.to_bits());
10421 }
10422 for percent in [150.0, -5.000_000_1, 105.000_000_1, f64::NAN, f64::INFINITY] {
10423 assert!(
10424 crate::RelativeHumidity::try_percent(percent).is_err(),
10425 "{percent} must be refused, not clamped"
10426 );
10427 }
10428 for (percent, end) in [(-5.0, 0.0), (100.0001, 100.0)] {
10430 assert_eq!(
10431 crate::RelativeHumidity::try_percent(percent)
10432 .expect("a reading in the band")
10433 .percent()
10434 .to_bits(),
10435 f64::to_bits(end),
10436 "{percent}"
10437 );
10438 }
10439 }
10440
10441 fn vertical_at(shot_azimuth: f64, range_m: f64) -> f64 {
10444 let inputs = BallisticInputs {
10445 muzzle_velocity: 800.0,
10446 bc_value: 0.5,
10447 bc_type: DragModel::G7,
10448 muzzle_angle: 0.02, enable_coriolis: true,
10450 latitude: Some(45.0),
10451 shot_azimuth,
10452 ground_threshold: f64::NEG_INFINITY, ..BallisticInputs::default()
10454 };
10455 let mut solver = TrajectorySolver::new(
10456 inputs,
10457 WindConditions::default(),
10458 AtmosphericConditions::default(),
10459 );
10460 solver.set_max_range(range_m + 50.0);
10461 let r = solver.solve().expect("solve");
10462 let pts = &r.points;
10463 for i in 1..pts.len() {
10464 if pts[i].position.x >= range_m {
10465 let p1 = &pts[i - 1];
10466 let p2 = &pts[i];
10467 let t = (range_m - p1.position.x) / (p2.position.x - p1.position.x);
10468 return p1.position.y + t * (p2.position.y - p1.position.y);
10469 }
10470 }
10471 panic!("range {range_m} not reached");
10472 }
10473
10474 #[test]
10479 fn eotvos_east_higher_than_west() {
10480 let range = 600.0;
10481 let east = vertical_at(FRAC_PI_2, range); let west = vertical_at(3.0 * FRAC_PI_2, range); let north = vertical_at(0.0, range); assert!(
10485 east > west,
10486 "east ({east:.5}) must be higher than west ({west:.5}) at {range} m (Eötvös)"
10487 );
10488 assert!(
10489 east > north && north > west,
10490 "north ({north:.5}) must lie between east ({east:.5}) and west ({west:.5})"
10491 );
10492 assert!(
10493 (east - west) > 1e-3,
10494 "E-W vertical separation ({:.6} m) should be physically meaningful, not FP noise",
10495 east - west
10496 );
10497 }
10498
10499 #[test]
10507 fn labeled_mach_crossings_match_pinned_pre_change_flat_vec_across_solvers() {
10508 let cases = [
10517 (
10518 "Euler",
10519 false,
10520 false,
10521 670.9870968186207_f64,
10522 805.5261199258687_f64,
10523 ),
10524 (
10525 "RK4",
10526 true,
10527 false,
10528 671.7249603175201_f64,
10529 805.9321158082175_f64,
10530 ),
10531 (
10532 "RK45",
10533 true,
10534 true,
10535 672.4897951903022_f64,
10536 806.5696791258861_f64,
10537 ),
10538 ];
10539
10540 for (solver_name, use_rk4, use_adaptive_rk45, expected_1_2, expected_1_0) in cases {
10541 let inputs = BallisticInputs {
10542 muzzle_velocity: 850.0,
10543 bc_value: 0.2,
10544 bc_type: DragModel::G7,
10545 muzzle_angle: 0.03,
10546 use_rk4,
10547 use_adaptive_rk45,
10548 ..BallisticInputs::default()
10549 };
10550 let mut solver = TrajectorySolver::new(
10551 inputs,
10552 WindConditions::default(),
10553 AtmosphericConditions::default(),
10554 );
10555 solver.set_max_range(2000.0);
10556 let result = solver.solve().expect("solve should succeed");
10557
10558 assert_eq!(
10559 result.mach_1_2_distance_m,
10560 Some(expected_1_2),
10561 "{solver_name}: mach_1_2_distance_m must match its pin (the pre-change flat-Vec \
10562 capture, re-captured for 0.50.0's aloft vapour model)"
10563 );
10564 assert_eq!(
10565 result.mach_1_0_distance_m,
10566 Some(expected_1_0),
10567 "{solver_name}: mach_1_0_distance_m must match its pin (the pre-change flat-Vec \
10568 capture, re-captured for 0.50.0's aloft vapour model)"
10569 );
10570
10571 let mach_1_2 = result.mach_1_2_distance_m.expect("crosses 1.2");
10572 let mach_1_0 = result.mach_1_0_distance_m.expect("crosses 1.0");
10573 let mach_0_9 = result
10574 .mach_0_9_distance_m
10575 .expect("this trajectory also goes past 0.9 within 2000 m");
10576 assert!(
10577 mach_1_2 < mach_1_0 && mach_1_0 < mach_0_9,
10578 "{solver_name}: labeled crossings must be strictly increasing downrange \
10579 (1.2={mach_1_2}, 1.0={mach_1_0}, 0.9={mach_0_9})"
10580 );
10581 }
10582 }
10583
10584 #[test]
10587 fn labeled_mach_crossings_are_none_for_a_fully_supersonic_trajectory() {
10588 for (solver_name, use_rk4, use_adaptive_rk45) in [
10589 ("Euler", false, false),
10590 ("RK4", true, false),
10591 ("RK45", true, true),
10592 ] {
10593 let inputs = BallisticInputs {
10594 muzzle_velocity: 850.0,
10595 bc_value: 0.2,
10596 bc_type: DragModel::G7,
10597 muzzle_angle: 0.03,
10598 use_rk4,
10599 use_adaptive_rk45,
10600 ..BallisticInputs::default()
10601 };
10602 let mut solver = TrajectorySolver::new(
10603 inputs,
10604 WindConditions::default(),
10605 AtmosphericConditions::default(),
10606 );
10607 solver.set_max_range(200.0);
10609 let result = solver.solve().expect("solve should succeed");
10610
10611 assert_eq!(
10612 result.mach_1_2_distance_m, None,
10613 "{solver_name}: must not report a 1.2 crossing that never happens"
10614 );
10615 assert_eq!(
10616 result.mach_1_0_distance_m, None,
10617 "{solver_name}: must not report a 1.0 crossing that never happens"
10618 );
10619 assert_eq!(
10620 result.mach_0_9_distance_m, None,
10621 "{solver_name}: must not report a 0.9 crossing that never happens"
10622 );
10623 }
10624 }
10625}
10626
10627#[cfg(test)]
10628mod cant_tests {
10629 use super::*;
10630
10631 fn base_inputs() -> BallisticInputs {
10632 BallisticInputs {
10633 muzzle_velocity: 800.0,
10634 bc_value: 0.5,
10635 bc_type: DragModel::G7,
10636 bullet_mass: 0.0109,
10637 bullet_diameter: 0.00782,
10638 bullet_length: 0.0309,
10639 sight_height: 0.05,
10640 twist_rate: 10.0,
10641 use_rk4: true,
10642 ..BallisticInputs::default()
10643 }
10644 }
10645
10646 fn solve_with(inputs: BallisticInputs, max_range: f64) -> TrajectoryResult {
10647 let mut s = TrajectorySolver::new(
10648 inputs,
10649 WindConditions::default(),
10650 AtmosphericConditions::default(),
10651 );
10652 s.set_max_range(max_range);
10653 s.solve().expect("solve")
10654 }
10655
10656 fn yz_at(result: &TrajectoryResult, x: f64) -> (f64, f64) {
10658 let pts = &result.points;
10659 for i in 1..pts.len() {
10660 if pts[i].position.x >= x {
10661 let (p1, p2) = (&pts[i - 1], &pts[i]);
10662 let dx = p2.position.x - p1.position.x;
10663 let t = if dx.abs() < 1e-12 {
10664 0.0
10665 } else {
10666 (x - p1.position.x) / dx
10667 };
10668 return (
10669 p1.position.y + t * (p2.position.y - p1.position.y),
10670 p1.position.z + t * (p2.position.z - p1.position.z),
10671 );
10672 }
10673 }
10674 panic!("trajectory never reached {x} m");
10675 }
10676
10677 #[test]
10678 fn cant_sign_clockwise_up_offset_goes_right_and_low() {
10679 let mut level = base_inputs();
10681 level.muzzle_angle = 0.003; let mut canted = level.clone();
10683 canted.cant_angle = 10f64.to_radians();
10684
10685 let (y0, z0) = yz_at(&solve_with(level, 400.0), 300.0);
10686 let (y1, z1) = yz_at(&solve_with(canted, 400.0), 300.0);
10687 assert!(
10688 z1 > z0 + 0.01,
10689 "clockwise cant must move POI right: z0={z0} z1={z1}"
10690 );
10691 assert!(
10692 y1 < y0 - 0.001,
10693 "clockwise cant must move POI low: y0={y0} y1={y1}"
10694 );
10695 }
10696
10697 #[test]
10698 fn pure_cant_shows_bore_offset_near_range() {
10699 let mut i = base_inputs();
10702 i.muzzle_angle = 0.0;
10703 i.cant_angle = 10f64.to_radians();
10704 let sh = i.sight_height;
10705 let r = solve_with(i, 60.0);
10706 let first = &r.points[1]; let expected = -sh * 10f64.to_radians().sin();
10708 assert!(
10709 (first.position.z - expected).abs() < 0.005,
10710 "near-muzzle lateral {} should be ~bore offset {expected}",
10711 first.position.z
10712 );
10713 }
10714
10715 #[test]
10716 fn zero_angle_is_independent_of_cant() {
10717 let a = base_inputs();
10718 let mut b = base_inputs();
10719 b.cant_angle = 15f64.to_radians();
10720 let za = calculate_zero_angle(a.clone(), 100.0, 0.0).expect("zero a");
10721 let zb = calculate_zero_angle(b.clone(), 100.0, 0.0).expect("zero b");
10722 assert_eq!(
10723 za.to_bits(),
10724 zb.to_bits(),
10725 "zeroing must ignore cant: {za} vs {zb}"
10726 );
10727 let _ = (a.cant_angle, b.cant_angle);
10729 }
10730
10731 #[test]
10732 fn nonfinite_cant_is_rejected() {
10733 let mut i = base_inputs();
10734 i.cant_angle = f64::NAN;
10735 let s = TrajectorySolver::new(
10736 i,
10737 WindConditions::default(),
10738 AtmosphericConditions::default(),
10739 );
10740 assert!(s.solve().is_err());
10741 }
10742
10743 #[test]
10744 fn incline_and_cant_compose_without_breaking() {
10745 let mut flat = base_inputs();
10747 flat.muzzle_angle = 0.003;
10748 flat.shooting_angle = 15f64.to_radians();
10749 let mut canted = flat.clone();
10750 canted.cant_angle = 10f64.to_radians();
10751 let (_, z_flat) = yz_at(&solve_with(flat, 400.0), 300.0);
10752 let (_, z_cant) = yz_at(&solve_with(canted, 400.0), 300.0);
10753 assert!(
10754 z_cant > z_flat,
10755 "cant must still deflect right on an incline"
10756 );
10757 }
10758}
10759
10760#[cfg(test)]
10761mod vertical_wind_tests {
10762 use super::*;
10763
10764 fn base_inputs() -> BallisticInputs {
10765 BallisticInputs {
10766 muzzle_velocity: 800.0,
10767 bc_value: 0.5,
10768 bc_type: DragModel::G7,
10769 bullet_mass: 0.0109,
10770 bullet_diameter: 0.00782,
10771 bullet_length: 0.0309,
10772 sight_height: 0.05,
10773 twist_rate: 10.0,
10774 use_rk4: true,
10775 ..BallisticInputs::default()
10776 }
10777 }
10778
10779 fn y_at(result: &TrajectoryResult, x: f64) -> f64 {
10781 let pts = &result.points;
10782 for i in 1..pts.len() {
10783 if pts[i].position.x >= x {
10784 let (p1, p2) = (&pts[i - 1], &pts[i]);
10785 let dx = p2.position.x - p1.position.x;
10786 let t = if dx.abs() < 1e-12 {
10787 0.0
10788 } else {
10789 (x - p1.position.x) / dx
10790 };
10791 return p1.position.y + t * (p2.position.y - p1.position.y);
10792 }
10793 }
10794 panic!("trajectory never reached {x} m");
10795 }
10796
10797 fn solve_with(
10798 inputs: BallisticInputs,
10799 wind: WindConditions,
10800 max_range: f64,
10801 ) -> TrajectoryResult {
10802 let mut s = TrajectorySolver::new(inputs, wind, AtmosphericConditions::default());
10803 s.set_max_range(max_range);
10804 s.solve().expect("solve")
10805 }
10806
10807 #[test]
10808 fn updraft_raises_poi_downrange() {
10809 let calm_inputs = base_inputs();
10812 let calm_wind = WindConditions::default();
10813 let updraft = WindConditions {
10814 vertical_speed: 5.0,
10815 ..Default::default()
10816 };
10817
10818 let calm = solve_with(calm_inputs.clone(), calm_wind, 500.0);
10819 let updraft_result = solve_with(calm_inputs, updraft, 500.0);
10820
10821 let y_calm = y_at(&calm, 400.0);
10822 let y_updraft = y_at(&updraft_result, 400.0);
10823 assert!(
10824 y_updraft > y_calm,
10825 "5 m/s updraft must raise POI at 400m: calm={y_calm}, updraft={y_updraft}"
10826 );
10827 }
10828
10829 #[test]
10830 fn zero_vertical_is_default_and_finite_required() {
10831 assert_eq!(WindConditions::default().vertical_speed, 0.0);
10832
10833 let inputs = base_inputs();
10834 let wind = WindConditions {
10835 vertical_speed: f64::NAN,
10836 ..Default::default()
10837 };
10838 let s = TrajectorySolver::new(inputs, wind, AtmosphericConditions::default());
10839 assert!(
10840 s.solve().is_err(),
10841 "NaN wind.vertical_speed must be rejected by validate_for_solve"
10842 );
10843 }
10844}
10845
10846#[cfg(test)]
10848mod bc_reference_standard_tests {
10849 use super::*;
10850
10851 fn base_inputs() -> BallisticInputs {
10852 BallisticInputs {
10853 muzzle_velocity: 800.0,
10854 bc_value: 0.5,
10855 bc_type: DragModel::G7,
10856 bullet_mass: 0.0109,
10857 bullet_diameter: 0.00782,
10858 bullet_length: 0.0309,
10859 sight_height: 0.05,
10860 twist_rate: 10.0,
10861 use_rk4: true,
10862 ..BallisticInputs::default()
10863 }
10864 }
10865
10866 fn y_and_speed_at(result: &TrajectoryResult, x: f64) -> (f64, f64) {
10868 let pts = &result.points;
10869 for i in 1..pts.len() {
10870 if pts[i].position.x >= x {
10871 let (p1, p2) = (&pts[i - 1], &pts[i]);
10872 let dx = p2.position.x - p1.position.x;
10873 let t = if dx.abs() < 1e-12 {
10874 0.0
10875 } else {
10876 (x - p1.position.x) / dx
10877 };
10878 return (
10879 p1.position.y + t * (p2.position.y - p1.position.y),
10880 p1.velocity_magnitude + t * (p2.velocity_magnitude - p1.velocity_magnitude),
10881 );
10882 }
10883 }
10884 panic!("trajectory never reached {x} m");
10885 }
10886
10887 #[test]
10890 fn asm_to_icao_ratio_matches_documented_value() {
10891 assert!(
10892 (crate::constants::ASM_TO_ICAO_BC - 0.98237).abs() < 1e-5,
10893 "ASM_TO_ICAO_BC = {} must equal 0.98237 to 5 decimal places",
10894 crate::constants::ASM_TO_ICAO_BC
10895 );
10896 assert_eq!(
10901 crate::constants::ASM_TO_ICAO_BC,
10902 crate::constants::ASM_DENSITY_LB_FT3 / crate::constants::ICAO_DENSITY_LB_FT3
10903 );
10904 }
10905
10906 #[test]
10909 fn default_bc_reference_standard_is_icao() {
10910 assert_eq!(
10911 BallisticInputs::default().bc_reference_standard,
10912 BcReferenceStandard::Icao
10913 );
10914 }
10915
10916 #[test]
10921 fn icao_reference_leaves_bc_value_bit_identical() {
10922 let raw_bc: f64 = 0.4372911; let inputs = BallisticInputs {
10924 bc_value: raw_bc,
10925 bc_reference_standard: BcReferenceStandard::Icao,
10926 ..base_inputs()
10927 };
10928 let solver = TrajectorySolver::new(
10929 inputs,
10930 WindConditions::default(),
10931 AtmosphericConditions::default(),
10932 );
10933 assert_eq!(solver.inputs.bc_value.to_bits(), raw_bc.to_bits());
10934 }
10935
10936 #[test]
10937 fn default_inputs_solve_is_unaffected_by_the_new_field_existing() {
10938 let a = TrajectorySolver::new(
10942 base_inputs(),
10943 WindConditions::default(),
10944 AtmosphericConditions::default(),
10945 )
10946 .solve()
10947 .expect("solve a");
10948 let b = TrajectorySolver::new(
10949 BallisticInputs { ..base_inputs() },
10950 WindConditions::default(),
10951 AtmosphericConditions::default(),
10952 )
10953 .solve()
10954 .expect("solve b");
10955 assert_eq!(a.impact_velocity.to_bits(), b.impact_velocity.to_bits());
10956 assert_eq!(a.max_range.to_bits(), b.max_range.to_bits());
10957 }
10958
10959 #[test]
10962 fn army_standard_metro_scales_bc_value_by_exactly_the_derived_ratio() {
10963 let raw_bc = 0.5;
10964 let inputs = BallisticInputs {
10965 bc_value: raw_bc,
10966 bc_reference_standard: BcReferenceStandard::ArmyStandardMetro,
10967 ..base_inputs()
10968 };
10969 let solver = TrajectorySolver::new(
10970 inputs,
10971 WindConditions::default(),
10972 AtmosphericConditions::default(),
10973 );
10974 assert_eq!(
10975 solver.inputs.bc_value,
10976 raw_bc * crate::constants::ASM_TO_ICAO_BC
10977 );
10978 }
10979
10980 #[test]
10981 fn army_standard_metro_scales_mach_keyed_bc_segments() {
10982 let inputs = BallisticInputs {
10983 bc_reference_standard: BcReferenceStandard::ArmyStandardMetro,
10984 bc_segments: Some(vec![(0.5, 0.40), (1.5, 0.30)]),
10985 ..base_inputs()
10986 };
10987 let solver = TrajectorySolver::new(
10988 inputs,
10989 WindConditions::default(),
10990 AtmosphericConditions::default(),
10991 );
10992 let segments = solver.inputs.bc_segments.as_ref().expect("segments");
10993 assert_eq!(segments[0], (0.5, 0.40 * crate::constants::ASM_TO_ICAO_BC));
10994 assert_eq!(segments[1], (1.5, 0.30 * crate::constants::ASM_TO_ICAO_BC));
10995 }
10996
10997 #[test]
10998 fn army_standard_metro_scales_velocity_keyed_bc_segments_data() {
10999 let inputs = BallisticInputs {
11000 bc_reference_standard: BcReferenceStandard::ArmyStandardMetro,
11001 bc_segments_data: Some(vec![
11002 crate::BCSegmentData {
11003 velocity_min: 0.0,
11004 velocity_max: 500.0,
11005 bc_value: 0.40,
11006 },
11007 crate::BCSegmentData {
11008 velocity_min: 500.0,
11009 velocity_max: 900.0,
11010 bc_value: 0.45,
11011 },
11012 ]),
11013 ..base_inputs()
11014 };
11015 let solver = TrajectorySolver::new(
11016 inputs,
11017 WindConditions::default(),
11018 AtmosphericConditions::default(),
11019 );
11020 let segments = solver.inputs.bc_segments_data.as_ref().expect("segments");
11021 assert_eq!(
11022 segments[0].bc_value,
11023 0.40 * crate::constants::ASM_TO_ICAO_BC
11024 );
11025 assert_eq!(
11026 segments[1].bc_value,
11027 0.45 * crate::constants::ASM_TO_ICAO_BC
11028 );
11029 assert_eq!(segments[0].velocity_min, 0.0);
11031 assert_eq!(segments[1].velocity_max, 900.0);
11032 }
11033
11034 #[test]
11039 fn army_standard_metro_moves_impact_in_the_more_drag_direction() {
11040 let solve_at = |standard: BcReferenceStandard| {
11041 let inputs = BallisticInputs {
11042 bc_value: 0.475,
11043 bc_reference_standard: standard,
11044 ..base_inputs()
11045 };
11046 let mut solver = TrajectorySolver::new(
11047 inputs,
11048 WindConditions::default(),
11049 AtmosphericConditions::default(),
11050 );
11051 solver.set_max_range(500.0);
11052 solver.solve().expect("solve")
11053 };
11054
11055 let icao = solve_at(BcReferenceStandard::Icao);
11056 let asm = solve_at(BcReferenceStandard::ArmyStandardMetro);
11057
11058 let (y_icao, v_icao) = y_and_speed_at(&icao, 400.0);
11059 let (y_asm, v_asm) = y_and_speed_at(&asm, 400.0);
11060
11061 assert!(
11062 y_asm < y_icao,
11063 "ArmyStandardMetro must drop MORE (lower y) at 400m than Icao for the same raw \
11064 bc_value: icao_y={y_icao}, asm_y={y_asm}"
11065 );
11066 assert!(
11067 v_asm < v_icao,
11068 "ArmyStandardMetro must retain LESS velocity at 400m than Icao for the same raw \
11069 bc_value: icao_v={v_icao}, asm_v={v_asm}"
11070 );
11071 }
11072
11073 #[test]
11080 fn monte_carlo_inherits_the_normalized_bc_reference() {
11081 let base_inputs_asm = BallisticInputs {
11082 bc_value: 0.475,
11083 bc_reference_standard: BcReferenceStandard::ArmyStandardMetro,
11084 ..base_inputs()
11085 };
11086 let wind = WindConditions::default();
11087
11088 let mut direct_solver = TrajectorySolver::new(
11094 base_inputs_asm.clone(),
11095 wind.clone(),
11096 AtmosphericConditions::default(),
11097 );
11098 direct_solver.set_max_range(base_inputs_asm.target_distance.max(1000.0) * 2.0);
11099 let direct = direct_solver.solve().expect("direct solve");
11100
11101 let mc_params = MonteCarloParams {
11102 num_simulations: 1,
11103 velocity_std_dev: 0.0,
11104 angle_std_dev: 0.0,
11105 bc_std_dev: 0.0,
11106 wind_speed_std_dev: 0.0,
11107 target_distance: None,
11108 base_wind_speed: 0.0,
11109 base_wind_direction: 0.0,
11110 azimuth_std_dev: 0.0,
11111 };
11112 let mc = run_monte_carlo_with_wind_and_direction_std_dev_seeded(
11113 base_inputs_asm,
11114 wind,
11115 mc_params,
11116 0.0,
11117 42,
11118 )
11119 .expect("monte carlo");
11120
11121 assert_eq!(mc.ranges.len(), 1);
11122 assert_eq!(
11123 mc.ranges[0].to_bits(),
11124 direct.max_range.to_bits(),
11125 "a zero-dispersion single MC sample must match a plain solve of the same \
11126 ASM-referenced inputs bit-for-bit"
11127 );
11128 assert_eq!(
11129 mc.impact_velocities[0].to_bits(),
11130 direct.impact_velocity.to_bits()
11131 );
11132 }
11133
11134 #[test]
11142 fn estimate_bc_fit_recovers_an_icao_referenced_bc() {
11143 let known_bc = 0.475;
11144 let velocity = 800.0;
11145 let mass = 0.0109;
11146 let diameter = 0.00782;
11147 let atmosphere = AtmosphericConditions::default();
11148
11149 let synth_inputs = BallisticInputs {
11150 muzzle_velocity: velocity,
11151 bc_value: known_bc,
11152 bc_type: DragModel::G7,
11153 bullet_mass: mass,
11154 bullet_diameter: diameter,
11155 bullet_length: 0.0309,
11156 sight_height: 0.05,
11157 twist_rate: 10.0,
11158 use_rk4: true,
11159 bc_reference_standard: BcReferenceStandard::Icao,
11160 ..BallisticInputs::default()
11161 };
11162 let mut solver =
11163 TrajectorySolver::new(synth_inputs, WindConditions::default(), atmosphere.clone());
11164 solver.set_max_range(500.0);
11165 let trajectory = solver.solve().expect("synthetic solve");
11166
11167 let points: Vec<(f64, f64)> = [100.0, 200.0, 300.0, 400.0]
11168 .iter()
11169 .map(|&d| {
11170 let (y, _) = {
11171 let pts = &trajectory.points;
11172 let mut found = None;
11173 for i in 1..pts.len() {
11174 if pts[i].position.x >= d {
11175 let (p1, p2) = (&pts[i - 1], &pts[i]);
11176 let dx = p2.position.x - p1.position.x;
11177 let t = if dx.abs() < 1e-12 {
11178 0.0
11179 } else {
11180 (d - p1.position.x) / dx
11181 };
11182 found =
11183 Some((p1.position.y + t * (p2.position.y - p1.position.y), 0.0));
11184 break;
11185 }
11186 }
11187 found.expect("trajectory reached observation distance")
11188 };
11189 (d, -y) })
11191 .collect();
11192
11193 let estimate = estimate_bc_fit(
11194 velocity,
11195 mass,
11196 diameter,
11197 &points,
11198 DragModel::G7,
11199 BcFitMode::Drop,
11200 atmosphere,
11201 None,
11202 0.05,
11203 )
11204 .expect("fit should converge");
11205
11206 assert!(
11207 (estimate.bc - known_bc).abs() < 0.02,
11208 "fit should recover the known ICAO-referenced bc={known_bc}, got {}",
11209 estimate.bc
11210 );
11211 }
11212
11213 #[test]
11216 fn custom_drag_table_makes_bc_reference_standard_numerically_inert() {
11217 let table =
11218 crate::drag::DragTable::try_new(vec![0.5, 1.0, 2.0, 3.0], vec![0.3, 0.4, 0.3, 0.2])
11219 .expect("valid table");
11220
11221 let solve_with = |standard: BcReferenceStandard| {
11222 let inputs = BallisticInputs {
11223 bc_value: 0.5, bc_reference_standard: standard,
11225 custom_drag_table: Some(table.clone()),
11226 ..base_inputs()
11227 };
11228 let mut solver = TrajectorySolver::new(
11229 inputs,
11230 WindConditions::default(),
11231 AtmosphericConditions::default(),
11232 );
11233 solver.set_max_range(500.0);
11234 solver.solve().expect("solve")
11235 };
11236
11237 let icao = solve_with(BcReferenceStandard::Icao);
11238 let asm = solve_with(BcReferenceStandard::ArmyStandardMetro);
11239
11240 assert_eq!(
11241 icao.impact_velocity.to_bits(),
11242 asm.impact_velocity.to_bits(),
11243 "a custom drag table must make bc_reference_standard fully inert"
11244 );
11245 assert_eq!(icao.max_range.to_bits(), asm.max_range.to_bits());
11246 }
11247
11248 #[test]
11249 fn custom_drag_table_inert_warning_fires_only_for_army_standard_metro_with_a_table() {
11250 let table = crate::drag::DragTable::try_new(vec![0.5, 1.0, 2.0], vec![0.3, 0.4, 0.3])
11251 .expect("valid table");
11252
11253 let no_table_icao = base_inputs();
11255 assert!(no_table_icao
11256 .bc_reference_standard_inert_warning()
11257 .is_none());
11258 let no_table_asm = BallisticInputs {
11259 bc_reference_standard: BcReferenceStandard::ArmyStandardMetro,
11260 ..base_inputs()
11261 };
11262 assert!(no_table_asm.bc_reference_standard_inert_warning().is_none());
11263
11264 let table_icao = BallisticInputs {
11266 custom_drag_table: Some(table.clone()),
11267 ..base_inputs()
11268 };
11269 assert!(table_icao.bc_reference_standard_inert_warning().is_none());
11270
11271 let table_asm = BallisticInputs {
11273 custom_drag_table: Some(table),
11274 bc_reference_standard: BcReferenceStandard::ArmyStandardMetro,
11275 ..base_inputs()
11276 };
11277 let warning = table_asm
11278 .bc_reference_standard_inert_warning()
11279 .expect("must warn");
11280 assert!(warning.contains("--bc-reference"));
11281 assert!(warning.contains("--drag-table"));
11282 }
11283}
11284
11285#[cfg(test)]
11291mod effective_drag_coefficient_tests {
11292 use super::*;
11293
11294 fn inputs_175gr_g7() -> BallisticInputs {
11295 let mut inputs = BallisticInputs {
11296 bc_value: 0.243,
11297 bc_type: DragModel::G7,
11298 muzzle_velocity: 823.0,
11299 ..Default::default()
11300 };
11301 inputs.bullet_mass = 175.0 * crate::constants::GRAINS_TO_KG;
11305 inputs.bullet_diameter = 0.308 * 0.0254;
11306 inputs.weight_grains = 175.0;
11307 inputs.caliber_inches = 0.308;
11308 inputs
11309 }
11310
11311 fn solver(inputs: BallisticInputs) -> TrajectorySolver {
11312 TrajectorySolver::new(
11313 inputs,
11314 WindConditions::default(),
11315 AtmosphericConditions::default(),
11316 )
11317 }
11318
11319 #[test]
11323 fn reports_the_projectiles_own_cd_not_the_reference_tables() {
11324 let inputs = inputs_175gr_g7();
11325 let sd = inputs.sectional_density_lb_in2().expect("SD");
11326 let solver = solver(inputs);
11327
11328 let sos = 340.0;
11329 let velocity = 800.0;
11330 let mach = velocity / sos;
11331
11332 let reference = crate::drag::get_drag_coefficient(mach, &DragModel::G7);
11333 let reported = solver
11334 .effective_drag_coefficient(velocity, sos)
11335 .expect("mass and diameter are set");
11336
11337 let expected = reference * sd / 0.243;
11338 assert!(
11339 (reported - expected).abs() < 1e-12,
11340 "reported {reported} != Cd_ref * SD / BC {expected}"
11341 );
11342 assert!(
11345 (reported - reference).abs() > 1e-6,
11346 "form factor collapsed to 1; this fixture no longer distinguishes the two values"
11347 );
11348 }
11349
11350 #[test]
11353 fn a_custom_drag_table_passes_through_unscaled() {
11354 let mut inputs = inputs_175gr_g7();
11355 inputs.custom_drag_table = Some(crate::drag::DragTable::new(
11356 vec![0.5, 3.0],
11357 vec![0.15, 0.40],
11358 ));
11359 let solver = solver(inputs);
11360
11361 let sos = 340.0;
11362 let velocity = 0.9 * sos;
11363 let table_value = solver
11364 .inputs
11365 .custom_drag_table
11366 .as_ref()
11367 .expect("table")
11368 .interpolate(0.9);
11369
11370 let reported = solver
11371 .effective_drag_coefficient(velocity, sos)
11372 .expect("mass and diameter are set");
11373 assert!(
11374 (reported - table_value).abs() < 1e-12,
11375 "custom table Cd {table_value} was rescaled to {reported}"
11376 );
11377 }
11378
11379 #[test]
11382 fn a_velocity_segmented_bc_steps_the_reported_cd() {
11383 let mut inputs = inputs_175gr_g7();
11384 inputs.use_bc_segments = true;
11385 inputs.bc_segments_data = Some(vec![
11386 crate::BCSegmentData {
11387 velocity_min: 2400.0,
11388 velocity_max: 4000.0,
11389 bc_value: 0.243,
11390 },
11391 crate::BCSegmentData {
11392 velocity_min: 0.0,
11393 velocity_max: 2400.0,
11394 bc_value: 0.200,
11395 },
11396 ]);
11397 let solver = solver(inputs);
11398
11399 let sos = 340.0;
11400 let above = solver
11402 .effective_drag_coefficient(2500.0 / 3.28084, sos)
11403 .expect("cd");
11404 let below = solver
11405 .effective_drag_coefficient(2300.0 / 3.28084, sos)
11406 .expect("cd");
11407
11408 assert!(
11410 below > above,
11411 "expected the 0.200 band to report a higher Cd than the 0.243 band; got {below} vs {above}"
11412 );
11413 }
11414
11415 #[test]
11418 fn is_absent_when_sectional_density_is_unknown() {
11419 let mut inputs = inputs_175gr_g7();
11420 inputs.weight_grains = 0.0;
11421 inputs.bullet_mass = 0.0;
11422 let solver = solver(inputs);
11423 assert!(solver.effective_drag_coefficient(800.0, 340.0).is_none());
11424 }
11425
11426 #[test]
11431 fn the_json_emit_rule_is_flag_gated_and_absent_when_cd_is_unknown() {
11432 let mut point = TrajectoryPoint {
11433 time: 0.0,
11434 position: nalgebra::Vector3::new(0.0, 0.0, 0.0),
11435 velocity_magnitude: 800.0,
11436 kinetic_energy: 3000.0,
11437 drag_coefficient: Some(0.31),
11438 };
11439 assert_eq!(point.drag_coefficient_json_value(true), Some(0.31));
11440 assert_eq!(
11441 point.drag_coefficient_json_value(false),
11442 None,
11443 "without the flag the key must not exist, so default JSON stays byte-identical"
11444 );
11445 point.drag_coefficient = None;
11446 assert_eq!(
11447 point.drag_coefficient_json_value(true),
11448 None,
11449 "unknown sectional density must yield an ABSENT key, not null"
11450 );
11451 }
11452
11453 #[test]
11455 fn every_point_of_a_solved_trajectory_carries_the_value() {
11456 let mut solver = solver(inputs_175gr_g7());
11457 solver.set_max_range(300.0);
11458 let result = solver.solve().expect("solve");
11459 assert!(!result.points.is_empty());
11460 assert!(
11461 result.points.iter().all(|p| p.drag_coefficient.is_some()),
11462 "the post-integration pass missed at least one point"
11463 );
11464 }
11465}
11466
11467#[cfg(test)]
11468mod boundary_layer_shear_height_tests {
11469 use super::*;
11476
11477 const MODELS: [&str; 2] = ["logarithmic", "power_law"];
11478
11479 fn ratio_rel_launch(height_rel_launch_m: f64, model: &str) -> f64 {
11480 crate::wind_shear::boundary_layer_speed_ratio(
11481 height_rel_launch_m,
11482 crate::wind_shear::boundary_layer_model_from_name(model),
11483 )
11484 }
11485
11486 fn assert_solver_shear_ratio(
11491 model: &str,
11492 muzzle_height: f64,
11493 shooting_angle: f64,
11494 position: Vector3<f64>,
11495 expected_ratio: f64,
11496 ) {
11497 let inputs = BallisticInputs {
11498 muzzle_height,
11499 shooting_angle,
11500 enable_wind_shear: true,
11501 wind_shear_model: model.to_string(),
11502 ..BallisticInputs::default()
11503 };
11504 let wind = WindConditions {
11505 speed: 10.0,
11506 direction: std::f64::consts::FRAC_PI_2,
11507 vertical_speed: 0.0,
11508 };
11509 let sheared = TrajectorySolver::new(
11510 inputs.clone(),
11511 wind.clone(),
11512 AtmosphericConditions::default(),
11513 );
11514 let uniform = TrajectorySolver::new(
11515 BallisticInputs {
11516 enable_wind_shear: false,
11517 ..inputs
11518 },
11519 wind.clone(),
11520 AtmosphericConditions::default(),
11521 );
11522 let station = sheared.station_air().unwrap();
11523 let velocity = Vector3::new(700.0, 5.0, 0.0);
11524 let scaled_wind =
11525 crate::wind::wind_vector(wind.speed, wind.direction, 0.0) * expected_ratio;
11526
11527 let with_shear =
11528 sheared.calculate_acceleration(&position, &velocity, &Vector3::zeros(), &station);
11529 let with_scaled_wind =
11530 uniform.calculate_acceleration(&position, &velocity, &scaled_wind, &station);
11531 assert!(
11532 (with_shear - with_scaled_wind).norm() <= 1e-12,
11533 "{model}, muzzle_height {muzzle_height} m, shooting angle {shooting_angle} rad, \
11534 position {position:?}: the shear multiplier is not {expected_ratio} \
11535 (acceleration {with_shear:?}, with the wind scaled by it {with_scaled_wind:?})"
11536 );
11537 }
11538
11539 #[test]
11544 fn solver_shear_reads_one_multiplier_at_one_height_above_ground() {
11545 for model in MODELS {
11546 let expected = ratio_rel_launch(58.5, model);
11548 assert!(
11549 expected > 1.2,
11550 "{model}: the fixture must be well above the floor"
11551 );
11552 assert_solver_shear_ratio(model, 1.5, 0.0, Vector3::new(1_000.0, 60.0, 0.0), expected);
11553 assert_solver_shear_ratio(model, 0.0, 0.0, Vector3::new(1_000.0, 58.5, 0.0), expected);
11554 }
11555 }
11556
11557 #[test]
11567 fn inclined_solver_shear_measures_height_along_the_line_of_sight() {
11568 let (x, y) = (800.0, 60.0);
11569 for angle in [0.3_f64, -0.3] {
11570 let world_height = crate::atmosphere::shot_frame_altitude(0.0, x, y, angle);
11571 for model in MODELS {
11572 let bore_frame = ratio_rel_launch(y, model);
11575 let ground_frame = ratio_rel_launch(y - 1.5, model);
11577 assert!(
11578 bore_frame > 1.25 && ground_frame > 1.25,
11579 "{model}: fixture too low"
11580 );
11581 assert!(
11582 (ratio_rel_launch(world_height, model) - bore_frame).abs() > 0.1,
11583 "{model}, angle {angle}: the fixture must tell the world height apart"
11584 );
11585 assert_solver_shear_ratio(model, 0.0, angle, Vector3::new(x, y, 0.0), bore_frame);
11586 assert_solver_shear_ratio(model, 1.5, angle, Vector3::new(x, y, 0.0), ground_frame);
11587 }
11588 }
11589 }
11590
11591 fn solve_end(inputs: BallisticInputs, max_range: f64) -> (Vector3<f64>, f64) {
11592 let mut solver = TrajectorySolver::new(
11593 inputs,
11594 WindConditions {
11595 speed: 10.0,
11596 direction: std::f64::consts::FRAC_PI_2,
11597 vertical_speed: 0.0,
11598 },
11599 AtmosphericConditions::default(),
11600 );
11601 solver.set_max_range(max_range);
11602 let result = solver.solve().unwrap();
11603 let peak_y = result
11604 .points
11605 .iter()
11606 .map(|p| p.position.y)
11607 .fold(f64::NEG_INFINITY, f64::max);
11608 (result.points.last().unwrap().position, peak_y)
11609 }
11610
11611 #[test]
11616 fn inclined_flat_fire_keeps_the_operative_wind_with_shear_on() {
11617 for shooting_angle in [15.0_f64.to_radians(), (-10.0_f64).to_radians()] {
11618 let inputs = BallisticInputs {
11619 muzzle_height: 1.5,
11620 muzzle_angle: 0.002,
11621 shooting_angle,
11622 bc_type: DragModel::G7,
11623 ..BallisticInputs::default()
11624 };
11625 let (off, peak_y) = solve_end(inputs.clone(), 600.0);
11626 assert!(
11627 peak_y < 8.0 && off.z.abs() > 0.5,
11628 "the fixture must stay low and drift: peak y {peak_y} m, drift {} m",
11629 off.z
11630 );
11631 for model in MODELS {
11632 let (on, _) = solve_end(
11633 BallisticInputs {
11634 enable_wind_shear: true,
11635 wind_shear_model: model.to_string(),
11636 ..inputs.clone()
11637 },
11638 600.0,
11639 );
11640 assert_eq!(
11641 (on.x.to_bits(), on.y.to_bits(), on.z.to_bits()),
11642 (off.x.to_bits(), off.y.to_bits(), off.z.to_bits()),
11643 "{model}, shooting angle {shooting_angle} rad: shear moved a flat shot \
11644 ({on:?} vs {off:?})"
11645 );
11646 }
11647 }
11648 }
11649
11650 #[test]
11655 fn model_none_applies_no_shear_with_the_flag_set() {
11656 let inputs = BallisticInputs {
11657 muzzle_height: 1.5,
11658 muzzle_angle: 0.12,
11659 bc_type: DragModel::G7,
11660 ..BallisticInputs::default()
11661 };
11662 let (off, peak_y) = solve_end(inputs.clone(), 1_000.0);
11663 assert!(
11664 peak_y > 100.0,
11665 "the fixture must be lofted: peak y {peak_y} m"
11666 );
11667 let with_model = |model: &str| {
11668 solve_end(
11669 BallisticInputs {
11670 enable_wind_shear: true,
11671 wind_shear_model: model.to_string(),
11672 ..inputs.clone()
11673 },
11674 1_000.0,
11675 )
11676 .0
11677 };
11678 let none = with_model("none");
11679 assert_eq!(
11680 (none.x.to_bits(), none.y.to_bits(), none.z.to_bits()),
11681 (off.x.to_bits(), off.y.to_bits(), off.z.to_bits()),
11682 "model none moved the shot: {none:?} vs shear off {off:?}"
11683 );
11684 let power_law = with_model("power_law");
11685 assert!(
11686 (power_law.z - off.z).abs() > 0.05,
11687 "the fixture must show shear: power law {} m vs off {} m",
11688 power_law.z,
11689 off.z
11690 );
11691 assert_eq!(with_model("typo").z.to_bits(), power_law.z.to_bits());
11693 }
11694}
11695
11696#[cfg(test)]
11697mod station_air_tests {
11698 use super::*;
11703 use crate::atmosphere::{calculate_atmosphere, resolve_station_conditions_with_presence};
11704
11705 fn solver(
11706 atmosphere: AtmosphericConditions,
11707 presence: StationAtmospherePresence,
11708 ) -> TrajectorySolver {
11709 TrajectorySolver::new_with_station_presence(
11710 BallisticInputs::default(),
11711 WindConditions::default(),
11712 atmosphere,
11713 presence,
11714 )
11715 }
11716
11717 #[test]
11718 fn station_air_is_calculate_atmosphere_at_the_resolved_station() {
11719 let atmospheres = [
11720 (0.0, 15.0, 1013.25, 0.0),
11721 (0.0, 15.0, 1013.25, 50.0),
11722 (1_500.0, 25.0, 830.0, 100.0),
11723 (1_500.0, 15.0, 1013.25, 37.5),
11726 (2_000.0, 15.0, 1013.25, 50.0),
11727 ];
11728 for presence in [
11729 StationAtmospherePresence::NEITHER,
11730 StationAtmospherePresence::BOTH,
11731 ] {
11732 for (altitude, temperature, pressure, humidity) in atmospheres {
11733 let solver = solver(
11734 AtmosphericConditions {
11735 temperature,
11736 pressure,
11737 humidity,
11738 altitude,
11739 },
11740 presence,
11741 );
11742 let station = solver.station_air().expect("valid station");
11743 let (temp_c, pressure_hpa) = resolve_station_conditions_with_presence(
11744 temperature,
11745 pressure,
11746 altitude,
11747 PressureReferenceMode::Absolute,
11748 presence,
11749 );
11750 let (density, sound) =
11751 calculate_atmosphere(altitude, Some(temp_c), Some(pressure_hpa), humidity);
11752 let got = [
11753 station.altitude_m(),
11754 station.temperature_c(),
11755 station.pressure_hpa(),
11756 station.humidity().percent(),
11757 station.density_kg_m3(),
11758 station.density_ratio(),
11759 station.speed_of_sound_mps(),
11760 ];
11761 let want = [
11762 altitude,
11763 temp_c,
11764 pressure_hpa,
11765 humidity,
11766 density,
11767 density / 1.225,
11768 sound,
11769 ];
11770 assert_eq!(
11771 got.map(f64::to_bits),
11772 want.map(f64::to_bits),
11773 "{presence:?} {altitude} m {temperature} C {pressure} hPa {humidity}%"
11774 );
11775 assert_eq!(
11777 [
11778 solver.resolved_atmosphere().0,
11779 solver.resolved_atmosphere().1,
11780 solver.resolved_atmosphere().2,
11781 solver.resolved_atmosphere().3,
11782 ]
11783 .map(f64::to_bits),
11784 [density, sound, temp_c, pressure_hpa].map(f64::to_bits)
11785 );
11786 }
11787 }
11788 }
11789
11790 #[test]
11795 fn out_of_range_station_humidity_is_rejected_never_clamped() {
11796 for humidity in [150.0, -5.000_000_1, 105.000_000_1, f64::NAN, f64::INFINITY] {
11798 let mut solver = solver(
11799 AtmosphericConditions {
11800 humidity,
11801 temperature: 30.0,
11802 ..AtmosphericConditions::default()
11803 },
11804 StationAtmospherePresence::BOTH,
11805 );
11806 solver.set_max_range(600.0);
11807 let station = solver
11808 .station_air()
11809 .expect_err(&format!("RH {humidity}: the station refuses it"));
11810 assert!(
11811 station.to_string().contains("atmosphere.humidity"),
11812 "{station}"
11813 );
11814 let solve = solver
11815 .solve()
11816 .expect_err(&format!("RH {humidity}: the solve refuses it"));
11817 assert!(solve.to_string().contains("atmosphere.humidity"), "{solve}");
11818 }
11819 for humidity in [0.0, 100.0] {
11821 let solver = solver(
11822 AtmosphericConditions {
11823 humidity,
11824 temperature: 30.0,
11825 ..AtmosphericConditions::default()
11826 },
11827 StationAtmospherePresence::BOTH,
11828 );
11829 let station = solver.station_air().expect("a valid station");
11830 assert_eq!(station.humidity().percent().to_bits(), humidity.to_bits());
11831 solver.solve().expect("a valid humidity flies");
11832 }
11833 }
11834
11835 #[test]
11840 fn a_station_reading_within_five_points_of_the_range_flies_the_end_bit_for_bit() {
11841 let flight = |humidity: f64, rk4: bool, rk45: bool| -> Vec<u64> {
11842 let mut solver = TrajectorySolver::new_with_station_presence(
11843 BallisticInputs {
11844 use_rk4: rk4,
11845 use_adaptive_rk45: rk45,
11846 ..BallisticInputs::default()
11847 },
11848 WindConditions::default(),
11849 AtmosphericConditions {
11850 humidity,
11851 temperature: 30.0,
11852 ..AtmosphericConditions::default()
11853 },
11854 StationAtmospherePresence::BOTH,
11855 );
11856 solver.set_max_range(600.0);
11857 let station = solver
11858 .station_air()
11859 .expect("a reading in the band is a station");
11860 let result = solver.solve().expect("a reading in the band flies");
11861 let mut bits = vec![
11862 station.humidity().percent().to_bits(),
11863 station.density_kg_m3().to_bits(),
11864 station.speed_of_sound_mps().to_bits(),
11865 ];
11866 for point in &result.points {
11867 bits.extend([
11868 point.time.to_bits(),
11869 point.position.x.to_bits(),
11870 point.position.y.to_bits(),
11871 point.position.z.to_bits(),
11872 point.velocity_magnitude.to_bits(),
11873 ]);
11874 }
11875 bits
11876 };
11877 for (rk4, rk45) in [(false, false), (true, false), (true, true)] {
11878 for (reading, end) in [
11879 (100.0001, 100.0),
11880 (101.7, 100.0),
11881 (105.0, 100.0),
11882 (-0.0001, 0.0),
11883 (-2.0, 0.0),
11884 (-5.0, 0.0),
11885 ] {
11886 assert_eq!(
11887 flight(reading, rk4, rk45),
11888 flight(end, rk4, rk45),
11889 "RH {reading} must fly {end} (rk4 {rk4}, rk45 {rk45})"
11890 );
11891 }
11892 }
11893 }
11894}
11895
11896#[cfg(test)]
11899mod humidity_consistency_tests;
11900
11901#[cfg(test)]
11905mod humidity_inputs_tests;