ballistics_engine/
cli_api.rs

1// CLI API module - provides simplified interfaces for command-line tool
2use 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// Unit system for input/output
18#[derive(Debug, Clone, Copy, PartialEq)]
19pub enum UnitSystem {
20    Imperial,
21    Metric,
22}
23
24// Output format for results
25#[derive(Debug, Clone, Copy, PartialEq)]
26pub enum OutputFormat {
27    Table,
28    Json,
29    Csv,
30}
31
32// Error type for CLI operations
33#[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// Ballistic input parameters - MBA-151 Reconciled Structure
61// Unified structure used by both ballistics-engine and ballistics_rust
62// Duplicates removed, all necessary fields included
63#[derive(Debug, Clone)]
64pub struct BallisticInputs {
65    // Core ballistics parameters (using intuitive names)
66    pub bc_value: f64,        // Ballistic coefficient (G1, G7, etc.)
67    pub bc_type: DragModel,   // Drag model (G1, G7, G8, etc.)
68    pub bullet_mass: f64,     // kg
69    pub muzzle_velocity: f64, // m/s
70    pub bullet_diameter: f64, // meters
71    pub bullet_length: f64,   // meters
72
73    // Targeting and positioning
74    pub muzzle_angle: f64,     // radians (launch angle)
75    pub target_distance: f64,  // meters
76    pub azimuth_angle: f64,    // horizontal aiming angle in radians
77    pub shooting_angle: f64,   // uphill/downhill angle in radians
78    pub sight_height: f64,     // meters above bore
79    pub muzzle_height: f64,    // meters above ground
80    pub target_height: f64,    // meters above ground for zeroing
81    pub ground_threshold: f64, // meters below which to stop
82
83    // Environmental conditions
84    pub altitude: f64,         // meters
85    pub temperature: f64,      // Celsius
86    pub pressure: f64,         // millibars/hPa
87    pub humidity: f64,         // relative humidity (0-1)
88    pub latitude: Option<f64>, // degrees
89
90    // Wind conditions
91    pub wind_speed: f64, // m/s
92    pub wind_angle: f64, // radians (0=headwind, 90=from right)
93
94    // Bullet characteristics
95    pub twist_rate: f64,               // inches per turn
96    pub is_twist_right: bool,          // right-hand twist
97    pub caliber_inches: f64,           // diameter in inches
98    pub weight_grains: f64,            // mass in grains
99    pub manufacturer: Option<String>,  // Bullet manufacturer
100    pub bullet_model: Option<String>,  // Bullet model name
101    pub bullet_id: Option<String>,     // Unique bullet identifier
102    pub bullet_cluster: Option<usize>, // BC cluster ID for cluster_bc module
103
104    // Integration method selection
105    pub use_rk4: bool,           // Use RK4 integration instead of Euler
106    pub use_adaptive_rk45: bool, // Use RK45 adaptive step size integration
107
108    // Advanced effects flags
109    pub enable_advanced_effects: bool,
110    pub use_powder_sensitivity: bool,
111    pub powder_temp_sensitivity: f64,
112    pub powder_temp: f64,           // Celsius
113    pub tipoff_yaw: f64,            // radians
114    pub tipoff_decay_distance: f64, // meters
115    pub use_bc_segments: bool,
116    pub bc_segments: Option<Vec<(f64, f64)>>, // Mach-BC pairs
117    pub bc_segments_data: Option<Vec<crate::BCSegmentData>>, // Velocity-BC segments
118    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, // meters
124    pub enable_pitch_damping: bool,
125    pub enable_precession_nutation: bool,
126    pub use_cluster_bc: bool, // Use cluster-based BC degradation
127
128    // Custom drag model support
129    pub custom_drag_table: Option<crate::drag::DragTable>,
130
131    // Legacy field for compatibility
132    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            // Core ballistics parameters
145            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, // Approximate
151
152            // Targeting and positioning
153            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,       // Default 0 - height is in sight_height
159            target_height: 0.0,       // Target at ground level by default
160            ground_threshold: -100.0, // Effectively disable ground detection (allow bullet to drop 100m below start)
161
162            // Environmental conditions
163            altitude: 0.0,
164            temperature: 15.0,
165            pressure: 1013.25, // Standard sea level pressure (millibars)
166            humidity: 0.5,     // 50% relative humidity
167            latitude: None,
168
169            // Wind conditions
170            wind_speed: 0.0,
171            wind_angle: 0.0,
172
173            // Bullet characteristics
174            twist_rate: 12.0, // 1:12" typical
175            is_twist_right: true,
176            caliber_inches: diameter_m / 0.0254, // Convert to inches
177            weight_grains: mass_kg / 0.00006479891, // Convert to grains
178            manufacturer: None,
179            bullet_model: None,
180            bullet_id: None,
181            bullet_cluster: None,
182
183            // Integration method selection
184            use_rk4: true,           // Use Runge-Kutta methods by default
185            use_adaptive_rk45: true, // Default to RK45 adaptive for best accuracy
186
187            // Advanced effects (disabled by default)
188            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, // Default 10 meter intervals
203            enable_pitch_damping: false,
204            enable_precession_nutation: false,
205            use_cluster_bc: false, // Disabled by default for backward compatibility
206
207            // Custom drag model support
208            custom_drag_table: None,
209
210            // Legacy field for compatibility
211            bc_type_str: None,
212        }
213    }
214}
215
216// Wind conditions
217#[derive(Debug, Clone)]
218pub struct WindConditions {
219    pub speed: f64,     // m/s
220    pub direction: f64, // radians (0 = North, PI/2 = East)
221}
222
223impl Default for WindConditions {
224    fn default() -> Self {
225        Self {
226            speed: 0.0,
227            direction: 0.0,
228        }
229    }
230}
231
232// Atmospheric conditions
233#[derive(Debug, Clone)]
234pub struct AtmosphericConditions {
235    pub temperature: f64, // Celsius
236    pub pressure: f64,    // hPa
237    pub humidity: f64,    // percentage (0-100)
238    pub altitude: f64,    // meters
239}
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// Trajectory point data
253#[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// Trajectory result
262#[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>>, // Trajectory samples at regular intervals
271    pub min_pitch_damping: Option<f64>, // Minimum pitch damping coefficient (for stability warning)
272    pub transonic_mach: Option<f64>,    // Mach number when entering transonic regime
273    pub angular_state: Option<AngularState>, // Final angular state if precession/nutation enabled
274    pub max_yaw_angle: Option<f64>,     // Maximum yaw angle during flight (radians)
275    pub max_precession_angle: Option<f64>, // Maximum precession angle (radians)
276}
277
278impl TrajectoryResult {
279    /// Interpolate position at a given downrange distance (Z coordinate).
280    /// Returns the interpolated (x, y, z) position at that range.
281    /// If the target range exceeds the trajectory, returns the last point.
282    pub fn position_at_range(&self, target_range: f64) -> Option<Vector3<f64>> {
283        if self.points.is_empty() {
284            return None;
285        }
286
287        // Find the two points that bracket the target range
288        for i in 0..self.points.len() - 1 {
289            let p1 = &self.points[i];
290            let p2 = &self.points[i + 1];
291
292            // Check if target range is between these two points
293            if p1.position.z <= target_range && p2.position.z >= target_range {
294                // Linear interpolation factor
295                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                // Interpolate X and Y, use exact target_range for Z
302                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        // Target range is beyond trajectory - return last point
311        self.points.last().map(|p| p.position)
312    }
313}
314
315// Trajectory solver
316pub 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        // Compute derived fields from base units
332        inputs.caliber_inches = inputs.bullet_diameter / 0.0254;
333        inputs.weight_grains = inputs.bullet_mass / 0.00006479891;
334
335        // Initialize cluster BC if enabled
336        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        // Create wind shear profile based on surface wind
362        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 // Default to power law
369            },
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, // Standard meteorological measurement height
376            roughness_length: 0.03, // Short grass
377            power_exponent: 1.0 / 7.0, // Neutral stability
378            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        // Simple trajectory integration using Euler method
399        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        // Calculate initial velocity components with both elevation and azimuth
406        // Standard ballistics coordinate system: X=lateral, Y=vertical, Z=downrange
407        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(), // X: lateral (side deviation)
410            self.inputs.muzzle_velocity * self.inputs.muzzle_angle.sin(), // Y: vertical component
411            horizontal_velocity * self.inputs.azimuth_angle.cos(), // Z: downrange (forward)
412        );
413
414        let mut points = Vec::new();
415        let mut max_height = position.y;
416        let mut min_pitch_damping = 1.0; // Track minimum pitch damping coefficient
417        let mut transonic_mach = None; // Track when we enter transonic
418
419        // Initialize angular state for precession/nutation tracking
420        let mut angular_state = if self.inputs.enable_precession_nutation {
421            Some(AngularState {
422                pitch_angle: 0.001, // Small initial disturbance
423                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        // Calculate air density
436        let air_density = calculate_air_density(&self.atmosphere);
437
438        // Wind vector: X=lateral (crosswind), Y=0, Z=downrange (head/tail wind)
439        let wind_vector = Vector3::new(
440            self.wind.speed * self.wind.direction.sin(), // X: lateral (crosswind)
441            0.0,
442            self.wind.speed * self.wind.direction.cos(), // Z: downrange (head/tail wind)
443        );
444
445        // Main integration loop (Z is downrange)
446        while position.z < self.max_range && position.y >= 0.0 && time < 100.0 {
447            // Store trajectory point
448            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            // Debug: Log first and every 100th point
460            // Coordinate system: X=lateral, Y=vertical, Z=downrange
461            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            // Track max height
467            if position.y > max_height {
468                max_height = position.y;
469            }
470
471            // Calculate pitch damping if enabled
472            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                // Track when we enter transonic
479                if transonic_mach.is_none() && mach < 1.2 && mach > 0.8 {
480                    transonic_mach = Some(mach);
481                }
482
483                // Calculate pitch damping coefficient
484                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                // Track minimum (most critical for stability)
493                if pitch_damping < min_pitch_damping {
494                    min_pitch_damping = pitch_damping;
495                }
496            }
497
498            // Calculate precession/nutation if enabled
499            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                    // Calculate spin rate from twist rate and velocity
508                    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                    // Create precession/nutation parameters
517                    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,       // Typical value
523                        transverse_inertia: 9.13e-7, // Typical value
524                        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                    // Update angular state
532                    *state = calculate_combined_angular_motion(
533                        &params,
534                        state,
535                        time,
536                        self.time_step,
537                        0.001, // Initial disturbance
538                    );
539
540                    // Track maximums
541                    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            // Calculate drag with altitude-dependent wind if enabled
551            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            // Calculate drag force
561            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            // Calculate acceleration
572            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            // Update state
580            velocity += acceleration * self.time_step;
581            position += velocity * self.time_step;
582            time += self.time_step;
583        }
584
585        // Get final values
586        let last_point = points.last().ok_or("No trajectory points generated")?;
587
588        // Create trajectory sampling data if enabled
589        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                        // Reconstruct velocity vectors from magnitude (approximate)
597                        Vector3::new(0.0, 0.0, p.velocity_magnitude)
598                    })
599                    .collect(),
600                transonic_distances: Vec::new(), // TODO: Track Mach transitions
601            };
602
603            let outputs = TrajectoryOutputs {
604                target_distance_horiz_m: last_point.position.z, // Z is downrange
605                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            // Sample at specified intervals
611            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, // Z is downrange
624            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        // RK4 trajectory integration for better accuracy
652        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        // Calculate initial velocity components with both elevation and azimuth
660        // Standard ballistics coordinate system: X=lateral, Y=vertical, Z=downrange
661        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(), // X: lateral (side deviation)
664            self.inputs.muzzle_velocity * self.inputs.muzzle_angle.sin(), // Y: vertical component
665            horizontal_velocity * self.inputs.azimuth_angle.cos(), // Z: downrange (forward)
666        );
667
668        let mut points = Vec::new();
669        let mut max_height = position.y;
670        let mut min_pitch_damping = 1.0; // Track minimum pitch damping coefficient
671        let mut transonic_mach = None; // Track when we enter transonic
672
673        // Initialize angular state for precession/nutation tracking
674        let mut angular_state = if self.inputs.enable_precession_nutation {
675            Some(AngularState {
676                pitch_angle: 0.001, // Small initial disturbance
677                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        // Calculate air density
690        let air_density = calculate_air_density(&self.atmosphere);
691
692        // Wind vector: X=lateral (crosswind), Y=0, Z=downrange (head/tail wind)
693        let wind_vector = Vector3::new(
694            self.wind.speed * self.wind.direction.sin(), // X: lateral (crosswind)
695            0.0,
696            self.wind.speed * self.wind.direction.cos(), // Z: downrange (head/tail wind)
697        );
698
699        // Main RK4 integration loop (Z is downrange)
700        while position.z < self.max_range && position.y >= 0.0 && time < 100.0 {
701            // Store trajectory point
702            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            // Calculate pitch damping if enabled (RK4 solver)
718            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                // Track when we enter transonic
725                if transonic_mach.is_none() && mach < 1.2 && mach > 0.8 {
726                    transonic_mach = Some(mach);
727                }
728
729                // Calculate pitch damping coefficient
730                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                // Track minimum (most critical for stability)
739                if pitch_damping < min_pitch_damping {
740                    min_pitch_damping = pitch_damping;
741                }
742            }
743
744            // Calculate precession/nutation if enabled (RK4 solver)
745            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                    // Calculate spin rate from twist rate and velocity
754                    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                    // Create precession/nutation parameters
763                    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,       // Typical value
769                        transverse_inertia: 9.13e-7, // Typical value
770                        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                    // Update angular state
778                    *state = calculate_combined_angular_motion(
779                        &params,
780                        state,
781                        time,
782                        self.time_step,
783                        0.001, // Initial disturbance
784                    );
785
786                    // Track maximums
787                    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            // RK4 method
797            let dt = self.time_step;
798
799            // k1
800            let acc1 = self.calculate_acceleration(&position, &velocity, air_density, &wind_vector);
801
802            // k2
803            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            // k3
808            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            // k4
813            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            // Update position and velocity
818            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        // Get final values
824        let last_point = points.last().ok_or("No trajectory points generated")?;
825
826        // Create trajectory sampling data if enabled
827        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                        // Reconstruct velocity vectors from magnitude (approximate)
835                        Vector3::new(0.0, 0.0, p.velocity_magnitude)
836                    })
837                    .collect(),
838                transonic_distances: Vec::new(), // TODO: Track Mach transitions
839            };
840
841            let outputs = TrajectoryOutputs {
842                target_distance_horiz_m: last_point.position.z, // Z is downrange
843                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            // Sample at specified intervals
849            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, // Z is downrange
862            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        // RK45 adaptive step size integration (Dormand-Prince method)
890        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        // Calculate initial velocity components
898        // Standard ballistics coordinate system: X=lateral, Y=vertical, Z=downrange
899        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(), // X: lateral (side deviation)
902            self.inputs.muzzle_velocity * self.inputs.muzzle_angle.sin(), // Y: vertical component
903            horizontal_velocity * self.inputs.azimuth_angle.cos(), // Z: downrange (forward)
904        );
905
906        let mut points = Vec::new();
907        let mut max_height = position.y;
908        let mut dt = 0.001; // Initial step size
909        let tolerance = 1e-6; // Error tolerance
910        let safety_factor = 0.9; // Safety factor for step size adjustment
911        let max_dt = 0.01; // Maximum step size
912        let min_dt = 1e-6; // Minimum step size
913
914        // Add a point counter to debug
915        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            // Z is downrange
923            iteration_count += 1;
924            if iteration_count > MAX_ITERATIONS {
925                break; // Prevent infinite loop
926            }
927
928            // Store current point
929            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            // Get atmospheric conditions and wind: X=lateral (crosswind), Y=0, Z=downrange (head/tail wind)
944            let air_density = calculate_air_density(&self.atmosphere);
945            let wind_vector = Vector3::new(
946                self.wind.speed * self.wind.direction.sin(), // X: lateral (crosswind)
947                0.0,
948                self.wind.speed * self.wind.direction.cos(), // Z: downrange (head/tail wind)
949            );
950
951            // RK45 step with adaptive step size
952            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            // Update step size with safety factor and bounds
962            dt = (safety_factor * new_dt).clamp(min_dt, max_dt);
963
964            // Update state
965            position = new_pos;
966            velocity = new_vel;
967            time += dt;
968        }
969
970        // Ensure we have at least one point
971        if points.is_empty() {
972            return Err(BallisticsError::from("No trajectory points calculated"));
973        }
974
975        let last_point = points.last().unwrap();
976
977        // Generate sampled trajectory points if enabled
978        let sampled_points = if self.inputs.enable_trajectory_sampling {
979            // Build trajectory data for sampling
980            let trajectory_data = TrajectoryData {
981                times: points.iter().map(|p| p.time).collect(),
982                positions: points.iter().map(|p| p.position).collect(),
983                velocities: points
984                    .iter()
985                    .map(|p| {
986                        // Approximate velocity direction from position changes
987                        Vector3::new(0.0, 0.0, p.velocity_magnitude)
988                    })
989                    .collect(),
990                transonic_distances: Vec::new(),
991            };
992
993            let outputs = TrajectoryOutputs {
994                target_distance_horiz_m: last_point.position.z,
995                target_vertical_height_m: last_point.position.y,
996                time_of_flight_s: last_point.time,
997                max_ord_dist_horiz_m: max_height,
998            };
999
1000            let samples = sample_trajectory(
1001                &trajectory_data,
1002                &outputs,
1003                self.inputs.sample_interval,
1004                self.inputs.bullet_mass,
1005            );
1006            Some(samples)
1007        } else {
1008            None
1009        };
1010
1011        Ok(TrajectoryResult {
1012            max_range: last_point.position.z, // Z is downrange
1013            max_height,
1014            time_of_flight: last_point.time,
1015            impact_velocity: last_point.velocity_magnitude,
1016            impact_energy: last_point.kinetic_energy,
1017            points,
1018            sampled_points,
1019            min_pitch_damping: None,
1020            transonic_mach: None,
1021            angular_state: None,
1022            max_yaw_angle: None,
1023            max_precession_angle: None,
1024        })
1025    }
1026
1027    fn rk45_step(
1028        &self,
1029        position: &Vector3<f64>,
1030        velocity: &Vector3<f64>,
1031        dt: f64,
1032        air_density: f64,
1033        wind_vector: &Vector3<f64>,
1034        tolerance: f64,
1035    ) -> (Vector3<f64>, Vector3<f64>, f64) {
1036        // Dormand-Prince coefficients
1037        const A21: f64 = 1.0 / 5.0;
1038        const A31: f64 = 3.0 / 40.0;
1039        const A32: f64 = 9.0 / 40.0;
1040        const A41: f64 = 44.0 / 45.0;
1041        const A42: f64 = -56.0 / 15.0;
1042        const A43: f64 = 32.0 / 9.0;
1043        const A51: f64 = 19372.0 / 6561.0;
1044        const A52: f64 = -25360.0 / 2187.0;
1045        const A53: f64 = 64448.0 / 6561.0;
1046        const A54: f64 = -212.0 / 729.0;
1047        const A61: f64 = 9017.0 / 3168.0;
1048        const A62: f64 = -355.0 / 33.0;
1049        const A63: f64 = 46732.0 / 5247.0;
1050        const A64: f64 = 49.0 / 176.0;
1051        const A65: f64 = -5103.0 / 18656.0;
1052        const A71: f64 = 35.0 / 384.0;
1053        const A73: f64 = 500.0 / 1113.0;
1054        const A74: f64 = 125.0 / 192.0;
1055        const A75: f64 = -2187.0 / 6784.0;
1056        const A76: f64 = 11.0 / 84.0;
1057
1058        // 5th order coefficients
1059        const B1: f64 = 35.0 / 384.0;
1060        const B3: f64 = 500.0 / 1113.0;
1061        const B4: f64 = 125.0 / 192.0;
1062        const B5: f64 = -2187.0 / 6784.0;
1063        const B6: f64 = 11.0 / 84.0;
1064
1065        // 4th order coefficients for error estimation
1066        const B1_ERR: f64 = 5179.0 / 57600.0;
1067        const B3_ERR: f64 = 7571.0 / 16695.0;
1068        const B4_ERR: f64 = 393.0 / 640.0;
1069        const B5_ERR: f64 = -92097.0 / 339200.0;
1070        const B6_ERR: f64 = 187.0 / 2100.0;
1071        const B7_ERR: f64 = 1.0 / 40.0;
1072
1073        // Compute RK45 stages
1074        let k1_v = self.calculate_acceleration(position, velocity, air_density, wind_vector);
1075        let k1_p = *velocity;
1076
1077        let p2 = position + dt * A21 * k1_p;
1078        let v2 = velocity + dt * A21 * k1_v;
1079        let k2_v = self.calculate_acceleration(&p2, &v2, air_density, wind_vector);
1080        let k2_p = v2;
1081
1082        let p3 = position + dt * (A31 * k1_p + A32 * k2_p);
1083        let v3 = velocity + dt * (A31 * k1_v + A32 * k2_v);
1084        let k3_v = self.calculate_acceleration(&p3, &v3, air_density, wind_vector);
1085        let k3_p = v3;
1086
1087        let p4 = position + dt * (A41 * k1_p + A42 * k2_p + A43 * k3_p);
1088        let v4 = velocity + dt * (A41 * k1_v + A42 * k2_v + A43 * k3_v);
1089        let k4_v = self.calculate_acceleration(&p4, &v4, air_density, wind_vector);
1090        let k4_p = v4;
1091
1092        let p5 = position + dt * (A51 * k1_p + A52 * k2_p + A53 * k3_p + A54 * k4_p);
1093        let v5 = velocity + dt * (A51 * k1_v + A52 * k2_v + A53 * k3_v + A54 * k4_v);
1094        let k5_v = self.calculate_acceleration(&p5, &v5, air_density, wind_vector);
1095        let k5_p = v5;
1096
1097        let p6 = position + dt * (A61 * k1_p + A62 * k2_p + A63 * k3_p + A64 * k4_p + A65 * k5_p);
1098        let v6 = velocity + dt * (A61 * k1_v + A62 * k2_v + A63 * k3_v + A64 * k4_v + A65 * k5_v);
1099        let k6_v = self.calculate_acceleration(&p6, &v6, air_density, wind_vector);
1100        let k6_p = v6;
1101
1102        let p7 = position + dt * (A71 * k1_p + A73 * k3_p + A74 * k4_p + A75 * k5_p + A76 * k6_p);
1103        let v7 = velocity + dt * (A71 * k1_v + A73 * k3_v + A74 * k4_v + A75 * k5_v + A76 * k6_v);
1104        let k7_v = self.calculate_acceleration(&p7, &v7, air_density, wind_vector);
1105        let k7_p = v7;
1106
1107        // 5th order solution
1108        let new_pos = position + dt * (B1 * k1_p + B3 * k3_p + B4 * k4_p + B5 * k5_p + B6 * k6_p);
1109        let new_vel = velocity + dt * (B1 * k1_v + B3 * k3_v + B4 * k4_v + B5 * k5_v + B6 * k6_v);
1110
1111        // 4th order solution for error estimate
1112        let pos_err = position
1113            + dt * (B1_ERR * k1_p
1114                + B3_ERR * k3_p
1115                + B4_ERR * k4_p
1116                + B5_ERR * k5_p
1117                + B6_ERR * k6_p
1118                + B7_ERR * k7_p);
1119        let vel_err = velocity
1120            + dt * (B1_ERR * k1_v
1121                + B3_ERR * k3_v
1122                + B4_ERR * k4_v
1123                + B5_ERR * k5_v
1124                + B6_ERR * k6_v
1125                + B7_ERR * k7_v);
1126
1127        // Estimate error
1128        let pos_error = (new_pos - pos_err).magnitude();
1129        let vel_error = (new_vel - vel_err).magnitude();
1130        let error = (pos_error + vel_error) / (1.0 + position.magnitude() + velocity.magnitude());
1131
1132        // Calculate new step size
1133        let dt_new = if error < tolerance {
1134            dt * (tolerance / error).powf(0.2).min(2.0)
1135        } else {
1136            dt * (tolerance / error).powf(0.25).max(0.1)
1137        };
1138
1139        (new_pos, new_vel, dt_new)
1140    }
1141
1142    fn calculate_acceleration(
1143        &self,
1144        position: &Vector3<f64>,
1145        velocity: &Vector3<f64>,
1146        air_density: f64,
1147        wind_vector: &Vector3<f64>,
1148    ) -> Vector3<f64> {
1149        // Calculate altitude-dependent wind if wind shear is enabled
1150        let actual_wind = if self.inputs.enable_wind_shear {
1151            self.get_wind_at_altitude(position.y)
1152        } else {
1153            *wind_vector
1154        };
1155
1156        let relative_velocity = velocity - actual_wind;
1157        let velocity_magnitude = relative_velocity.magnitude();
1158
1159        if velocity_magnitude < 0.001 {
1160            return Vector3::new(0.0, -9.81, 0.0);
1161        }
1162
1163        // Get drag coefficient from drag model (Mach-indexed from drag tables)
1164        let cd = self.calculate_drag_coefficient(velocity_magnitude);
1165
1166        // Apply cluster BC correction if enabled
1167        let effective_bc = if let Some(ref cluster_bc) = self.cluster_bc {
1168            // Convert velocity to fps for cluster BC calculation
1169            let velocity_fps = velocity_magnitude * 3.28084;
1170            cluster_bc.apply_correction(
1171                self.inputs.bc_value,
1172                self.inputs.caliber_inches * 0.0254, // Convert back to meters for consistency
1173                self.inputs.weight_grains,
1174                velocity_fps,
1175            )
1176        } else {
1177            self.inputs.bc_value
1178        };
1179
1180        // Use proper ballistics retardation formula
1181        // This matches the proven formula from fast_trajectory.rs
1182        // The standard retardation factor converts Cd to drag deceleration
1183        let velocity_fps = velocity_magnitude * 3.28084; // m/s to fps
1184        let cd_to_retard = 0.000683 * 0.30; // Standard ballistics constant
1185        let standard_factor = cd * cd_to_retard;
1186        let density_scale = air_density / 1.225; // Scale relative to standard air (1.225 kg/m³)
1187
1188        // Drag acceleration in ft/s² then convert to m/s²
1189        let a_drag_ft_s2 =
1190            (velocity_fps * velocity_fps) * standard_factor * density_scale / effective_bc;
1191        let a_drag_m_s2 = a_drag_ft_s2 * 0.3048; // ft/s² to m/s²
1192
1193        // Apply drag opposite to velocity direction
1194        let drag_acceleration = -a_drag_m_s2 * (relative_velocity / velocity_magnitude);
1195
1196        // Total acceleration = drag + gravity
1197        drag_acceleration + Vector3::new(0.0, -9.81, 0.0)
1198    }
1199
1200    fn calculate_drag_coefficient(&self, velocity: f64) -> f64 {
1201        // Calculate speed of sound based on atmospheric temperature
1202        let temp_c = self.atmosphere.temperature;
1203        let temp_k = temp_c + 273.15;
1204        let gamma = 1.4; // Ratio of specific heats for air
1205        let r_specific = 287.05; // Specific gas constant for air (J/kg·K)
1206        let speed_of_sound = (gamma * r_specific * temp_k).sqrt();
1207        let mach = velocity / speed_of_sound;
1208
1209        // Get drag coefficient from the drag tables (Mach-indexed)
1210        let base_cd = crate::drag::get_drag_coefficient(mach, &self.inputs.bc_type);
1211
1212        // Determine projectile shape for transonic corrections
1213        let projectile_shape = if let Some(ref model) = self.inputs.bullet_model {
1214            // Try to determine shape from bullet model string
1215            if model.to_lowercase().contains("boat") || model.to_lowercase().contains("bt") {
1216                ProjectileShape::BoatTail
1217            } else if model.to_lowercase().contains("round") || model.to_lowercase().contains("rn")
1218            {
1219                ProjectileShape::RoundNose
1220            } else if model.to_lowercase().contains("flat") || model.to_lowercase().contains("fb") {
1221                ProjectileShape::FlatBase
1222            } else {
1223                // Use heuristic based on caliber, weight, and drag model
1224                get_projectile_shape(
1225                    self.inputs.bullet_diameter,
1226                    self.inputs.bullet_mass / 0.00006479891, // Convert kg to grains
1227                    &self.inputs.bc_type.to_string(),
1228                )
1229            }
1230        } else {
1231            // Use heuristic based on caliber, weight, and drag model
1232            get_projectile_shape(
1233                self.inputs.bullet_diameter,
1234                self.inputs.bullet_mass / 0.00006479891, // Convert kg to grains
1235                &self.inputs.bc_type.to_string(),
1236            )
1237        };
1238
1239        // Apply transonic corrections
1240        // Enable wave drag if advanced effects are enabled
1241        let include_wave_drag = self.inputs.enable_advanced_effects;
1242        transonic_correction(mach, base_cd, projectile_shape, include_wave_drag)
1243    }
1244}
1245
1246// Monte Carlo parameters
1247#[derive(Debug, Clone)]
1248pub struct MonteCarloParams {
1249    pub num_simulations: usize,
1250    pub velocity_std_dev: f64,
1251    pub angle_std_dev: f64,
1252    pub bc_std_dev: f64,
1253    pub wind_speed_std_dev: f64,
1254    pub target_distance: Option<f64>,
1255    pub base_wind_speed: f64,
1256    pub base_wind_direction: f64,
1257    pub azimuth_std_dev: f64, // Horizontal aiming variation in radians
1258}
1259
1260impl Default for MonteCarloParams {
1261    fn default() -> Self {
1262        Self {
1263            num_simulations: 1000,
1264            velocity_std_dev: 1.0,
1265            angle_std_dev: 0.001,
1266            bc_std_dev: 0.01,
1267            wind_speed_std_dev: 1.0,
1268            target_distance: None,
1269            base_wind_speed: 0.0,
1270            base_wind_direction: 0.0,
1271            azimuth_std_dev: 0.001, // Default horizontal spread ~0.057 degrees
1272        }
1273    }
1274}
1275
1276// Monte Carlo results
1277#[derive(Debug, Clone)]
1278pub struct MonteCarloResults {
1279    pub ranges: Vec<f64>,
1280    pub impact_velocities: Vec<f64>,
1281    pub impact_positions: Vec<Vector3<f64>>,
1282}
1283
1284// Run Monte Carlo simulation (backwards compatibility)
1285pub fn run_monte_carlo(
1286    base_inputs: BallisticInputs,
1287    params: MonteCarloParams,
1288) -> Result<MonteCarloResults, BallisticsError> {
1289    let base_wind = WindConditions {
1290        speed: params.base_wind_speed,
1291        direction: params.base_wind_direction,
1292    };
1293    run_monte_carlo_with_wind(base_inputs, base_wind, params)
1294}
1295
1296// Run Monte Carlo simulation with wind
1297pub fn run_monte_carlo_with_wind(
1298    base_inputs: BallisticInputs,
1299    base_wind: WindConditions,
1300    params: MonteCarloParams,
1301) -> Result<MonteCarloResults, BallisticsError> {
1302    use rand::thread_rng;
1303    use rand_distr::{Distribution, Normal};
1304
1305    let mut rng = thread_rng();
1306    let mut ranges = Vec::new();
1307    let mut impact_velocities = Vec::new();
1308    let mut impact_positions = Vec::new();
1309
1310    // First, calculate baseline trajectory with no variations
1311    let baseline_solver =
1312        TrajectorySolver::new(base_inputs.clone(), base_wind.clone(), Default::default());
1313    let baseline_result = baseline_solver.solve()?;
1314
1315    // Determine target distance: use explicit target or baseline max range
1316    let target_distance = params.target_distance.unwrap_or(baseline_result.max_range);
1317
1318    // Get baseline position at target distance (interpolated)
1319    let baseline_at_target = baseline_result
1320        .position_at_range(target_distance)
1321        .ok_or("Could not interpolate baseline at target distance")?;
1322
1323    // Create normal distributions for variations
1324    let velocity_dist = Normal::new(base_inputs.muzzle_velocity, params.velocity_std_dev)
1325        .map_err(|e| format!("Invalid velocity distribution: {}", e))?;
1326    let angle_dist = Normal::new(base_inputs.muzzle_angle, params.angle_std_dev)
1327        .map_err(|e| format!("Invalid angle distribution: {}", e))?;
1328    let bc_dist = Normal::new(base_inputs.bc_value, params.bc_std_dev)
1329        .map_err(|e| format!("Invalid BC distribution: {}", e))?;
1330    let wind_speed_dist = Normal::new(base_wind.speed, params.wind_speed_std_dev)
1331        .map_err(|e| format!("Invalid wind speed distribution: {}", e))?;
1332    let wind_dir_dist =
1333        Normal::new(base_wind.direction, params.wind_speed_std_dev * 0.1) // Small variation in direction
1334            .map_err(|e| format!("Invalid wind direction distribution: {}", e))?;
1335    let azimuth_dist = Normal::new(base_inputs.azimuth_angle, params.azimuth_std_dev)
1336        .map_err(|e| format!("Invalid azimuth distribution: {}", e))?;
1337
1338    // Create distribution for pointing errors (simulates shooter's aiming consistency)
1339    let pointing_error_dist = Normal::new(0.0, params.angle_std_dev * target_distance)
1340        .map_err(|e| format!("Invalid pointing distribution: {}", e))?;
1341
1342    for _ in 0..params.num_simulations {
1343        // Create varied inputs
1344        let mut inputs = base_inputs.clone();
1345        inputs.muzzle_velocity = velocity_dist.sample(&mut rng).max(0.0);
1346        inputs.muzzle_angle = angle_dist.sample(&mut rng);
1347        inputs.bc_value = bc_dist.sample(&mut rng).max(0.01);
1348        inputs.azimuth_angle = azimuth_dist.sample(&mut rng); // Add horizontal variation
1349
1350        // Create varied wind (now based on base wind conditions)
1351        let wind = WindConditions {
1352            speed: wind_speed_dist.sample(&mut rng).abs(),
1353            direction: wind_dir_dist.sample(&mut rng),
1354        };
1355
1356        // Run trajectory
1357        let solver = TrajectorySolver::new(inputs, wind, Default::default());
1358        match solver.solve() {
1359            Ok(result) => {
1360                ranges.push(result.max_range);
1361                impact_velocities.push(result.impact_velocity);
1362
1363                // Interpolate position at target distance (not ground impact)
1364                if let Some(pos_at_target) = result.position_at_range(target_distance) {
1365                    // Calculate deviation from baseline at the SAME target distance
1366                    // X = lateral deviation (windage), Y = vertical deviation (elevation)
1367                    let mut deviation = Vector3::new(
1368                        pos_at_target.x - baseline_at_target.x, // Lateral deviation
1369                        pos_at_target.y - baseline_at_target.y, // Vertical deviation
1370                        0.0, // Z deviation is 0 since we're comparing at same range
1371                    );
1372
1373                    // Add additional pointing error to simulate realistic group sizes
1374                    // This represents the shooter's ability to aim consistently
1375                    let pointing_error_y = pointing_error_dist.sample(&mut rng);
1376                    deviation.y += pointing_error_y;
1377
1378                    impact_positions.push(deviation);
1379                }
1380            }
1381            Err(_) => {
1382                // Skip failed simulations
1383                continue;
1384            }
1385        }
1386    }
1387
1388    if ranges.is_empty() {
1389        return Err("No successful simulations".into());
1390    }
1391
1392    Ok(MonteCarloResults {
1393        ranges,
1394        impact_velocities,
1395        impact_positions,
1396    })
1397}
1398
1399// Calculate zero angle for a target
1400pub fn calculate_zero_angle(
1401    inputs: BallisticInputs,
1402    target_distance: f64,
1403    target_height: f64,
1404) -> Result<f64, BallisticsError> {
1405    calculate_zero_angle_with_conditions(
1406        inputs,
1407        target_distance,
1408        target_height,
1409        WindConditions::default(),
1410        AtmosphericConditions::default(),
1411    )
1412}
1413
1414pub fn calculate_zero_angle_with_conditions(
1415    inputs: BallisticInputs,
1416    target_distance: f64,
1417    target_height: f64,
1418    wind: WindConditions,
1419    atmosphere: AtmosphericConditions,
1420) -> Result<f64, BallisticsError> {
1421    // Helper function to get height at target distance for a given angle
1422    let get_height_at_angle = |angle: f64| -> Result<Option<f64>, BallisticsError> {
1423        let mut test_inputs = inputs.clone();
1424        test_inputs.muzzle_angle = angle;
1425
1426        let mut solver = TrajectorySolver::new(test_inputs, wind.clone(), atmosphere.clone());
1427        solver.set_max_range(target_distance * 2.0);
1428        solver.set_time_step(0.001);
1429        let result = solver.solve()?;
1430
1431        // Z is downrange in standard ballistics coordinates
1432        for i in 0..result.points.len() {
1433            if result.points[i].position.z >= target_distance {
1434                if i > 0 {
1435                    let p1 = &result.points[i - 1];
1436                    let p2 = &result.points[i];
1437                    let t = (target_distance - p1.position.z) / (p2.position.z - p1.position.z);
1438                    return Ok(Some(p1.position.y + t * (p2.position.y - p1.position.y)));
1439                } else {
1440                    return Ok(Some(result.points[i].position.y));
1441                }
1442            }
1443        }
1444        Ok(None)
1445    };
1446
1447    // Binary search for the angle that hits the target
1448    // Use only positive angles to ensure proper ballistic arc (upward trajectory)
1449    let mut low_angle = 0.0; // radians (horizontal)
1450    let mut high_angle = 0.2; // radians (about 11 degrees)
1451    let tolerance = 0.00001; // radians
1452    let max_iterations = 50;
1453
1454    // MBA-194: Validate bracketing before starting binary search
1455    // Check that the target height is actually between low and high angle trajectories
1456    let low_height = get_height_at_angle(low_angle)?;
1457    let high_height = get_height_at_angle(high_angle)?;
1458
1459    match (low_height, high_height) {
1460        (Some(lh), Some(hh)) => {
1461            let low_error = lh - target_height;
1462            let high_error = hh - target_height;
1463
1464            // For proper bracketing, low angle should undershoot (negative error)
1465            // and high angle should overshoot (positive error)
1466            if low_error > 0.0 && high_error > 0.0 {
1467                // Both angles overshoot - target is too close or height too low
1468                // This shouldn't happen for typical zeroing, but handle gracefully
1469                // Try to find a valid bracket by reducing low_angle (can't go negative)
1470                // Since we can't go below 0, just proceed and let binary search find best
1471            } else if low_error < 0.0 && high_error < 0.0 {
1472                // Both angles undershoot - target is beyond effective range
1473                // Try expanding high_angle up to 45 degrees (0.785 rad)
1474                let mut expanded = false;
1475                for multiplier in [2.0, 3.0, 4.0] {
1476                    let new_high = (high_angle * multiplier).min(0.785);
1477                    if let Ok(Some(h)) = get_height_at_angle(new_high) {
1478                        if h - target_height > 0.0 {
1479                            high_angle = new_high;
1480                            expanded = true;
1481                            break;
1482                        }
1483                    }
1484                    if new_high >= 0.785 {
1485                        break;
1486                    }
1487                }
1488                if !expanded {
1489                    return Err("Cannot find zero angle: target beyond effective range even at maximum angle".into());
1490                }
1491            }
1492            // If signs are opposite, we have valid bracketing - proceed
1493        }
1494        (None, Some(_hh)) => {
1495            // Low angle doesn't reach target, high does - this is fine
1496            // Binary search will increase low_angle until trajectory reaches
1497        }
1498        (Some(_lh), None) => {
1499            // High angle doesn't reach target - shouldn't happen
1500            return Err(
1501                "Cannot find zero angle: high angle trajectory doesn't reach target distance"
1502                    .into(),
1503            );
1504        }
1505        (None, None) => {
1506            // Neither reaches target - target too far
1507            return Err(
1508                "Cannot find zero angle: trajectory cannot reach target distance at any angle"
1509                    .into(),
1510            );
1511        }
1512    }
1513
1514    for _iteration in 0..max_iterations {
1515        let mid_angle = (low_angle + high_angle) / 2.0;
1516
1517        let mut test_inputs = inputs.clone();
1518        test_inputs.muzzle_angle = mid_angle;
1519
1520        let mut solver = TrajectorySolver::new(test_inputs, wind.clone(), atmosphere.clone());
1521        // Make sure we calculate far enough to reach the target
1522        solver.set_max_range(target_distance * 2.0);
1523        solver.set_time_step(0.001);
1524        let result = solver.solve()?;
1525
1526        // Find the height at target distance (Z is downrange)
1527        let mut height_at_target = None;
1528        for i in 0..result.points.len() {
1529            if result.points[i].position.z >= target_distance {
1530                if i > 0 {
1531                    // Linear interpolation
1532                    let p1 = &result.points[i - 1];
1533                    let p2 = &result.points[i];
1534                    let t = (target_distance - p1.position.z) / (p2.position.z - p1.position.z);
1535                    height_at_target = Some(p1.position.y + t * (p2.position.y - p1.position.y));
1536                } else {
1537                    height_at_target = Some(result.points[i].position.y);
1538                }
1539                break;
1540            }
1541        }
1542
1543        match height_at_target {
1544            Some(height) => {
1545                let error = height - target_height;
1546                // MBA-193: Check height error FIRST (primary convergence criterion)
1547                // Height accuracy is what matters for zeroing - angle tolerance is secondary
1548                if error.abs() < 0.001 {
1549                    return Ok(mid_angle);
1550                }
1551
1552                // Only use angle tolerance as convergence criterion if we have
1553                // exhausted angle precision AND height error is still acceptable
1554                // (within 10mm which is reasonable for long range)
1555                if (high_angle - low_angle).abs() < tolerance {
1556                    if error.abs() < 0.01 {
1557                        // Height error within 10mm - acceptable for practical use
1558                        return Ok(mid_angle);
1559                    }
1560                    // Angle converged but height error too large - this shouldn't happen
1561                    // with proper tolerance values, but return best effort
1562                    return Ok(mid_angle);
1563                }
1564
1565                if error > 0.0 {
1566                    high_angle = mid_angle;
1567                } else {
1568                    low_angle = mid_angle;
1569                }
1570            }
1571            None => {
1572                // Trajectory didn't reach target distance, increase angle
1573                low_angle = mid_angle;
1574
1575                // MBA-193: Check angle tolerance for None case too
1576                if (high_angle - low_angle).abs() < tolerance {
1577                    return Err("Trajectory cannot reach target distance - angle converged without valid solution".into());
1578                }
1579            }
1580        }
1581    }
1582
1583    Err("Failed to find zero angle".into())
1584}
1585
1586// Estimate BC from trajectory data
1587pub fn estimate_bc_from_trajectory(
1588    velocity: f64,
1589    mass: f64,
1590    diameter: f64,
1591    points: &[(f64, f64)], // (distance, drop) pairs
1592) -> Result<f64, BallisticsError> {
1593    // Simple BC estimation using least squares
1594    let mut best_bc = 0.5;
1595    let mut best_error = f64::MAX;
1596    let mut found_valid = false;
1597
1598    // Try different BC values
1599    for bc in (100..1000).step_by(10) {
1600        let bc_value = bc as f64 / 1000.0;
1601
1602        let inputs = BallisticInputs {
1603            muzzle_velocity: velocity,
1604            bc_value,
1605            bullet_mass: mass,
1606            bullet_diameter: diameter,
1607            ..Default::default()
1608        };
1609
1610        let mut solver = TrajectorySolver::new(inputs, Default::default(), Default::default());
1611        // Set max range for BC estimation
1612        solver.set_max_range(points.last().map(|(d, _)| *d * 1.5).unwrap_or(1000.0));
1613
1614        let result = match solver.solve() {
1615            Ok(r) => r,
1616            Err(_) => continue, // Skip this BC value if solve fails
1617        };
1618
1619        // Calculate error
1620        let mut total_error = 0.0;
1621        for (target_dist, target_drop) in points {
1622            // Find drop at this distance
1623            let mut calculated_drop = None;
1624            for i in 0..result.points.len() {
1625                if result.points[i].position.z >= *target_dist {
1626                    if i > 0 {
1627                        // Linear interpolation
1628                        let p1 = &result.points[i - 1];
1629                        let p2 = &result.points[i];
1630                        let t = (target_dist - p1.position.z) / (p2.position.z - p1.position.z);
1631                        calculated_drop =
1632                            Some(-(p1.position.y + t * (p2.position.y - p1.position.y)));
1633                    } else {
1634                        calculated_drop = Some(-result.points[i].position.y);
1635                    }
1636                    break;
1637                }
1638            }
1639
1640            if let Some(drop) = calculated_drop {
1641                let error = (drop - target_drop).abs();
1642                total_error += error * error;
1643            }
1644        }
1645
1646        if total_error < best_error {
1647            best_error = total_error;
1648            best_bc = bc_value;
1649            found_valid = true;
1650        }
1651    }
1652
1653    if !found_valid {
1654        return Err(BallisticsError::from("Unable to estimate BC from provided data. Check that drop values are in correct units.".to_string()));
1655    }
1656
1657    Ok(best_bc)
1658}
1659
1660// Helper function to calculate air density
1661fn calculate_air_density(atmosphere: &AtmosphericConditions) -> f64 {
1662    // Simplified air density calculation
1663    // P / (R * T) where R is specific gas constant for dry air
1664    let r_specific = 287.058; // J/(kg·K)
1665    let temperature_k = atmosphere.temperature + 273.15;
1666
1667    // Convert pressure from hPa to Pa
1668    let pressure_pa = atmosphere.pressure * 100.0;
1669
1670    // Basic density calculation
1671    let density = pressure_pa / (r_specific * temperature_k);
1672
1673    // Altitude correction (simplified)
1674    let altitude_factor = (-atmosphere.altitude / 8000.0).exp();
1675
1676    density * altitude_factor
1677}
1678
1679// Add rand dependencies for Monte Carlo
1680use rand;
1681use rand_distr;