Skip to main content

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::WindShearModel;
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 enable_magnus: bool,   // Magnus side force (independent of Coriolis)
111    pub enable_coriolis: bool, // Coriolis deflection (requires latitude)
112    pub use_powder_sensitivity: bool,
113    pub powder_temp_sensitivity: f64,
114    pub powder_temp: f64,           // Celsius
115    pub tipoff_yaw: f64,            // radians
116    pub tipoff_decay_distance: f64, // meters
117    pub use_bc_segments: bool,
118    pub bc_segments: Option<Vec<(f64, f64)>>, // Mach-BC pairs
119    pub bc_segments_data: Option<Vec<crate::BCSegmentData>>, // Velocity-BC segments
120    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, // meters
126    pub enable_pitch_damping: bool,
127    pub enable_precession_nutation: bool,
128    pub use_cluster_bc: bool, // Use cluster-based BC degradation
129
130    // Custom drag model support
131    pub custom_drag_table: Option<crate::drag::DragTable>,
132
133    // Legacy field for compatibility
134    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            // Core ballistics parameters
147            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, // Approximate (match the CLI's 4.5-caliber heuristic)
153
154            // Targeting and positioning
155            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,       // Default 0 - height is in sight_height
161            target_height: 0.0,       // Target at ground level by default
162            ground_threshold: -100.0, // Effectively disable ground detection (allow bullet to drop 100m below start)
163
164            // Environmental conditions
165            altitude: 0.0,
166            temperature: 15.0,
167            pressure: 1013.25, // Standard sea level pressure (millibars)
168            humidity: 0.5,     // 50% relative humidity
169            latitude: None,
170
171            // Wind conditions
172            wind_speed: 0.0,
173            wind_angle: 0.0,
174
175            // Bullet characteristics
176            twist_rate: 12.0, // 1:12" typical
177            is_twist_right: true,
178            caliber_inches: diameter_m / 0.0254, // Convert to inches
179            weight_grains: mass_kg / 0.00006479891, // Convert to grains
180            manufacturer: None,
181            bullet_model: None,
182            bullet_id: None,
183            bullet_cluster: None,
184
185            // Integration method selection
186            use_rk4: true,           // Use Runge-Kutta methods by default
187            use_adaptive_rk45: true, // Default to RK45 adaptive for best accuracy
188
189            // Advanced effects (disabled by default)
190            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, // Default 10 meter intervals
207            enable_pitch_damping: false,
208            enable_precession_nutation: false,
209            use_cluster_bc: false, // Disabled by default for backward compatibility
210
211            // Custom drag model support
212            custom_drag_table: None,
213
214            // Legacy field for compatibility
215            bc_type_str: None,
216        }
217    }
218}
219
220// Wind conditions
221#[derive(Debug, Clone)]
222pub struct WindConditions {
223    pub speed: f64,     // m/s
224    pub direction: f64, // radians (0 = North, PI/2 = East)
225}
226
227impl Default for WindConditions {
228    fn default() -> Self {
229        Self {
230            speed: 0.0,
231            direction: 0.0,
232        }
233    }
234}
235
236// Atmospheric conditions
237#[derive(Debug, Clone)]
238pub struct AtmosphericConditions {
239    pub temperature: f64, // Celsius
240    pub pressure: f64,    // hPa
241    pub humidity: f64,    // percentage (0-100)
242    pub altitude: f64,    // meters
243}
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// Trajectory point data
257#[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// Trajectory result
266#[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>>, // Trajectory samples at regular intervals
275    pub min_pitch_damping: Option<f64>, // Minimum pitch damping coefficient (for stability warning)
276    pub transonic_mach: Option<f64>,    // Mach number when entering transonic regime
277    pub angular_state: Option<AngularState>, // Final angular state if precession/nutation enabled
278    pub max_yaw_angle: Option<f64>,     // Maximum yaw angle during flight (radians)
279    pub max_precession_angle: Option<f64>, // Maximum precession angle (radians)
280}
281
282impl TrajectoryResult {
283    /// Interpolate position at a given downrange distance (X coordinate, McCoy).
284    /// Returns the interpolated (x, y, z) position at that range.
285    /// If the target range exceeds the trajectory, returns the last point.
286    pub fn position_at_range(&self, target_range: f64) -> Option<Vector3<f64>> {
287        if self.points.is_empty() {
288            return None;
289        }
290
291        // Find the two points that bracket the target range
292        for i in 0..self.points.len() - 1 {
293            let p1 = &self.points[i];
294            let p2 = &self.points[i + 1];
295
296            // Check if target range is between these two points (X is downrange)
297            if p1.position.x <= target_range && p2.position.x >= target_range {
298                // Linear interpolation factor
299                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                // Interpolate Y and Z, use exact target_range for X
306                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        // Target range is beyond trajectory - return last point
315        self.points.last().map(|p| p.position)
316    }
317}
318
319// Trajectory solver
320pub 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        // Compute derived fields from base units
336        inputs.caliber_inches = inputs.bullet_diameter / 0.0254;
337        inputs.weight_grains = inputs.bullet_mass / 0.00006479891;
338
339        // Initialize cluster BC if enabled
340        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        // Scale the operative surface wind by the boundary-layer multiplier. `altitude_m` is the
366        // bullet's height relative to the muzzle (McCoy Y). The multiplier is floored at 1.0, so
367        // flat-fire trajectories keep ~full wind and only high-arcing shots see increased wind.
368        //
369        // We build the vector with THIS solver's non-shear sign convention (X=+cos, Z=+sin; see
370        // the `wind_vector` used in solve_rk4/solve_euler) and scale it, so that "shear on" equals
371        // "shear off" * ratio (ratio == 1.0 for flat fire). The previous code both attenuated the
372        // wind near the line of sight and flipped its sign relative to the non-shear path.
373        let model = if self.inputs.wind_shear_model == "logarithmic" {
374            WindShearModel::Logarithmic
375        } else {
376            WindShearModel::PowerLaw // default to power law
377        };
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, // X: downrange head/tail
382            0.0,
383            self.wind.speed * self.wind.direction.sin() * speed_ratio, // Z: lateral crosswind
384        )
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    /// Gyroscopic spin drift via the empirical Litz model, applied in the engine
402    /// (not the WASM formatter) so it covers Euler/RK4/RK45 and all consumers.
403    /// Uses the canonical SI fields and converts to grains/inches correctly,
404    /// avoiding the kg/m-vs-grains/in unit bug in `calculate_enhanced_spin_drift`.
405    /// Frame (McCoy): Z = lateral (windage), so drift adds to `position.z`.
406    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; // m -> in
411        let m_gr = self.inputs.bullet_mass / 0.00006479891; // kg -> grains
412        let twist_in = self.inputs.twist_rate; // inches/turn
413        if d_in <= 0.0 || m_gr <= 0.0 || twist_in <= 0.0 {
414            return;
415        }
416
417        // Real length when available, else 4.5 cal (typical match bullet).
418        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); // Litz drift, inches
431            p.position.z += sign * sd_in * 0.0254; // in -> m, Z = lateral
432        }
433
434        // sampled_points are snapshotted from the PRE-drift trajectory inside each solver, so the
435        // sampled wind_drift_m column would omit the spin drift that result.points carry. Apply
436        // the same Litz drift to keep the two user-facing outputs consistent.
437        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        // Simple trajectory integration using Euler method
450        let mut time = 0.0;
451        // Bullet starts at the BORE position, which is muzzle_height above ground
452        // The sight is sight_height ABOVE the bore, so we don't add sight_height here
453        let mut position = Vector3::new(
454            0.0,
455            self.inputs.muzzle_height, // Bore position above ground (NOT + sight_height)
456            0.0,
457        );
458        // Calculate initial velocity components with both elevation and azimuth
459        // McCoy coordinate system: X=downrange, Y=vertical, Z=lateral (right)
460        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(), // X: downrange (forward)
463            self.inputs.muzzle_velocity * self.inputs.muzzle_angle.sin(), // Y: vertical component
464            horizontal_velocity * self.inputs.azimuth_angle.sin(), // Z: lateral (side deviation)
465        );
466
467        let mut points = Vec::new();
468        let mut max_height = position.y;
469        let mut min_pitch_damping = 1.0; // Track minimum pitch damping coefficient
470        let mut transonic_mach = None; // Track when we enter transonic
471
472        // Initialize angular state for precession/nutation tracking
473        let mut angular_state = if self.inputs.enable_precession_nutation {
474            Some(AngularState {
475                pitch_angle: 0.001, // Small initial disturbance
476                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        // Calculate air density
489        let air_density = calculate_air_density(&self.atmosphere);
490
491        // Wind vector (McCoy): X=downrange (head/tail wind), Y=0, Z=lateral (crosswind)
492        let wind_vector = Vector3::new(
493            self.wind.speed * self.wind.direction.cos(), // X: downrange (head/tail wind)
494            0.0,
495            self.wind.speed * self.wind.direction.sin(), // Z: lateral (crosswind)
496        );
497
498        // Pitch-damping coefficients depend only on the (constant) bullet_model; compute once
499        // instead of re-deriving them (with a to_lowercase alloc) every integration step.
500        let pitch_coeffs = PitchDampingCoefficients::from_bullet_type(
501            self.inputs.bullet_model.as_deref().unwrap_or("default"),
502        );
503
504        // Main integration loop (X is downrange)
505        while position.x < self.max_range && position.y > self.inputs.ground_threshold && time < 100.0 {
506            // Store trajectory point
507            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            // Debug: log first and every 100th point. Debug builds only — this was ungated and
519            // polluted release/WASM stderr on the --use-euler path (the other solvers have none).
520            // McCoy coordinate system: X=downrange, Y=vertical, Z=lateral
521            #[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            // Track max height
528            if position.y > max_height {
529                max_height = position.y;
530            }
531
532            // Calculate pitch damping if enabled
533            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                // Track when we enter transonic
540                if transonic_mach.is_none() && mach < 1.2 && mach > 0.8 {
541                    transonic_mach = Some(mach);
542                }
543
544                // Calculate pitch damping coefficient
545                let pitch_damping = calculate_pitch_damping_coefficient(mach, &pitch_coeffs);
546
547                // Track minimum (most critical for stability)
548                if pitch_damping < min_pitch_damping {
549                    min_pitch_damping = pitch_damping;
550                }
551            }
552
553            // Calculate precession/nutation if enabled
554            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                    // Calculate spin rate from twist rate and velocity
563                    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                    // Create precession/nutation parameters
572                    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,       // Typical value
578                        transverse_inertia: 9.13e-7, // Typical value
579                        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                    // Update angular state
587                    *state = calculate_combined_angular_motion(
588                        &params,
589                        state,
590                        time,
591                        self.time_step,
592                        0.001, // Initial disturbance
593                    );
594
595                    // Track maximums
596                    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            // Use the same acceleration kernel as RK4/RK45 so all three solvers share ONE drag
606            // model. solve_euler previously used a bespoke frontal-area drag (0.5*rho*Cd*A*v^2/m)
607            // that IGNORED the ballistic coefficient entirely (diverging up to ~2.3x from the
608            // BC-retardation RK4/RK45 path), and also omitted the Magnus/Coriolis terms.
609            // calculate_acceleration applies BC-retardation drag, gravity, Coriolis, Magnus, wind
610            // shear, and the zero-relative-velocity gravity-only guard.
611            let acceleration =
612                self.calculate_acceleration(&position, &velocity, air_density, &wind_vector);
613
614            // Update state
615            velocity += acceleration * self.time_step;
616            position += velocity * self.time_step;
617            time += self.time_step;
618        }
619
620        // Get final values
621        let last_point = points.last().ok_or("No trajectory points generated")?;
622
623        // Create trajectory sampling data if enabled
624        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                        // Reconstruct velocity vectors from magnitude (approximate)
632                        Vector3::new(0.0, 0.0, p.velocity_magnitude)
633                    })
634                    .collect(),
635                transonic_distances: Vec::new(), // TODO: Track Mach transitions
636            };
637
638            // For LOS calculation in ground-referenced coordinates:
639            // sight_position_m is the sight's actual y-position above ground
640            // (muzzle_height + sight_height, not just sight_height)
641            // For flat shots, target is at same height as the sight (horizontal LOS)
642            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, // X is downrange
645                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            // Sample at specified intervals
652            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, // X is downrange
665            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        // RK4 trajectory integration for better accuracy
693        let mut time = 0.0;
694        // Bullet starts at the BORE position, which is muzzle_height above ground
695        // The sight is sight_height ABOVE the bore, so we don't add sight_height here
696        // The sight_height affects the LOS calculation and zero angle, not the starting position
697        let mut position = Vector3::new(
698            0.0,
699            self.inputs.muzzle_height, // Bore position above ground (NOT + sight_height)
700            0.0,
701        );
702
703        // Calculate initial velocity components with both elevation and azimuth
704        // McCoy coordinate system: X=downrange, Y=vertical, Z=lateral (right)
705        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(), // X: downrange (forward)
708            self.inputs.muzzle_velocity * self.inputs.muzzle_angle.sin(), // Y: vertical component
709            horizontal_velocity * self.inputs.azimuth_angle.sin(), // Z: lateral (side deviation)
710        );
711
712        let mut points = Vec::new();
713        let mut max_height = position.y;
714        let mut min_pitch_damping = 1.0; // Track minimum pitch damping coefficient
715        let mut transonic_mach = None; // Track when we enter transonic
716
717        // Initialize angular state for precession/nutation tracking
718        let mut angular_state = if self.inputs.enable_precession_nutation {
719            Some(AngularState {
720                pitch_angle: 0.001, // Small initial disturbance
721                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        // Calculate air density
734        let air_density = calculate_air_density(&self.atmosphere);
735
736        // Wind vector (McCoy): X=downrange (head/tail wind), Y=0, Z=lateral (crosswind)
737        let wind_vector = Vector3::new(
738            self.wind.speed * self.wind.direction.cos(), // X: downrange (head/tail wind)
739            0.0,
740            self.wind.speed * self.wind.direction.sin(), // Z: lateral (crosswind)
741        );
742
743        // Pitch-damping coefficients depend only on the (constant) bullet_model; compute once
744        // instead of re-deriving them (with a to_lowercase alloc) every integration step.
745        let pitch_coeffs = PitchDampingCoefficients::from_bullet_type(
746            self.inputs.bullet_model.as_deref().unwrap_or("default"),
747        );
748
749        // Main RK4 integration loop (X is downrange)
750        while position.x < self.max_range && position.y > self.inputs.ground_threshold && time < 100.0 {
751            // Store trajectory point
752            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            // Calculate pitch damping if enabled (RK4 solver)
768            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                // Track when we enter transonic
775                if transonic_mach.is_none() && mach < 1.2 && mach > 0.8 {
776                    transonic_mach = Some(mach);
777                }
778
779                // Calculate pitch damping coefficient
780                let pitch_damping = calculate_pitch_damping_coefficient(mach, &pitch_coeffs);
781
782                // Track minimum (most critical for stability)
783                if pitch_damping < min_pitch_damping {
784                    min_pitch_damping = pitch_damping;
785                }
786            }
787
788            // Calculate precession/nutation if enabled (RK4 solver)
789            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                    // Calculate spin rate from twist rate and velocity
798                    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                    // Create precession/nutation parameters
807                    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,       // Typical value
813                        transverse_inertia: 9.13e-7, // Typical value
814                        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                    // Update angular state
822                    *state = calculate_combined_angular_motion(
823                        &params,
824                        state,
825                        time,
826                        self.time_step,
827                        0.001, // Initial disturbance
828                    );
829
830                    // Track maximums
831                    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            // RK4 method
841            let dt = self.time_step;
842
843            // k1
844            let acc1 = self.calculate_acceleration(&position, &velocity, air_density, &wind_vector);
845
846            // k2
847            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            // k3
852            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            // k4
857            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            // Update position and velocity
862            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        // Get final values
868        let last_point = points.last().ok_or("No trajectory points generated")?;
869
870        // Create trajectory sampling data if enabled
871        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                        // Reconstruct velocity vectors from magnitude (approximate)
879                        Vector3::new(0.0, 0.0, p.velocity_magnitude)
880                    })
881                    .collect(),
882                transonic_distances: Vec::new(), // TODO: Track Mach transitions
883            };
884
885            // For LOS calculation in ground-referenced coordinates:
886            // sight_position_m is the sight's actual y-position above ground
887            // (muzzle_height + sight_height, not just sight_height)
888            // For flat shots, target is at same height as the sight (horizontal LOS)
889            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, // X is downrange
892                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            // Sample at specified intervals
899            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, // X is downrange
912            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        // RK45 adaptive step size integration (Dormand-Prince method)
940        let mut time = 0.0;
941        // Bullet starts at the BORE position, which is muzzle_height above ground
942        // The sight is sight_height ABOVE the bore, so we don't add sight_height here
943        let mut position = Vector3::new(
944            0.0,
945            self.inputs.muzzle_height, // Bore position above ground (NOT + sight_height)
946            0.0,
947        );
948
949        // Calculate initial velocity components
950        // McCoy coordinate system: X=downrange, Y=vertical, Z=lateral (right)
951        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(), // X: downrange (forward)
954            self.inputs.muzzle_velocity * self.inputs.muzzle_angle.sin(), // Y: vertical component
955            horizontal_velocity * self.inputs.azimuth_angle.sin(), // Z: lateral (side deviation)
956        );
957
958        let mut points = Vec::new();
959        let mut max_height = position.y;
960        let mut dt = 0.001; // Initial step size
961        let tolerance = 1e-6; // Error tolerance
962        let safety_factor = 0.9; // Safety factor for step size adjustment
963        let max_dt = 0.01; // Maximum step size
964        let min_dt = 1e-6; // Minimum step size
965
966        // Add a point counter to debug
967        let mut iteration_count = 0;
968        const MAX_ITERATIONS: usize = 100000;
969
970        // Air density and wind are constant for the whole solve (self.atmosphere / self.wind
971        // are immutable); compute once instead of every iteration (mirrors solve_rk4).
972        let air_density = calculate_air_density(&self.atmosphere);
973        let wind_vector = Vector3::new(
974            self.wind.speed * self.wind.direction.cos(), // X: downrange (head/tail wind)
975            0.0,
976            self.wind.speed * self.wind.direction.sin(), // Z: lateral (crosswind)
977        );
978
979        while position.x < self.max_range
980            && position.y > self.inputs.ground_threshold
981            && time < 100.0
982        {
983            // X is downrange
984            iteration_count += 1;
985            if iteration_count > MAX_ITERATIONS {
986                break; // Prevent infinite loop
987            }
988
989            // Store current point
990            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            // RK45 step with adaptive step size (air_density / wind_vector hoisted above)
1005            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            // Advance state and time by the dt actually used for THIS step. (Previously dt
1015            // was overwritten with the adapted next-step size BEFORE `time += dt`, so every
1016            // reported time advanced by the NEXT step's dt — desyncing time from state and
1017            // corrupting time_of_flight and per-point / sampled times.)
1018            position = new_pos;
1019            velocity = new_vel;
1020            time += dt;
1021
1022            // Adapt the step size for the NEXT iteration.
1023            dt = (safety_factor * new_dt).clamp(min_dt, max_dt);
1024        }
1025
1026        // Ensure we have at least one point
1027        if points.is_empty() {
1028            return Err(BallisticsError::from("No trajectory points calculated"));
1029        }
1030
1031        let last_point = points.last().unwrap();
1032
1033        // Generate sampled trajectory points if enabled
1034        let sampled_points = if self.inputs.enable_trajectory_sampling {
1035            // Build trajectory data for sampling
1036            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                        // Approximate velocity direction from position changes
1043                        Vector3::new(0.0, 0.0, p.velocity_magnitude)
1044                    })
1045                    .collect(),
1046                transonic_distances: Vec::new(),
1047            };
1048
1049            // For LOS calculation in ground-referenced coordinates:
1050            // sight_position_m is the sight's actual y-position above ground
1051            // (muzzle_height + sight_height, not just sight_height)
1052            // For flat shots, target is at same height as the sight (horizontal LOS)
1053            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, // X is downrange
1075            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        // Dormand-Prince coefficients
1099        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        // 5th order coefficients
1121        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        // 4th order coefficients for error estimation
1128        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        // Compute RK45 stages
1136        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        // 5th order solution
1170        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        // 4th order solution for error estimate
1174        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        // Estimate error
1190        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        // Calculate new step size
1195        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        // Calculate altitude-dependent wind if wind shear is enabled
1212        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        // Get drag coefficient from drag model (Mach-indexed from drag tables)
1226        let cd = self.calculate_drag_coefficient(velocity_magnitude);
1227
1228        // Convert velocity to fps for BC lookups
1229        let velocity_fps = velocity_magnitude * 3.28084;
1230
1231        // Look up BC from segments if available (highest priority - most accurate)
1232        let base_bc = if let Some(ref segments) = self.inputs.bc_segments_data {
1233            // Find matching segment for current velocity
1234            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        // Apply cluster BC correction if enabled (on top of segment BC)
1244        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, // predict_cluster normalizes against an inches range
1248                self.inputs.weight_grains,
1249                velocity_fps,
1250            )
1251        } else {
1252            base_bc
1253        };
1254        // Guard bc_value == 0 (allowed on the FFI/WASM surfaces, which lack the CLI's 0.001
1255        // lower bound): dividing by effective_bc below would be Inf -> NaN. Inert for valid
1256        // BCs (>= 0.001).
1257        let effective_bc = effective_bc.max(1e-6);
1258
1259        // Use proper ballistics retardation formula
1260        // This matches the proven formula from fast_trajectory.rs
1261        // The standard retardation factor converts Cd to drag deceleration
1262        // Note: velocity_fps already calculated above for BC segment lookup
1263        let cd_to_retard = 0.000683 * 0.30; // Standard ballistics constant
1264        let standard_factor = cd * cd_to_retard;
1265        let density_scale = air_density / 1.225; // Scale relative to standard air (1.225 kg/m³)
1266
1267        // Drag acceleration in ft/s² then convert to m/s²
1268        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; // ft/s² to m/s²
1271
1272        // Apply drag opposite to velocity direction
1273        let drag_acceleration = -a_drag_m_s2 * (relative_velocity / velocity_magnitude);
1274
1275        // Total acceleration = drag + gravity
1276        let mut accel = drag_acceleration + Vector3::new(0.0, -crate::constants::G_ACCEL_MPS2, 0.0);
1277
1278        // Coriolis (Earth rotation). McCoy frame: X=downrange, Y=vertical, Z=lateral,
1279        // azimuth 0 = North. McCoy frame: X=downrange, Y=vertical, Z=lateral.
1280        if self.inputs.enable_coriolis {
1281            if let Some(lat_deg) = self.inputs.latitude {
1282                let omega_earth = 7.2921159e-5_f64; // rad/s
1283                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(), // X: downrange component
1287                    omega_earth * lat.sin(),            // Y: vertical component
1288                    omega_earth * lat.cos() * az.sin(), // Z: lateral component
1289                );
1290                // Coriolis is -2 Ω×v. Migrating from the engine's original
1291                // left-handed (lateral, up, downrange) frame to McCoy right-handed
1292                // (downrange, up, lateral) is a reflection, which negates the cross
1293                // product; the +2 here reproduces the original deflection in the new
1294                // frame (output-preserving relabel).
1295                accel += 2.0 * omega.cross(velocity);
1296            }
1297        }
1298
1299        // Magnus side force (spinning projectile). SI units in this solver.
1300        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            // Imperial conversions for the stability / yaw-of-repose helpers.
1311            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            // Yaw of repose (radians); zero for unstable bullets (Sg <= 1).
1321            let (yaw_rad, _) = crate::spin_drift::calculate_yaw_of_repose(
1322                sg,
1323                velocity_magnitude,
1324                spin_rad_s,
1325                0.0, // crosswind handled elsewhere
1326                0.0, // pitch rate not tracked
1327                air_density,
1328                d_in,
1329                l_in,
1330                m_gr,
1331                mach,
1332                "match",
1333                false,
1334            );
1335
1336            // Proper McCoy Magnus FORCE: F = q S C_Npa (pd/2V) sin(alpha_R).
1337            let diameter_m = self.inputs.bullet_diameter; // already meters
1338            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            // Horizontal direction perpendicular to velocity. In McCoy (RH) frame,
1350            // v_unit × up = +Z (right) for a downrange shot, matching spin-drift sign.
1351            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        // Calculate speed of sound based on atmospheric temperature
1369        let temp_c = self.atmosphere.temperature;
1370        let temp_k = temp_c + 273.15;
1371        let gamma = 1.4; // Ratio of specific heats for air
1372        let r_specific = 287.05; // Specific gas constant for air (J/kg·K)
1373        let speed_of_sound = (gamma * r_specific * temp_k).sqrt();
1374        let mach = velocity / speed_of_sound;
1375
1376        // Get drag coefficient from the drag tables (Mach-indexed)
1377        let base_cd = crate::drag::get_drag_coefficient(mach, &self.inputs.bc_type);
1378
1379        // Borrowed &'static str for the drag-model name. bc_type.to_string() goes through
1380        // Debug and heap-allocates a String on every call; this match is bit-identical
1381        // (Display == Debug == variant name) with no per-step allocation.
1382        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        // Determine projectile shape for transonic corrections
1394        let projectile_shape = if let Some(ref model) = self.inputs.bullet_model {
1395            // Lowercase the model name once instead of allocating a new String per check
1396            // (this runs 4-7x per integration step).
1397            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                // Use heuristic based on caliber, weight, and drag model
1406                get_projectile_shape(
1407                    self.inputs.caliber_inches, // INCHES — get_projectile_shape expects inches, not meters
1408                    self.inputs.bullet_mass / 0.00006479891, // Convert kg to grains
1409                    bc_type_str,
1410                )
1411            }
1412        } else {
1413            // Use heuristic based on caliber, weight, and drag model
1414            get_projectile_shape(
1415                self.inputs.caliber_inches, // INCHES — get_projectile_shape expects inches, not meters
1416                self.inputs.bullet_mass / 0.00006479891, // Convert kg to grains
1417                bc_type_str,
1418            )
1419        };
1420
1421        // Apply transonic corrections
1422        // Note: Wave drag is disabled because G7/G1 drag functions already include
1423        // transonic effects. Adding wave drag on top would double-count the drag rise.
1424        // Wave drag should only be enabled for custom drag functions that don't
1425        // include transonic behavior.
1426        let include_wave_drag = false;
1427        transonic_correction(mach, base_cd, projectile_shape, include_wave_drag)
1428    }
1429}
1430
1431// Monte Carlo parameters
1432#[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, // Horizontal aiming variation in radians
1443}
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, // Default horizontal spread ~0.057 degrees
1457        }
1458    }
1459}
1460
1461// Monte Carlo results
1462#[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
1469// Run Monte Carlo simulation (backwards compatibility)
1470pub 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
1481// Run Monte Carlo simulation with wind
1482pub 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    // First, calculate baseline trajectory with no variations
1496    let baseline_solver =
1497        TrajectorySolver::new(base_inputs.clone(), base_wind.clone(), Default::default());
1498    let baseline_result = baseline_solver.solve()?;
1499
1500    // Determine target distance: use explicit target or baseline max range
1501    let target_distance = params.target_distance.unwrap_or(baseline_result.max_range);
1502
1503    // Get baseline position at target distance (interpolated)
1504    let baseline_at_target = baseline_result
1505        .position_at_range(target_distance)
1506        .ok_or("Could not interpolate baseline at target distance")?;
1507
1508    // Create normal distributions for variations
1509    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) // Small variation in direction
1519            .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    // Create distribution for pointing errors (simulates shooter's aiming consistency)
1524    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        // Create varied inputs
1529        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); // Add horizontal variation
1534
1535        // Create varied wind (now based on base wind conditions)
1536        let wind = WindConditions {
1537            speed: wind_speed_dist.sample(&mut rng).abs(),
1538            direction: wind_dir_dist.sample(&mut rng),
1539        };
1540
1541        // Run trajectory
1542        let solver = TrajectorySolver::new(inputs, wind, Default::default());
1543        match solver.solve() {
1544            Ok(result) => {
1545                // Skip samples that fell short of the target (e.g. a low muzzle-velocity draw):
1546                // position_at_range would clamp to the ground-impact point (a large spurious
1547                // deviation). Exclude such samples from ALL THREE result vectors so they stay
1548                // equal-length and per-sample aligned — the FFI exposes them under ONE count
1549                // (ranges.len()), so a shorter impact_positions would leave uninitialized tail
1550                // slots read across the C ABI. The common case (all samples reach the target) is
1551                // unaffected; range/velocity stats stay consistent with the dispersion stats.
1552                if result.max_range < target_distance {
1553                    continue;
1554                }
1555                // Position at target distance (not ground impact). Always Some here since
1556                // max_range >= target_distance and an Ok result has a non-empty trajectory;
1557                // skip defensively (keeping the vectors aligned) if it ever returns None.
1558                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                // Calculate deviation from baseline at the SAME target distance (McCoy)
1567                // X = downrange (0 here), Y = vertical (elevation), Z = lateral (windage)
1568                let mut deviation = Vector3::new(
1569                    0.0, // X downrange deviation is 0 since we compare at same range
1570                    pos_at_target.y - baseline_at_target.y, // Vertical deviation
1571                    pos_at_target.z - baseline_at_target.z, // Lateral deviation (windage)
1572                );
1573
1574                // Add additional pointing error to simulate realistic group sizes
1575                // This represents the shooter's ability to aim consistently
1576                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                // Skip failed simulations
1583                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
1599// Calculate zero angle for a target
1600pub 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    // Helper function to get height at target distance for a given angle
1622    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        // X is downrange in McCoy coordinates
1632        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    // Binary search for the angle that hits the target
1648    // Use only positive angles to ensure proper ballistic arc (upward trajectory)
1649    let mut low_angle = 0.0; // radians (horizontal)
1650    let mut high_angle = 0.2; // radians (about 11 degrees)
1651    let tolerance = 0.00001; // radians
1652    let max_iterations = 50;
1653
1654    // MBA-194: Validate bracketing before starting binary search
1655    // Check that the target height is actually between low and high angle trajectories
1656    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            // For proper bracketing, low angle should undershoot (negative error)
1665            // and high angle should overshoot (positive error)
1666            if low_error > 0.0 && high_error > 0.0 {
1667                // Both angles overshoot - target is too close or height too low
1668                // This shouldn't happen for typical zeroing, but handle gracefully
1669                // Try to find a valid bracket by reducing low_angle (can't go negative)
1670                // Since we can't go below 0, just proceed and let binary search find best
1671            } else if low_error < 0.0 && high_error < 0.0 {
1672                // Both angles undershoot - target is beyond effective range
1673                // Try expanding high_angle up to 45 degrees (0.785 rad)
1674                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            // If signs are opposite, we have valid bracketing - proceed
1693        }
1694        (None, Some(_hh)) => {
1695            // Low angle doesn't reach target, high does - this is fine
1696            // Binary search will increase low_angle until trajectory reaches
1697        }
1698        (Some(_lh), None) => {
1699            // High angle doesn't reach target - shouldn't happen
1700            return Err(
1701                "Cannot find zero angle: high angle trajectory doesn't reach target distance"
1702                    .into(),
1703            );
1704        }
1705        (None, None) => {
1706            // Neither reaches target - target too far
1707            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        // Make sure we calculate far enough to reach the target
1722        solver.set_max_range(target_distance * 2.0);
1723        solver.set_time_step(0.001);
1724        let result = solver.solve()?;
1725
1726        // Find the height at target distance (X is downrange)
1727        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                    // Linear interpolation
1732                    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                // MBA-193: Check height error FIRST (primary convergence criterion)
1747                // Height accuracy is what matters for zeroing - angle tolerance is secondary
1748                if error.abs() < 0.001 {
1749                    return Ok(mid_angle);
1750                }
1751
1752                // Only use angle tolerance as convergence criterion if we have
1753                // exhausted angle precision AND height error is still acceptable
1754                // (within 10mm which is reasonable for long range)
1755                if (high_angle - low_angle).abs() < tolerance {
1756                    if error.abs() < 0.01 {
1757                        // Height error within 10mm - acceptable for practical use
1758                        return Ok(mid_angle);
1759                    }
1760                    // Angle bracket collapsed but the height error is still too large: the
1761                    // target is not actually reachable / was never bracketed. Returning
1762                    // Ok(mid_angle) here reported a NOT-zeroed angle as success (callers use
1763                    // it directly as muzzle_angle); surface it as an error instead.
1764                    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                // Trajectory didn't reach target distance, increase angle
1775                low_angle = mid_angle;
1776
1777                // MBA-193: Check angle tolerance for None case too
1778                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
1788// Estimate BC from trajectory data
1789pub fn estimate_bc_from_trajectory(
1790    velocity: f64,
1791    mass: f64,
1792    diameter: f64,
1793    points: &[(f64, f64)], // (distance, drop) pairs
1794) -> Result<f64, BallisticsError> {
1795    // Simple BC estimation using least squares
1796    let mut best_bc = 0.5;
1797    let mut best_error = f64::MAX;
1798    let mut found_valid = false;
1799
1800    // Try different BC values
1801    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        // Set max range for BC estimation
1814        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, // Skip this BC value if solve fails
1819        };
1820
1821        // Calculate error
1822        let mut total_error = 0.0;
1823        for (target_dist, target_drop) in points {
1824            // Find drop at this distance
1825            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                        // Linear interpolation
1830                        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
1862// Helper function to calculate air density
1863fn calculate_air_density(atmosphere: &AtmosphericConditions) -> f64 {
1864    // Use the shared atmosphere model so ALL solvers agree on air density. An explicitly-set
1865    // pressure/temperature is authoritative; the previous body's extra exp(-altitude/8000) factor
1866    // double-counted altitude and ignored humidity. resolve_station_pressure / _temperature pass
1867    // explicit values through unchanged, but when either is left at its sea-level default they
1868    // return None so altitude drives BOTH the station pressure AND the lapse-rate temperature via
1869    // the ICAO standard — otherwise `--altitude` alone gave sea-level density (and, with only the
1870    // pressure derived, still 15 °C air, ~7% too thin at 3 km). Humidity (0-100) is always applied.
1871    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
1880// Add rand dependencies for Monte Carlo
1881use rand;
1882use rand_distr;
1883
1884#[cfg(test)]
1885mod ground_termination_tests {
1886    use super::*;
1887
1888    // Regression lock for the unified ground termination: solve_euler/solve_rk4/solve_rk45 all
1889    // loop while `position.y > ground_threshold` (default -100.0), so they agree with RK45. A
1890    // lofted shot that returns to launch level before reaching max_range must keep descending to
1891    // the -100 m floor instead of stopping at y = 0 — and RK4-fixed and RK45 must behave the same.
1892    #[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; // ~5.7 deg: arcs up, then descends past launch level
1897            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            // Huge max range: termination must be driven by ground_threshold, not the range cap.
1907            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}