1use crate::cluster_bc::ClusterBCDegradation;
3use crate::pitch_damping::{calculate_pitch_damping_coefficient, PitchDampingCoefficients};
4use crate::precession_nutation::{
5 calculate_combined_angular_motion, AngularState, PrecessionNutationParams,
6};
7use crate::trajectory_sampling::{
8 sample_trajectory, TrajectoryData, TrajectoryOutputs, TrajectorySample,
9};
10use crate::transonic_drag::{get_projectile_shape, transonic_correction, ProjectileShape};
11use crate::wind_shear::{WindLayer, WindShearModel, WindShearProfile};
12use crate::DragModel;
13use nalgebra::Vector3;
14use std::error::Error;
15use std::fmt;
16
17#[derive(Debug, Clone, Copy, PartialEq)]
19pub enum UnitSystem {
20 Imperial,
21 Metric,
22}
23
24#[derive(Debug, Clone, Copy, PartialEq)]
26pub enum OutputFormat {
27 Table,
28 Json,
29 Csv,
30}
31
32#[derive(Debug)]
34pub struct BallisticsError {
35 message: String,
36}
37
38impl fmt::Display for BallisticsError {
39 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
40 write!(f, "{}", self.message)
41 }
42}
43
44impl Error for BallisticsError {}
45
46impl From<String> for BallisticsError {
47 fn from(msg: String) -> Self {
48 BallisticsError { message: msg }
49 }
50}
51
52impl From<&str> for BallisticsError {
53 fn from(msg: &str) -> Self {
54 BallisticsError {
55 message: msg.to_string(),
56 }
57 }
58}
59
60#[derive(Debug, Clone)]
64pub struct BallisticInputs {
65 pub bc_value: f64, pub bc_type: DragModel, 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 shooting_angle: f64, pub sight_height: f64, pub muzzle_height: f64, pub target_height: f64, pub ground_threshold: f64, pub altitude: f64, pub temperature: f64, pub pressure: f64, pub humidity: f64, 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,
110 pub use_powder_sensitivity: bool,
111 pub powder_temp_sensitivity: f64,
112 pub powder_temp: f64, pub tipoff_yaw: f64, pub tipoff_decay_distance: f64, pub use_bc_segments: bool,
116 pub bc_segments: Option<Vec<(f64, f64)>>, pub bc_segments_data: Option<Vec<crate::BCSegmentData>>, pub use_enhanced_spin_drift: bool,
119 pub use_form_factor: bool,
120 pub enable_wind_shear: bool,
121 pub wind_shear_model: String,
122 pub enable_trajectory_sampling: bool,
123 pub sample_interval: f64, pub enable_pitch_damping: bool,
125 pub enable_precession_nutation: bool,
126 pub use_cluster_bc: bool, pub custom_drag_table: Option<crate::drag::DragTable>,
130
131 pub bc_type_str: Option<String>,
133}
134
135impl Default for BallisticInputs {
136 fn default() -> Self {
137 let mass_kg = 0.01;
138 let diameter_m = 0.00762;
139 let bc = 0.5;
140 let muzzle_angle_rad = 0.0;
141 let bc_type = DragModel::G1;
142
143 Self {
144 bc_value: bc,
146 bc_type,
147 bullet_mass: mass_kg,
148 muzzle_velocity: 800.0,
149 bullet_diameter: diameter_m,
150 bullet_length: diameter_m * 4.0, muzzle_angle: muzzle_angle_rad,
154 target_distance: 100.0,
155 azimuth_angle: 0.0,
156 shooting_angle: 0.0,
157 sight_height: 0.05,
158 muzzle_height: 0.0, target_height: 0.0, ground_threshold: -100.0, altitude: 0.0,
164 temperature: 15.0,
165 pressure: 1013.25, humidity: 0.5, latitude: None,
168
169 wind_speed: 0.0,
171 wind_angle: 0.0,
172
173 twist_rate: 12.0, is_twist_right: true,
176 caliber_inches: diameter_m / 0.0254, weight_grains: mass_kg / 0.00006479891, manufacturer: None,
179 bullet_model: None,
180 bullet_id: None,
181 bullet_cluster: None,
182
183 use_rk4: true, use_adaptive_rk45: true, enable_advanced_effects: false,
189 use_powder_sensitivity: false,
190 powder_temp_sensitivity: 0.0,
191 powder_temp: 15.0,
192 tipoff_yaw: 0.0,
193 tipoff_decay_distance: 50.0,
194 use_bc_segments: false,
195 bc_segments: None,
196 bc_segments_data: None,
197 use_enhanced_spin_drift: false,
198 use_form_factor: false,
199 enable_wind_shear: false,
200 wind_shear_model: "none".to_string(),
201 enable_trajectory_sampling: false,
202 sample_interval: 10.0, enable_pitch_damping: false,
204 enable_precession_nutation: false,
205 use_cluster_bc: false, custom_drag_table: None,
209
210 bc_type_str: None,
212 }
213 }
214}
215
216#[derive(Debug, Clone)]
218pub struct WindConditions {
219 pub speed: f64, pub direction: f64, }
222
223impl Default for WindConditions {
224 fn default() -> Self {
225 Self {
226 speed: 0.0,
227 direction: 0.0,
228 }
229 }
230}
231
232#[derive(Debug, Clone)]
234pub struct AtmosphericConditions {
235 pub temperature: f64, pub pressure: f64, pub humidity: f64, pub altitude: f64, }
240
241impl Default for AtmosphericConditions {
242 fn default() -> Self {
243 Self {
244 temperature: 15.0,
245 pressure: 1013.25,
246 humidity: 50.0,
247 altitude: 0.0,
248 }
249 }
250}
251
252#[derive(Debug, Clone)]
254pub struct TrajectoryPoint {
255 pub time: f64,
256 pub position: Vector3<f64>,
257 pub velocity_magnitude: f64,
258 pub kinetic_energy: f64,
259}
260
261#[derive(Debug, Clone)]
263pub struct TrajectoryResult {
264 pub max_range: f64,
265 pub max_height: f64,
266 pub time_of_flight: f64,
267 pub impact_velocity: f64,
268 pub impact_energy: f64,
269 pub points: Vec<TrajectoryPoint>,
270 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>, }
277
278impl TrajectoryResult {
279 pub fn position_at_range(&self, target_range: f64) -> Option<Vector3<f64>> {
283 if self.points.is_empty() {
284 return None;
285 }
286
287 for i in 0..self.points.len() - 1 {
289 let p1 = &self.points[i];
290 let p2 = &self.points[i + 1];
291
292 if p1.position.z <= target_range && p2.position.z >= target_range {
294 let dz = p2.position.z - p1.position.z;
296 if dz.abs() < 1e-10 {
297 return Some(p1.position);
298 }
299 let t = (target_range - p1.position.z) / dz;
300
301 return Some(Vector3::new(
303 p1.position.x + t * (p2.position.x - p1.position.x),
304 p1.position.y + t * (p2.position.y - p1.position.y),
305 target_range,
306 ));
307 }
308 }
309
310 self.points.last().map(|p| p.position)
312 }
313}
314
315pub struct TrajectorySolver {
317 inputs: BallisticInputs,
318 wind: WindConditions,
319 atmosphere: AtmosphericConditions,
320 max_range: f64,
321 time_step: f64,
322 cluster_bc: Option<ClusterBCDegradation>,
323}
324
325impl TrajectorySolver {
326 pub fn new(
327 mut inputs: BallisticInputs,
328 wind: WindConditions,
329 atmosphere: AtmosphericConditions,
330 ) -> Self {
331 inputs.caliber_inches = inputs.bullet_diameter / 0.0254;
333 inputs.weight_grains = inputs.bullet_mass / 0.00006479891;
334
335 let cluster_bc = if inputs.use_cluster_bc {
337 Some(ClusterBCDegradation::new())
338 } else {
339 None
340 };
341
342 Self {
343 inputs,
344 wind,
345 atmosphere,
346 max_range: 1000.0,
347 time_step: 0.001,
348 cluster_bc,
349 }
350 }
351
352 pub fn set_max_range(&mut self, range: f64) {
353 self.max_range = range;
354 }
355
356 pub fn set_time_step(&mut self, step: f64) {
357 self.time_step = step;
358 }
359
360 fn get_wind_at_altitude(&self, altitude_m: f64) -> Vector3<f64> {
361 let profile = WindShearProfile {
363 model: if self.inputs.wind_shear_model == "logarithmic" {
364 WindShearModel::Logarithmic
365 } else if self.inputs.wind_shear_model == "power" {
366 WindShearModel::PowerLaw
367 } else {
368 WindShearModel::PowerLaw },
370 surface_wind: WindLayer {
371 altitude_m: 0.0,
372 speed_mps: self.wind.speed,
373 direction_deg: self.wind.direction.to_degrees(),
374 },
375 reference_height: 10.0, roughness_length: 0.03, power_exponent: 1.0 / 7.0, geostrophic_wind: None,
379 custom_layers: Vec::new(),
380 };
381
382 profile.get_wind_at_altitude(altitude_m)
383 }
384
385 pub fn solve(&self) -> Result<TrajectoryResult, BallisticsError> {
386 if self.inputs.use_rk4 {
387 if self.inputs.use_adaptive_rk45 {
388 self.solve_rk45()
389 } else {
390 self.solve_rk4()
391 }
392 } else {
393 self.solve_euler()
394 }
395 }
396
397 fn solve_euler(&self) -> Result<TrajectoryResult, BallisticsError> {
398 let mut time = 0.0;
400 let mut position = Vector3::new(
401 0.0,
402 self.inputs.sight_height + self.inputs.muzzle_height,
403 0.0,
404 );
405 let horizontal_velocity = self.inputs.muzzle_velocity * self.inputs.muzzle_angle.cos();
408 let mut velocity = Vector3::new(
409 horizontal_velocity * self.inputs.azimuth_angle.sin(), self.inputs.muzzle_velocity * self.inputs.muzzle_angle.sin(), horizontal_velocity * self.inputs.azimuth_angle.cos(), );
413
414 let mut points = Vec::new();
415 let mut max_height = position.y;
416 let mut min_pitch_damping = 1.0; let mut transonic_mach = None; let mut angular_state = if self.inputs.enable_precession_nutation {
421 Some(AngularState {
422 pitch_angle: 0.001, yaw_angle: 0.001,
424 pitch_rate: 0.0,
425 yaw_rate: 0.0,
426 precession_angle: 0.0,
427 nutation_phase: 0.0,
428 })
429 } else {
430 None
431 };
432 let mut max_yaw_angle = 0.0;
433 let mut max_precession_angle = 0.0;
434
435 let air_density = calculate_air_density(&self.atmosphere);
437
438 let wind_vector = Vector3::new(
440 self.wind.speed * self.wind.direction.sin(), 0.0,
442 self.wind.speed * self.wind.direction.cos(), );
444
445 while position.z < self.max_range && position.y >= 0.0 && time < 100.0 {
447 let velocity_magnitude = velocity.magnitude();
449 let kinetic_energy =
450 0.5 * self.inputs.bullet_mass * velocity_magnitude * velocity_magnitude;
451
452 points.push(TrajectoryPoint {
453 time,
454 position: position,
455 velocity_magnitude,
456 kinetic_energy,
457 });
458
459 if points.len() == 1 || points.len() % 100 == 0 {
462 eprintln!("Trajectory point {}: time={:.3}s, lateral={:.2}m, vertical={:.2}m, downrange={:.2}m, vel={:.1}m/s",
463 points.len(), time, position.x, position.y, position.z, velocity_magnitude);
464 }
465
466 if position.y > max_height {
468 max_height = position.y;
469 }
470
471 if self.inputs.enable_pitch_damping {
473 let temp_c = self.atmosphere.temperature;
474 let temp_k = temp_c + 273.15;
475 let speed_of_sound = (1.4 * 287.05 * temp_k).sqrt();
476 let mach = velocity_magnitude / speed_of_sound;
477
478 if transonic_mach.is_none() && mach < 1.2 && mach > 0.8 {
480 transonic_mach = Some(mach);
481 }
482
483 let bullet_type = if let Some(ref model) = self.inputs.bullet_model {
485 model.as_str()
486 } else {
487 "default"
488 };
489 let coeffs = PitchDampingCoefficients::from_bullet_type(bullet_type);
490 let pitch_damping = calculate_pitch_damping_coefficient(mach, &coeffs);
491
492 if pitch_damping < min_pitch_damping {
494 min_pitch_damping = pitch_damping;
495 }
496 }
497
498 if self.inputs.enable_precession_nutation {
500 if let Some(ref mut state) = angular_state {
501 let velocity_magnitude = velocity.magnitude();
502 let temp_c = self.atmosphere.temperature;
503 let temp_k = temp_c + 273.15;
504 let speed_of_sound = (1.4 * 287.05 * temp_k).sqrt();
505 let mach = velocity_magnitude / speed_of_sound;
506
507 let spin_rate_rad_s = if self.inputs.twist_rate > 0.0 {
509 let velocity_fps = velocity_magnitude * 3.28084;
510 let twist_rate_ft = self.inputs.twist_rate / 12.0;
511 (velocity_fps / twist_rate_ft) * 2.0 * std::f64::consts::PI
512 } else {
513 0.0
514 };
515
516 let params = PrecessionNutationParams {
518 mass_kg: self.inputs.bullet_mass,
519 caliber_m: self.inputs.bullet_diameter,
520 length_m: self.inputs.bullet_length,
521 spin_rate_rad_s,
522 spin_inertia: 6.94e-8, transverse_inertia: 9.13e-7, velocity_mps: velocity_magnitude,
525 air_density_kg_m3: air_density,
526 mach,
527 pitch_damping_coeff: -0.8,
528 nutation_damping_factor: 0.05,
529 };
530
531 *state = calculate_combined_angular_motion(
533 ¶ms,
534 state,
535 time,
536 self.time_step,
537 0.001, );
539
540 if state.yaw_angle.abs() > max_yaw_angle {
542 max_yaw_angle = state.yaw_angle.abs();
543 }
544 if state.precession_angle.abs() > max_precession_angle {
545 max_precession_angle = state.precession_angle.abs();
546 }
547 }
548 }
549
550 let actual_wind = if self.inputs.enable_wind_shear {
552 self.get_wind_at_altitude(position.y)
553 } else {
554 wind_vector
555 };
556 let velocity_rel = velocity - actual_wind;
557 let velocity_rel_mag = velocity_rel.magnitude();
558 let drag_coefficient = self.calculate_drag_coefficient(velocity_rel_mag);
559
560 let drag_force = 0.5
562 * air_density
563 * drag_coefficient
564 * self.inputs.bullet_diameter
565 * self.inputs.bullet_diameter
566 * std::f64::consts::PI
567 / 4.0
568 * velocity_rel_mag
569 * velocity_rel_mag;
570
571 let drag_acceleration = -drag_force / self.inputs.bullet_mass;
573 let acceleration = Vector3::new(
574 drag_acceleration * velocity_rel.x / velocity_rel_mag,
575 drag_acceleration * velocity_rel.y / velocity_rel_mag - 9.80665,
576 drag_acceleration * velocity_rel.z / velocity_rel_mag,
577 );
578
579 velocity += acceleration * self.time_step;
581 position += velocity * self.time_step;
582 time += self.time_step;
583 }
584
585 let last_point = points.last().ok_or("No trajectory points generated")?;
587
588 let sampled_points = if self.inputs.enable_trajectory_sampling {
590 let trajectory_data = TrajectoryData {
591 times: points.iter().map(|p| p.time).collect(),
592 positions: points.iter().map(|p| p.position).collect(),
593 velocities: points
594 .iter()
595 .map(|p| {
596 Vector3::new(0.0, 0.0, p.velocity_magnitude)
598 })
599 .collect(),
600 transonic_distances: Vec::new(), };
602
603 let outputs = TrajectoryOutputs {
604 target_distance_horiz_m: last_point.position.z, target_vertical_height_m: last_point.position.y,
606 time_of_flight_s: last_point.time,
607 max_ord_dist_horiz_m: max_height,
608 };
609
610 let samples = sample_trajectory(
612 &trajectory_data,
613 &outputs,
614 self.inputs.sample_interval,
615 self.inputs.bullet_mass,
616 );
617 Some(samples)
618 } else {
619 None
620 };
621
622 Ok(TrajectoryResult {
623 max_range: last_point.position.z, max_height,
625 time_of_flight: last_point.time,
626 impact_velocity: last_point.velocity_magnitude,
627 impact_energy: last_point.kinetic_energy,
628 points,
629 sampled_points,
630 min_pitch_damping: if self.inputs.enable_pitch_damping {
631 Some(min_pitch_damping)
632 } else {
633 None
634 },
635 transonic_mach,
636 angular_state,
637 max_yaw_angle: if self.inputs.enable_precession_nutation {
638 Some(max_yaw_angle)
639 } else {
640 None
641 },
642 max_precession_angle: if self.inputs.enable_precession_nutation {
643 Some(max_precession_angle)
644 } else {
645 None
646 },
647 })
648 }
649
650 fn solve_rk4(&self) -> Result<TrajectoryResult, BallisticsError> {
651 let mut time = 0.0;
653 let mut position = Vector3::new(
654 0.0,
655 self.inputs.sight_height + self.inputs.muzzle_height,
656 0.0,
657 );
658
659 let horizontal_velocity = self.inputs.muzzle_velocity * self.inputs.muzzle_angle.cos();
662 let mut velocity = Vector3::new(
663 horizontal_velocity * self.inputs.azimuth_angle.sin(), self.inputs.muzzle_velocity * self.inputs.muzzle_angle.sin(), horizontal_velocity * self.inputs.azimuth_angle.cos(), );
667
668 let mut points = Vec::new();
669 let mut max_height = position.y;
670 let mut min_pitch_damping = 1.0; let mut transonic_mach = None; let mut angular_state = if self.inputs.enable_precession_nutation {
675 Some(AngularState {
676 pitch_angle: 0.001, yaw_angle: 0.001,
678 pitch_rate: 0.0,
679 yaw_rate: 0.0,
680 precession_angle: 0.0,
681 nutation_phase: 0.0,
682 })
683 } else {
684 None
685 };
686 let mut max_yaw_angle = 0.0;
687 let mut max_precession_angle = 0.0;
688
689 let air_density = calculate_air_density(&self.atmosphere);
691
692 let wind_vector = Vector3::new(
694 self.wind.speed * self.wind.direction.sin(), 0.0,
696 self.wind.speed * self.wind.direction.cos(), );
698
699 while position.z < self.max_range && position.y >= 0.0 && time < 100.0 {
701 let velocity_magnitude = velocity.magnitude();
703 let kinetic_energy =
704 0.5 * self.inputs.bullet_mass * velocity_magnitude * velocity_magnitude;
705
706 points.push(TrajectoryPoint {
707 time,
708 position: position,
709 velocity_magnitude,
710 kinetic_energy,
711 });
712
713 if position.y > max_height {
714 max_height = position.y;
715 }
716
717 if self.inputs.enable_pitch_damping {
719 let temp_c = self.atmosphere.temperature;
720 let temp_k = temp_c + 273.15;
721 let speed_of_sound = (1.4 * 287.05 * temp_k).sqrt();
722 let mach = velocity_magnitude / speed_of_sound;
723
724 if transonic_mach.is_none() && mach < 1.2 && mach > 0.8 {
726 transonic_mach = Some(mach);
727 }
728
729 let bullet_type = if let Some(ref model) = self.inputs.bullet_model {
731 model.as_str()
732 } else {
733 "default"
734 };
735 let coeffs = PitchDampingCoefficients::from_bullet_type(bullet_type);
736 let pitch_damping = calculate_pitch_damping_coefficient(mach, &coeffs);
737
738 if pitch_damping < min_pitch_damping {
740 min_pitch_damping = pitch_damping;
741 }
742 }
743
744 if self.inputs.enable_precession_nutation {
746 if let Some(ref mut state) = angular_state {
747 let velocity_magnitude = velocity.magnitude();
748 let temp_c = self.atmosphere.temperature;
749 let temp_k = temp_c + 273.15;
750 let speed_of_sound = (1.4 * 287.05 * temp_k).sqrt();
751 let mach = velocity_magnitude / speed_of_sound;
752
753 let spin_rate_rad_s = if self.inputs.twist_rate > 0.0 {
755 let velocity_fps = velocity_magnitude * 3.28084;
756 let twist_rate_ft = self.inputs.twist_rate / 12.0;
757 (velocity_fps / twist_rate_ft) * 2.0 * std::f64::consts::PI
758 } else {
759 0.0
760 };
761
762 let params = PrecessionNutationParams {
764 mass_kg: self.inputs.bullet_mass,
765 caliber_m: self.inputs.bullet_diameter,
766 length_m: self.inputs.bullet_length,
767 spin_rate_rad_s,
768 spin_inertia: 6.94e-8, transverse_inertia: 9.13e-7, velocity_mps: velocity_magnitude,
771 air_density_kg_m3: air_density,
772 mach,
773 pitch_damping_coeff: -0.8,
774 nutation_damping_factor: 0.05,
775 };
776
777 *state = calculate_combined_angular_motion(
779 ¶ms,
780 state,
781 time,
782 self.time_step,
783 0.001, );
785
786 if state.yaw_angle.abs() > max_yaw_angle {
788 max_yaw_angle = state.yaw_angle.abs();
789 }
790 if state.precession_angle.abs() > max_precession_angle {
791 max_precession_angle = state.precession_angle.abs();
792 }
793 }
794 }
795
796 let dt = self.time_step;
798
799 let acc1 = self.calculate_acceleration(&position, &velocity, air_density, &wind_vector);
801
802 let pos2 = position + velocity * (dt * 0.5);
804 let vel2 = velocity + acc1 * (dt * 0.5);
805 let acc2 = self.calculate_acceleration(&pos2, &vel2, air_density, &wind_vector);
806
807 let pos3 = position + vel2 * (dt * 0.5);
809 let vel3 = velocity + acc2 * (dt * 0.5);
810 let acc3 = self.calculate_acceleration(&pos3, &vel3, air_density, &wind_vector);
811
812 let pos4 = position + vel3 * dt;
814 let vel4 = velocity + acc3 * dt;
815 let acc4 = self.calculate_acceleration(&pos4, &vel4, air_density, &wind_vector);
816
817 position += (velocity + vel2 * 2.0 + vel3 * 2.0 + vel4) * (dt / 6.0);
819 velocity += (acc1 + acc2 * 2.0 + acc3 * 2.0 + acc4) * (dt / 6.0);
820 time += dt;
821 }
822
823 let last_point = points.last().ok_or("No trajectory points generated")?;
825
826 let sampled_points = if self.inputs.enable_trajectory_sampling {
828 let trajectory_data = TrajectoryData {
829 times: points.iter().map(|p| p.time).collect(),
830 positions: points.iter().map(|p| p.position).collect(),
831 velocities: points
832 .iter()
833 .map(|p| {
834 Vector3::new(0.0, 0.0, p.velocity_magnitude)
836 })
837 .collect(),
838 transonic_distances: Vec::new(), };
840
841 let outputs = TrajectoryOutputs {
842 target_distance_horiz_m: last_point.position.z, target_vertical_height_m: last_point.position.y,
844 time_of_flight_s: last_point.time,
845 max_ord_dist_horiz_m: max_height,
846 };
847
848 let samples = sample_trajectory(
850 &trajectory_data,
851 &outputs,
852 self.inputs.sample_interval,
853 self.inputs.bullet_mass,
854 );
855 Some(samples)
856 } else {
857 None
858 };
859
860 Ok(TrajectoryResult {
861 max_range: last_point.position.z, max_height,
863 time_of_flight: last_point.time,
864 impact_velocity: last_point.velocity_magnitude,
865 impact_energy: last_point.kinetic_energy,
866 points,
867 sampled_points,
868 min_pitch_damping: if self.inputs.enable_pitch_damping {
869 Some(min_pitch_damping)
870 } else {
871 None
872 },
873 transonic_mach,
874 angular_state,
875 max_yaw_angle: if self.inputs.enable_precession_nutation {
876 Some(max_yaw_angle)
877 } else {
878 None
879 },
880 max_precession_angle: if self.inputs.enable_precession_nutation {
881 Some(max_precession_angle)
882 } else {
883 None
884 },
885 })
886 }
887
888 fn solve_rk45(&self) -> Result<TrajectoryResult, BallisticsError> {
889 let mut time = 0.0;
891 let mut position = Vector3::new(
892 0.0,
893 self.inputs.sight_height + self.inputs.muzzle_height,
894 0.0,
895 );
896
897 let horizontal_velocity = self.inputs.muzzle_velocity * self.inputs.muzzle_angle.cos();
900 let mut velocity = Vector3::new(
901 horizontal_velocity * self.inputs.azimuth_angle.sin(), self.inputs.muzzle_velocity * self.inputs.muzzle_angle.sin(), horizontal_velocity * self.inputs.azimuth_angle.cos(), );
905
906 let mut points = Vec::new();
907 let mut max_height = position.y;
908 let mut dt = 0.001; let tolerance = 1e-6; let safety_factor = 0.9; let max_dt = 0.01; let min_dt = 1e-6; let mut iteration_count = 0;
916 const MAX_ITERATIONS: usize = 100000;
917
918 while position.z < self.max_range
919 && position.y > self.inputs.ground_threshold
920 && time < 100.0
921 {
922 iteration_count += 1;
924 if iteration_count > MAX_ITERATIONS {
925 break; }
927
928 let velocity_magnitude = velocity.magnitude();
930 let kinetic_energy = 0.5 * self.inputs.bullet_mass * velocity_magnitude.powi(2);
931
932 points.push(TrajectoryPoint {
933 time,
934 position: position,
935 velocity_magnitude,
936 kinetic_energy,
937 });
938
939 if position.y > max_height {
940 max_height = position.y;
941 }
942
943 let air_density = calculate_air_density(&self.atmosphere);
945 let wind_vector = Vector3::new(
946 self.wind.speed * self.wind.direction.sin(), 0.0,
948 self.wind.speed * self.wind.direction.cos(), );
950
951 let (new_pos, new_vel, new_dt) = self.rk45_step(
953 &position,
954 &velocity,
955 dt,
956 air_density,
957 &wind_vector,
958 tolerance,
959 );
960
961 dt = (safety_factor * new_dt).clamp(min_dt, max_dt);
963
964 position = new_pos;
966 velocity = new_vel;
967 time += dt;
968 }
969
970 if points.is_empty() {
972 return Err(BallisticsError::from("No trajectory points calculated"));
973 }
974
975 let last_point = points.last().unwrap();
976
977 Ok(TrajectoryResult {
978 max_range: last_point.position.z, max_height,
980 time_of_flight: last_point.time,
981 impact_velocity: last_point.velocity_magnitude,
982 impact_energy: last_point.kinetic_energy,
983 points,
984 sampled_points: None, min_pitch_damping: None,
986 transonic_mach: None,
987 angular_state: None,
988 max_yaw_angle: None,
989 max_precession_angle: None,
990 })
991 }
992
993 fn rk45_step(
994 &self,
995 position: &Vector3<f64>,
996 velocity: &Vector3<f64>,
997 dt: f64,
998 air_density: f64,
999 wind_vector: &Vector3<f64>,
1000 tolerance: f64,
1001 ) -> (Vector3<f64>, Vector3<f64>, f64) {
1002 const A21: f64 = 1.0 / 5.0;
1004 const A31: f64 = 3.0 / 40.0;
1005 const A32: f64 = 9.0 / 40.0;
1006 const A41: f64 = 44.0 / 45.0;
1007 const A42: f64 = -56.0 / 15.0;
1008 const A43: f64 = 32.0 / 9.0;
1009 const A51: f64 = 19372.0 / 6561.0;
1010 const A52: f64 = -25360.0 / 2187.0;
1011 const A53: f64 = 64448.0 / 6561.0;
1012 const A54: f64 = -212.0 / 729.0;
1013 const A61: f64 = 9017.0 / 3168.0;
1014 const A62: f64 = -355.0 / 33.0;
1015 const A63: f64 = 46732.0 / 5247.0;
1016 const A64: f64 = 49.0 / 176.0;
1017 const A65: f64 = -5103.0 / 18656.0;
1018 const A71: f64 = 35.0 / 384.0;
1019 const A73: f64 = 500.0 / 1113.0;
1020 const A74: f64 = 125.0 / 192.0;
1021 const A75: f64 = -2187.0 / 6784.0;
1022 const A76: f64 = 11.0 / 84.0;
1023
1024 const B1: f64 = 35.0 / 384.0;
1026 const B3: f64 = 500.0 / 1113.0;
1027 const B4: f64 = 125.0 / 192.0;
1028 const B5: f64 = -2187.0 / 6784.0;
1029 const B6: f64 = 11.0 / 84.0;
1030
1031 const B1_ERR: f64 = 5179.0 / 57600.0;
1033 const B3_ERR: f64 = 7571.0 / 16695.0;
1034 const B4_ERR: f64 = 393.0 / 640.0;
1035 const B5_ERR: f64 = -92097.0 / 339200.0;
1036 const B6_ERR: f64 = 187.0 / 2100.0;
1037 const B7_ERR: f64 = 1.0 / 40.0;
1038
1039 let k1_v = self.calculate_acceleration(position, velocity, air_density, wind_vector);
1041 let k1_p = *velocity;
1042
1043 let p2 = position + dt * A21 * k1_p;
1044 let v2 = velocity + dt * A21 * k1_v;
1045 let k2_v = self.calculate_acceleration(&p2, &v2, air_density, wind_vector);
1046 let k2_p = v2;
1047
1048 let p3 = position + dt * (A31 * k1_p + A32 * k2_p);
1049 let v3 = velocity + dt * (A31 * k1_v + A32 * k2_v);
1050 let k3_v = self.calculate_acceleration(&p3, &v3, air_density, wind_vector);
1051 let k3_p = v3;
1052
1053 let p4 = position + dt * (A41 * k1_p + A42 * k2_p + A43 * k3_p);
1054 let v4 = velocity + dt * (A41 * k1_v + A42 * k2_v + A43 * k3_v);
1055 let k4_v = self.calculate_acceleration(&p4, &v4, air_density, wind_vector);
1056 let k4_p = v4;
1057
1058 let p5 = position + dt * (A51 * k1_p + A52 * k2_p + A53 * k3_p + A54 * k4_p);
1059 let v5 = velocity + dt * (A51 * k1_v + A52 * k2_v + A53 * k3_v + A54 * k4_v);
1060 let k5_v = self.calculate_acceleration(&p5, &v5, air_density, wind_vector);
1061 let k5_p = v5;
1062
1063 let p6 = position + dt * (A61 * k1_p + A62 * k2_p + A63 * k3_p + A64 * k4_p + A65 * k5_p);
1064 let v6 = velocity + dt * (A61 * k1_v + A62 * k2_v + A63 * k3_v + A64 * k4_v + A65 * k5_v);
1065 let k6_v = self.calculate_acceleration(&p6, &v6, air_density, wind_vector);
1066 let k6_p = v6;
1067
1068 let p7 = position + dt * (A71 * k1_p + A73 * k3_p + A74 * k4_p + A75 * k5_p + A76 * k6_p);
1069 let v7 = velocity + dt * (A71 * k1_v + A73 * k3_v + A74 * k4_v + A75 * k5_v + A76 * k6_v);
1070 let k7_v = self.calculate_acceleration(&p7, &v7, air_density, wind_vector);
1071 let k7_p = v7;
1072
1073 let new_pos = position + dt * (B1 * k1_p + B3 * k3_p + B4 * k4_p + B5 * k5_p + B6 * k6_p);
1075 let new_vel = velocity + dt * (B1 * k1_v + B3 * k3_v + B4 * k4_v + B5 * k5_v + B6 * k6_v);
1076
1077 let pos_err = position
1079 + dt * (B1_ERR * k1_p
1080 + B3_ERR * k3_p
1081 + B4_ERR * k4_p
1082 + B5_ERR * k5_p
1083 + B6_ERR * k6_p
1084 + B7_ERR * k7_p);
1085 let vel_err = velocity
1086 + dt * (B1_ERR * k1_v
1087 + B3_ERR * k3_v
1088 + B4_ERR * k4_v
1089 + B5_ERR * k5_v
1090 + B6_ERR * k6_v
1091 + B7_ERR * k7_v);
1092
1093 let pos_error = (new_pos - pos_err).magnitude();
1095 let vel_error = (new_vel - vel_err).magnitude();
1096 let error = (pos_error + vel_error) / (1.0 + position.magnitude() + velocity.magnitude());
1097
1098 let dt_new = if error < tolerance {
1100 dt * (tolerance / error).powf(0.2).min(2.0)
1101 } else {
1102 dt * (tolerance / error).powf(0.25).max(0.1)
1103 };
1104
1105 (new_pos, new_vel, dt_new)
1106 }
1107
1108 fn calculate_acceleration(
1109 &self,
1110 position: &Vector3<f64>,
1111 velocity: &Vector3<f64>,
1112 air_density: f64,
1113 wind_vector: &Vector3<f64>,
1114 ) -> Vector3<f64> {
1115 let actual_wind = if self.inputs.enable_wind_shear {
1117 self.get_wind_at_altitude(position.y)
1118 } else {
1119 *wind_vector
1120 };
1121
1122 let relative_velocity = velocity - actual_wind;
1123 let velocity_magnitude = relative_velocity.magnitude();
1124
1125 if velocity_magnitude < 0.001 {
1126 return Vector3::new(0.0, -9.81, 0.0);
1127 }
1128
1129 let cd = self.calculate_drag_coefficient(velocity_magnitude);
1131
1132 let effective_bc = if let Some(ref cluster_bc) = self.cluster_bc {
1134 let velocity_fps = velocity_magnitude * 3.28084;
1136 cluster_bc.apply_correction(
1137 self.inputs.bc_value,
1138 self.inputs.caliber_inches * 0.0254, self.inputs.weight_grains,
1140 velocity_fps,
1141 )
1142 } else {
1143 self.inputs.bc_value
1144 };
1145
1146 let velocity_fps = velocity_magnitude * 3.28084; let cd_to_retard = 0.000683 * 0.30; let standard_factor = cd * cd_to_retard;
1152 let density_scale = air_density / 1.225; let a_drag_ft_s2 =
1156 (velocity_fps * velocity_fps) * standard_factor * density_scale / effective_bc;
1157 let a_drag_m_s2 = a_drag_ft_s2 * 0.3048; let drag_acceleration = -a_drag_m_s2 * (relative_velocity / velocity_magnitude);
1161
1162 drag_acceleration + Vector3::new(0.0, -9.81, 0.0)
1164 }
1165
1166 fn calculate_drag_coefficient(&self, velocity: f64) -> f64 {
1167 let temp_c = self.atmosphere.temperature;
1169 let temp_k = temp_c + 273.15;
1170 let gamma = 1.4; let r_specific = 287.05; let speed_of_sound = (gamma * r_specific * temp_k).sqrt();
1173 let mach = velocity / speed_of_sound;
1174
1175 let base_cd = crate::drag::get_drag_coefficient(mach, &self.inputs.bc_type);
1177
1178 let projectile_shape = if let Some(ref model) = self.inputs.bullet_model {
1180 if model.to_lowercase().contains("boat") || model.to_lowercase().contains("bt") {
1182 ProjectileShape::BoatTail
1183 } else if model.to_lowercase().contains("round") || model.to_lowercase().contains("rn")
1184 {
1185 ProjectileShape::RoundNose
1186 } else if model.to_lowercase().contains("flat") || model.to_lowercase().contains("fb") {
1187 ProjectileShape::FlatBase
1188 } else {
1189 get_projectile_shape(
1191 self.inputs.bullet_diameter,
1192 self.inputs.bullet_mass / 0.00006479891, &self.inputs.bc_type.to_string(),
1194 )
1195 }
1196 } else {
1197 get_projectile_shape(
1199 self.inputs.bullet_diameter,
1200 self.inputs.bullet_mass / 0.00006479891, &self.inputs.bc_type.to_string(),
1202 )
1203 };
1204
1205 let include_wave_drag = self.inputs.enable_advanced_effects;
1208 transonic_correction(mach, base_cd, projectile_shape, include_wave_drag)
1209 }
1210}
1211
1212#[derive(Debug, Clone)]
1214pub struct MonteCarloParams {
1215 pub num_simulations: usize,
1216 pub velocity_std_dev: f64,
1217 pub angle_std_dev: f64,
1218 pub bc_std_dev: f64,
1219 pub wind_speed_std_dev: f64,
1220 pub target_distance: Option<f64>,
1221 pub base_wind_speed: f64,
1222 pub base_wind_direction: f64,
1223 pub azimuth_std_dev: f64, }
1225
1226impl Default for MonteCarloParams {
1227 fn default() -> Self {
1228 Self {
1229 num_simulations: 1000,
1230 velocity_std_dev: 1.0,
1231 angle_std_dev: 0.001,
1232 bc_std_dev: 0.01,
1233 wind_speed_std_dev: 1.0,
1234 target_distance: None,
1235 base_wind_speed: 0.0,
1236 base_wind_direction: 0.0,
1237 azimuth_std_dev: 0.001, }
1239 }
1240}
1241
1242#[derive(Debug, Clone)]
1244pub struct MonteCarloResults {
1245 pub ranges: Vec<f64>,
1246 pub impact_velocities: Vec<f64>,
1247 pub impact_positions: Vec<Vector3<f64>>,
1248}
1249
1250pub fn run_monte_carlo(
1252 base_inputs: BallisticInputs,
1253 params: MonteCarloParams,
1254) -> Result<MonteCarloResults, BallisticsError> {
1255 let base_wind = WindConditions {
1256 speed: params.base_wind_speed,
1257 direction: params.base_wind_direction,
1258 };
1259 run_monte_carlo_with_wind(base_inputs, base_wind, params)
1260}
1261
1262pub fn run_monte_carlo_with_wind(
1264 base_inputs: BallisticInputs,
1265 base_wind: WindConditions,
1266 params: MonteCarloParams,
1267) -> Result<MonteCarloResults, BallisticsError> {
1268 use rand::thread_rng;
1269 use rand_distr::{Distribution, Normal};
1270
1271 let mut rng = thread_rng();
1272 let mut ranges = Vec::new();
1273 let mut impact_velocities = Vec::new();
1274 let mut impact_positions = Vec::new();
1275
1276 let baseline_solver =
1278 TrajectorySolver::new(base_inputs.clone(), base_wind.clone(), Default::default());
1279 let baseline_result = baseline_solver.solve()?;
1280
1281 let target_distance = params.target_distance.unwrap_or(baseline_result.max_range);
1283
1284 let baseline_at_target = baseline_result
1286 .position_at_range(target_distance)
1287 .ok_or("Could not interpolate baseline at target distance")?;
1288
1289 let velocity_dist = Normal::new(base_inputs.muzzle_velocity, params.velocity_std_dev)
1291 .map_err(|e| format!("Invalid velocity distribution: {}", e))?;
1292 let angle_dist = Normal::new(base_inputs.muzzle_angle, params.angle_std_dev)
1293 .map_err(|e| format!("Invalid angle distribution: {}", e))?;
1294 let bc_dist = Normal::new(base_inputs.bc_value, params.bc_std_dev)
1295 .map_err(|e| format!("Invalid BC distribution: {}", e))?;
1296 let wind_speed_dist = Normal::new(base_wind.speed, params.wind_speed_std_dev)
1297 .map_err(|e| format!("Invalid wind speed distribution: {}", e))?;
1298 let wind_dir_dist =
1299 Normal::new(base_wind.direction, params.wind_speed_std_dev * 0.1) .map_err(|e| format!("Invalid wind direction distribution: {}", e))?;
1301 let azimuth_dist = Normal::new(base_inputs.azimuth_angle, params.azimuth_std_dev)
1302 .map_err(|e| format!("Invalid azimuth distribution: {}", e))?;
1303
1304 let pointing_error_dist = Normal::new(0.0, params.angle_std_dev * target_distance)
1306 .map_err(|e| format!("Invalid pointing distribution: {}", e))?;
1307
1308 for _ in 0..params.num_simulations {
1309 let mut inputs = base_inputs.clone();
1311 inputs.muzzle_velocity = velocity_dist.sample(&mut rng).max(0.0);
1312 inputs.muzzle_angle = angle_dist.sample(&mut rng);
1313 inputs.bc_value = bc_dist.sample(&mut rng).max(0.01);
1314 inputs.azimuth_angle = azimuth_dist.sample(&mut rng); let wind = WindConditions {
1318 speed: wind_speed_dist.sample(&mut rng).abs(),
1319 direction: wind_dir_dist.sample(&mut rng),
1320 };
1321
1322 let solver = TrajectorySolver::new(inputs, wind, Default::default());
1324 match solver.solve() {
1325 Ok(result) => {
1326 ranges.push(result.max_range);
1327 impact_velocities.push(result.impact_velocity);
1328
1329 if let Some(pos_at_target) = result.position_at_range(target_distance) {
1331 let mut deviation = Vector3::new(
1334 pos_at_target.x - baseline_at_target.x, pos_at_target.y - baseline_at_target.y, 0.0, );
1338
1339 let pointing_error_y = pointing_error_dist.sample(&mut rng);
1342 deviation.y += pointing_error_y;
1343
1344 impact_positions.push(deviation);
1345 }
1346 }
1347 Err(_) => {
1348 continue;
1350 }
1351 }
1352 }
1353
1354 if ranges.is_empty() {
1355 return Err("No successful simulations".into());
1356 }
1357
1358 Ok(MonteCarloResults {
1359 ranges,
1360 impact_velocities,
1361 impact_positions,
1362 })
1363}
1364
1365pub fn calculate_zero_angle(
1367 inputs: BallisticInputs,
1368 target_distance: f64,
1369 target_height: f64,
1370) -> Result<f64, BallisticsError> {
1371 calculate_zero_angle_with_conditions(
1372 inputs,
1373 target_distance,
1374 target_height,
1375 WindConditions::default(),
1376 AtmosphericConditions::default(),
1377 )
1378}
1379
1380pub fn calculate_zero_angle_with_conditions(
1381 inputs: BallisticInputs,
1382 target_distance: f64,
1383 target_height: f64,
1384 wind: WindConditions,
1385 atmosphere: AtmosphericConditions,
1386) -> Result<f64, BallisticsError> {
1387 let get_height_at_angle = |angle: f64| -> Result<Option<f64>, BallisticsError> {
1389 let mut test_inputs = inputs.clone();
1390 test_inputs.muzzle_angle = angle;
1391
1392 let mut solver = TrajectorySolver::new(test_inputs, wind.clone(), atmosphere.clone());
1393 solver.set_max_range(target_distance * 2.0);
1394 solver.set_time_step(0.001);
1395 let result = solver.solve()?;
1396
1397 for i in 0..result.points.len() {
1399 if result.points[i].position.z >= target_distance {
1400 if i > 0 {
1401 let p1 = &result.points[i - 1];
1402 let p2 = &result.points[i];
1403 let t = (target_distance - p1.position.z) / (p2.position.z - p1.position.z);
1404 return Ok(Some(p1.position.y + t * (p2.position.y - p1.position.y)));
1405 } else {
1406 return Ok(Some(result.points[i].position.y));
1407 }
1408 }
1409 }
1410 Ok(None)
1411 };
1412
1413 let mut low_angle = 0.0; let mut high_angle = 0.2; let tolerance = 0.00001; let max_iterations = 50;
1419
1420 let low_height = get_height_at_angle(low_angle)?;
1423 let high_height = get_height_at_angle(high_angle)?;
1424
1425 match (low_height, high_height) {
1426 (Some(lh), Some(hh)) => {
1427 let low_error = lh - target_height;
1428 let high_error = hh - target_height;
1429
1430 if low_error > 0.0 && high_error > 0.0 {
1433 } else if low_error < 0.0 && high_error < 0.0 {
1438 let mut expanded = false;
1441 for multiplier in [2.0, 3.0, 4.0] {
1442 let new_high = (high_angle * multiplier).min(0.785);
1443 if let Ok(Some(h)) = get_height_at_angle(new_high) {
1444 if h - target_height > 0.0 {
1445 high_angle = new_high;
1446 expanded = true;
1447 break;
1448 }
1449 }
1450 if new_high >= 0.785 {
1451 break;
1452 }
1453 }
1454 if !expanded {
1455 return Err("Cannot find zero angle: target beyond effective range even at maximum angle".into());
1456 }
1457 }
1458 }
1460 (None, Some(_hh)) => {
1461 }
1464 (Some(_lh), None) => {
1465 return Err(
1467 "Cannot find zero angle: high angle trajectory doesn't reach target distance"
1468 .into(),
1469 );
1470 }
1471 (None, None) => {
1472 return Err(
1474 "Cannot find zero angle: trajectory cannot reach target distance at any angle"
1475 .into(),
1476 );
1477 }
1478 }
1479
1480 for _iteration in 0..max_iterations {
1481 let mid_angle = (low_angle + high_angle) / 2.0;
1482
1483 let mut test_inputs = inputs.clone();
1484 test_inputs.muzzle_angle = mid_angle;
1485
1486 let mut solver = TrajectorySolver::new(test_inputs, wind.clone(), atmosphere.clone());
1487 solver.set_max_range(target_distance * 2.0);
1489 solver.set_time_step(0.001);
1490 let result = solver.solve()?;
1491
1492 let mut height_at_target = None;
1494 for i in 0..result.points.len() {
1495 if result.points[i].position.z >= target_distance {
1496 if i > 0 {
1497 let p1 = &result.points[i - 1];
1499 let p2 = &result.points[i];
1500 let t = (target_distance - p1.position.z) / (p2.position.z - p1.position.z);
1501 height_at_target = Some(p1.position.y + t * (p2.position.y - p1.position.y));
1502 } else {
1503 height_at_target = Some(result.points[i].position.y);
1504 }
1505 break;
1506 }
1507 }
1508
1509 match height_at_target {
1510 Some(height) => {
1511 let error = height - target_height;
1512 if error.abs() < 0.001 {
1515 return Ok(mid_angle);
1516 }
1517
1518 if (high_angle - low_angle).abs() < tolerance {
1522 if error.abs() < 0.01 {
1523 return Ok(mid_angle);
1525 }
1526 return Ok(mid_angle);
1529 }
1530
1531 if error > 0.0 {
1532 high_angle = mid_angle;
1533 } else {
1534 low_angle = mid_angle;
1535 }
1536 }
1537 None => {
1538 low_angle = mid_angle;
1540
1541 if (high_angle - low_angle).abs() < tolerance {
1543 return Err("Trajectory cannot reach target distance - angle converged without valid solution".into());
1544 }
1545 }
1546 }
1547 }
1548
1549 Err("Failed to find zero angle".into())
1550}
1551
1552pub fn estimate_bc_from_trajectory(
1554 velocity: f64,
1555 mass: f64,
1556 diameter: f64,
1557 points: &[(f64, f64)], ) -> Result<f64, BallisticsError> {
1559 let mut best_bc = 0.5;
1561 let mut best_error = f64::MAX;
1562 let mut found_valid = false;
1563
1564 for bc in (100..1000).step_by(10) {
1566 let bc_value = bc as f64 / 1000.0;
1567
1568 let inputs = BallisticInputs {
1569 muzzle_velocity: velocity,
1570 bc_value,
1571 bullet_mass: mass,
1572 bullet_diameter: diameter,
1573 ..Default::default()
1574 };
1575
1576 let mut solver = TrajectorySolver::new(inputs, Default::default(), Default::default());
1577 solver.set_max_range(points.last().map(|(d, _)| *d * 1.5).unwrap_or(1000.0));
1579
1580 let result = match solver.solve() {
1581 Ok(r) => r,
1582 Err(_) => continue, };
1584
1585 let mut total_error = 0.0;
1587 for (target_dist, target_drop) in points {
1588 let mut calculated_drop = None;
1590 for i in 0..result.points.len() {
1591 if result.points[i].position.z >= *target_dist {
1592 if i > 0 {
1593 let p1 = &result.points[i - 1];
1595 let p2 = &result.points[i];
1596 let t = (target_dist - p1.position.z) / (p2.position.z - p1.position.z);
1597 calculated_drop =
1598 Some(-(p1.position.y + t * (p2.position.y - p1.position.y)));
1599 } else {
1600 calculated_drop = Some(-result.points[i].position.y);
1601 }
1602 break;
1603 }
1604 }
1605
1606 if let Some(drop) = calculated_drop {
1607 let error = (drop - target_drop).abs();
1608 total_error += error * error;
1609 }
1610 }
1611
1612 if total_error < best_error {
1613 best_error = total_error;
1614 best_bc = bc_value;
1615 found_valid = true;
1616 }
1617 }
1618
1619 if !found_valid {
1620 return Err(BallisticsError::from("Unable to estimate BC from provided data. Check that drop values are in correct units.".to_string()));
1621 }
1622
1623 Ok(best_bc)
1624}
1625
1626fn calculate_air_density(atmosphere: &AtmosphericConditions) -> f64 {
1628 let r_specific = 287.058; let temperature_k = atmosphere.temperature + 273.15;
1632
1633 let pressure_pa = atmosphere.pressure * 100.0;
1635
1636 let density = pressure_pa / (r_specific * temperature_k);
1638
1639 let altitude_factor = (-atmosphere.altitude / 8000.0).exp();
1641
1642 density * altitude_factor
1643}
1644
1645use rand;
1647use rand_distr;