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::WindShearModel;
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 enable_magnus: bool, pub enable_coriolis: bool, pub use_powder_sensitivity: bool,
113 pub powder_temp_sensitivity: f64,
114 pub powder_temp: f64, pub tipoff_yaw: f64, pub tipoff_decay_distance: f64, pub use_bc_segments: bool,
118 pub bc_segments: Option<Vec<(f64, f64)>>, pub bc_segments_data: Option<Vec<crate::BCSegmentData>>, pub use_enhanced_spin_drift: bool,
121 pub use_form_factor: bool,
122 pub enable_wind_shear: bool,
123 pub wind_shear_model: String,
124 pub enable_trajectory_sampling: bool,
125 pub sample_interval: f64, pub enable_pitch_damping: bool,
127 pub enable_precession_nutation: bool,
128 pub use_cluster_bc: bool, pub custom_drag_table: Option<crate::drag::DragTable>,
132
133 pub bc_type_str: Option<String>,
135}
136
137impl Default for BallisticInputs {
138 fn default() -> Self {
139 let mass_kg = 0.01;
140 let diameter_m = 0.00762;
141 let bc = 0.5;
142 let muzzle_angle_rad = 0.0;
143 let bc_type = DragModel::G1;
144
145 Self {
146 bc_value: bc,
148 bc_type,
149 bullet_mass: mass_kg,
150 muzzle_velocity: 800.0,
151 bullet_diameter: diameter_m,
152 bullet_length: diameter_m * 4.5, muzzle_angle: muzzle_angle_rad,
156 target_distance: 100.0,
157 azimuth_angle: 0.0,
158 shooting_angle: 0.0,
159 sight_height: 0.05,
160 muzzle_height: 0.0, target_height: 0.0, ground_threshold: -100.0, altitude: 0.0,
166 temperature: 15.0,
167 pressure: 1013.25, humidity: 0.5, latitude: None,
170
171 wind_speed: 0.0,
173 wind_angle: 0.0,
174
175 twist_rate: 12.0, is_twist_right: true,
178 caliber_inches: diameter_m / 0.0254, weight_grains: mass_kg / 0.00006479891, manufacturer: None,
181 bullet_model: None,
182 bullet_id: None,
183 bullet_cluster: None,
184
185 use_rk4: true, use_adaptive_rk45: true, enable_advanced_effects: false,
191 enable_magnus: false,
192 enable_coriolis: false,
193 use_powder_sensitivity: false,
194 powder_temp_sensitivity: 0.0,
195 powder_temp: 15.0,
196 tipoff_yaw: 0.0,
197 tipoff_decay_distance: 50.0,
198 use_bc_segments: false,
199 bc_segments: None,
200 bc_segments_data: None,
201 use_enhanced_spin_drift: false,
202 use_form_factor: false,
203 enable_wind_shear: false,
204 wind_shear_model: "none".to_string(),
205 enable_trajectory_sampling: false,
206 sample_interval: 10.0, enable_pitch_damping: false,
208 enable_precession_nutation: false,
209 use_cluster_bc: false, custom_drag_table: None,
213
214 bc_type_str: None,
216 }
217 }
218}
219
220#[derive(Debug, Clone)]
222pub struct WindConditions {
223 pub speed: f64, pub direction: f64, }
226
227impl Default for WindConditions {
228 fn default() -> Self {
229 Self {
230 speed: 0.0,
231 direction: 0.0,
232 }
233 }
234}
235
236#[derive(Debug, Clone)]
238pub struct AtmosphericConditions {
239 pub temperature: f64, pub pressure: f64, pub humidity: f64, pub altitude: f64, }
244
245impl Default for AtmosphericConditions {
246 fn default() -> Self {
247 Self {
248 temperature: 15.0,
249 pressure: 1013.25,
250 humidity: 50.0,
251 altitude: 0.0,
252 }
253 }
254}
255
256#[derive(Debug, Clone)]
258pub struct TrajectoryPoint {
259 pub time: f64,
260 pub position: Vector3<f64>,
261 pub velocity_magnitude: f64,
262 pub kinetic_energy: f64,
263}
264
265#[derive(Debug, Clone)]
267pub struct TrajectoryResult {
268 pub max_range: f64,
269 pub max_height: f64,
270 pub time_of_flight: f64,
271 pub impact_velocity: f64,
272 pub impact_energy: f64,
273 pub points: Vec<TrajectoryPoint>,
274 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>, }
281
282impl TrajectoryResult {
283 pub fn position_at_range(&self, target_range: f64) -> Option<Vector3<f64>> {
287 if self.points.is_empty() {
288 return None;
289 }
290
291 for i in 0..self.points.len() - 1 {
293 let p1 = &self.points[i];
294 let p2 = &self.points[i + 1];
295
296 if p1.position.x <= target_range && p2.position.x >= target_range {
298 let dx = p2.position.x - p1.position.x;
300 if dx.abs() < 1e-10 {
301 return Some(p1.position);
302 }
303 let t = (target_range - p1.position.x) / dx;
304
305 return Some(Vector3::new(
307 target_range,
308 p1.position.y + t * (p2.position.y - p1.position.y),
309 p1.position.z + t * (p2.position.z - p1.position.z),
310 ));
311 }
312 }
313
314 self.points.last().map(|p| p.position)
316 }
317}
318
319pub struct TrajectorySolver {
321 inputs: BallisticInputs,
322 wind: WindConditions,
323 atmosphere: AtmosphericConditions,
324 max_range: f64,
325 time_step: f64,
326 cluster_bc: Option<ClusterBCDegradation>,
327}
328
329impl TrajectorySolver {
330 pub fn new(
331 mut inputs: BallisticInputs,
332 wind: WindConditions,
333 atmosphere: AtmosphericConditions,
334 ) -> Self {
335 inputs.caliber_inches = inputs.bullet_diameter / 0.0254;
337 inputs.weight_grains = inputs.bullet_mass / 0.00006479891;
338
339 let cluster_bc = if inputs.use_cluster_bc {
341 Some(ClusterBCDegradation::new())
342 } else {
343 None
344 };
345
346 Self {
347 inputs,
348 wind,
349 atmosphere,
350 max_range: 1000.0,
351 time_step: 0.001,
352 cluster_bc,
353 }
354 }
355
356 pub fn set_max_range(&mut self, range: f64) {
357 self.max_range = range;
358 }
359
360 pub fn set_time_step(&mut self, step: f64) {
361 self.time_step = step;
362 }
363
364 fn get_wind_at_altitude(&self, altitude_m: f64) -> Vector3<f64> {
365 let model = if self.inputs.wind_shear_model == "logarithmic" {
374 WindShearModel::Logarithmic
375 } else {
376 WindShearModel::PowerLaw };
378 let speed_ratio = crate::wind_shear::boundary_layer_speed_ratio(altitude_m, model);
379
380 Vector3::new(
381 self.wind.speed * self.wind.direction.cos() * speed_ratio, 0.0,
383 self.wind.speed * self.wind.direction.sin() * speed_ratio, )
385 }
386
387 pub fn solve(&self) -> Result<TrajectoryResult, BallisticsError> {
388 let mut result = if self.inputs.use_rk4 {
389 if self.inputs.use_adaptive_rk45 {
390 self.solve_rk45()?
391 } else {
392 self.solve_rk4()?
393 }
394 } else {
395 self.solve_euler()?
396 };
397 self.apply_spin_drift(&mut result);
398 Ok(result)
399 }
400
401 fn apply_spin_drift(&self, result: &mut TrajectoryResult) {
407 if !self.inputs.use_enhanced_spin_drift {
408 return;
409 }
410 let d_in = self.inputs.bullet_diameter / 0.0254; let m_gr = self.inputs.bullet_mass / 0.00006479891; let twist_in = self.inputs.twist_rate; if d_in <= 0.0 || m_gr <= 0.0 || twist_in <= 0.0 {
414 return;
415 }
416
417 let length_in = if self.inputs.bullet_length > 0.0 {
419 self.inputs.bullet_length / 0.0254
420 } else {
421 4.5 * d_in
422 };
423 let sg = crate::spin_drift::miller_stability(d_in, m_gr, twist_in, length_in);
424 let sign = if self.inputs.is_twist_right { 1.0 } else { -1.0 };
425
426 for p in result.points.iter_mut() {
427 if p.time <= 0.0 {
428 continue;
429 }
430 let sd_in = 1.25 * (sg + 1.2) * p.time.powf(1.83); p.position.z += sign * sd_in * 0.0254; }
433
434 if let Some(samples) = result.sampled_points.as_mut() {
438 for s in samples.iter_mut() {
439 if s.time_s <= 0.0 {
440 continue;
441 }
442 let sd_in = 1.25 * (sg + 1.2) * s.time_s.powf(1.83);
443 s.wind_drift_m += sign * sd_in * 0.0254;
444 }
445 }
446 }
447
448 fn solve_euler(&self) -> Result<TrajectoryResult, BallisticsError> {
449 let mut time = 0.0;
451 let mut position = Vector3::new(
454 0.0,
455 self.inputs.muzzle_height, 0.0,
457 );
458 let horizontal_velocity = self.inputs.muzzle_velocity * self.inputs.muzzle_angle.cos();
461 let mut velocity = Vector3::new(
462 horizontal_velocity * self.inputs.azimuth_angle.cos(), self.inputs.muzzle_velocity * self.inputs.muzzle_angle.sin(), horizontal_velocity * self.inputs.azimuth_angle.sin(), );
466
467 let mut points = Vec::new();
468 let mut max_height = position.y;
469 let mut min_pitch_damping = 1.0; let mut transonic_mach = None; let mut angular_state = if self.inputs.enable_precession_nutation {
474 Some(AngularState {
475 pitch_angle: 0.001, yaw_angle: 0.001,
477 pitch_rate: 0.0,
478 yaw_rate: 0.0,
479 precession_angle: 0.0,
480 nutation_phase: 0.0,
481 })
482 } else {
483 None
484 };
485 let mut max_yaw_angle = 0.0;
486 let mut max_precession_angle = 0.0;
487
488 let air_density = calculate_air_density(&self.atmosphere);
490
491 let wind_vector = Vector3::new(
493 self.wind.speed * self.wind.direction.cos(), 0.0,
495 self.wind.speed * self.wind.direction.sin(), );
497
498 let pitch_coeffs = PitchDampingCoefficients::from_bullet_type(
501 self.inputs.bullet_model.as_deref().unwrap_or("default"),
502 );
503
504 while position.x < self.max_range && position.y > self.inputs.ground_threshold && time < 100.0 {
506 let velocity_magnitude = velocity.magnitude();
508 let kinetic_energy =
509 0.5 * self.inputs.bullet_mass * velocity_magnitude * velocity_magnitude;
510
511 points.push(TrajectoryPoint {
512 time,
513 position: position,
514 velocity_magnitude,
515 kinetic_energy,
516 });
517
518 #[cfg(debug_assertions)]
522 if points.len() == 1 || points.len() % 100 == 0 {
523 eprintln!("Trajectory point {}: time={:.3}s, downrange={:.2}m, vertical={:.2}m, lateral={:.2}m, vel={:.1}m/s",
524 points.len(), time, position.x, position.y, position.z, velocity_magnitude);
525 }
526
527 if position.y > max_height {
529 max_height = position.y;
530 }
531
532 if self.inputs.enable_pitch_damping {
534 let temp_c = self.atmosphere.temperature;
535 let temp_k = temp_c + 273.15;
536 let speed_of_sound = (1.4 * 287.05 * temp_k).sqrt();
537 let mach = velocity_magnitude / speed_of_sound;
538
539 if transonic_mach.is_none() && mach < 1.2 && mach > 0.8 {
541 transonic_mach = Some(mach);
542 }
543
544 let pitch_damping = calculate_pitch_damping_coefficient(mach, &pitch_coeffs);
546
547 if pitch_damping < min_pitch_damping {
549 min_pitch_damping = pitch_damping;
550 }
551 }
552
553 if self.inputs.enable_precession_nutation {
555 if let Some(ref mut state) = angular_state {
556 let velocity_magnitude = velocity.magnitude();
557 let temp_c = self.atmosphere.temperature;
558 let temp_k = temp_c + 273.15;
559 let speed_of_sound = (1.4 * 287.05 * temp_k).sqrt();
560 let mach = velocity_magnitude / speed_of_sound;
561
562 let spin_rate_rad_s = if self.inputs.twist_rate > 0.0 {
564 let velocity_fps = velocity_magnitude * 3.28084;
565 let twist_rate_ft = self.inputs.twist_rate / 12.0;
566 (velocity_fps / twist_rate_ft) * 2.0 * std::f64::consts::PI
567 } else {
568 0.0
569 };
570
571 let params = PrecessionNutationParams {
573 mass_kg: self.inputs.bullet_mass,
574 caliber_m: self.inputs.bullet_diameter,
575 length_m: self.inputs.bullet_length,
576 spin_rate_rad_s,
577 spin_inertia: 6.94e-8, transverse_inertia: 9.13e-7, velocity_mps: velocity_magnitude,
580 air_density_kg_m3: air_density,
581 mach,
582 pitch_damping_coeff: -0.8,
583 nutation_damping_factor: 0.05,
584 };
585
586 *state = calculate_combined_angular_motion(
588 ¶ms,
589 state,
590 time,
591 self.time_step,
592 0.001, );
594
595 if state.yaw_angle.abs() > max_yaw_angle {
597 max_yaw_angle = state.yaw_angle.abs();
598 }
599 if state.precession_angle.abs() > max_precession_angle {
600 max_precession_angle = state.precession_angle.abs();
601 }
602 }
603 }
604
605 let acceleration =
612 self.calculate_acceleration(&position, &velocity, air_density, &wind_vector);
613
614 velocity += acceleration * self.time_step;
616 position += velocity * self.time_step;
617 time += self.time_step;
618 }
619
620 let last_point = points.last().ok_or("No trajectory points generated")?;
622
623 let sampled_points = if self.inputs.enable_trajectory_sampling {
625 let trajectory_data = TrajectoryData {
626 times: points.iter().map(|p| p.time).collect(),
627 positions: points.iter().map(|p| p.position).collect(),
628 velocities: points
629 .iter()
630 .map(|p| {
631 Vector3::new(0.0, 0.0, p.velocity_magnitude)
633 })
634 .collect(),
635 transonic_distances: Vec::new(), };
637
638 let sight_position_m = self.inputs.muzzle_height + self.inputs.sight_height;
643 let outputs = TrajectoryOutputs {
644 target_distance_horiz_m: last_point.position.x, target_vertical_height_m: sight_position_m,
646 time_of_flight_s: last_point.time,
647 max_ord_dist_horiz_m: max_height,
648 sight_height_m: sight_position_m,
649 };
650
651 let samples = sample_trajectory(
653 &trajectory_data,
654 &outputs,
655 self.inputs.sample_interval,
656 self.inputs.bullet_mass,
657 );
658 Some(samples)
659 } else {
660 None
661 };
662
663 Ok(TrajectoryResult {
664 max_range: last_point.position.x, max_height,
666 time_of_flight: last_point.time,
667 impact_velocity: last_point.velocity_magnitude,
668 impact_energy: last_point.kinetic_energy,
669 points,
670 sampled_points,
671 min_pitch_damping: if self.inputs.enable_pitch_damping {
672 Some(min_pitch_damping)
673 } else {
674 None
675 },
676 transonic_mach,
677 angular_state,
678 max_yaw_angle: if self.inputs.enable_precession_nutation {
679 Some(max_yaw_angle)
680 } else {
681 None
682 },
683 max_precession_angle: if self.inputs.enable_precession_nutation {
684 Some(max_precession_angle)
685 } else {
686 None
687 },
688 })
689 }
690
691 fn solve_rk4(&self) -> Result<TrajectoryResult, BallisticsError> {
692 let mut time = 0.0;
694 let mut position = Vector3::new(
698 0.0,
699 self.inputs.muzzle_height, 0.0,
701 );
702
703 let horizontal_velocity = self.inputs.muzzle_velocity * self.inputs.muzzle_angle.cos();
706 let mut velocity = Vector3::new(
707 horizontal_velocity * self.inputs.azimuth_angle.cos(), self.inputs.muzzle_velocity * self.inputs.muzzle_angle.sin(), horizontal_velocity * self.inputs.azimuth_angle.sin(), );
711
712 let mut points = Vec::new();
713 let mut max_height = position.y;
714 let mut min_pitch_damping = 1.0; let mut transonic_mach = None; let mut angular_state = if self.inputs.enable_precession_nutation {
719 Some(AngularState {
720 pitch_angle: 0.001, yaw_angle: 0.001,
722 pitch_rate: 0.0,
723 yaw_rate: 0.0,
724 precession_angle: 0.0,
725 nutation_phase: 0.0,
726 })
727 } else {
728 None
729 };
730 let mut max_yaw_angle = 0.0;
731 let mut max_precession_angle = 0.0;
732
733 let air_density = calculate_air_density(&self.atmosphere);
735
736 let wind_vector = Vector3::new(
738 self.wind.speed * self.wind.direction.cos(), 0.0,
740 self.wind.speed * self.wind.direction.sin(), );
742
743 let pitch_coeffs = PitchDampingCoefficients::from_bullet_type(
746 self.inputs.bullet_model.as_deref().unwrap_or("default"),
747 );
748
749 while position.x < self.max_range && position.y > self.inputs.ground_threshold && time < 100.0 {
751 let velocity_magnitude = velocity.magnitude();
753 let kinetic_energy =
754 0.5 * self.inputs.bullet_mass * velocity_magnitude * velocity_magnitude;
755
756 points.push(TrajectoryPoint {
757 time,
758 position: position,
759 velocity_magnitude,
760 kinetic_energy,
761 });
762
763 if position.y > max_height {
764 max_height = position.y;
765 }
766
767 if self.inputs.enable_pitch_damping {
769 let temp_c = self.atmosphere.temperature;
770 let temp_k = temp_c + 273.15;
771 let speed_of_sound = (1.4 * 287.05 * temp_k).sqrt();
772 let mach = velocity_magnitude / speed_of_sound;
773
774 if transonic_mach.is_none() && mach < 1.2 && mach > 0.8 {
776 transonic_mach = Some(mach);
777 }
778
779 let pitch_damping = calculate_pitch_damping_coefficient(mach, &pitch_coeffs);
781
782 if pitch_damping < min_pitch_damping {
784 min_pitch_damping = pitch_damping;
785 }
786 }
787
788 if self.inputs.enable_precession_nutation {
790 if let Some(ref mut state) = angular_state {
791 let velocity_magnitude = velocity.magnitude();
792 let temp_c = self.atmosphere.temperature;
793 let temp_k = temp_c + 273.15;
794 let speed_of_sound = (1.4 * 287.05 * temp_k).sqrt();
795 let mach = velocity_magnitude / speed_of_sound;
796
797 let spin_rate_rad_s = if self.inputs.twist_rate > 0.0 {
799 let velocity_fps = velocity_magnitude * 3.28084;
800 let twist_rate_ft = self.inputs.twist_rate / 12.0;
801 (velocity_fps / twist_rate_ft) * 2.0 * std::f64::consts::PI
802 } else {
803 0.0
804 };
805
806 let params = PrecessionNutationParams {
808 mass_kg: self.inputs.bullet_mass,
809 caliber_m: self.inputs.bullet_diameter,
810 length_m: self.inputs.bullet_length,
811 spin_rate_rad_s,
812 spin_inertia: 6.94e-8, transverse_inertia: 9.13e-7, velocity_mps: velocity_magnitude,
815 air_density_kg_m3: air_density,
816 mach,
817 pitch_damping_coeff: -0.8,
818 nutation_damping_factor: 0.05,
819 };
820
821 *state = calculate_combined_angular_motion(
823 ¶ms,
824 state,
825 time,
826 self.time_step,
827 0.001, );
829
830 if state.yaw_angle.abs() > max_yaw_angle {
832 max_yaw_angle = state.yaw_angle.abs();
833 }
834 if state.precession_angle.abs() > max_precession_angle {
835 max_precession_angle = state.precession_angle.abs();
836 }
837 }
838 }
839
840 let dt = self.time_step;
842
843 let acc1 = self.calculate_acceleration(&position, &velocity, air_density, &wind_vector);
845
846 let pos2 = position + velocity * (dt * 0.5);
848 let vel2 = velocity + acc1 * (dt * 0.5);
849 let acc2 = self.calculate_acceleration(&pos2, &vel2, air_density, &wind_vector);
850
851 let pos3 = position + vel2 * (dt * 0.5);
853 let vel3 = velocity + acc2 * (dt * 0.5);
854 let acc3 = self.calculate_acceleration(&pos3, &vel3, air_density, &wind_vector);
855
856 let pos4 = position + vel3 * dt;
858 let vel4 = velocity + acc3 * dt;
859 let acc4 = self.calculate_acceleration(&pos4, &vel4, air_density, &wind_vector);
860
861 position += (velocity + vel2 * 2.0 + vel3 * 2.0 + vel4) * (dt / 6.0);
863 velocity += (acc1 + acc2 * 2.0 + acc3 * 2.0 + acc4) * (dt / 6.0);
864 time += dt;
865 }
866
867 let last_point = points.last().ok_or("No trajectory points generated")?;
869
870 let sampled_points = if self.inputs.enable_trajectory_sampling {
872 let trajectory_data = TrajectoryData {
873 times: points.iter().map(|p| p.time).collect(),
874 positions: points.iter().map(|p| p.position).collect(),
875 velocities: points
876 .iter()
877 .map(|p| {
878 Vector3::new(0.0, 0.0, p.velocity_magnitude)
880 })
881 .collect(),
882 transonic_distances: Vec::new(), };
884
885 let sight_position_m = self.inputs.muzzle_height + self.inputs.sight_height;
890 let outputs = TrajectoryOutputs {
891 target_distance_horiz_m: last_point.position.x, target_vertical_height_m: sight_position_m,
893 time_of_flight_s: last_point.time,
894 max_ord_dist_horiz_m: max_height,
895 sight_height_m: sight_position_m,
896 };
897
898 let samples = sample_trajectory(
900 &trajectory_data,
901 &outputs,
902 self.inputs.sample_interval,
903 self.inputs.bullet_mass,
904 );
905 Some(samples)
906 } else {
907 None
908 };
909
910 Ok(TrajectoryResult {
911 max_range: last_point.position.x, max_height,
913 time_of_flight: last_point.time,
914 impact_velocity: last_point.velocity_magnitude,
915 impact_energy: last_point.kinetic_energy,
916 points,
917 sampled_points,
918 min_pitch_damping: if self.inputs.enable_pitch_damping {
919 Some(min_pitch_damping)
920 } else {
921 None
922 },
923 transonic_mach,
924 angular_state,
925 max_yaw_angle: if self.inputs.enable_precession_nutation {
926 Some(max_yaw_angle)
927 } else {
928 None
929 },
930 max_precession_angle: if self.inputs.enable_precession_nutation {
931 Some(max_precession_angle)
932 } else {
933 None
934 },
935 })
936 }
937
938 fn solve_rk45(&self) -> Result<TrajectoryResult, BallisticsError> {
939 let mut time = 0.0;
941 let mut position = Vector3::new(
944 0.0,
945 self.inputs.muzzle_height, 0.0,
947 );
948
949 let horizontal_velocity = self.inputs.muzzle_velocity * self.inputs.muzzle_angle.cos();
952 let mut velocity = Vector3::new(
953 horizontal_velocity * self.inputs.azimuth_angle.cos(), self.inputs.muzzle_velocity * self.inputs.muzzle_angle.sin(), horizontal_velocity * self.inputs.azimuth_angle.sin(), );
957
958 let mut points = Vec::new();
959 let mut max_height = position.y;
960 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;
968 const MAX_ITERATIONS: usize = 100000;
969
970 let air_density = calculate_air_density(&self.atmosphere);
973 let wind_vector = Vector3::new(
974 self.wind.speed * self.wind.direction.cos(), 0.0,
976 self.wind.speed * self.wind.direction.sin(), );
978
979 while position.x < self.max_range
980 && position.y > self.inputs.ground_threshold
981 && time < 100.0
982 {
983 iteration_count += 1;
985 if iteration_count > MAX_ITERATIONS {
986 break; }
988
989 let velocity_magnitude = velocity.magnitude();
991 let kinetic_energy = 0.5 * self.inputs.bullet_mass * velocity_magnitude.powi(2);
992
993 points.push(TrajectoryPoint {
994 time,
995 position: position,
996 velocity_magnitude,
997 kinetic_energy,
998 });
999
1000 if position.y > max_height {
1001 max_height = position.y;
1002 }
1003
1004 let (new_pos, new_vel, new_dt) = self.rk45_step(
1006 &position,
1007 &velocity,
1008 dt,
1009 air_density,
1010 &wind_vector,
1011 tolerance,
1012 );
1013
1014 position = new_pos;
1019 velocity = new_vel;
1020 time += dt;
1021
1022 dt = (safety_factor * new_dt).clamp(min_dt, max_dt);
1024 }
1025
1026 if points.is_empty() {
1028 return Err(BallisticsError::from("No trajectory points calculated"));
1029 }
1030
1031 let last_point = points.last().unwrap();
1032
1033 let sampled_points = if self.inputs.enable_trajectory_sampling {
1035 let trajectory_data = TrajectoryData {
1037 times: points.iter().map(|p| p.time).collect(),
1038 positions: points.iter().map(|p| p.position).collect(),
1039 velocities: points
1040 .iter()
1041 .map(|p| {
1042 Vector3::new(0.0, 0.0, p.velocity_magnitude)
1044 })
1045 .collect(),
1046 transonic_distances: Vec::new(),
1047 };
1048
1049 let sight_position_m = self.inputs.muzzle_height + self.inputs.sight_height;
1054 let outputs = TrajectoryOutputs {
1055 target_distance_horiz_m: last_point.position.x,
1056 target_vertical_height_m: sight_position_m,
1057 time_of_flight_s: last_point.time,
1058 max_ord_dist_horiz_m: max_height,
1059 sight_height_m: sight_position_m,
1060 };
1061
1062 let samples = sample_trajectory(
1063 &trajectory_data,
1064 &outputs,
1065 self.inputs.sample_interval,
1066 self.inputs.bullet_mass,
1067 );
1068 Some(samples)
1069 } else {
1070 None
1071 };
1072
1073 Ok(TrajectoryResult {
1074 max_range: last_point.position.x, max_height,
1076 time_of_flight: last_point.time,
1077 impact_velocity: last_point.velocity_magnitude,
1078 impact_energy: last_point.kinetic_energy,
1079 points,
1080 sampled_points,
1081 min_pitch_damping: None,
1082 transonic_mach: None,
1083 angular_state: None,
1084 max_yaw_angle: None,
1085 max_precession_angle: None,
1086 })
1087 }
1088
1089 fn rk45_step(
1090 &self,
1091 position: &Vector3<f64>,
1092 velocity: &Vector3<f64>,
1093 dt: f64,
1094 air_density: f64,
1095 wind_vector: &Vector3<f64>,
1096 tolerance: f64,
1097 ) -> (Vector3<f64>, Vector3<f64>, f64) {
1098 const A21: f64 = 1.0 / 5.0;
1100 const A31: f64 = 3.0 / 40.0;
1101 const A32: f64 = 9.0 / 40.0;
1102 const A41: f64 = 44.0 / 45.0;
1103 const A42: f64 = -56.0 / 15.0;
1104 const A43: f64 = 32.0 / 9.0;
1105 const A51: f64 = 19372.0 / 6561.0;
1106 const A52: f64 = -25360.0 / 2187.0;
1107 const A53: f64 = 64448.0 / 6561.0;
1108 const A54: f64 = -212.0 / 729.0;
1109 const A61: f64 = 9017.0 / 3168.0;
1110 const A62: f64 = -355.0 / 33.0;
1111 const A63: f64 = 46732.0 / 5247.0;
1112 const A64: f64 = 49.0 / 176.0;
1113 const A65: f64 = -5103.0 / 18656.0;
1114 const A71: f64 = 35.0 / 384.0;
1115 const A73: f64 = 500.0 / 1113.0;
1116 const A74: f64 = 125.0 / 192.0;
1117 const A75: f64 = -2187.0 / 6784.0;
1118 const A76: f64 = 11.0 / 84.0;
1119
1120 const B1: f64 = 35.0 / 384.0;
1122 const B3: f64 = 500.0 / 1113.0;
1123 const B4: f64 = 125.0 / 192.0;
1124 const B5: f64 = -2187.0 / 6784.0;
1125 const B6: f64 = 11.0 / 84.0;
1126
1127 const B1_ERR: f64 = 5179.0 / 57600.0;
1129 const B3_ERR: f64 = 7571.0 / 16695.0;
1130 const B4_ERR: f64 = 393.0 / 640.0;
1131 const B5_ERR: f64 = -92097.0 / 339200.0;
1132 const B6_ERR: f64 = 187.0 / 2100.0;
1133 const B7_ERR: f64 = 1.0 / 40.0;
1134
1135 let k1_v = self.calculate_acceleration(position, velocity, air_density, wind_vector);
1137 let k1_p = *velocity;
1138
1139 let p2 = position + dt * A21 * k1_p;
1140 let v2 = velocity + dt * A21 * k1_v;
1141 let k2_v = self.calculate_acceleration(&p2, &v2, air_density, wind_vector);
1142 let k2_p = v2;
1143
1144 let p3 = position + dt * (A31 * k1_p + A32 * k2_p);
1145 let v3 = velocity + dt * (A31 * k1_v + A32 * k2_v);
1146 let k3_v = self.calculate_acceleration(&p3, &v3, air_density, wind_vector);
1147 let k3_p = v3;
1148
1149 let p4 = position + dt * (A41 * k1_p + A42 * k2_p + A43 * k3_p);
1150 let v4 = velocity + dt * (A41 * k1_v + A42 * k2_v + A43 * k3_v);
1151 let k4_v = self.calculate_acceleration(&p4, &v4, air_density, wind_vector);
1152 let k4_p = v4;
1153
1154 let p5 = position + dt * (A51 * k1_p + A52 * k2_p + A53 * k3_p + A54 * k4_p);
1155 let v5 = velocity + dt * (A51 * k1_v + A52 * k2_v + A53 * k3_v + A54 * k4_v);
1156 let k5_v = self.calculate_acceleration(&p5, &v5, air_density, wind_vector);
1157 let k5_p = v5;
1158
1159 let p6 = position + dt * (A61 * k1_p + A62 * k2_p + A63 * k3_p + A64 * k4_p + A65 * k5_p);
1160 let v6 = velocity + dt * (A61 * k1_v + A62 * k2_v + A63 * k3_v + A64 * k4_v + A65 * k5_v);
1161 let k6_v = self.calculate_acceleration(&p6, &v6, air_density, wind_vector);
1162 let k6_p = v6;
1163
1164 let p7 = position + dt * (A71 * k1_p + A73 * k3_p + A74 * k4_p + A75 * k5_p + A76 * k6_p);
1165 let v7 = velocity + dt * (A71 * k1_v + A73 * k3_v + A74 * k4_v + A75 * k5_v + A76 * k6_v);
1166 let k7_v = self.calculate_acceleration(&p7, &v7, air_density, wind_vector);
1167 let k7_p = v7;
1168
1169 let new_pos = position + dt * (B1 * k1_p + B3 * k3_p + B4 * k4_p + B5 * k5_p + B6 * k6_p);
1171 let new_vel = velocity + dt * (B1 * k1_v + B3 * k3_v + B4 * k4_v + B5 * k5_v + B6 * k6_v);
1172
1173 let pos_err = position
1175 + dt * (B1_ERR * k1_p
1176 + B3_ERR * k3_p
1177 + B4_ERR * k4_p
1178 + B5_ERR * k5_p
1179 + B6_ERR * k6_p
1180 + B7_ERR * k7_p);
1181 let vel_err = velocity
1182 + dt * (B1_ERR * k1_v
1183 + B3_ERR * k3_v
1184 + B4_ERR * k4_v
1185 + B5_ERR * k5_v
1186 + B6_ERR * k6_v
1187 + B7_ERR * k7_v);
1188
1189 let pos_error = (new_pos - pos_err).magnitude();
1191 let vel_error = (new_vel - vel_err).magnitude();
1192 let error = (pos_error + vel_error) / (1.0 + position.magnitude() + velocity.magnitude());
1193
1194 let dt_new = if error < tolerance {
1196 dt * (tolerance / error).powf(0.2).min(2.0)
1197 } else {
1198 dt * (tolerance / error).powf(0.25).max(0.1)
1199 };
1200
1201 (new_pos, new_vel, dt_new)
1202 }
1203
1204 fn calculate_acceleration(
1205 &self,
1206 position: &Vector3<f64>,
1207 velocity: &Vector3<f64>,
1208 air_density: f64,
1209 wind_vector: &Vector3<f64>,
1210 ) -> Vector3<f64> {
1211 let actual_wind = if self.inputs.enable_wind_shear {
1213 self.get_wind_at_altitude(position.y)
1214 } else {
1215 *wind_vector
1216 };
1217
1218 let relative_velocity = velocity - actual_wind;
1219 let velocity_magnitude = relative_velocity.magnitude();
1220
1221 if velocity_magnitude < 0.001 {
1222 return Vector3::new(0.0, -crate::constants::G_ACCEL_MPS2, 0.0);
1223 }
1224
1225 let cd = self.calculate_drag_coefficient(velocity_magnitude);
1227
1228 let velocity_fps = velocity_magnitude * 3.28084;
1230
1231 let base_bc = if let Some(ref segments) = self.inputs.bc_segments_data {
1233 segments
1235 .iter()
1236 .find(|seg| velocity_fps >= seg.velocity_min && velocity_fps < seg.velocity_max)
1237 .map(|seg| seg.bc_value)
1238 .unwrap_or(self.inputs.bc_value)
1239 } else {
1240 self.inputs.bc_value
1241 };
1242
1243 let effective_bc = if let Some(ref cluster_bc) = self.cluster_bc {
1245 cluster_bc.apply_correction(
1246 base_bc,
1247 self.inputs.caliber_inches, self.inputs.weight_grains,
1249 velocity_fps,
1250 )
1251 } else {
1252 base_bc
1253 };
1254 let effective_bc = effective_bc.max(1e-6);
1258
1259 let cd_to_retard = 0.000683 * 0.30; let standard_factor = cd * cd_to_retard;
1265 let density_scale = air_density / 1.225; let a_drag_ft_s2 =
1269 (velocity_fps * velocity_fps) * standard_factor * density_scale / effective_bc;
1270 let a_drag_m_s2 = a_drag_ft_s2 * 0.3048; let drag_acceleration = -a_drag_m_s2 * (relative_velocity / velocity_magnitude);
1274
1275 let mut accel = drag_acceleration + Vector3::new(0.0, -crate::constants::G_ACCEL_MPS2, 0.0);
1277
1278 if self.inputs.enable_coriolis {
1281 if let Some(lat_deg) = self.inputs.latitude {
1282 let omega_earth = 7.2921159e-5_f64; let lat = lat_deg.to_radians();
1284 let az = self.inputs.azimuth_angle;
1285 let omega = Vector3::new(
1286 omega_earth * lat.cos() * az.cos(), omega_earth * lat.sin(), omega_earth * lat.cos() * az.sin(), );
1290 accel += 2.0 * omega.cross(velocity);
1296 }
1297 }
1298
1299 if self.inputs.enable_magnus
1301 && self.inputs.bullet_diameter > 0.0
1302 && self.inputs.twist_rate > 0.0
1303 {
1304 let (_, spin_rad_s) =
1305 crate::spin_drift::calculate_spin_rate(velocity_magnitude, self.inputs.twist_rate);
1306 let temp_k = self.atmosphere.temperature + 273.15;
1307 let speed_of_sound = (1.4 * 287.05 * temp_k).sqrt();
1308 let mach = velocity_magnitude / speed_of_sound;
1309
1310 let d_in = self.inputs.bullet_diameter / 0.0254;
1312 let m_gr = self.inputs.bullet_mass / 0.00006479891;
1313 let l_in = if self.inputs.bullet_length > 0.0 {
1314 self.inputs.bullet_length / 0.0254
1315 } else {
1316 4.5 * d_in
1317 };
1318 let sg = crate::spin_drift::miller_stability(d_in, m_gr, self.inputs.twist_rate, l_in);
1319
1320 let (yaw_rad, _) = crate::spin_drift::calculate_yaw_of_repose(
1322 sg,
1323 velocity_magnitude,
1324 spin_rad_s,
1325 0.0, 0.0, air_density,
1328 d_in,
1329 l_in,
1330 m_gr,
1331 mach,
1332 "match",
1333 false,
1334 );
1335
1336 let diameter_m = self.inputs.bullet_diameter; let spin_param = spin_rad_s * diameter_m / (2.0 * velocity_magnitude);
1339 let c_np = crate::derivatives::calculate_magnus_moment_coefficient(mach);
1340 let area = std::f64::consts::PI * (diameter_m / 2.0).powi(2);
1341 let magnus_force = 0.5
1342 * air_density
1343 * velocity_magnitude.powi(2)
1344 * area
1345 * c_np
1346 * spin_param
1347 * yaw_rad.sin();
1348
1349 let velocity_unit = relative_velocity / velocity_magnitude;
1352 let up = Vector3::new(0.0, 1.0, 0.0);
1353 let mut dir = velocity_unit.cross(&up);
1354 let dir_norm = dir.norm();
1355 if dir_norm > 1e-12 && magnus_force.abs() > 1e-12 {
1356 dir /= dir_norm;
1357 if !self.inputs.is_twist_right {
1358 dir = -dir;
1359 }
1360 accel += (magnus_force / self.inputs.bullet_mass) * dir;
1361 }
1362 }
1363
1364 accel
1365 }
1366
1367 fn calculate_drag_coefficient(&self, velocity: f64) -> f64 {
1368 let temp_c = self.atmosphere.temperature;
1370 let temp_k = temp_c + 273.15;
1371 let gamma = 1.4; let r_specific = 287.05; let speed_of_sound = (gamma * r_specific * temp_k).sqrt();
1374 let mach = velocity / speed_of_sound;
1375
1376 let base_cd = crate::drag::get_drag_coefficient(mach, &self.inputs.bc_type);
1378
1379 let bc_type_str: &str = match self.inputs.bc_type {
1383 crate::DragModel::G1 => "G1",
1384 crate::DragModel::G2 => "G2",
1385 crate::DragModel::G5 => "G5",
1386 crate::DragModel::G6 => "G6",
1387 crate::DragModel::G7 => "G7",
1388 crate::DragModel::G8 => "G8",
1389 crate::DragModel::GI => "GI",
1390 crate::DragModel::GS => "GS",
1391 };
1392
1393 let projectile_shape = if let Some(ref model) = self.inputs.bullet_model {
1395 let m = model.to_lowercase();
1398 if m.contains("boat") || m.contains("bt") {
1399 ProjectileShape::BoatTail
1400 } else if m.contains("round") || m.contains("rn") {
1401 ProjectileShape::RoundNose
1402 } else if m.contains("flat") || m.contains("fb") {
1403 ProjectileShape::FlatBase
1404 } else {
1405 get_projectile_shape(
1407 self.inputs.caliber_inches, self.inputs.bullet_mass / 0.00006479891, bc_type_str,
1410 )
1411 }
1412 } else {
1413 get_projectile_shape(
1415 self.inputs.caliber_inches, self.inputs.bullet_mass / 0.00006479891, bc_type_str,
1418 )
1419 };
1420
1421 let include_wave_drag = false;
1427 transonic_correction(mach, base_cd, projectile_shape, include_wave_drag)
1428 }
1429}
1430
1431#[derive(Debug, Clone)]
1433pub struct MonteCarloParams {
1434 pub num_simulations: usize,
1435 pub velocity_std_dev: f64,
1436 pub angle_std_dev: f64,
1437 pub bc_std_dev: f64,
1438 pub wind_speed_std_dev: f64,
1439 pub target_distance: Option<f64>,
1440 pub base_wind_speed: f64,
1441 pub base_wind_direction: f64,
1442 pub azimuth_std_dev: f64, }
1444
1445impl Default for MonteCarloParams {
1446 fn default() -> Self {
1447 Self {
1448 num_simulations: 1000,
1449 velocity_std_dev: 1.0,
1450 angle_std_dev: 0.001,
1451 bc_std_dev: 0.01,
1452 wind_speed_std_dev: 1.0,
1453 target_distance: None,
1454 base_wind_speed: 0.0,
1455 base_wind_direction: 0.0,
1456 azimuth_std_dev: 0.001, }
1458 }
1459}
1460
1461#[derive(Debug, Clone)]
1463pub struct MonteCarloResults {
1464 pub ranges: Vec<f64>,
1465 pub impact_velocities: Vec<f64>,
1466 pub impact_positions: Vec<Vector3<f64>>,
1467}
1468
1469pub fn run_monte_carlo(
1471 base_inputs: BallisticInputs,
1472 params: MonteCarloParams,
1473) -> Result<MonteCarloResults, BallisticsError> {
1474 let base_wind = WindConditions {
1475 speed: params.base_wind_speed,
1476 direction: params.base_wind_direction,
1477 };
1478 run_monte_carlo_with_wind(base_inputs, base_wind, params)
1479}
1480
1481pub fn run_monte_carlo_with_wind(
1483 base_inputs: BallisticInputs,
1484 base_wind: WindConditions,
1485 params: MonteCarloParams,
1486) -> Result<MonteCarloResults, BallisticsError> {
1487 use rand::thread_rng;
1488 use rand_distr::{Distribution, Normal};
1489
1490 let mut rng = thread_rng();
1491 let mut ranges = Vec::new();
1492 let mut impact_velocities = Vec::new();
1493 let mut impact_positions = Vec::new();
1494
1495 let baseline_solver =
1497 TrajectorySolver::new(base_inputs.clone(), base_wind.clone(), Default::default());
1498 let baseline_result = baseline_solver.solve()?;
1499
1500 let target_distance = params.target_distance.unwrap_or(baseline_result.max_range);
1502
1503 let baseline_at_target = baseline_result
1505 .position_at_range(target_distance)
1506 .ok_or("Could not interpolate baseline at target distance")?;
1507
1508 let velocity_dist = Normal::new(base_inputs.muzzle_velocity, params.velocity_std_dev)
1510 .map_err(|e| format!("Invalid velocity distribution: {}", e))?;
1511 let angle_dist = Normal::new(base_inputs.muzzle_angle, params.angle_std_dev)
1512 .map_err(|e| format!("Invalid angle distribution: {}", e))?;
1513 let bc_dist = Normal::new(base_inputs.bc_value, params.bc_std_dev)
1514 .map_err(|e| format!("Invalid BC distribution: {}", e))?;
1515 let wind_speed_dist = Normal::new(base_wind.speed, params.wind_speed_std_dev)
1516 .map_err(|e| format!("Invalid wind speed distribution: {}", e))?;
1517 let wind_dir_dist =
1518 Normal::new(base_wind.direction, params.wind_speed_std_dev * 0.1) .map_err(|e| format!("Invalid wind direction distribution: {}", e))?;
1520 let azimuth_dist = Normal::new(base_inputs.azimuth_angle, params.azimuth_std_dev)
1521 .map_err(|e| format!("Invalid azimuth distribution: {}", e))?;
1522
1523 let pointing_error_dist = Normal::new(0.0, params.angle_std_dev * target_distance)
1525 .map_err(|e| format!("Invalid pointing distribution: {}", e))?;
1526
1527 for _ in 0..params.num_simulations {
1528 let mut inputs = base_inputs.clone();
1530 inputs.muzzle_velocity = velocity_dist.sample(&mut rng).max(0.0);
1531 inputs.muzzle_angle = angle_dist.sample(&mut rng);
1532 inputs.bc_value = bc_dist.sample(&mut rng).max(0.01);
1533 inputs.azimuth_angle = azimuth_dist.sample(&mut rng); let wind = WindConditions {
1537 speed: wind_speed_dist.sample(&mut rng).abs(),
1538 direction: wind_dir_dist.sample(&mut rng),
1539 };
1540
1541 let solver = TrajectorySolver::new(inputs, wind, Default::default());
1543 match solver.solve() {
1544 Ok(result) => {
1545 if result.max_range < target_distance {
1553 continue;
1554 }
1555 let pos_at_target = match result.position_at_range(target_distance) {
1559 Some(p) => p,
1560 None => continue,
1561 };
1562
1563 ranges.push(result.max_range);
1564 impact_velocities.push(result.impact_velocity);
1565
1566 let mut deviation = Vector3::new(
1569 0.0, pos_at_target.y - baseline_at_target.y, pos_at_target.z - baseline_at_target.z, );
1573
1574 let pointing_error_y = pointing_error_dist.sample(&mut rng);
1577 deviation.y += pointing_error_y;
1578
1579 impact_positions.push(deviation);
1580 }
1581 Err(_) => {
1582 continue;
1584 }
1585 }
1586 }
1587
1588 if ranges.is_empty() {
1589 return Err("No successful simulations".into());
1590 }
1591
1592 Ok(MonteCarloResults {
1593 ranges,
1594 impact_velocities,
1595 impact_positions,
1596 })
1597}
1598
1599pub fn calculate_zero_angle(
1601 inputs: BallisticInputs,
1602 target_distance: f64,
1603 target_height: f64,
1604) -> Result<f64, BallisticsError> {
1605 calculate_zero_angle_with_conditions(
1606 inputs,
1607 target_distance,
1608 target_height,
1609 WindConditions::default(),
1610 AtmosphericConditions::default(),
1611 )
1612}
1613
1614pub fn calculate_zero_angle_with_conditions(
1615 inputs: BallisticInputs,
1616 target_distance: f64,
1617 target_height: f64,
1618 wind: WindConditions,
1619 atmosphere: AtmosphericConditions,
1620) -> Result<f64, BallisticsError> {
1621 let get_height_at_angle = |angle: f64| -> Result<Option<f64>, BallisticsError> {
1623 let mut test_inputs = inputs.clone();
1624 test_inputs.muzzle_angle = angle;
1625
1626 let mut solver = TrajectorySolver::new(test_inputs, wind.clone(), atmosphere.clone());
1627 solver.set_max_range(target_distance * 2.0);
1628 solver.set_time_step(0.001);
1629 let result = solver.solve()?;
1630
1631 for i in 0..result.points.len() {
1633 if result.points[i].position.x >= target_distance {
1634 if i > 0 {
1635 let p1 = &result.points[i - 1];
1636 let p2 = &result.points[i];
1637 let t = (target_distance - p1.position.x) / (p2.position.x - p1.position.x);
1638 return Ok(Some(p1.position.y + t * (p2.position.y - p1.position.y)));
1639 } else {
1640 return Ok(Some(result.points[i].position.y));
1641 }
1642 }
1643 }
1644 Ok(None)
1645 };
1646
1647 let mut low_angle = 0.0; let mut high_angle = 0.2; let tolerance = 0.00001; let max_iterations = 50;
1653
1654 let low_height = get_height_at_angle(low_angle)?;
1657 let high_height = get_height_at_angle(high_angle)?;
1658
1659 match (low_height, high_height) {
1660 (Some(lh), Some(hh)) => {
1661 let low_error = lh - target_height;
1662 let high_error = hh - target_height;
1663
1664 if low_error > 0.0 && high_error > 0.0 {
1667 } else if low_error < 0.0 && high_error < 0.0 {
1672 let mut expanded = false;
1675 for multiplier in [2.0, 3.0, 4.0] {
1676 let new_high = (high_angle * multiplier).min(0.785);
1677 if let Ok(Some(h)) = get_height_at_angle(new_high) {
1678 if h - target_height > 0.0 {
1679 high_angle = new_high;
1680 expanded = true;
1681 break;
1682 }
1683 }
1684 if new_high >= 0.785 {
1685 break;
1686 }
1687 }
1688 if !expanded {
1689 return Err("Cannot find zero angle: target beyond effective range even at maximum angle".into());
1690 }
1691 }
1692 }
1694 (None, Some(_hh)) => {
1695 }
1698 (Some(_lh), None) => {
1699 return Err(
1701 "Cannot find zero angle: high angle trajectory doesn't reach target distance"
1702 .into(),
1703 );
1704 }
1705 (None, None) => {
1706 return Err(
1708 "Cannot find zero angle: trajectory cannot reach target distance at any angle"
1709 .into(),
1710 );
1711 }
1712 }
1713
1714 for _iteration in 0..max_iterations {
1715 let mid_angle = (low_angle + high_angle) / 2.0;
1716
1717 let mut test_inputs = inputs.clone();
1718 test_inputs.muzzle_angle = mid_angle;
1719
1720 let mut solver = TrajectorySolver::new(test_inputs, wind.clone(), atmosphere.clone());
1721 solver.set_max_range(target_distance * 2.0);
1723 solver.set_time_step(0.001);
1724 let result = solver.solve()?;
1725
1726 let mut height_at_target = None;
1728 for i in 0..result.points.len() {
1729 if result.points[i].position.x >= target_distance {
1730 if i > 0 {
1731 let p1 = &result.points[i - 1];
1733 let p2 = &result.points[i];
1734 let t = (target_distance - p1.position.x) / (p2.position.x - p1.position.x);
1735 height_at_target = Some(p1.position.y + t * (p2.position.y - p1.position.y));
1736 } else {
1737 height_at_target = Some(result.points[i].position.y);
1738 }
1739 break;
1740 }
1741 }
1742
1743 match height_at_target {
1744 Some(height) => {
1745 let error = height - target_height;
1746 if error.abs() < 0.001 {
1749 return Ok(mid_angle);
1750 }
1751
1752 if (high_angle - low_angle).abs() < tolerance {
1756 if error.abs() < 0.01 {
1757 return Ok(mid_angle);
1759 }
1760 return Err("Zero angle did not converge: residual height error too large (target not reachable / not bracketed)".into());
1765 }
1766
1767 if error > 0.0 {
1768 high_angle = mid_angle;
1769 } else {
1770 low_angle = mid_angle;
1771 }
1772 }
1773 None => {
1774 low_angle = mid_angle;
1776
1777 if (high_angle - low_angle).abs() < tolerance {
1779 return Err("Trajectory cannot reach target distance - angle converged without valid solution".into());
1780 }
1781 }
1782 }
1783 }
1784
1785 Err("Failed to find zero angle".into())
1786}
1787
1788pub fn estimate_bc_from_trajectory(
1790 velocity: f64,
1791 mass: f64,
1792 diameter: f64,
1793 points: &[(f64, f64)], ) -> Result<f64, BallisticsError> {
1795 let mut best_bc = 0.5;
1797 let mut best_error = f64::MAX;
1798 let mut found_valid = false;
1799
1800 for bc in (100..1000).step_by(10) {
1802 let bc_value = bc as f64 / 1000.0;
1803
1804 let inputs = BallisticInputs {
1805 muzzle_velocity: velocity,
1806 bc_value,
1807 bullet_mass: mass,
1808 bullet_diameter: diameter,
1809 ..Default::default()
1810 };
1811
1812 let mut solver = TrajectorySolver::new(inputs, Default::default(), Default::default());
1813 solver.set_max_range(points.last().map(|(d, _)| *d * 1.5).unwrap_or(1000.0));
1815
1816 let result = match solver.solve() {
1817 Ok(r) => r,
1818 Err(_) => continue, };
1820
1821 let mut total_error = 0.0;
1823 for (target_dist, target_drop) in points {
1824 let mut calculated_drop = None;
1826 for i in 0..result.points.len() {
1827 if result.points[i].position.x >= *target_dist {
1828 if i > 0 {
1829 let p1 = &result.points[i - 1];
1831 let p2 = &result.points[i];
1832 let t = (target_dist - p1.position.x) / (p2.position.x - p1.position.x);
1833 calculated_drop =
1834 Some(-(p1.position.y + t * (p2.position.y - p1.position.y)));
1835 } else {
1836 calculated_drop = Some(-result.points[i].position.y);
1837 }
1838 break;
1839 }
1840 }
1841
1842 if let Some(drop) = calculated_drop {
1843 let error = (drop - target_drop).abs();
1844 total_error += error * error;
1845 }
1846 }
1847
1848 if total_error < best_error {
1849 best_error = total_error;
1850 best_bc = bc_value;
1851 found_valid = true;
1852 }
1853 }
1854
1855 if !found_valid {
1856 return Err(BallisticsError::from("Unable to estimate BC from provided data. Check that drop values are in correct units.".to_string()));
1857 }
1858
1859 Ok(best_bc)
1860}
1861
1862fn calculate_air_density(atmosphere: &AtmosphericConditions) -> f64 {
1864 crate::atmosphere::calculate_atmosphere(
1872 atmosphere.altitude,
1873 crate::atmosphere::resolve_station_temperature(atmosphere.temperature, atmosphere.altitude),
1874 crate::atmosphere::resolve_station_pressure(atmosphere.pressure, atmosphere.altitude),
1875 atmosphere.humidity,
1876 )
1877 .0
1878}
1879
1880use rand;
1882use rand_distr;
1883
1884#[cfg(test)]
1885mod ground_termination_tests {
1886 use super::*;
1887
1888 #[test]
1893 fn rk4_and_rk45_descend_to_ground_threshold() {
1894 for adaptive in [false, true] {
1895 let mut inputs = BallisticInputs::default();
1896 inputs.muzzle_angle = 0.1; inputs.use_rk4 = true;
1898 inputs.use_adaptive_rk45 = adaptive;
1899 assert_eq!(inputs.ground_threshold, -100.0, "default ground_threshold is -100 m");
1900
1901 let mut solver = TrajectorySolver::new(
1902 inputs,
1903 WindConditions::default(),
1904 AtmosphericConditions::default(),
1905 );
1906 solver.set_max_range(1.0e7);
1908
1909 let result = solver.solve().expect("solve should succeed");
1910 let final_y = result
1911 .points
1912 .last()
1913 .expect("trajectory has points")
1914 .position
1915 .y;
1916 assert!(
1917 final_y < -1.0,
1918 "adaptive_rk45={adaptive}: final y = {final_y} m; a lofted shot should descend \
1919 past launch level toward the ground_threshold floor, not stop at y = 0"
1920 );
1921 }
1922 }
1923}