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::mc_stats::{
4    wilson_interval, BernoulliConfidenceSequence, ConfidenceLevel, Welford,
5};
6use crate::pitch_damping::{calculate_pitch_damping_coefficient, PitchDampingCoefficients};
7use crate::precession_nutation::{
8    calculate_combined_angular_motion, projectile_moments_of_inertia, AngularState,
9    PrecessionNutationParams,
10};
11use crate::trajectory_sampling::{
12    projected_sample_count, sample_trajectory, TrajectoryData, TrajectoryOutputs,
13    TrajectorySample,
14};
15use crate::trajectory_observation::{bracket_param, Bracket, TrajectoryTermination};
16use crate::wind_shear::WindShearModel;
17use crate::DragModel;
18use nalgebra::{Vector3, Vector6};
19use std::error::Error;
20use std::fmt;
21
22/// Unit system for CLI-style inputs and outputs.
23///
24/// The single crate-wide unit-system selector, shared by the CLI binary
25/// (`--units`), the truing core ([`crate::truing`]) and the WEZ sweep core
26/// ([`crate::wez`]). It only selects how user-facing quantities are
27/// interpreted and displayed; the solver itself always works in SI.
28///
29/// Variant order (Metric first) is load-bearing for the CLI: clap lists
30/// `--units` possible values in declaration order.
31#[derive(Debug, Clone, Copy, PartialEq)]
32#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
33pub enum UnitSystem {
34    /// Metric units (velocity in m/s, mass in grams, distance in meters, diameter in mm, Celsius)
35    Metric,
36    /// Imperial units (velocity in fps, mass in grains, distance in yards, diameter in inches, Fahrenheit)
37    Imperial,
38}
39
40// Output format for results
41#[derive(Debug, Clone, Copy, PartialEq)]
42pub enum OutputFormat {
43    Table,
44    Json,
45    Csv,
46}
47
48/// Which standard atmosphere a ballistic coefficient's numeric value is referenced to
49/// (MBA-1365).
50///
51/// A BC is not a pure property of the bullet — it also encodes an assumed reference air
52/// density. This engine's retardation constant ([`crate::constants::CD_TO_RETARD`]) is
53/// calibrated against the ICAO Standard Atmosphere's sea-level density
54/// ([`crate::constants::ICAO_DENSITY_LB_FT3`]), which most modern published BCs already
55/// assume. Some vendors (notably Sierra, Hornady, and Barnes for many bullets) instead
56/// publish BCs referenced to the older, denser Army Standard Metro atmosphere
57/// ([`crate::constants::ASM_DENSITY_LB_FT3`]). Feeding an ASM-referenced BC into this
58/// engine as if it were ICAO-referenced under-predicts drag by about 1.8% — declaring
59/// `ArmyStandardMetro` here corrects for that exactly once, at input normalization (see
60/// [`crate::constants::ASM_TO_ICAO_BC`] and `TrajectorySolver::new`).
61///
62/// Does not apply when a custom drag table (`BallisticInputs::custom_drag_table`) is
63/// active: that path divides by sectional density, not a BC value, so no BC reference
64/// conversion is physically meaningful there (see
65/// `BallisticInputs::bc_reference_standard_inert_warning`).
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
67#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
68pub enum BcReferenceStandard {
69    /// The ICAO Standard Atmosphere reference density — matches this engine's
70    /// retardation constant. The default; byte-identical to pre-MBA-1365 behavior.
71    #[default]
72    Icao,
73    /// The (older) Army Standard Metro reference density used by some vendor-published
74    /// BCs (e.g. many Sierra/Hornady/Barnes bullets).
75    ArmyStandardMetro,
76}
77
78/// Shared text for the MBA-1365 "`--bc-reference army-standard-metro` is inert" warning —
79/// single source of truth for every surface that can trigger it (native CLI, WASM,
80/// [`BallisticInputs::bc_reference_standard_inert_warning`]) so the wording can't drift.
81pub const BC_REFERENCE_STANDARD_INERT_WARNING: &str =
82    "warning: --bc-reference army-standard-metro has no effect together with a custom drag \
83     table (--drag-table): the deck's Cd is divided by sectional density, not a BC value, so \
84     no BC-reference conversion applies";
85
86// Error type for CLI operations
87#[derive(Debug)]
88pub struct BallisticsError {
89    message: String,
90}
91
92impl fmt::Display for BallisticsError {
93    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
94        write!(f, "{}", self.message)
95    }
96}
97
98impl Error for BallisticsError {}
99
100impl From<String> for BallisticsError {
101    fn from(msg: String) -> Self {
102        BallisticsError { message: msg }
103    }
104}
105
106impl From<&str> for BallisticsError {
107    fn from(msg: &str) -> Self {
108        BallisticsError {
109            message: msg.to_string(),
110        }
111    }
112}
113
114/// Which plane sampled drop values are referenced to (MBA-1403).
115///
116/// See [`BallisticInputs::drops_reference`]. This is an output-mode toggle for the
117/// trajectory sampler, not new plane machinery: the solver implements incline as gravity
118/// rotation into the shot frame, so sampled drop is already perpendicular to the LOS and
119/// the JBM-equivalent "target" mode is a `1 / cos(shooting_angle)` reference transform
120/// plus relabeling.
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
122pub enum DropsReference {
123    /// Drop measured perpendicular to the line of sight (the historical default).
124    #[default]
125    Los,
126    /// Drop measured vertically in the target plane (JBM's "target plane" reference):
127    /// the LOS-perpendicular drop scaled by `1 / cos(shooting_angle)`.
128    Target,
129}
130
131// Ballistic input parameters - MBA-151 Reconciled Structure
132// Unified structure used by both ballistics-engine and ballistics_rust
133// Duplicates removed, all necessary fields included
134#[derive(Debug, Clone)]
135pub struct BallisticInputs {
136    // Core ballistics parameters (using intuitive names)
137    pub bc_value: f64,        // Ballistic coefficient (G1, G7, etc.)
138    pub bc_type: DragModel,   // Drag model (G1, G7, G8, etc.)
139    /// Which standard atmosphere `bc_value`/`bc_segments`/`bc_segments_data` are
140    /// referenced to (MBA-1365). `Icao` (the default) is a no-op; `ArmyStandardMetro`
141    /// is converted to the ICAO reference exactly once, in `TrajectorySolver::new`,
142    /// before any retardation math runs. See [`BcReferenceStandard`].
143    pub bc_reference_standard: BcReferenceStandard,
144    pub bullet_mass: f64,     // kg
145    pub muzzle_velocity: f64, // m/s
146    pub bullet_diameter: f64, // meters
147    pub bullet_length: f64,   // meters
148
149    // Targeting and positioning
150    pub muzzle_angle: f64,    // radians (launch angle)
151    pub target_distance: f64, // meters
152    pub azimuth_angle: f64, // horizontal aiming angle in radians (small aim offset within the shot frame)
153    /// Compass bearing the shot is fired ALONG, radians, 0 = North, π/2 = East.
154    /// Used only by the Coriolis model (Earth-rotation depends on which way downrange
155    /// points relative to true North). Distinct from `azimuth_angle`, which is the
156    /// small horizontal *aiming* offset and rotates the launch velocity.
157    pub shot_azimuth: f64,
158    pub shooting_angle: f64,   // uphill/downhill angle in radians
159    /// Rifle cant angle in radians about the line of sight — positive = clockwise from the
160    /// shooter's view (top of the scope tips right). Rotates the sight-frame aim offsets
161    /// (`muzzle_angle`, `azimuth_angle`) about the LOS and swings the bore's sight-height
162    /// offset laterally, producing the classic canted-rifle POI error (right-and-low for
163    /// clockwise cant with an upward zero). Zeroing always solves un-canted ("zero level,
164    /// fire canted"). NOTE: treats `muzzle_angle` as a sight-frame offset — the standard
165    /// zero-then-fire usage; a raw gravity-frame launch angle would not rotate physically.
166    /// 0.0 = level rifle (bit-identical to pre-cant behavior). (MBA-1286)
167    pub cant_angle: f64,
168    pub sight_height: f64,     // meters above bore
169    /// Lateral offset between the sight axis and the bore axis, meters (MBA-1396;
170    /// offset-mounted optics): positive = the sight sits RIGHT of the bore, so the bore
171    /// starts LEFT of the line of sight (initial lateral position `z -= offset`). When a
172    /// zero is solved, a windage-zero convergence term of `offset / zero_distance` is
173    /// added to `azimuth_angle` (see [`BallisticInputs::windage_zero_bias_rad`]) so the
174    /// trajectory crosses the LOS laterally at the zero range — matching AB/JBM/Shooter,
175    /// not a constant parallel offset. Without a zero solve (an explicit muzzle angle),
176    /// only the physical displacement applies. Distinct from `zero_poi_horizontal_m`,
177    /// which is an angular ZERO-STATE bias, not mount geometry. 0.0 (the default) is
178    /// byte-identical to pre-MBA-1396 behavior.
179    pub sight_offset_lateral_m: f64,
180    pub muzzle_height: f64,    // meters above ground
181    pub target_height: f64,    // meters above ground for zeroing
182    /// Deliberate vertical point-of-impact offset AT THE ZERO RANGE, meters (MBA-1359;
183    /// Kestrel "zero height" semantics): positive = the rifle is deliberately zeroed to
184    /// impact HIGH by this much at the zero distance. Applied POST-solve by
185    /// `calculate_and_set_zero_angle` as a constant angular bias of
186    /// `zero_poi_vertical_m / zero_distance` on the solved elevation — the zero trials
187    /// themselves always solve perfect convergence, and the small-angle addition is
188    /// identical in both zero target frames. 0.0 (the default) is byte-identical to
189    /// pre-MBA-1359 behavior.
190    pub zero_poi_vertical_m: f64,
191    /// Deliberate horizontal point-of-impact offset AT THE ZERO RANGE, meters (MBA-1359;
192    /// Kestrel "zero offset" semantics): positive = impacts RIGHT by this much at the
193    /// zero distance. Applied POST-solve as an azimuth bias of
194    /// `zero_poi_horizontal_m / zero_distance` when a zero is solved — see
195    /// [`BallisticInputs::windage_zero_bias_rad`]. 0.0 (the default) is neutral.
196    pub zero_poi_horizontal_m: f64,
197    pub ground_threshold: f64, // meters below which to stop
198
199    // Environmental conditions
200    pub altitude: f64,    // meters
201    pub temperature: f64, // Celsius
202    pub pressure: f64,    // millibars/hPa
203    /// Relative humidity as a FRACTION in `[0, 1]` (e.g. 0.5 = 50%). NOTE the scale
204    /// differs from [`AtmosphericConditions::humidity`], which is a PERCENT in `[0, 100]`.
205    /// The atmosphere helpers (`calculate_air_density_*`) expect percent, so convert via
206    /// [`BallisticInputs::humidity_percent`] before passing this value to them (MBA-722).
207    pub humidity: f64,
208    pub latitude: Option<f64>, // degrees
209
210    // Wind conditions
211    pub wind_speed: f64, // m/s
212    pub wind_angle: f64, // radians (0=headwind, PI/2=from right)
213
214    // Bullet characteristics
215    pub twist_rate: f64,               // inches per turn
216    pub is_twist_right: bool,          // right-hand twist
217    pub caliber_inches: f64,           // diameter in inches
218    pub weight_grains: f64,            // mass in grains
219    pub manufacturer: Option<String>,  // Bullet manufacturer
220    pub bullet_model: Option<String>,  // Bullet model name
221    pub bullet_id: Option<String>,     // Unique bullet identifier
222    pub bullet_cluster: Option<usize>, // BC cluster ID for cluster_bc module
223
224    // Integration method selection
225    pub use_rk4: bool,           // Use RK4 integration instead of Euler
226    pub use_adaptive_rk45: bool, // Use RK45 adaptive step size integration
227
228    // Advanced effects flags
229    pub enable_advanced_effects: bool,
230    pub enable_magnus: bool,   // Magnus force (independent of Coriolis)
231    pub enable_coriolis: bool, // Coriolis deflection (requires latitude)
232    pub use_powder_sensitivity: bool,
233    pub powder_temp_sensitivity: f64, // m/s per degree Celsius
234    pub powder_temp: f64,           // Celsius
235    /// Optional measured powder-temperature -> muzzle-velocity curve, as
236    /// (temperature_celsius, muzzle_velocity_m_s) points sorted ascending by
237    /// temperature. When present it supersedes the linear `powder_temp_sensitivity`
238    /// model: the muzzle velocity is interpolated from this table at the ambient
239    /// `temperature` (clamped to the endpoints — no extrapolation beyond measured
240    /// data). This is the data-driven, non-linear alternative to the constant slope.
241    pub powder_temp_curve: Option<Vec<(f64, f64)>>,
242    /// Temperature (Celsius) at which to interpolate `powder_temp_curve` — the POWDER
243    /// temperature, which may differ from the ambient `temperature` (air). `None` uses
244    /// `temperature`. Decouples the velocity lookup from the air-density temperature.
245    pub powder_curve_temp_c: Option<f64>,
246    pub tipoff_yaw: f64,            // radians
247    pub tipoff_decay_distance: f64, // meters
248    /// Quadratic yaw-drag coefficient CD_delta2 (per rad^2, actual-Cd space) applied
249    /// additively to the tip-off yaw: CD = CD0 + CD_delta2 * delta^2 (McCoy, Modern
250    /// Exterior Ballistics). Literature values for spitzer rifle bullets run ~4-20
251    /// per rad^2 (7.62 M80 ~= 9.6); the default 7.5 is a documented mid-range
252    /// constant. Only active when `tipoff_yaw` is nonzero (MBA-1227).
253    pub cd_delta2: f64,
254    /// Enables velocity-keyed `bc_segments_data`. Explicit Mach-keyed `bc_segments` retain their
255    /// legacy behavior and remain active when this flag is false.
256    pub use_bc_segments: bool,
257    pub bc_segments: Option<Vec<(f64, f64)>>, // Mach-BC pairs
258    pub bc_segments_data: Option<Vec<crate::BCSegmentData>>, // Velocity-BC segments
259    pub use_enhanced_spin_drift: bool,
260    /// Legacy compatibility flag. Name-derived "form factors" are intentionally not multiplied
261    /// into reference Cd when `bc_value` is already the retardation denominator (MBA-1184).
262    pub use_form_factor: bool,
263    pub enable_wind_shear: bool,
264    pub wind_shear_model: String,
265    pub enable_trajectory_sampling: bool,
266    pub sample_interval: f64, // meters
267    /// Which plane sampled drop values are referenced to (MBA-1403). The default
268    /// [`DropsReference::Los`] keeps the historical behavior (drop perpendicular to the
269    /// line of sight) byte-identical; [`DropsReference::Target`] reports drop as vertical
270    /// in the target plane — the LOS-perpendicular drop scaled by
271    /// `1 / cos(shooting_angle)` (JBM's "target plane" checkbox) — and, when a non-zero
272    /// `target_height` is supplied, slopes the sampler's LOS datum toward it. This is an
273    /// OUTPUT-mode toggle: the solved trajectory itself is unchanged, and zero-solve
274    /// `target_height` semantics are untouched.
275    pub drops_reference: DropsReference,
276    pub enable_pitch_damping: bool,
277    pub enable_precession_nutation: bool,
278    // MBA-959: apply aerodynamic jump as a muzzle launch-angle perturbation.
279    // EXPERIMENTAL — the underlying model is heuristic and not yet validated; default OFF.
280    pub enable_aerodynamic_jump: bool,
281    pub use_cluster_bc: bool, // Use cluster-based BC degradation
282
283    // Custom drag model support
284    pub custom_drag_table: Option<crate::drag::DragTable>,
285    /// Whole-curve multiplier applied to the custom deck's interpolated Cd (MBA-1356):
286    /// `Cd_used = table.interpolate(mach) * cd_scale`. Meaningful only alongside
287    /// `custom_drag_table` — it is read at the three custom-deck interpolation sites in
288    /// cli_api.rs/derivatives.rs/fast_trajectory.rs and left untouched on the standard
289    /// G-model/BC path (those users true their drag via `--bc-adjustment` instead; scaling
290    /// a reference table too would double-count). Default `1.0` is neutral (byte-identical
291    /// to the pre-MBA-1356 behavior). Validated finite and > 0 by `validate_for_solve`.
292    pub cd_scale: f64,
293
294    // Legacy field for compatibility
295    pub bc_type_str: Option<String>,
296}
297
298impl BallisticInputs {
299    /// `humidity` as a PERCENT in `[0, 100]`, clamped — the scale the atmosphere
300    /// density helpers expect. Centralizes the 0–1 → 0–100 conversion so callers don't
301    /// re-derive it (and can't accidentally feed the raw 0–1 fraction as a percentage).
302    /// See the field doc on [`BallisticInputs::humidity`] (MBA-722).
303    pub fn humidity_percent(&self) -> f64 {
304        (self.humidity * 100.0).clamp(0.0, 100.0)
305    }
306
307    /// Azimuth bias (radians) a zero solved at `zero_distance_m` applies to the launch
308    /// direction. Two independent terms share this one convergence point:
309    /// * MBA-1359 — the deliberate horizontal POI offset at the zero range
310    ///   (`zero_poi_horizontal_m`), an angular zero-state bias;
311    /// * MBA-1396 — the lateral sight-mount offset (`sight_offset_lateral_m`): the bore
312    ///   starts `offset` left of the LOS (see `initial_position`), so the windage zero
313    ///   steers `offset / zero_distance` right to cross the LOS at the zero range.
314    ///
315    /// `calculate_and_set_zero_angle` applies this to its OWN solver's `azimuth_angle`;
316    /// callers that copy a solved zero angle onto separate flight inputs (the CLI/WASM
317    /// auto-zero paths) must add this to their flight `azimuth_angle` themselves — the
318    /// returned elevation angle cannot carry it. Returns exactly `0.0` when both offsets
319    /// are `0.0` or `zero_distance_m` is not positive, so default inputs stay
320    /// byte-identical.
321    pub fn windage_zero_bias_rad(&self, zero_distance_m: f64) -> f64 {
322        if zero_distance_m > 0.0 {
323            (self.zero_poi_horizontal_m + self.sight_offset_lateral_m) / zero_distance_m
324        } else {
325            0.0
326        }
327    }
328
329    /// Sectional density in lb/in²: `weight_grains / 7000 / diameter_in²`.
330    ///
331    /// Derived from the imperial mirror fields (`weight_grains` / `caliber_inches`), falling
332    /// back to the SI `bullet_mass` (kg) / `bullet_diameter` (meters) for SI-only callers
333    /// (mirrors the fallbacks in derivatives.rs). `None` when neither source is usable.
334    pub fn sectional_density_lb_in2(&self) -> Option<f64> {
335        let weight_gr = if self.weight_grains > 0.0 {
336            self.weight_grains
337        } else {
338            self.bullet_mass / crate::constants::GRAINS_TO_KG // kg -> grains
339        };
340        let diameter_in = if self.caliber_inches > 0.0 {
341            self.caliber_inches
342        } else {
343            self.bullet_diameter / 0.0254 // meters -> inches
344        };
345        if weight_gr > 0.0 && diameter_in > 0.0 {
346            Some(weight_gr / 7000.0 / (diameter_in * diameter_in))
347        } else {
348            None
349        }
350    }
351
352    /// Retardation denominator to use when `custom_drag_table` is active.
353    ///
354    /// A custom drag table supplies the projectile's ACTUAL drag coefficient, so the
355    /// point-mass retardation formula must divide it by the projectile's SECTIONAL DENSITY
356    /// (lb/in²), not by a ballistic coefficient: BC = SD / i (form factor i vs the reference
357    /// projectile), and with the projectile's own curve i == 1, so Cd_own / SD == Cd_ref / BC.
358    /// Dividing the curve's Cd by `bc_value` made custom-table trajectories wrongly scale
359    /// with whatever BC happened to be set.
360    ///
361    /// Falls back to `fallback_bc` (with a one-time stderr warning) when mass/diameter are
362    /// unavailable, so degenerate inputs degrade to the old behavior instead of panicking.
363    pub fn custom_drag_denominator(&self, fallback_bc: f64) -> f64 {
364        match self.sectional_density_lb_in2() {
365            Some(sd) => sd,
366            None => {
367                static WARN_ONCE: std::sync::Once = std::sync::Once::new();
368                WARN_ONCE.call_once(|| {
369                    eprintln!(
370                        "Warning: custom drag table active but bullet mass/diameter are \
371                         unavailable; falling back to bc_value for the retardation denominator"
372                    );
373                });
374                fallback_bc
375            }
376        }
377    }
378
379    /// Whether a declared `bc_reference_standard` is inert on this configuration
380    /// (MBA-1365), and if so, the message explaining why.
381    ///
382    /// A custom drag table (`custom_drag_table`) supplies the projectile's actual Cd and
383    /// divides by sectional density, not by a BC value (see `custom_drag_denominator`),
384    /// so an `ArmyStandardMetro` reference has no physical effect once a table is active.
385    /// Pure and side-effect-free — same shape as `main.rs`'s `adjustment_unit_noop_warning`
386    /// (MBA-1414) — so each surface decides how to surface it: the native CLI prints it to
387    /// stderr once per run, while the WASM browser terminal (no visible stderr) splices it
388    /// into its table-output text instead.
389    pub fn bc_reference_standard_inert_warning(&self) -> Option<&'static str> {
390        if self.custom_drag_table.is_some()
391            && matches!(self.bc_reference_standard, BcReferenceStandard::ArmyStandardMetro)
392        {
393            Some(BC_REFERENCE_STANDARD_INERT_WARNING)
394        } else {
395            None
396        }
397    }
398
399    /// Apply every input-conditioning step integration requires, exactly once (MBA-1415).
400    ///
401    /// **Every public entry point into integration must call this**, not just
402    /// [`TrajectorySolver::new`]. `fast_trajectory::fast_integrate` and
403    /// `fast_integrate_with_segments` are `pub` and are called directly by the Python
404    /// binding, so conditioning that lives only in the solver constructor is invisible to
405    /// those consumers: the caller sets a field, gets no error, and the value is silently
406    /// ignored. That exact shape has already cost this project twice — MBA-1296 (a dropped
407    /// field that zeroed Coriolis in production) and the MBA-1356 review catch
408    /// (`cd_scale` dropped by the segmented fast path). Adding a step here rather than at a
409    /// call site is what keeps the next one from repeating it.
410    ///
411    /// **Idempotent**, and it must stay that way: Monte Carlo builds a solver per sample, and
412    /// the fast entry points may receive inputs that already passed through a solver. Each
413    /// step below is either an absolute override (derived fields, powder-resolved velocity) or
414    /// self-disarming (the BC conversion rewrites `bc_reference_standard` to the reference it
415    /// just converted into, so a second call finds nothing to do). A step that scales a value
416    /// in place without disarming itself would double-apply silently — do not add one.
417    pub fn normalize_for_solve(&mut self) {
418        // MBA-1365: normalize a declared Army-Standard-Metro BC reference to the ICAO
419        // reference this engine's retardation constant (CD_TO_RETARD) is calibrated against,
420        // before any retardation math runs. Every BC representation on these inputs (the
421        // scalar, explicit Mach segments, and velocity segments) is a real BC and gets the
422        // same treatment. `Icao` (the default) takes this branch never, so callers that never
423        // set the field are byte-identical to pre-MBA-1365 behavior. A custom drag table
424        // divides by sectional density rather than a BC, so the conversion is physically inert
425        // there — see `bc_reference_standard_inert_warning`, which callers surface at their own
426        // display sites (native stderr / WASM table text) from their OWN copy of the inputs,
427        // before this runs.
428        if matches!(
429            self.bc_reference_standard,
430            BcReferenceStandard::ArmyStandardMetro
431        ) {
432            self.bc_value *= crate::constants::ASM_TO_ICAO_BC;
433            if let Some(segments) = self.bc_segments.as_mut() {
434                for (_mach, bc) in segments.iter_mut() {
435                    *bc *= crate::constants::ASM_TO_ICAO_BC;
436                }
437            }
438            if let Some(segments) = self.bc_segments_data.as_mut() {
439                for segment in segments.iter_mut() {
440                    segment.bc_value *= crate::constants::ASM_TO_ICAO_BC;
441                }
442            }
443            // Disarm: these BC values are now ICAO-referenced, which is simply true, and it
444            // makes a second call a no-op instead of a silent second scaling.
445            self.bc_reference_standard = BcReferenceStandard::Icao;
446        }
447
448        // Derived imperial fields, recomputed from the canonical SI values. These are an
449        // absolute override, NOT a fallback: a caller that sets only `caliber_inches` /
450        // `weight_grains` and leaves the SI fields at their defaults has those imperial values
451        // overwritten here. SI is authoritative on these inputs.
452        self.caliber_inches = self.bullet_diameter / 0.0254;
453        self.weight_grains = self.bullet_mass / crate::constants::GRAINS_TO_KG;
454
455        // Resolve the muzzle velocity for the ambient temperature before integration. A
456        // measured powder-temperature -> velocity curve (data-driven, non-linear) takes
457        // precedence when supplied; otherwise fall back to the linear powder-temperature-
458        // sensitivity model (MBA-963). Both operate in canonical SI (Celsius, m/s), so every
459        // solver built from these inputs — the main trajectory AND the zero-angle search —
460        // sees the same temperature-resolved velocity. In particular, when a zero solve passes
461        // the zero-day temperature, the curve automatically yields the zero-day velocity.
462        // (The curve interpolates at the POWDER temperature — powder_curve_temp_c, falling
463        // back to ambient. Air temperature still drives density separately; this only sets the
464        // velocity. Absolute override, so applying it twice is a no-op.)
465        self.muzzle_velocity = resolve_powder_adjusted_velocity(
466            self.muzzle_velocity,
467            self.temperature,
468            self.use_powder_sensitivity,
469            self.powder_temp_sensitivity,
470            self.powder_temp,
471            self.powder_temp_curve.as_deref(),
472            self.powder_curve_temp_c,
473        );
474    }
475}
476
477impl Default for BallisticInputs {
478    fn default() -> Self {
479        let mass_kg = 0.01;
480        let diameter_m = 0.00762;
481        let bc = 0.5;
482        let muzzle_angle_rad = 0.0;
483        let bc_type = DragModel::G1;
484
485        Self {
486            // Core ballistics parameters
487            bc_value: bc,
488            bc_type,
489            bc_reference_standard: BcReferenceStandard::Icao,
490            bullet_mass: mass_kg,
491            muzzle_velocity: 800.0,
492            bullet_diameter: diameter_m,
493            // MBA-1135: mass-based length estimate so the default is self-consistent with the
494            // default mass/diameter (was a mass-blind 4.5-caliber literal). The twist default below
495            // stays a fixed 1:12" per the ticket (a constant is a sensible velocity-agnostic default).
496            bullet_length: crate::stability::estimate_bullet_length_m(diameter_m, mass_kg),
497
498            // Targeting and positioning
499            muzzle_angle: muzzle_angle_rad,
500            target_distance: 100.0,
501            azimuth_angle: 0.0,
502            shot_azimuth: 0.0,
503            shooting_angle: 0.0,
504            cant_angle: 0.0,
505            sight_height: 0.05,
506            sight_offset_lateral_m: 0.0, // Sight directly above the bore (MBA-1396)
507            muzzle_height: 0.0,       // Default 0 - height is in sight_height
508            target_height: 0.0,       // Target at ground level by default
509            zero_poi_vertical_m: 0.0, // No deliberate POI offset at the zero range (MBA-1359)
510            zero_poi_horizontal_m: 0.0,
511            ground_threshold: -100.0, // Effectively disable ground detection (allow bullet to drop 100m below start)
512
513            // Environmental conditions
514            altitude: 0.0,
515            temperature: 15.0,
516            pressure: 1013.25, // Standard sea level pressure (millibars)
517            humidity: 0.5,     // 50% relative humidity
518            latitude: None,
519
520            // Wind conditions
521            wind_speed: 0.0,
522            wind_angle: 0.0,
523
524            // Bullet characteristics
525            twist_rate: 12.0, // 1:12" typical
526            is_twist_right: true,
527            caliber_inches: diameter_m / 0.0254, // Convert to inches
528            weight_grains: mass_kg / crate::constants::GRAINS_TO_KG, // Convert to grains
529            manufacturer: None,
530            bullet_model: None,
531            bullet_id: None,
532            bullet_cluster: None,
533
534            // Integration method selection
535            use_rk4: true,           // Use Runge-Kutta methods by default
536            use_adaptive_rk45: true, // Default to RK45 adaptive for best accuracy
537
538            // Advanced effects (disabled by default)
539            enable_advanced_effects: false,
540            enable_magnus: false,
541            enable_coriolis: false,
542            use_powder_sensitivity: false,
543            powder_temp_sensitivity: 0.0,
544            powder_temp: 15.0,
545            powder_temp_curve: None,
546            powder_curve_temp_c: None,
547            tipoff_yaw: 0.0,
548            tipoff_decay_distance: 50.0,
549            cd_delta2: 7.5,
550            use_bc_segments: false,
551            bc_segments: None,
552            bc_segments_data: None,
553            use_enhanced_spin_drift: false,
554            use_form_factor: false,
555            enable_wind_shear: false,
556            wind_shear_model: "none".to_string(),
557            enable_trajectory_sampling: false,
558            sample_interval: 10.0, // Default 10 meter intervals
559            drops_reference: DropsReference::Los, // historical LOS-perpendicular drops
560            enable_pitch_damping: false,
561            enable_precession_nutation: false,
562            enable_aerodynamic_jump: false,
563            use_cluster_bc: false, // Disabled by default for backward compatibility
564
565            // Custom drag model support
566            custom_drag_table: None,
567            cd_scale: 1.0,
568
569            // Legacy field for compatibility
570            bc_type_str: None,
571        }
572    }
573}
574
575/// Interpolate a muzzle velocity (m/s) from a measured powder-temperature curve at
576/// `temp_c` (Celsius). `curve` is `(temperature_celsius, velocity_m_s)` points; it is
577/// sorted ascending by temperature before use. Values below the first point or above
578/// the last are CLAMPED to the endpoint velocity (no extrapolation beyond measured
579/// data), and segments are linearly interpolated. A single point yields a constant.
580pub fn interpolate_powder_temp_curve(curve: &[(f64, f64)], temp_c: f64) -> f64 {
581    debug_assert!(!curve.is_empty());
582    if curve.is_empty() {
583        return 0.0;
584    }
585    // Defensive: accept unsorted input by sorting a local copy only when needed.
586    // Callers (CLI/WASM parsers) already sort, so the common path is a no-op scan.
587    let mut sorted;
588    let pts: &[(f64, f64)] = if curve.windows(2).all(|w| w[0].0 <= w[1].0) {
589        curve
590    } else {
591        sorted = curve.to_vec();
592        sorted.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
593        &sorted
594    };
595    let n = pts.len();
596    if temp_c <= pts[0].0 {
597        return pts[0].1; // clamp below the coldest measured point
598    }
599    if temp_c >= pts[n - 1].0 {
600        return pts[n - 1].1; // clamp above the hottest measured point
601    }
602    for i in 1..n {
603        let (t0, v0) = pts[i - 1];
604        let (t1, v1) = pts[i];
605        if temp_c <= t1 {
606            let span = t1 - t0;
607            if span.abs() < f64::EPSILON {
608                return v1; // coincident temps: avoid divide-by-zero, take the upper
609            }
610            let f = (temp_c - t0) / span;
611            return v0 + f * (v1 - v0);
612        }
613    }
614    pts[n - 1].1
615}
616
617/// Parse a `--sweep START:END:STEP` temperature range (display units) for the
618/// `powder` command — ONE parser shared by the native CLI and WASM so their
619/// validation cannot drift. Returns the
620/// inclusive row temperatures. Guarded: STEP must be positive, END >= START, and the
621/// row count is capped so a typo can't emit an unbounded table.
622pub fn parse_powder_sweep(s: &str) -> Result<Vec<f64>, String> {
623    const MAX_SWEEP_ROWS: usize = 500;
624    let parts: Vec<&str> = s.split(':').collect();
625    if parts.len() != 3 {
626        return Err(format!(
627            "Invalid --sweep '{}': expected START:END:STEP (e.g. \"20:110:10\")",
628            s
629        ));
630    }
631    let parse = |p: &str, name: &str| -> Result<f64, String> {
632        p.trim()
633            .parse::<f64>()
634            .map_err(|_| format!("Invalid --sweep {}: '{}' is not a number", name, p.trim()))
635    };
636    let start = parse(parts[0], "START")?;
637    let end = parse(parts[1], "END")?;
638    let step = parse(parts[2], "STEP")?;
639    if !step.is_finite() || step <= 0.0 {
640        return Err(format!("Invalid --sweep STEP {}: must be positive", step));
641    }
642    if !start.is_finite() || !end.is_finite() || end < start {
643        return Err(format!(
644            "Invalid --sweep range {}:{}: END must be >= START",
645            start, end
646        ));
647    }
648    // Row count computed and bounds-checked in f64 BEFORE the usize cast: a huge
649    // range would saturate the cast and overflow the `+ 1` (panic under
650    // overflow-checks, wrap-to-zero in release — silently bypassing this cap).
651    // The epsilon keeps a fractional STEP whose quotient lands a hair below an
652    // integer (e.g. 0:0.3:0.1 -> 2.9999999999999996) from dropping the END row.
653    let n_f = ((end - start) / step + 1e-9).floor();
654    if !n_f.is_finite() || n_f + 1.0 > MAX_SWEEP_ROWS as f64 {
655        return Err(format!(
656            "--sweep would produce more than {} rows; use a larger STEP",
657            MAX_SWEEP_ROWS
658        ));
659    }
660    let n = n_f as usize + 1;
661    // Index-multiplied (not accumulated) so float drift can't drop the END row.
662    Ok((0..n).map(|i| start + step * i as f64).collect())
663}
664
665/// Resolve the powder-temperature-adjusted muzzle velocity (m/s) — the velocity the
666/// solver actually flies. A non-empty measured `powder_temp_curve` takes precedence
667/// (interpolated at `powder_curve_temp_c`, falling back to the ambient
668/// `ambient_temperature_c`; clamped at the endpoints) and REPLACES the nominal
669/// velocity; otherwise, when `use_powder_sensitivity` is set, the linear model adds
670/// `sensitivity x (ambient - reference)` to it. All inputs canonical SI (Celsius,
671/// m/s). This is the single shared implementation behind the trajectory solve, the
672/// `powder` CLI/WASM command (MBA-737), and anything else that must agree with them.
673pub fn resolve_powder_adjusted_velocity(
674    nominal_velocity_mps: f64,
675    ambient_temperature_c: f64,
676    use_powder_sensitivity: bool,
677    powder_temp_sensitivity_mps_per_c: f64,
678    powder_reference_temp_c: f64,
679    powder_temp_curve: Option<&[(f64, f64)]>,
680    powder_curve_temp_c: Option<f64>,
681) -> f64 {
682    if let Some(curve) = powder_temp_curve {
683        if !curve.is_empty() {
684            let lookup_c = powder_curve_temp_c.unwrap_or(ambient_temperature_c);
685            return interpolate_powder_temp_curve(curve, lookup_c);
686        }
687        // A supplied-but-empty curve has always suppressed the linear fallback
688        // (the historical `else if`); preserve that exactly.
689        return nominal_velocity_mps;
690    }
691    if use_powder_sensitivity {
692        let temp_delta_c = ambient_temperature_c - powder_reference_temp_c;
693        return nominal_velocity_mps + powder_temp_sensitivity_mps_per_c * temp_delta_c;
694    }
695    nominal_velocity_mps
696}
697
698// Wind conditions
699#[derive(Debug, Clone)]
700pub struct WindConditions {
701    pub speed: f64, // m/s
702    // radians, wind-FROM convention: 0 = headwind, PI/2 = from the right,
703    // PI = tailwind, 3*PI/2 = from the left (matches WindSock / the bindings).
704    pub direction: f64,
705    /// Vertical wind component, m/s. POSITIVE = UPDRAFT (raises POI downrange); negative =
706    /// downdraft. Default 0.0. Enters the wind vector via [`crate::wind::wind_vector`]'s third
707    /// argument (MBA-728). Boundary-layer shear scales horizontal wind only — vertical passes
708    /// through unscaled wherever shear is applied on top of this. This scalar field (like
709    /// [`WindConditions::speed`]/[`WindConditions::direction`]) is ignored once downrange wind
710    /// segments are set on the solver — each [`crate::wind::WindSegment`] carries its own
711    /// `vertical_mps` instead.
712    pub vertical_speed: f64,
713}
714
715impl Default for WindConditions {
716    fn default() -> Self {
717        Self {
718            speed: 0.0,
719            direction: 0.0,
720            vertical_speed: 0.0,
721        }
722    }
723}
724
725// Atmospheric conditions
726#[derive(Debug, Clone)]
727pub struct AtmosphericConditions {
728    pub temperature: f64, // Celsius
729    pub pressure: f64,    // hPa
730    /// Relative humidity as a PERCENT in `[0, 100]`. NOTE: [`BallisticInputs::humidity`]
731    /// uses a 0–1 FRACTION instead — convert with `BallisticInputs::humidity_percent` when
732    /// crossing between them (MBA-722).
733    pub humidity: f64,
734    pub altitude: f64, // meters
735}
736
737impl Default for AtmosphericConditions {
738    fn default() -> Self {
739        Self {
740            temperature: 15.0,
741            pressure: 1013.25,
742            humidity: 50.0,
743            altitude: 0.0,
744        }
745    }
746}
747
748// Trajectory point data
749#[derive(Debug, Clone)]
750pub struct TrajectoryPoint {
751    pub time: f64,
752    pub position: Vector3<f64>,
753    pub velocity_magnitude: f64,
754    pub kinetic_energy: f64,
755    /// The projectile's own drag coefficient at this point (MBA-1423).
756    ///
757    /// Filled in one pass after integration finishes, not at the sites that build this struct,
758    /// so a solver family added later cannot silently omit it. `None` when sectional density is
759    /// unavailable — see [`TrajectorySolver::effective_drag_coefficient`] for the definition and
760    /// why this is the projectile's Cd rather than the reference table's.
761    pub drag_coefficient: Option<f64>,
762}
763
764impl TrajectoryPoint {
765    /// The value `--with-drag-coefficient` emits for this point, or `None` when the JSON key
766    /// must be ABSENT — flag off, or sectional density unknown (MBA-1427).
767    ///
768    /// Host-compilable on purpose. The browser terminal's emit site lives in `src/wasm.rs`,
769    /// which is `cfg(target_arch = "wasm32")`-gated out of every native build — CI never
770    /// executes a line of it. Keeping the gating rule here means a native test can pin the
771    /// absent-not-null contract even though the surface that applies it only compiles for wasm.
772    pub fn drag_coefficient_json_value(&self, with_drag_coefficient: bool) -> Option<f64> {
773        if with_drag_coefficient {
774            self.drag_coefficient
775        } else {
776            None
777        }
778    }
779}
780
781// Trajectory result
782#[derive(Debug, Clone)]
783pub struct TrajectoryResult {
784    pub max_range: f64,
785    pub max_height: f64,
786    pub time_of_flight: f64,
787    pub impact_velocity: f64,
788    pub impact_energy: f64,
789    /// Projectile mass used to derive full-state observation energy.
790    pub projectile_mass_kg: f64,
791    /// Height of the horizontal line of sight in the solver's ground-referenced frame.
792    pub line_of_sight_height_m: f64,
793    /// Station speed of sound used for Mach observations and transition flags.
794    pub station_speed_of_sound_mps: f64,
795    /// Explicit reason the integration stopped; consumers must not infer this from the endpoint.
796    pub termination: TrajectoryTermination,
797    pub points: Vec<TrajectoryPoint>,
798    pub sampled_points: Option<Vec<TrajectorySample>>, // Trajectory samples at regular intervals
799    pub min_pitch_damping: Option<f64>, // Minimum pitch damping coefficient (for stability warning)
800    pub transonic_mach: Option<f64>,    // Mach number when entering transonic regime
801    pub angular_state: Option<AngularState>, // Final angular state if precession/nutation enabled
802    pub max_yaw_angle: Option<f64>,     // Maximum yaw angle during flight (radians)
803    pub max_precession_angle: Option<f64>, // Maximum precession angle (radians)
804    // MBA-959: aerodynamic-jump components applied at the muzzle (None unless
805    // enable_aerodynamic_jump). EXPERIMENTAL.
806    pub aerodynamic_jump: Option<crate::aerodynamic_jump::AerodynamicJumpComponents>,
807    /// Downrange distance (m) of the downward Mach 1.2 crossing (station speed of sound),
808    /// populated identically by all three solver paths (Euler/RK4/RK45). `None` if the
809    /// trajectory never crosses 1.2 while descending (e.g. launched already below 1.2, or the
810    /// solve terminates while still above it). MBA-1405: feeds `mv_calibration_window`.
811    pub mach_1_2_distance_m: Option<f64>,
812    /// Downrange distance (m) of the downward Mach 1.0 crossing. `None` if the trajectory
813    /// never goes subsonic within the solve. MBA-1405: the far edge of the MV calibration
814    /// window (`mv_calibration_window`) is this distance.
815    pub mach_1_0_distance_m: Option<f64>,
816    /// Downrange distance (m) of the downward Mach 0.9 crossing. `None` if the trajectory
817    /// never crosses 0.9 while descending. MBA-1405: feeds `dsf_window_start`. NOTE: unlike
818    /// the 1.2/1.0 crossings, this one is intentionally NOT reflected in the historical flat
819    /// `transonic_distances` Vec threaded through
820    /// [`crate::trajectory_sampling::TrajectoryData`] — existing consumers of that Vec
821    /// interpret it strictly as `{1.2, 1.0}`, so this field is the only place the 0.9
822    /// crossing is recorded.
823    pub mach_0_9_distance_m: Option<f64>,
824}
825
826const RK45_TOLERANCE: f64 = 1e-6;
827const RK45_SAFETY_FACTOR: f64 = 0.9;
828const RK45_MAX_DT: f64 = 0.01;
829const RK45_MIN_DT: f64 = 1e-6;
830const TRAJECTORY_TIME_LIMIT_S: f64 = 100.0;
831
832/// Hard ceiling for points retained by a single [`TrajectorySolver`] result.
833///
834/// The cap applies across Euler, fixed RK4, and adaptive RK45, including the exact terminal
835/// endpoint. Solves that would exceed it return [`BallisticsError`] instead of
836/// truncating or growing their point buffer without bound.
837pub const MAX_TRAJECTORY_POINTS: usize = 250_000;
838
839/// Pack the CLI solver's split position/velocity vectors into the shared six-component RK45 norm.
840fn cli_rk45_error_norm(
841    position: &Vector3<f64>,
842    velocity: &Vector3<f64>,
843    fifth_position: &Vector3<f64>,
844    fifth_velocity: &Vector3<f64>,
845    fourth_position: &Vector3<f64>,
846    fourth_velocity: &Vector3<f64>,
847) -> f64 {
848    let pack_state = |position: &Vector3<f64>, velocity: &Vector3<f64>| {
849        Vector6::new(
850            position.x, position.y, position.z, velocity.x, velocity.y, velocity.z,
851        )
852    };
853    let state = pack_state(position, velocity);
854    let fifth_order = pack_state(fifth_position, fifth_velocity);
855    let fourth_order = pack_state(fourth_position, fourth_velocity);
856
857    crate::trajectory_integration::rk45_error_norm(&state, &fifth_order, &fourth_order)
858}
859
860struct Rk45Trial {
861    position: Vector3<f64>,
862    velocity: Vector3<f64>,
863    suggested_dt: f64,
864    error: f64,
865}
866
867struct Rk45AcceptedStep {
868    position: Vector3<f64>,
869    velocity: Vector3<f64>,
870    used_dt: f64,
871    next_dt: f64,
872    error: f64,
873}
874
875/// Tracks the downward (decelerating) Mach crossings of a solved trajectory.
876///
877/// `record_downward_crossings` is called once per integration step from all three solver
878/// paths (Euler/RK4/RK45). It both (a) appends to the historical flat `distances` Vec — used
879/// unchanged by [`crate::trajectory_sampling`] to flag sampled points — and (b) records each
880/// threshold's exact crossing distance on `self`, for callers that want the labeled value
881/// directly (MBA-1405) rather than positionally decoding the flat Vec.
882///
883/// IMPORTANT: only the historical 1.2/1.0 thresholds are appended to `distances`. The 0.9
884/// threshold added for MBA-1405 is recorded ONLY on `self.mach_0_9_distance_m` — existing
885/// consumers of the flat Vec interpret it strictly as `{mach_1_2, mach_1_0}` (in that order,
886/// when present), so appending a third entry would silently corrupt their positional
887/// assumptions.
888#[derive(Default)]
889struct MachTransitionTracker {
890    previous_mach: Option<f64>,
891    crossed_transonic: bool,
892    crossed_subsonic: bool,
893    crossed_narrow: bool,
894    /// Downrange distance (m) of the downward Mach 1.2 crossing, once seen. Mirrors the first
895    /// flat-Vec entry.
896    mach_1_2_distance_m: Option<f64>,
897    /// Downrange distance (m) of the downward Mach 1.0 crossing, once seen. Mirrors the second
898    /// flat-Vec entry.
899    mach_1_0_distance_m: Option<f64>,
900    /// Downrange distance (m) of the downward Mach 0.9 crossing, once seen. NOT reflected in
901    /// the flat Vec (see struct docs).
902    mach_0_9_distance_m: Option<f64>,
903}
904
905impl MachTransitionTracker {
906    fn record_downward_crossings(&mut self, mach: f64, downrange_m: f64, distances: &mut Vec<f64>) {
907        if !mach.is_finite() {
908            self.previous_mach = None;
909            return;
910        }
911
912        if let Some(previous_mach) = self.previous_mach {
913            if !self.crossed_transonic && previous_mach >= 1.2 && mach < 1.2 {
914                self.crossed_transonic = true;
915                distances.push(downrange_m);
916                self.mach_1_2_distance_m = Some(downrange_m);
917            }
918            if !self.crossed_subsonic && previous_mach >= 1.0 && mach < 1.0 {
919                self.crossed_subsonic = true;
920                distances.push(downrange_m);
921                self.mach_1_0_distance_m = Some(downrange_m);
922            }
923            if !self.crossed_narrow && previous_mach >= 0.9 && mach < 0.9 {
924                self.crossed_narrow = true;
925                // Intentionally NOT pushed to `distances` — see struct docs.
926                self.mach_0_9_distance_m = Some(downrange_m);
927            }
928        }
929        self.previous_mach = Some(mach);
930    }
931}
932
933impl TrajectoryResult {
934    /// Interpolate position at a given downrange distance (X coordinate, McCoy).
935    /// Returns the interpolated (x, y, z) position at that range.
936    /// If the target range exceeds the trajectory, returns the last point.
937    pub fn position_at_range(&self, target_range: f64) -> Option<Vector3<f64>> {
938        if self.points.is_empty() {
939            return None;
940        }
941
942        // Find the two points that bracket the target range
943        for i in 0..self.points.len() - 1 {
944            let p1 = &self.points[i];
945            let p2 = &self.points[i + 1];
946
947            // Check if target range is between these two points (X is downrange)
948            if p1.position.x <= target_range && p2.position.x >= target_range {
949                // Linear interpolation factor
950                let dx = p2.position.x - p1.position.x;
951                if dx.abs() < 1e-10 {
952                    return Some(p1.position);
953                }
954                let t = (target_range - p1.position.x) / dx;
955
956                // Interpolate Y and Z, use exact target_range for X
957                return Some(Vector3::new(
958                    target_range,
959                    p1.position.y + t * (p2.position.y - p1.position.y),
960                    p1.position.z + t * (p2.position.z - p1.position.z),
961                ));
962            }
963        }
964
965        // Target range is beyond trajectory - return last point
966        self.points.last().map(|p| p.position)
967    }
968}
969
970// Trajectory solver
971#[derive(Debug, Clone, Copy, PartialEq, Eq)]
972enum StationAtmosphereResolution {
973    /// Preserve the historical CLI/FFI convention: sea-level standard values at a nonzero
974    /// altitude are treated as omitted and resolved from the ICAO atmosphere.
975    LegacyDefaultSentinels,
976    /// Temperature and pressure have already been resolved by a presence-aware caller and must
977    /// remain authoritative even when they equal the historical sentinel values.
978    Authoritative,
979}
980
981#[derive(Clone)]
982pub struct TrajectorySolver {
983    inputs: BallisticInputs,
984    wind: WindConditions,
985    atmosphere: AtmosphericConditions,
986    station_atmosphere_resolution: StationAtmosphereResolution,
987    max_range: f64,
988    time_step: f64,
989    max_trajectory_points: usize,
990    cluster_bc: Option<ClusterBCDegradation>,
991    /// Geometry-derived `(longitudinal, transverse)` moments used by angular diagnostics.
992    precession_nutation_inertias: (f64, f64),
993    /// Optional downrange-segmented wind. When `Some`, the per-step wind vector is
994    /// looked up by downrange distance from this `WindSock` and the scalar `wind`
995    /// field is ignored. When `None`, the constant `wind` vector is used (default),
996    /// so a non-segmented solve is numerically identical to pre-feature behavior.
997    wind_sock: Option<crate::wind::WindSock>,
998    /// Optional downrange-segmented atmosphere (MBA-1137). When `Some`, the per-substep local
999    /// atmosphere recompute samples the base (station-referenced) temperature/pressure/humidity by
1000    /// downrange distance from this `AtmoSock`, then feeds them through the SAME altitude-lapse
1001    /// pipeline as a single-station solve — so the downrange zone and the vertical altitude lapse
1002    /// compose without double-counting. When `None` (default), the resolved single-station
1003    /// conditions are used.
1004    atmo_sock: Option<crate::atmosphere::AtmoSock>,
1005}
1006
1007/// Which frame a zero solve's `target_height_m` lives in (MBA-1412).
1008///
1009/// `SightLine`: the classic zero contract — the height is sight geometry (typically the sight
1010/// height) and the rifle zeroes LEVEL, per the MBA-1286 doctrine that a zero is a property of a
1011/// level rifle; `shooting_angle` applies to the subsequent shot only. Used by
1012/// `calculate_zero_angle_with_conditions` and every legacy surface behind it (bindings, WASM,
1013/// FFI, CLI).
1014///
1015/// `WorldVertical`: solve-json v1's documented contract (docs/SOLVE_JSON_V1.md) — the height is
1016/// an absolute world-vertical height above the ground datum; inclined zeroing projects the
1017/// shot-frame trajectory into the world frame (MBA-1302 behavior, unchanged).
1018#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1019pub(crate) enum ZeroTargetFrame {
1020    SightLine,
1021    WorldVertical,
1022}
1023
1024/// Both line-of-sight crossings a single fixed bore angle can produce (Tier 2 whole-branch
1025/// review, C2): a rifle whose sight sits above its bore generally crosses a level line of
1026/// sight TWICE on a rising shot — an ascending "near zero" close to the muzzle, and a
1027/// descending "far zero" past the apex. The classic 25/300-yard battle-zero pairing is one
1028/// bore angle producing both. `TrajectorySolver`'s internal `find_zero_range` and the public
1029/// `calculate_zero_range_from_angle_*` functions return both rather than silently choosing
1030/// one, because `find_zero_angle`'s own choice of root depends on the target distance it was
1031/// asked to solve for — the forward and inverse solvers are NOT a single-valued pair.
1032///
1033/// Either field may be `None` when the solved envelope doesn't reach that crossing (e.g. a
1034/// short `--max-range` that stops before the far crossing, or a target height high enough
1035/// that the trajectory never rises to it at all). At least one is always `Some` on `Ok`.
1036#[derive(Debug, Clone, Copy, PartialEq)]
1037pub struct ZeroCrossings {
1038    /// Downrange distance (meters) of the near, ascending crossing, if the solved envelope
1039    /// reaches it.
1040    pub near_m: Option<f64>,
1041    /// Downrange distance (meters) of the far, descending crossing -- what "sighted in at D
1042    /// yards" conventionally means -- if the solved envelope reaches it.
1043    pub far_m: Option<f64>,
1044}
1045
1046impl TrajectorySolver {
1047    pub fn new(
1048        inputs: BallisticInputs,
1049        wind: WindConditions,
1050        atmosphere: AtmosphericConditions,
1051    ) -> Self {
1052        Self::new_with_station_atmosphere_resolution(
1053            inputs,
1054            wind,
1055            atmosphere,
1056            StationAtmosphereResolution::LegacyDefaultSentinels,
1057        )
1058    }
1059
1060    /// Construct a solver from station temperature and pressure that a presence-aware service
1061    /// has already resolved. Unlike [`Self::new`], exact sea-level standard values remain
1062    /// authoritative at nonzero altitude rather than acting as legacy omission sentinels.
1063    ///
1064    /// `pub` (MBA-1397; was `pub(crate)`): a QNH-aware caller (native CLI, WASM) that has
1065    /// already reduced a declared altimeter setting to station pressure via
1066    /// [`crate::atmosphere::resolve_station_conditions_with_pressure_mode`] needs this
1067    /// constructor too, and those callers live in a different crate (`src/main.rs` is a
1068    /// separate binary crate over the library). Widening visibility only, no signature
1069    /// change: every existing `pub(crate)` caller is unaffected.
1070    pub fn new_with_resolved_station_atmosphere(
1071        inputs: BallisticInputs,
1072        wind: WindConditions,
1073        atmosphere: AtmosphericConditions,
1074    ) -> Self {
1075        Self::new_with_station_atmosphere_resolution(
1076            inputs,
1077            wind,
1078            atmosphere,
1079            StationAtmosphereResolution::Authoritative,
1080        )
1081    }
1082
1083    fn new_with_station_atmosphere_resolution(
1084        mut inputs: BallisticInputs,
1085        wind: WindConditions,
1086        atmosphere: AtmosphericConditions,
1087        station_atmosphere_resolution: StationAtmosphereResolution,
1088    ) -> Self {
1089        // MBA-1415: every input-conditioning step lives in one shared, idempotent helper that
1090        // the fast_integrate* entry points call too. Keeping it out of this constructor is the
1091        // point: conditioning that lives only here is invisible to the external bindings that
1092        // call the fast path directly.
1093        inputs.normalize_for_solve();
1094
1095        // Initialize cluster BC if enabled
1096        let cluster_bc = if inputs.use_cluster_bc {
1097            Some(ClusterBCDegradation::new())
1098        } else {
1099            None
1100        };
1101        let precession_nutation_inertias = projectile_moments_of_inertia(
1102            inputs.bullet_mass,
1103            inputs.bullet_diameter,
1104            inputs.bullet_length,
1105        );
1106
1107        Self {
1108            inputs,
1109            wind,
1110            atmosphere,
1111            station_atmosphere_resolution,
1112            max_range: 1000.0,
1113            time_step: 0.001,
1114            max_trajectory_points: MAX_TRAJECTORY_POINTS,
1115            cluster_bc,
1116            precession_nutation_inertias,
1117            wind_sock: None,
1118            atmo_sock: None,
1119        }
1120    }
1121
1122    pub fn set_max_range(&mut self, range: f64) {
1123        self.max_range = range;
1124    }
1125
1126    pub fn set_time_step(&mut self, step: f64) {
1127        self.time_step = step;
1128    }
1129
1130    /// Calculate a level-rifle zero with this solver's configured atmosphere, wind (including
1131    /// downrange segments), effects, integration method, and time step, then install the resulting
1132    /// muzzle angle on this solver. The solver is mutated only after a zero has converged.
1133    pub(crate) fn calculate_and_set_zero_angle(
1134        &mut self,
1135        target_distance_m: f64,
1136        target_height_m: f64,
1137        frame: ZeroTargetFrame,
1138    ) -> Result<f64, BallisticsError> {
1139        let angle = self.find_zero_angle(target_distance_m, target_height_m, frame)?;
1140        // MBA-1359: a deliberate POI offset at the zero range (Kestrel ZH/ZO) is an angular
1141        // bias ON the solved angle, applied post-solve so the zero trials above still solve
1142        // perfect convergence. The small-angle addition is frame-independent (identical in
1143        // SightLine and WorldVertical), and with both offsets at their 0.0 defaults the
1144        // additions below are exact no-ops (byte-identical). The returned angle carries the
1145        // vertical bias so auto-zero callers that copy it onto flight inputs inherit it; the
1146        // horizontal bias lands on THIS solver's azimuth_angle — separate flight inputs must
1147        // add `windage_zero_bias_rad` themselves.
1148        let angle = if target_distance_m > 0.0 {
1149            angle + self.inputs.zero_poi_vertical_m / target_distance_m
1150        } else {
1151            angle
1152        };
1153        self.inputs.muzzle_angle = angle;
1154        self.apply_windage_zero_bias(target_distance_m);
1155        Ok(angle)
1156    }
1157
1158    /// Apply just the windage-zero convergence bias (see
1159    /// [`BallisticInputs::windage_zero_bias_rad`]) to this solver's azimuth, for a zero at
1160    /// `target_distance_m`, without searching for or installing an elevation.
1161    ///
1162    /// Used by [`Self::calculate_and_set_zero_angle`] above as part of a full zero search, and
1163    /// by solve_v1's round-trip re-solve path (0.33.0 decision-support Task 2) on its own: when
1164    /// an explicit `muzzle_angle_rad` already carries the correct elevation (round-tripped from
1165    /// a previous `resolved_request`, which bakes any `zero_poi_vertical_m` bias into that
1166    /// angle already), the elevation search does not run, but the windage term is a SEPARATE
1167    /// quantity that depends only on `zero_distance_m` -- not on whether the elevation was
1168    /// searched for or supplied directly -- so it must still be applied here or an
1169    /// offset-mounted sight / deliberate horizontal zero bias would silently stop converging
1170    /// once a request round-trips.
1171    pub(crate) fn apply_windage_zero_bias(&mut self, target_distance_m: f64) {
1172        self.inputs.azimuth_angle += self.inputs.windage_zero_bias_rad(target_distance_m);
1173    }
1174
1175    fn find_zero_angle(
1176        &self,
1177        target_distance_m: f64,
1178        target_height_m: f64,
1179        frame: ZeroTargetFrame,
1180    ) -> Result<f64, BallisticsError> {
1181        // Binary search for the angle that hits the target. Use only positive angles to ensure a
1182        // proper upward ballistic arc.
1183        let mut low_angle = 0.0;
1184        let mut high_angle = 0.2; // about 11 degrees
1185        let tolerance = 1e-7;
1186        let max_iterations = 60;
1187
1188        // MBA-194: validate the initial bracket before starting the binary search.
1189        let low_height = self.zero_trial_height_at(low_angle, target_distance_m, frame)?;
1190        let high_height = self.zero_trial_height_at(high_angle, target_distance_m, frame)?;
1191
1192        match (low_height, high_height) {
1193            (Some(low_height), Some(high_height)) => {
1194                let low_error = low_height - target_height_m;
1195                let high_error = high_height - target_height_m;
1196
1197                if low_error > 0.0 && high_error > 0.0 {
1198                    // Both angles overshoot. Zero degrees is the lowest supported launch angle;
1199                    // retain the historical behavior and let the search choose its best result.
1200                } else if low_error < 0.0 && high_error < 0.0 {
1201                    // Both angles undershoot. Preserve the historical expansion up to 45 degrees.
1202                    let mut expanded = false;
1203                    for multiplier in [2.0, 3.0, 4.0] {
1204                        let new_high = (high_angle * multiplier).min(0.785);
1205                        if let Ok(Some(height)) =
1206                            self.zero_trial_height_at(new_high, target_distance_m, frame)
1207                        {
1208                            if height - target_height_m > 0.0 {
1209                                high_angle = new_high;
1210                                expanded = true;
1211                                break;
1212                            }
1213                        }
1214                        if new_high >= 0.785 {
1215                            break;
1216                        }
1217                    }
1218                    if !expanded {
1219                        return Err("Cannot find zero angle: target beyond effective range even at maximum angle".into());
1220                    }
1221                }
1222            }
1223            (None, Some(_)) => {
1224                // The low angle does not reach the target while the high angle does; the search
1225                // will raise the low end until it reaches a valid trajectory.
1226            }
1227            (Some(_), None) => {
1228                return Err(
1229                    "Cannot find zero angle: high angle trajectory doesn't reach target distance"
1230                        .into(),
1231                );
1232            }
1233            (None, None) => {
1234                return Err(
1235                    "Cannot find zero angle: trajectory cannot reach target distance at any angle"
1236                        .into(),
1237                );
1238            }
1239        }
1240
1241        for _ in 0..max_iterations {
1242            let mid_angle = (low_angle + high_angle) / 2.0;
1243            match self.zero_trial_height_at(mid_angle, target_distance_m, frame)? {
1244                Some(height) => {
1245                    let error = height - target_height_m;
1246                    // MBA-193: height accuracy is the primary convergence criterion. At 0.1 mm,
1247                    // short-range zero-day atmosphere differences remain observable.
1248                    if error.abs() < 0.0001 {
1249                        return Ok(mid_angle);
1250                    }
1251
1252                    // Only use angle tolerance after precision is exhausted and the remaining
1253                    // height error is still practically acceptable.
1254                    if (high_angle - low_angle).abs() < tolerance {
1255                        if error.abs() < 0.01 {
1256                            return Ok(mid_angle);
1257                        }
1258                        return Err("Zero angle did not converge: residual height error too large (target not reachable / not bracketed)".into());
1259                    }
1260
1261                    if error > 0.0 {
1262                        high_angle = mid_angle;
1263                    } else {
1264                        low_angle = mid_angle;
1265                    }
1266                }
1267                None => {
1268                    low_angle = mid_angle;
1269                    if (high_angle - low_angle).abs() < tolerance {
1270                        return Err("Trajectory cannot reach target distance - angle converged without valid solution".into());
1271                    }
1272                }
1273            }
1274        }
1275
1276        Err("Failed to find zero angle".into())
1277    }
1278
1279    /// Solve one zero-angle trial without losing any solver configuration. Only the trial clone's
1280    /// launch angle, level-rifle convention, and integration range differ from the final solve.
1281    fn zero_trial_height_at(
1282        &self,
1283        angle_rad: f64,
1284        target_distance_m: f64,
1285        frame: ZeroTargetFrame,
1286    ) -> Result<Option<f64>, BallisticsError> {
1287        let mut trial = self.clone();
1288        trial.inputs.muzzle_angle = angle_rad;
1289        // MBA-959: zero on the bare bore so aerodynamic jump remains an additive fire-time POI
1290        // shift rather than being silently absorbed by the zero search.
1291        trial.inputs.enable_aerodynamic_jump = false;
1292        // MBA-1286: a zero is a property of a level rifle's sight geometry. Cant is applied only
1293        // to the subsequent shot.
1294        trial.inputs.cant_angle = 0.0;
1295        // MBA-1412: in the SightLine contract the incline is likewise a shot-time condition,
1296        // not sight geometry. MBA-1302 left it in the trial while shot_frame_altitude lifted
1297        // heights into the gravity frame, adding d*sin(shooting_angle) (~9 m at 5.71 deg /
1298        // 100 yd) against a sight-frame target height, so no inclined legacy caller could
1299        // bracket. Zero level; shoot inclined. solve-json v1's WorldVertical contract keeps
1300        // the MBA-1302 projection (its callers supply world-frame heights).
1301        if frame == ZeroTargetFrame::SightLine {
1302            trial.inputs.shooting_angle = 0.0;
1303        }
1304        trial.set_max_range(target_distance_m * 2.0);
1305        let result = trial.solve()?;
1306
1307        for (index, point) in result.points.iter().enumerate() {
1308            if point.position.x >= target_distance_m {
1309                let shot_y_m = if index == 0 {
1310                    point.position.y
1311                } else {
1312                    let previous = &result.points[index - 1];
1313                    let span = point.position.x - previous.position.x;
1314                    let fraction = (target_distance_m - previous.position.x) / span;
1315                    previous.position.y + fraction * (point.position.y - previous.position.y)
1316                };
1317                return Ok(Some(crate::atmosphere::shot_frame_altitude(
1318                    0.0,
1319                    target_distance_m,
1320                    shot_y_m,
1321                    trial.inputs.shooting_angle,
1322                )));
1323            }
1324        }
1325        Ok(None)
1326    }
1327
1328    /// Inverse of [`Self::find_zero_angle`] (MBA-1402), corrected by the Tier 2 whole-branch
1329    /// review (C2): given a FIXED bore angle rather than searching for one, run that
1330    /// trajectory and locate the downrange distance(s) where it crosses `target_height_m` —
1331    /// the zero RANGE(S) a stored/portable bore angle implies under THESE conditions. Hornady
1332    /// and Kestrel 4DOF treat the zero angle as the portable quantity (captured once, then
1333    /// reusable independent of the day it was solved); this is what makes that value usable
1334    /// again.
1335    ///
1336    /// A rifle whose sight sits above the bore generally crosses a level line of sight TWICE
1337    /// on a rising shot: once ascending, close to the muzzle (the "near zero"), and once
1338    /// descending past the apex (the "far zero"). Both are equally real zero ranges for the
1339    /// SAME bore angle — this is the classic 25/300-yard battle-zero relationship: a rifle
1340    /// zeroed at 25 yd (the near crossing of its bore angle) is, for the same angle, ALSO
1341    /// zeroed again around 300 yd (the far crossing). [`Self::find_zero_angle`]'s own choice
1342    /// of root depends on which target distance it was asked to solve for, so this is not a
1343    /// single-valued inverse of that function — it is this function's job to report both
1344    /// roots it can find rather than silently pick one and call it "the" zero range.
1345    ///
1346    /// Returns [`ZeroCrossings`] with the near (first ascending, error negative → positive)
1347    /// and far (descending, error positive → negative) crossings independently, either of
1348    /// which may be absent if the solved envelope doesn't reach it (e.g. `--max-range` too
1349    /// short to reach the far crossing, or an angle so shallow / a target height so high that
1350    /// the near crossing never happens). Errors only when NEITHER crossing is found. Each
1351    /// crossing distance is linearly interpolated between its two bracketing sample points,
1352    /// mirroring `zero_trial_height_at`'s own height-at-a-known-distance interpolation in the
1353    /// other direction.
1354    fn find_zero_range(
1355        &self,
1356        angle_rad: f64,
1357        target_height_m: f64,
1358        frame: ZeroTargetFrame,
1359    ) -> Result<ZeroCrossings, BallisticsError> {
1360        let mut trial = self.clone();
1361        trial.inputs.muzzle_angle = angle_rad;
1362        // Mirrors zero_trial_height_at's trial setup exactly (MBA-959 / MBA-1286 / MBA-1412),
1363        // so both directions apply the same conventions.
1364        trial.inputs.enable_aerodynamic_jump = false;
1365        trial.inputs.cant_angle = 0.0;
1366        if frame == ZeroTargetFrame::SightLine {
1367            trial.inputs.shooting_angle = 0.0;
1368        }
1369        let result = trial.solve()?;
1370
1371        // The height-above-target-height error is, for a normal flat-fire trajectory,
1372        // unimodal: it starts below the line of sight (bore below sight), rises through it
1373        // ONCE (ascending -- the near zero), continues to the apex, then falls back through
1374        // it ONCE more (descending -- the far zero) before diverging away for good. So at
1375        // most one ascending and one descending crossing exist; classify each sign change by
1376        // direction rather than by position (first/last) so a near-only trajectory (solved
1377        // range too short to reach the far crossing) is never mislabeled as "far".
1378        let mut near_crossing: Option<f64> = None;
1379        let mut far_crossing: Option<f64> = None;
1380        let mut previous: Option<(f64, f64)> = None; // (downrange_m, height_error_m)
1381        for point in &result.points {
1382            let height = crate::atmosphere::shot_frame_altitude(
1383                0.0,
1384                point.position.x,
1385                point.position.y,
1386                trial.inputs.shooting_angle,
1387            );
1388            let error = height - target_height_m;
1389            if let Some((prev_x, prev_error)) = previous {
1390                if prev_error == 0.0 {
1391                    // An exact touch is itself a crossing; assign it to whichever slot is
1392                    // still open (near first, since it can only occur before far).
1393                    if near_crossing.is_none() {
1394                        near_crossing = Some(prev_x);
1395                    } else {
1396                        far_crossing = Some(prev_x);
1397                    }
1398                }
1399                if prev_error * error < 0.0 {
1400                    let fraction = prev_error / (prev_error - error);
1401                    let crossing = prev_x + fraction * (point.position.x - prev_x);
1402                    if prev_error < 0.0 && error > 0.0 {
1403                        // Ascending: the near zero. Keep only the first one found.
1404                        if near_crossing.is_none() {
1405                            near_crossing = Some(crossing);
1406                        }
1407                    } else {
1408                        // Descending: the far zero.
1409                        far_crossing = Some(crossing);
1410                    }
1411                }
1412            }
1413            previous = Some((point.position.x, error));
1414        }
1415        // The loop above only resolves a point once a later point makes it `previous`; catch
1416        // the trajectory's very last sampled point landing exactly on the line too.
1417        if let Some((last_x, last_error)) = previous {
1418            if last_error == 0.0 {
1419                if near_crossing.is_none() {
1420                    near_crossing = Some(last_x);
1421                } else {
1422                    far_crossing = Some(last_x);
1423                }
1424            }
1425        }
1426
1427        if near_crossing.is_none() && far_crossing.is_none() {
1428            return Err(BallisticsError::from(
1429                "Cannot find zero range: this angle never crosses the target height within the \
1430                 solved range (angle too shallow to reach it, or both crossings lie beyond \
1431                 the solver's max range)."
1432                    .to_string(),
1433            ));
1434        }
1435
1436        Ok(ZeroCrossings {
1437            near_m: near_crossing,
1438            far_m: far_crossing,
1439        })
1440    }
1441
1442    /// Equivalent horizontal range for an inclined shot (MBA-1395): the flat-fire range
1443    /// whose ANGULAR elevation correction — relative to the SAME dialed zero — equals the
1444    /// inclined solution's angular correction at `target_range_m`. This is the
1445    /// "shoot-to" range SIG BDX (AMR), Leica (EHR), and Gunwerks BR2 report so users of
1446    /// fixed BDC turrets/reticles can dial as if the shot were flat, computed by an
1447    /// inverse lookup over one flat re-solve (McDonald's Sierra inclined-fire treatment /
1448    /// Litz) rather than the rifleman's-rule cosine approximation, which matches LINEAR
1449    /// drop and accumulates error at long range.
1450    ///
1451    /// The solver's current state IS the inclined solution: `muzzle_angle` carries the
1452    /// solved zero and `shooting_angle` the look angle. The flat reference clones the
1453    /// solver and zeroes only `shooting_angle` (the WASM auto-zero flat-clone precedent),
1454    /// keeping the zero, wind, atmosphere, and integration configuration identical, so
1455    /// both angular corrections are measured against the same zero.
1456    ///
1457    /// Returns `None` where the inverse is ill-defined instead of guessing:
1458    /// - `target_range_m <= zero_distance_m` (inside the zero, no BDC correction exists);
1459    /// - the inclined correction at the target is not positive (bullet at/above the LOS);
1460    /// - either solve fails, or the flat solve cannot bracket the correction.
1461    ///
1462    /// Past the zero range the flat correction is monotone in range, so a plain bisection
1463    /// over the flat solve's interpolated corrections converges; the answer is refined to
1464    /// centimeter level, far below any display precision.
1465    pub fn equivalent_horizontal_range(
1466        &self,
1467        target_range_m: f64,
1468        zero_distance_m: f64,
1469    ) -> Option<f64> {
1470        if !target_range_m.is_finite() || !zero_distance_m.is_finite() {
1471            return None;
1472        }
1473        if target_range_m <= zero_distance_m || target_range_m <= 0.0 {
1474            return None;
1475        }
1476
1477        // Height of the bullet path at a downrange distance, linearly interpolated
1478        // between integration points (mirrors zero_trial_height_at's interpolation).
1479        // In the shot frame the LOS is the x-axis, so drop below the LOS is
1480        // `los_height - y` for the inclined and flat solves alike.
1481        fn path_y_at(points: &[TrajectoryPoint], distance_m: f64) -> Option<f64> {
1482            match bracket_param(points.len(), |i| points[i].position.x, distance_m) {
1483                // Below the first point: clamp to it (mirrors zero_trial_height_at's
1484                // interpolation, which the doc comment above promises). Fewer than two points
1485                // is not a case a real solved trajectory reaches; treat it like Above (no
1486                // extrapolation) rather than guessing.
1487                Bracket::Below => Some(points[0].position.y),
1488                Bracket::Above | Bracket::Degenerate => None,
1489                Bracket::Inside { lo, t } => {
1490                    let hi = lo + 1;
1491                    Some(
1492                        points[lo].position.y
1493                            + t * (points[hi].position.y - points[lo].position.y),
1494                    )
1495                }
1496            }
1497        }
1498
1499        // Inclined solution's angular correction at the target (radians, small-angle:
1500        // drop below the LOS divided by range). Sampling is display-side only — turn it
1501        // off in both internal solves.
1502        let mut inclined = self.clone();
1503        inclined.inputs.enable_trajectory_sampling = false;
1504        let inclined_result = inclined.solve().ok()?;
1505        let los_height = inclined_result.line_of_sight_height_m;
1506        let inclined_drop = los_height - path_y_at(&inclined_result.points, target_range_m)?;
1507        let correction = inclined_drop / target_range_m;
1508        if correction <= 0.0 {
1509            return None;
1510        }
1511
1512        // One flat re-solve against the same zero.
1513        let mut flat = self.clone();
1514        flat.inputs.enable_trajectory_sampling = false;
1515        flat.inputs.shooting_angle = 0.0;
1516        let flat_result = flat.solve().ok()?;
1517        let flat_correction_at = |range_m: f64| -> Option<f64> {
1518            Some((los_height - path_y_at(&flat_result.points, range_m)?) / range_m)
1519        };
1520
1521        // Bracket, then bisect. Gravity's along-LOS component only shrinks under a look
1522        // angle, so the flat correction at the true range bounds the inclined one from
1523        // above and the equivalent range lies in (zero_distance, target_range]. The flat
1524        // clone can strike the ground SHORT of the inclined terminal (an uphill shot
1525        // stays airborne longer), so the upper bracket is additionally capped at the
1526        // flat solve's own terminal distance — the shoot-to range is shorter than the
1527        // true range, so the cap does not exclude the root.
1528        let flat_terminal_m = flat_result.points.last().map(|p| p.position.x)?;
1529        let mut low = zero_distance_m.max(1.0);
1530        let mut high = target_range_m.min(flat_terminal_m);
1531        if high <= low {
1532            return None;
1533        }
1534        if flat_correction_at(low)? - correction > 0.0 {
1535            return None; // no bracket below
1536        }
1537        if flat_correction_at(high)? - correction < 0.0 {
1538            return None; // no bracket above (correction not reachable flat)
1539        }
1540        for _ in 0..60 {
1541            let mid = 0.5 * (low + high);
1542            let error = flat_correction_at(mid)? - correction;
1543            if error.abs() == 0.0 {
1544                return Some(mid);
1545            }
1546            if error < 0.0 {
1547                low = mid;
1548            } else {
1549                high = mid;
1550            }
1551            if high - low < 0.01 {
1552                break;
1553            }
1554        }
1555        Some(0.5 * (low + high))
1556    }
1557
1558    /// Reject malformed state before it reaches an integration loop.
1559    ///
1560    /// `new` resolves powder-temperature velocity overrides and refreshes the imperial mirror
1561    /// fields, so validation belongs here: it sees the effective muzzle velocity, covers values
1562    /// changed through solver setters, and applies uniformly to Euler, RK4, and RK45.
1563    fn validate_for_solve(&self) -> Result<(), BallisticsError> {
1564        let require_finite = |name: &str, value: f64| {
1565            if value.is_finite() {
1566                Ok(())
1567            } else {
1568                Err(BallisticsError::from(format!("{name} must be finite")))
1569            }
1570        };
1571        let require_positive = |name: &str, value: f64| {
1572            if value.is_finite() && value > 0.0 {
1573                Ok(())
1574            } else {
1575                Err(BallisticsError::from(format!(
1576                    "{name} must be finite and greater than zero"
1577                )))
1578            }
1579        };
1580
1581        // These four quantities are required by every point-mass solve. In particular, validate
1582        // muzzle_velocity after `new` has applied a measured curve or linear powder correction.
1583        // A custom drag table supplies the actual Cd and divides by sectional density, so bc_value
1584        // is physically ignored (see custom_drag_denominator). Require it only in the no-table case;
1585        // mass + diameter are always required (they drive the SD denominator when a table is set).
1586        if self.inputs.custom_drag_table.is_none() {
1587            require_positive("bc_value", self.inputs.bc_value)?;
1588        }
1589        require_positive("bullet_mass", self.inputs.bullet_mass)?;
1590        require_positive("bullet_diameter", self.inputs.bullet_diameter)?;
1591        require_positive("muzzle_velocity", self.inputs.muzzle_velocity)?;
1592        // MBA-1356: cd_scale multiplies the custom-deck Cd; a non-finite or non-positive value
1593        // would zero/invert drag or poison integration with NaN. Required unconditionally (not
1594        // gated on custom_drag_table) since the default (1.0) is always valid and a caller could
1595        // set an invalid scale without ever setting a table. The [0.5, 2.0] "unusual" range is a
1596        // CLI-level warning (Task 2), not a hard engine rule.
1597        require_positive("cd_scale", self.inputs.cd_scale)?;
1598
1599        require_finite("muzzle_angle", self.inputs.muzzle_angle)?;
1600        require_finite("azimuth_angle", self.inputs.azimuth_angle)?;
1601        require_finite("shooting_angle", self.inputs.shooting_angle)?;
1602        require_finite("cant_angle", self.inputs.cant_angle)?;
1603        require_finite("muzzle_height", self.inputs.muzzle_height)?;
1604
1605        // MBA-1359: a deliberate zero POI offset is a small linear offset at the zero range
1606        // (fractions of an inch to a few inches). |1 m| is far beyond any plausible
1607        // deliberate offset and almost certainly a unit error (inches/cm passed as meters).
1608        for (name, value) in [
1609            ("zero_poi_vertical_m", self.inputs.zero_poi_vertical_m),
1610            ("zero_poi_horizontal_m", self.inputs.zero_poi_horizontal_m),
1611        ] {
1612            require_finite(name, value)?;
1613            if value.abs() >= 1.0 {
1614                return Err(BallisticsError::from(format!(
1615                    "{name} must be smaller than 1.0 m in magnitude (it is a linear POI \
1616                     offset at the zero range, in meters)"
1617                )));
1618            }
1619        }
1620
1621        // MBA-1396: a lateral sight-mount offset is physically bounded by rail/mount
1622        // geometry (an inch or two). |0.5 m| is almost certainly a unit error
1623        // (inches/mm passed as meters).
1624        require_finite(
1625            "sight_offset_lateral_m",
1626            self.inputs.sight_offset_lateral_m,
1627        )?;
1628        if self.inputs.sight_offset_lateral_m.abs() >= 0.5 {
1629            return Err(BallisticsError::from(
1630                "sight_offset_lateral_m must be smaller than 0.5 m in magnitude (it is \
1631                 the lateral sight-to-bore mount offset, in meters)",
1632            ));
1633        }
1634
1635        // Negative infinity is the documented ignore-ground sentinel. NaN and positive infinity
1636        // make the loop condition meaningless and are rejected.
1637        if !(self.inputs.ground_threshold.is_finite()
1638            || self.inputs.ground_threshold == f64::NEG_INFINITY)
1639        {
1640            return Err(BallisticsError::from(
1641                "ground_threshold must be finite or negative infinity",
1642            ));
1643        }
1644
1645        match &self.wind_sock {
1646            Some(wind_sock) => wind_sock
1647                .validate_segments()
1648                .map_err(BallisticsError::from)?,
1649            None => {
1650                require_finite("wind.speed", self.wind.speed)?;
1651                require_finite("wind.direction", self.wind.direction)?;
1652                require_finite("wind.vertical_speed", self.wind.vertical_speed)?;
1653            }
1654        }
1655
1656        require_finite("atmosphere.temperature", self.atmosphere.temperature)?;
1657        require_finite("atmosphere.pressure", self.atmosphere.pressure)?;
1658        require_finite("atmosphere.humidity", self.atmosphere.humidity)?;
1659        require_finite("atmosphere.altitude", self.atmosphere.altitude)?;
1660
1661        require_positive("max_range", self.max_range)?;
1662        // Adaptive RK45 owns its step size; the caller-provided fixed step is used only by Euler
1663        // and fixed RK4.
1664        if !self.inputs.use_rk4 || !self.inputs.use_adaptive_rk45 {
1665            require_positive("time_step", self.time_step)?;
1666        }
1667
1668        if self.inputs.enable_trajectory_sampling {
1669            require_finite("sight_height", self.inputs.sight_height)?;
1670            require_positive("sample_interval", self.inputs.sample_interval)?;
1671            projected_sample_count(self.max_range, self.inputs.sample_interval)?;
1672        }
1673
1674        // MBA-1403: the target-plane drops reference divides sampled drop by
1675        // cos(shooting_angle); at or beyond 90 degrees the transform is undefined.
1676        // Gated on the non-default mode only, so LOS-mode validation is unchanged.
1677        if self.inputs.drops_reference == DropsReference::Target {
1678            require_finite("target_height", self.inputs.target_height)?;
1679            if self.inputs.shooting_angle.cos() <= 1e-9 {
1680                return Err(BallisticsError::from(
1681                    "drops reference 'target' is undefined for shooting angles at or beyond 90 degrees",
1682                ));
1683            }
1684        }
1685
1686        if self.inputs.enable_coriolis {
1687            require_finite("shot_azimuth", self.inputs.shot_azimuth)?;
1688            if let Some(latitude) = self.inputs.latitude {
1689                require_finite("latitude", latitude)?;
1690            }
1691        }
1692
1693        Ok(())
1694    }
1695
1696    /// Public solve results must never report success with NaN or infinity, nor with values a
1697    /// physical trajectory cannot produce: a negative terminal downrange distance, time of
1698    /// flight, speed, or energy (MBA-1293 — a stiff-input integration explosion reported
1699    /// `Ok(max_range: -50.59)`). The input gate catches malformed scalar state; this
1700    /// postcondition also covers overflow and malformed optional tables/segments without
1701    /// imposing arbitrary upper bounds on otherwise finite inputs.
1702    fn validate_result_sanity(&self, result: &TrajectoryResult) -> Result<(), BallisticsError> {
1703        let require_finite = |name: &str, value: f64| {
1704            if value.is_finite() {
1705                Ok(())
1706            } else {
1707                Err(BallisticsError::from(format!(
1708                    "trajectory result contains non-finite {name}"
1709                )))
1710            }
1711        };
1712        let require_non_negative = |name: &str, value: f64| {
1713            if value >= 0.0 {
1714                Ok(())
1715            } else {
1716                Err(BallisticsError::from(format!(
1717                    "trajectory result contains non-physical negative {name} ({value})"
1718                )))
1719            }
1720        };
1721        let require_indexed_finite = |collection: &str, index: usize, field: &str, value: f64| {
1722            if value.is_finite() {
1723                Ok(())
1724            } else {
1725                Err(BallisticsError::from(format!(
1726                    "trajectory result contains non-finite {collection}[{index}].{field}"
1727                )))
1728            }
1729        };
1730        let require_indexed_non_negative =
1731            |collection: &str, index: usize, field: &str, value: f64| {
1732                if value >= 0.0 {
1733                    Ok(())
1734                } else {
1735                    Err(BallisticsError::from(format!(
1736                        "trajectory result contains non-physical negative {collection}[{index}].{field} ({value})"
1737                    )))
1738                }
1739            };
1740
1741        require_finite("max_range", result.max_range)?;
1742        require_finite("max_height", result.max_height)?;
1743        require_finite("time_of_flight", result.time_of_flight)?;
1744        require_finite("impact_velocity", result.impact_velocity)?;
1745        require_finite("impact_energy", result.impact_energy)?;
1746        require_finite("projectile_mass_kg", result.projectile_mass_kg)?;
1747        require_finite(
1748            "line_of_sight_height_m",
1749            result.line_of_sight_height_m,
1750        )?;
1751        require_finite(
1752            "station_speed_of_sound_mps",
1753            result.station_speed_of_sound_mps,
1754        )?;
1755
1756        // The solve starts at x = 0 and only ever fires downrange, so these scalars are
1757        // non-negative for every physically meaningful trajectory. (max_height is exempt:
1758        // points can legitimately sit below y = 0 with an elevated muzzle.)
1759        require_non_negative("max_range", result.max_range)?;
1760        require_non_negative("time_of_flight", result.time_of_flight)?;
1761        require_non_negative("impact_velocity", result.impact_velocity)?;
1762        require_non_negative("impact_energy", result.impact_energy)?;
1763        require_non_negative("projectile_mass_kg", result.projectile_mass_kg)?;
1764        require_non_negative(
1765            "station_speed_of_sound_mps",
1766            result.station_speed_of_sound_mps,
1767        )?;
1768
1769        for (index, point) in result.points.iter().enumerate() {
1770            require_indexed_finite("points", index, "time", point.time)?;
1771            require_indexed_finite("points", index, "position.x", point.position.x)?;
1772            require_indexed_finite("points", index, "position.y", point.position.y)?;
1773            require_indexed_finite("points", index, "position.z", point.position.z)?;
1774            require_indexed_finite(
1775                "points",
1776                index,
1777                "velocity_magnitude",
1778                point.velocity_magnitude,
1779            )?;
1780            require_indexed_finite("points", index, "kinetic_energy", point.kinetic_energy)?;
1781            require_indexed_non_negative("points", index, "time", point.time)?;
1782            require_indexed_non_negative(
1783                "points",
1784                index,
1785                "velocity_magnitude",
1786                point.velocity_magnitude,
1787            )?;
1788            require_indexed_non_negative("points", index, "kinetic_energy", point.kinetic_energy)?;
1789        }
1790
1791        if let Some(samples) = &result.sampled_points {
1792            for (index, sample) in samples.iter().enumerate() {
1793                require_indexed_finite("sampled_points", index, "distance_m", sample.distance_m)?;
1794                require_indexed_finite("sampled_points", index, "drop_m", sample.drop_m)?;
1795                require_indexed_finite(
1796                    "sampled_points",
1797                    index,
1798                    "wind_drift_m",
1799                    sample.wind_drift_m,
1800                )?;
1801                require_indexed_finite(
1802                    "sampled_points",
1803                    index,
1804                    "velocity_mps",
1805                    sample.velocity_mps,
1806                )?;
1807                require_indexed_finite("sampled_points", index, "energy_j", sample.energy_j)?;
1808                require_indexed_finite("sampled_points", index, "time_s", sample.time_s)?;
1809            }
1810        }
1811
1812        for (name, value) in [
1813            ("min_pitch_damping", result.min_pitch_damping),
1814            ("transonic_mach", result.transonic_mach),
1815            ("max_yaw_angle", result.max_yaw_angle),
1816            ("max_precession_angle", result.max_precession_angle),
1817        ] {
1818            if let Some(value) = value {
1819                require_finite(name, value)?;
1820            }
1821        }
1822
1823        if let Some(state) = result.angular_state {
1824            for (name, value) in [
1825                ("angular_state.pitch_angle", state.pitch_angle),
1826                ("angular_state.yaw_angle", state.yaw_angle),
1827                ("angular_state.pitch_rate", state.pitch_rate),
1828                ("angular_state.yaw_rate", state.yaw_rate),
1829                ("angular_state.precession_angle", state.precession_angle),
1830                ("angular_state.nutation_phase", state.nutation_phase),
1831            ] {
1832                require_finite(name, value)?;
1833            }
1834        }
1835
1836        if let Some(jump) = result.aerodynamic_jump {
1837            for (name, value) in [
1838                ("aerodynamic_jump.vertical_jump_moa", jump.vertical_jump_moa),
1839                (
1840                    "aerodynamic_jump.horizontal_jump_moa",
1841                    jump.horizontal_jump_moa,
1842                ),
1843                ("aerodynamic_jump.jump_angle_rad", jump.jump_angle_rad),
1844                (
1845                    "aerodynamic_jump.magnus_component_moa",
1846                    jump.magnus_component_moa,
1847                ),
1848                ("aerodynamic_jump.yaw_component_moa", jump.yaw_component_moa),
1849                (
1850                    "aerodynamic_jump.stabilization_factor",
1851                    jump.stabilization_factor,
1852                ),
1853            ] {
1854                require_finite(name, value)?;
1855            }
1856        }
1857
1858        Ok(())
1859    }
1860
1861    /// Integration methods store the pre-step state in `points`. Validate each newly accepted
1862    /// state as well, otherwise a poisoned final step could terminate the loop and leave only the
1863    /// previous finite point in an apparently successful result.
1864    ///
1865    /// Beyond finiteness, an accepted state must respect the physical speed budget: drag is
1866    /// dissipative (it drives the projectile toward the wind frame, never past it), Magnus and
1867    /// Coriolis act perpendicular to the velocity and do no work, and gravity adds at most g*t.
1868    /// Ground-frame speed therefore cannot legitimately exceed muzzle speed + strongest wind +
1869    /// g*t. Exceeding that budget means the integrator itself diverged — for stiff inputs the
1870    /// minimum-step RK45 acceptance can multiply speed by orders of magnitude in one step
1871    /// (MBA-1293: 13x and a sign reversal in a single 1 microsecond step) — so the solve must
1872    /// fail rather than report the garbage as `Ok`.
1873    fn validate_integration_state(
1874        &self,
1875        position: &Vector3<f64>,
1876        velocity: &Vector3<f64>,
1877        time: f64,
1878    ) -> Result<(), BallisticsError> {
1879        if !(position.iter().all(|value| value.is_finite())
1880            && velocity.iter().all(|value| value.is_finite())
1881            && time.is_finite())
1882        {
1883            return Err(BallisticsError::from(
1884                "trajectory integration produced a non-finite state (often from physically \
1885                 extreme inputs — e.g. an absurd bore/muzzle height placing the launch far \
1886                 from sea level, or a degenerate atmosphere; check those inputs, or set \
1887                 --altitude explicitly)",
1888            ));
1889        }
1890
1891        let speed = velocity.magnitude();
1892        let budget = self.speed_budget(time);
1893        if speed > budget {
1894            return Err(BallisticsError::from(format!(
1895                "trajectory integration diverged: speed {speed:.3e} m/s at t={time:.6}s exceeds \
1896                 the physical budget of {budget:.3e} m/s"
1897            )));
1898        }
1899        Ok(())
1900    }
1901
1902    /// Ceiling on ground-frame speed a physical trajectory can reach by time `t` (see
1903    /// [`Self::validate_integration_state`]). The factor-2 slack absorbs boundary-layer
1904    /// wind-shear amplification and integrator transients; genuine divergence clears the
1905    /// budget by orders of magnitude.
1906    fn speed_budget(&self, time: f64) -> f64 {
1907        let scalar_wind = self.wind.speed.abs() + self.wind.vertical_speed.abs();
1908        let wind_bound = match &self.wind_sock {
1909            Some(sock) => scalar_wind.max(sock.max_speed_mps()),
1910            None => scalar_wind,
1911        };
1912        2.0 * (self.inputs.muzzle_velocity + wind_bound + 10.0)
1913            + crate::constants::G_ACCEL_MPS2 * time
1914    }
1915
1916    /// Store one public trajectory point without exceeding the per-solve resource budget.
1917    fn push_trajectory_point(
1918        &self,
1919        points: &mut Vec<TrajectoryPoint>,
1920        point: TrajectoryPoint,
1921    ) -> Result<(), BallisticsError> {
1922        if points.len() >= self.max_trajectory_points {
1923            return Err(BallisticsError::from(format!(
1924                "trajectory point limit of {} exceeded",
1925                self.max_trajectory_points
1926            )));
1927        }
1928        points.push(point);
1929        Ok(())
1930    }
1931
1932    /// Supply downrange-segmented wind. Each segment is `(speed_kmh, angle_deg,
1933    /// until_distance_m)`; the wind for a given downrange distance is the first
1934    /// segment whose `until_distance_m` exceeds it (a step function), and wind is
1935    /// zero beyond the last segment. An empty list clears segmented wind (reverts
1936    /// to the scalar `wind`). The angle convention matches `WindConditions`
1937    /// (0 = headwind, 90 = from the right).
1938    pub fn set_wind_segments(&mut self, segments: Vec<crate::wind::WindSegment>) {
1939        self.wind_sock = if segments.is_empty() {
1940            None
1941        } else {
1942            Some(crate::wind::WindSock::new(segments))
1943        };
1944    }
1945
1946    /// Supply downrange-segmented atmosphere (MBA-1137). Each segment is
1947    /// `(temp_c, pressure_hpa, humidity_percent, until_distance_m)`, defined at the shooter base
1948    /// altitude; the per-substep local-atmosphere recompute selects the active zone by downrange
1949    /// distance (first zone whose `until_distance_m` exceeds it; the last zone is held beyond the
1950    /// final threshold). The zone's base conditions are composed with the vertical altitude lapse
1951    /// via `get_local_atmosphere_humid`, so a steeply-arcing shot still sees the y-lapse on top of
1952    /// the zone base. An empty list clears segmented atmosphere (reverts to the resolved
1953    /// single-station conditions).
1954    pub fn set_atmo_segments(&mut self, segments: Vec<crate::atmosphere::AtmoSegment>) {
1955        self.atmo_sock = if segments.is_empty() {
1956            None
1957        } else {
1958            Some(crate::atmosphere::AtmoSock::new(segments))
1959        };
1960    }
1961
1962    /// Effective initial launch direction `(elevation, azimuth)` in radians, including
1963    /// the aerodynamic-jump muzzle perturbation when `enable_aerodynamic_jump` is set.
1964    ///
1965    /// Aerodynamic jump is the fixed angular departure imparted as the projectile
1966    /// transitions from the constrained bore to free flight; applying it as an initial
1967    /// launch-angle offset is the physically correct integration point. Returns the bare
1968    /// `(muzzle_angle, azimuth_angle)` when the flag is off, so a default solve is
1969    /// numerically identical to pre-feature behavior. (MBA-959)
1970    fn launch_angles_from(
1971        &self,
1972        aj: Option<&crate::aerodynamic_jump::AerodynamicJumpComponents>,
1973    ) -> (f64, f64) {
1974        let (mut elev, mut azim) = (self.inputs.muzzle_angle, self.inputs.azimuth_angle);
1975        // MBA-1286: cant rotates the sight-frame aim offsets about the line of sight.
1976        // Positive = clockwise from the shooter: the upward zero correction leaks right
1977        // (+z) and shrinks by cos(cant) -> POI right and low. Exactly-0.0 skips all float
1978        // ops so un-canted solves stay bit-identical. Aerodynamic jump is added AFTER the
1979        // rotation: it arises at bore exit from crosswind/spin in the ground frame, not
1980        // from the rifle's sight geometry.
1981        if self.inputs.cant_angle != 0.0 {
1982            let (sin_c, cos_c) = self.inputs.cant_angle.sin_cos();
1983            let (e0, a0) = (elev, azim);
1984            elev = e0 * cos_c - a0 * sin_c;
1985            azim = a0 * cos_c + e0 * sin_c;
1986        }
1987        match aj {
1988            Some(c) => {
1989                // vertical_/horizontal_jump_moa ARE the jump angles expressed in MOA.
1990                const MOA_PER_RAD: f64 = 3437.7467707849;
1991                (
1992                    elev + c.vertical_jump_moa / MOA_PER_RAD,
1993                    azim + c.horizontal_jump_moa / MOA_PER_RAD,
1994                )
1995            }
1996            None => (elev, azim),
1997        }
1998    }
1999
2000    /// Compute the aerodynamic-jump components for the current inputs, or `None` when the
2001    /// feature is disabled / inputs are degenerate.
2002    ///
2003    /// Uses Bryan Litz's crosswind aerodynamic-jump estimator
2004    /// (`Y = 0.01*Sg - 0.0024*L + 0.032` MOA/mph) fed by the engine's own Miller Sg.
2005    /// Aerodynamic jump is a vertical effect, so only the elevation is perturbed.
2006    /// The estimator is a regression best near Sg ~ 1.75 — see MBA-959.
2007    fn aerodynamic_jump_components(
2008        &self,
2009    ) -> Option<crate::aerodynamic_jump::AerodynamicJumpComponents> {
2010        if !self.inputs.enable_aerodynamic_jump {
2011            return None;
2012        }
2013        // Reject degenerate/non-finite inputs before they can reach the launch angle.
2014        // A bare `<= 0.0` test lets NaN through (NaN comparisons are always false), and a
2015        // NaN/Inf here would poison the muzzle angle and collapse the whole trajectory.
2016        let diameter_m = self.inputs.bullet_diameter;
2017        if !(self.inputs.twist_rate.is_finite()
2018            && self.inputs.twist_rate != 0.0
2019            && diameter_m.is_finite()
2020            && diameter_m > 0.0
2021            && self.inputs.bullet_length.is_finite()
2022            && self.inputs.bullet_length > 0.0
2023            && self.inputs.muzzle_velocity.is_finite())
2024        {
2025            return None;
2026        }
2027
2028        // Engine's own gyroscopic (Miller) stability factor — same Sg shown elsewhere.
2029        let (_, _, temp_c, pressure_hpa) = self.resolved_atmosphere();
2030        let sg = crate::stability::compute_stability_coefficient(
2031            &self.inputs,
2032            (self.atmosphere.altitude, temp_c, pressure_hpa, 0.0),
2033        );
2034        if !(sg.is_finite() && sg > 0.0) {
2035            return None;
2036        }
2037        let length_calibers = self.inputs.bullet_length / diameter_m;
2038
2039        // Crosswind-from-the-right (mph) for Litz's estimator. Wind direction uses the
2040        // wind-FROM convention (0 = headwind, +90deg = from the right), matching the
2041        // fast-integrate path (fast_trajectory::aerodynamic_jump_launch_offset_rad) and
2042        // the lateral windage sign, so a from-the-right wind on a right-twist barrel
2043        // jumps the impact UP and drifts it left.
2044        const MS_TO_MPH: f64 = 2.236_936_292_054_4;
2045        let crosswind_from_right_mps = if let Some(sock) = &self.wind_sock {
2046            -sock.vector_for_range_stateless(0.0)[2]
2047        } else {
2048            self.wind.speed * self.wind.direction.sin()
2049        };
2050        let crosswind_from_right_mph = crosswind_from_right_mps * MS_TO_MPH;
2051
2052        let vertical_jump_moa = crate::aerodynamic_jump::litz_crosswind_jump_moa(
2053            sg,
2054            length_calibers,
2055            crosswind_from_right_mph,
2056            self.inputs.is_twist_right,
2057        );
2058        if !vertical_jump_moa.is_finite() {
2059            return None;
2060        }
2061
2062        const MOA_PER_RAD: f64 = 3437.7467707849;
2063        Some(crate::aerodynamic_jump::AerodynamicJumpComponents {
2064            vertical_jump_moa,
2065            // Aerodynamic jump is a vertical effect; the Litz estimator has no horizontal term.
2066            horizontal_jump_moa: 0.0,
2067            jump_angle_rad: vertical_jump_moa.abs() / MOA_PER_RAD,
2068            magnus_component_moa: 0.0,
2069            yaw_component_moa: 0.0,
2070            stabilization_factor: (sg / 1.5).clamp(0.0, 1.0),
2071        })
2072    }
2073
2074    fn resolved_atmosphere(&self) -> (f64, f64, f64, f64) {
2075        let (temp_c, pressure_hpa) = match self.station_atmosphere_resolution {
2076            StationAtmosphereResolution::LegacyDefaultSentinels => {
2077                crate::atmosphere::resolve_station_conditions(
2078                    self.atmosphere.temperature,
2079                    self.atmosphere.pressure,
2080                    self.atmosphere.altitude,
2081                )
2082            }
2083            StationAtmosphereResolution::Authoritative => {
2084                (self.atmosphere.temperature, self.atmosphere.pressure)
2085            }
2086        };
2087        let (density, speed_of_sound) = crate::atmosphere::calculate_atmosphere(
2088            self.atmosphere.altitude,
2089            Some(temp_c),
2090            Some(pressure_hpa),
2091            self.atmosphere.humidity,
2092        );
2093        (density, speed_of_sound, temp_c, pressure_hpa)
2094    }
2095
2096    fn precession_nutation_params(
2097        &self,
2098        velocity_mps: f64,
2099        air_density_kg_m3: f64,
2100        speed_of_sound_mps: f64,
2101    ) -> PrecessionNutationParams {
2102        let (spin_inertia, transverse_inertia) = self.precession_nutation_inertias;
2103        let spin_rate_rad_s = if self.inputs.twist_rate > 0.0 {
2104            let velocity_fps = velocity_mps * 3.28084;
2105            let twist_rate_ft = self.inputs.twist_rate / 12.0;
2106            (velocity_fps / twist_rate_ft) * 2.0 * std::f64::consts::PI
2107        } else {
2108            0.0
2109        };
2110
2111        PrecessionNutationParams {
2112            mass_kg: self.inputs.bullet_mass,
2113            caliber_m: self.inputs.bullet_diameter,
2114            length_m: self.inputs.bullet_length,
2115            spin_rate_rad_s,
2116            spin_inertia,
2117            transverse_inertia,
2118            velocity_mps,
2119            air_density_kg_m3,
2120            mach: velocity_mps / speed_of_sound_mps,
2121            pitch_damping_coeff: PitchDampingCoefficients::default().subsonic,
2122            nutation_damping_factor: 0.05,
2123        }
2124    }
2125
2126    /// Append the exact state at the earliest boundary crossed by the final integration step.
2127    ///
2128    /// Each solver stores its pre-step state. Keeping only that point makes early ground and time
2129    /// exits indistinguishable from ordinary integration knots, and historically left the
2130    /// reported endpoint one step short. Interpolating all supported boundaries here gives every
2131    /// solver one explicit terminal point and one authoritative termination reason.
2132    fn append_terminal_endpoint(
2133        &self,
2134        points: &mut Vec<TrajectoryPoint>,
2135        post_position: Vector3<f64>,
2136        post_velocity: Vector3<f64>,
2137        post_time: f64,
2138        max_height: &mut f64,
2139    ) -> Result<TrajectoryTermination, BallisticsError> {
2140        let previous = points
2141            .last()
2142            .cloned()
2143            .ok_or_else(|| BallisticsError::from("No trajectory points generated"))?;
2144
2145        let mut crossings = Vec::with_capacity(3);
2146        if previous.position.x < self.max_range && post_position.x >= self.max_range {
2147            let span = post_position.x - previous.position.x;
2148            if span.is_finite() && span > 0.0 {
2149                crossings.push((
2150                    (self.max_range - previous.position.x) / span,
2151                    TrajectoryTermination::MaxRange,
2152                ));
2153            }
2154        }
2155        if self.inputs.ground_threshold.is_finite()
2156            && previous.position.y > self.inputs.ground_threshold
2157            && post_position.y <= self.inputs.ground_threshold
2158        {
2159            let span = post_position.y - previous.position.y;
2160            if span.is_finite() && span < 0.0 {
2161                crossings.push((
2162                    (self.inputs.ground_threshold - previous.position.y) / span,
2163                    TrajectoryTermination::GroundThreshold,
2164                ));
2165            }
2166        }
2167        if previous.time < TRAJECTORY_TIME_LIMIT_S && post_time >= TRAJECTORY_TIME_LIMIT_S {
2168            let span = post_time - previous.time;
2169            if span.is_finite() && span > 0.0 {
2170                crossings.push((
2171                    (TRAJECTORY_TIME_LIMIT_S - previous.time) / span,
2172                    TrajectoryTermination::TimeLimit,
2173                ));
2174            }
2175        }
2176
2177        let (fraction, termination) = crossings
2178            .into_iter()
2179            .filter(|(fraction, _)| fraction.is_finite() && (0.0..=1.0).contains(fraction))
2180            .min_by(|left, right| {
2181                let priority = |termination: TrajectoryTermination| match termination {
2182                    TrajectoryTermination::GroundThreshold => 0,
2183                    TrajectoryTermination::MaxRange => 1,
2184                    TrajectoryTermination::TimeLimit => 2,
2185                    TrajectoryTermination::VelocityFloor => 3,
2186                };
2187                left.0
2188                    .total_cmp(&right.0)
2189                    .then_with(|| priority(left.1).cmp(&priority(right.1)))
2190            })
2191            .ok_or_else(|| {
2192                BallisticsError::from(
2193                    "trajectory integration stopped without crossing a supported boundary",
2194                )
2195            })?;
2196
2197        let mut position = previous.position + (post_position - previous.position) * fraction;
2198        match termination {
2199            TrajectoryTermination::MaxRange => position.x = self.max_range,
2200            TrajectoryTermination::GroundThreshold => {
2201                position.y = self.inputs.ground_threshold;
2202            }
2203            TrajectoryTermination::TimeLimit | TrajectoryTermination::VelocityFloor => {}
2204        }
2205        let velocity_magnitude = previous.velocity_magnitude
2206            + (post_velocity.magnitude() - previous.velocity_magnitude) * fraction;
2207        let mut time = previous.time + (post_time - previous.time) * fraction;
2208        if termination == TrajectoryTermination::TimeLimit {
2209            time = TRAJECTORY_TIME_LIMIT_S;
2210        }
2211        let kinetic_energy =
2212            0.5 * self.inputs.bullet_mass * velocity_magnitude * velocity_magnitude;
2213
2214        if position.y > *max_height {
2215            *max_height = position.y;
2216        }
2217        let terminal_point = TrajectoryPoint {
2218            time,
2219            position,
2220            velocity_magnitude,
2221            kinetic_energy,
2222            drag_coefficient: None,
2223        };
2224        if terminal_point.position.x < previous.position.x {
2225            return Err(BallisticsError::from(
2226                "trajectory terminal state reversed downrange before the crossed boundary",
2227            ));
2228        }
2229        if terminal_point.position.x == previous.position.x {
2230            // A very early ground/time crossing can be distinct in time but less than one ULP
2231            // downrange. There is no representable range at which to retain both states, so make
2232            // the terminal state authoritative instead of creating a duplicate-X trajectory that
2233            // the checked observation API must reject.
2234            let last = points.last_mut().ok_or_else(|| {
2235                BallisticsError::from("trajectory points disappeared during terminal finalization")
2236            })?;
2237            *last = terminal_point;
2238        } else {
2239            self.push_trajectory_point(points, terminal_point)?;
2240        }
2241        Ok(termination)
2242    }
2243
2244    fn gravity_acceleration(&self) -> Vector3<f64> {
2245        let theta = self.inputs.shooting_angle;
2246        Vector3::new(
2247            -crate::constants::G_ACCEL_MPS2 * theta.sin(),
2248            -crate::constants::G_ACCEL_MPS2 * theta.cos(),
2249            0.0,
2250        )
2251    }
2252
2253    fn get_wind_at_altitude(&self, altitude_m: f64) -> Vector3<f64> {
2254        // Scale the operative surface wind by the boundary-layer multiplier. `altitude_m` is the
2255        // bullet's height relative to the muzzle (McCoy Y). The multiplier is floored at 1.0, so
2256        // flat-fire trajectories keep ~full wind and only high-arcing shots see increased wind.
2257        //
2258        // We build the vector with THIS solver's non-shear sign convention (X=-cos, Z=-sin; see
2259        // the `wind_vector` used in solve_rk4/solve_euler, matching WindSock) and scale it, so that
2260        // "shear on" equals "shear off" * ratio (ratio == 1.0 for flat fire). An earlier revision
2261        // attenuated the wind near the line of sight and flipped its sign relative to the non-shear
2262        // path; this keeps them sign-consistent.
2263        // Map the requested model name to the boundary-layer model (MBA-965).
2264        // Names match wind_shear::get_wind_at_position. Unknown strings should
2265        // never reach here (the CLI parses an enum), but default to PowerLaw to
2266        // preserve the historical "exponential" behaviour for any caller that
2267        // forwards an unexpected value.
2268        let model = match self.inputs.wind_shear_model.as_str() {
2269            "logarithmic" => WindShearModel::Logarithmic,
2270            "power_law" | "powerlaw" | "exponential" => WindShearModel::PowerLaw,
2271            "ekman_spiral" | "ekman" => WindShearModel::EkmanSpiral,
2272            "custom_layers" | "custom" => WindShearModel::CustomLayers,
2273            _ => WindShearModel::PowerLaw,
2274        };
2275        let speed_ratio = crate::wind_shear::boundary_layer_speed_ratio(altitude_m, model);
2276
2277        // 0deg = headwind, 90deg = from the right (McCoy wind-FROM convention, matching
2278        // WindConditions / WindSock); wind enters drag via velocity - wind.
2279        //
2280        // MBA-728: the horizontal vector is built with vertical=0.0 and scaled by speed_ratio,
2281        // then wind.vertical_speed is added back UNSCALED — boundary-layer shear scales
2282        // horizontal wind only, vertical passes through as-is.
2283        crate::wind::wind_vector(self.wind.speed, self.wind.direction, 0.0) * speed_ratio
2284            + Vector3::new(0.0, self.wind.vertical_speed, 0.0)
2285    }
2286
2287    pub fn solve(&self) -> Result<TrajectoryResult, BallisticsError> {
2288        self.validate_for_solve()?;
2289        let mut result = if self.inputs.use_rk4 {
2290            if self.inputs.use_adaptive_rk45 {
2291                self.solve_rk45()?
2292            } else {
2293                self.solve_rk4()?
2294            }
2295        } else {
2296            self.solve_euler()?
2297        };
2298        self.apply_spin_drift(&mut result);
2299        self.validate_result_sanity(&result)?;
2300        Ok(result)
2301    }
2302
2303    /// Gyroscopic spin drift via the empirical Litz model, applied in the engine
2304    /// (not the WASM formatter) so it covers Euler/RK4/RK45 and all consumers.
2305    /// Uses the canonical SI fields and converts to grains/inches correctly,
2306    /// avoiding the kg/m-vs-grains/in unit bug in `calculate_enhanced_spin_drift`.
2307    /// Frame (McCoy): Z = lateral (windage), so drift adds to `position.z`.
2308    fn apply_spin_drift(&self, result: &mut TrajectoryResult) {
2309        if !self.inputs.use_enhanced_spin_drift {
2310            return;
2311        }
2312        let d_in = self.inputs.bullet_diameter / 0.0254; // m -> in
2313        let m_gr = self.inputs.bullet_mass / crate::constants::GRAINS_TO_KG; // kg -> grains
2314        let twist_in = self.inputs.twist_rate; // inches/turn
2315        if d_in <= 0.0 || m_gr <= 0.0 || twist_in <= 0.0 {
2316            return;
2317        }
2318
2319        // MBA-1134 (rank 31): single source of truth for the muzzle Sg —
2320        // stability::compute_stability_coefficient via spin_drift::effective_sg_from_inputs. This
2321        // ADDS the (v/2800)^(1/3) muzzle-velocity term the bare miller_stability() lacked, so the
2322        // spin-drift Sg now matches the reported SG and the aerodynamic-jump Sg. The linear Miller
2323        // density correction ((T/T0)*(P0/P), a no-op at sea-level standard) and the 4.5-caliber
2324        // length fallback are handled inside effective_sg_from_inputs.
2325        let sg = self.effective_spin_drift_sg();
2326
2327        for p in result.points.iter_mut() {
2328            if p.time <= 0.0 {
2329                continue;
2330            }
2331            // Canonical Litz drift, shared with the fast / Monte-Carlo path (spin_drift::litz_*).
2332            p.position.z +=
2333                crate::spin_drift::litz_drift_meters(sg, p.time, self.inputs.is_twist_right);
2334        }
2335
2336        // sampled_points are snapshotted from the PRE-drift trajectory inside each solver, so the
2337        // sampled wind_drift_m column would omit the spin drift that result.points carry. Apply
2338        // the same canonical Litz drift to keep the two user-facing outputs consistent.
2339        if let Some(samples) = result.sampled_points.as_mut() {
2340            for s in samples.iter_mut() {
2341                if s.time_s <= 0.0 {
2342                    continue;
2343                }
2344                s.wind_drift_m +=
2345                    crate::spin_drift::litz_drift_meters(sg, s.time_s, self.inputs.is_twist_right);
2346            }
2347        }
2348    }
2349
2350    /// Muzzle gyroscopic stability Sg used by the empirical Litz spin-drift post-process
2351    /// (MBA-1134). Extracted so the exact value is unit-testable and provably identical to the Sg
2352    /// the fast / Monte-Carlo path uses — both go through
2353    /// [`crate::spin_drift::effective_sg_from_inputs`] with the resolved muzzle atmosphere.
2354    fn effective_spin_drift_sg(&self) -> f64 {
2355        let (_, _, temp_c, press_hpa) = self.resolved_atmosphere();
2356        crate::spin_drift::effective_sg_from_inputs(&self.inputs, temp_c, press_hpa)
2357    }
2358
2359    /// Bore muzzle position at t=0 (bore-origin frame, `muzzle_height` above ground).
2360    /// With cant the rifle rotates about the LINE OF SIGHT, so the bore — sight_height
2361    /// below the sight — swings laterally by `-sight_height*sin(cant)` (left of the aim
2362    /// plane for clockwise cant) and rises by `sight_height*(1-cos(cant))` toward the
2363    /// pivot. (MBA-1286)
2364    ///
2365    /// A lateral sight-mount offset (MBA-1396) additionally displaces the bore
2366    /// `sight_offset_lateral_m` from the LOS (a sight mounted right of the bore puts the
2367    /// bore left of the sight line). Cant rotates the WHOLE bore-to-sight displacement
2368    /// vector rigidly about the LOS, so the vertical drop `-sight_height` and the lateral
2369    /// offset `-sight_offset_lateral_m` couple: rotating `(u, w) = (-sh, -off)` by the
2370    /// cant angle gives `y += sh*(1-cos) + off*sin` and `z = -sh*sin - off*cos`. Both the
2371    /// cant-only case (off = 0) and the offset-only case (cos = 1, sin = 0) collapse to
2372    /// the historical terms, so only a simultaneously canted AND offset rifle sees the
2373    /// coupling. The windage-zero convergence that makes the trajectory cross the LOS at
2374    /// the zero range lives in `windage_zero_bias_rad`, not here. Exactly-0.0 cant AND
2375    /// offset return the historical position (bit-identical).
2376    fn initial_position(&self) -> Vector3<f64> {
2377        if self.inputs.cant_angle == 0.0 && self.inputs.sight_offset_lateral_m == 0.0 {
2378            return Vector3::new(0.0, self.inputs.muzzle_height, 0.0);
2379        }
2380        let (sin_c, cos_c) = self.inputs.cant_angle.sin_cos();
2381        let sh = self.inputs.sight_height;
2382        let off = self.inputs.sight_offset_lateral_m;
2383        Vector3::new(
2384            0.0,
2385            self.inputs.muzzle_height + sh * (1.0 - cos_c) + off * sin_c,
2386            -sh * sin_c - off * cos_c,
2387        )
2388    }
2389
2390    /// Shared post-integration sampling used by all three integrators (MBA-1403).
2391    ///
2392    /// Builds the `TrajectoryData`/`TrajectoryOutputs` pair and runs
2393    /// [`sample_trajectory`] when `enable_trajectory_sampling` is set. This is the
2394    /// single place the sampler's LOS datum (`target_vertical_height_m`) is chosen,
2395    /// replacing three per-integrator copies that had to be edited in parallel.
2396    fn build_sampled_points(
2397        &self,
2398        points: &[TrajectoryPoint],
2399        max_height: f64,
2400        transonic_distances: Vec<f64>,
2401        mach_transitions: &MachTransitionTracker,
2402    ) -> Result<Option<Vec<TrajectorySample>>, BallisticsError> {
2403        if !self.inputs.enable_trajectory_sampling {
2404            return Ok(None);
2405        }
2406
2407        let last_point = points.last().ok_or("No trajectory points generated")?;
2408        let trajectory_data = TrajectoryData {
2409            times: points.iter().map(|p| p.time).collect(),
2410            positions: points.iter().map(|p| p.position).collect(),
2411            velocities: points
2412                .iter()
2413                .map(|p| {
2414                    // Reconstruct velocity vectors from magnitude (approximate)
2415                    Vector3::new(0.0, 0.0, p.velocity_magnitude)
2416                })
2417                .collect(),
2418            transonic_distances, // populated by the integrator at each Mach-threshold crossing
2419            mach_1_2_distance_m: mach_transitions.mach_1_2_distance_m,
2420            mach_1_0_distance_m: mach_transitions.mach_1_0_distance_m,
2421            mach_0_9_distance_m: mach_transitions.mach_0_9_distance_m,
2422        };
2423
2424        // For LOS calculation in ground-referenced coordinates:
2425        // sight_position_m is the sight's actual y-position above ground
2426        // (muzzle_height + sight_height, not just sight_height)
2427        // For flat shots, target is at same height as the sight (horizontal LOS)
2428        let sight_position_m = self.inputs.muzzle_height + self.inputs.sight_height;
2429        let target_reference = self.inputs.drops_reference == DropsReference::Target;
2430        // MBA-1403: only the (new, non-default) target mode reads `target_height` here,
2431        // and only when a real (non-zero) height was supplied — the sampler's LOS then
2432        // slopes toward the actual target instead of staying at the sight height. LOS
2433        // mode keeps the historical datum byte-identically, and zero-solve
2434        // `target_height` semantics (an explicit function argument, never this field)
2435        // are untouched.
2436        let target_vertical_height_m = if target_reference && self.inputs.target_height != 0.0 {
2437            self.inputs.target_height
2438        } else {
2439            sight_position_m
2440        };
2441        let outputs = TrajectoryOutputs {
2442            target_distance_horiz_m: last_point.position.x, // X is downrange
2443            target_vertical_height_m,
2444            time_of_flight_s: last_point.time,
2445            max_ord_dist_horiz_m: max_height,
2446            sight_height_m: sight_position_m,
2447        };
2448
2449        // Sample at specified intervals
2450        let mut samples = sample_trajectory(
2451            &trajectory_data,
2452            &outputs,
2453            self.inputs.sample_interval,
2454            self.inputs.bullet_mass,
2455        )?;
2456
2457        // MBA-1403 target-plane reference: scale the LOS-perpendicular drop to vertical
2458        // in the target plane. Scaling by the positive constant 1/cos preserves signs
2459        // and ordering, so the sampler's zero-crossing/apex flags are unaffected.
2460        // validate_for_solve rejects target mode at |shooting_angle| >= 90 degrees, so
2461        // cos_theta is strictly positive here. Downstream mil/moa conversions derive
2462        // from drop_m, so they inherit the transform without further edits.
2463        if target_reference {
2464            let cos_theta = self.inputs.shooting_angle.cos();
2465            for sample in &mut samples {
2466                sample.drop_m /= cos_theta;
2467            }
2468        }
2469        Ok(Some(samples))
2470    }
2471
2472    fn solve_euler(&self) -> Result<TrajectoryResult, BallisticsError> {
2473        // Simple trajectory integration using Euler method
2474        let mut time = 0.0;
2475        // Bullet starts at the BORE position, which is muzzle_height above ground
2476        // The sight is sight_height ABOVE the bore, so we don't add sight_height here
2477        // cant-adjusted via initial_position (MBA-1286)
2478        let mut position = self.initial_position();
2479        // Calculate initial velocity components with both elevation and azimuth
2480        // McCoy coordinate system: X=downrange, Y=vertical, Z=lateral (right)
2481        // Launch direction includes the aerodynamic-jump muzzle perturbation when enabled
2482        // (a no-op returning the bare muzzle/azimuth angles otherwise). MBA-959. Computed
2483        // once here and reused for the result so it isn't evaluated twice per solve.
2484        let aj_components = self.aerodynamic_jump_components();
2485        let (launch_elev, launch_azim) = self.launch_angles_from(aj_components.as_ref());
2486        let horizontal_velocity = self.inputs.muzzle_velocity * launch_elev.cos();
2487        let mut velocity = Vector3::new(
2488            horizontal_velocity * launch_azim.cos(), // X: downrange (forward)
2489            self.inputs.muzzle_velocity * launch_elev.sin(), // Y: vertical component
2490            horizontal_velocity * launch_azim.sin(), // Z: lateral (side deviation)
2491        );
2492
2493        let mut points = Vec::new();
2494        let mut max_height = position.y;
2495        let mut min_pitch_damping = f64::INFINITY; // Track minimum pitch damping coefficient
2496        let mut transonic_mach = None; // Track when we enter transonic
2497                                       // Downrange distances where the projectile crosses Mach 1.2 (transonic) then Mach 1.0
2498                                       // (subsonic), so the sampled trajectory output can flag those transitions
2499                                       // (trajectory_sampling::add_trajectory_flags consumes this).
2500        let mut transonic_distances: Vec<f64> = Vec::new();
2501        let mut mach_transitions = MachTransitionTracker::default();
2502
2503        // Initialize angular state for precession/nutation tracking
2504        let mut angular_state = if self.inputs.enable_precession_nutation {
2505            Some(AngularState {
2506                pitch_angle: 0.001, // Small initial disturbance
2507                yaw_angle: 0.001,
2508                pitch_rate: 0.0,
2509                yaw_rate: 0.0,
2510                precession_angle: 0.0,
2511                nutation_phase: 0.0,
2512            })
2513        } else {
2514            None
2515        };
2516        let mut max_yaw_angle = 0.0;
2517        let mut max_precession_angle = 0.0;
2518
2519        // Calculate air density
2520        let (air_density, speed_of_sound, resolved_temp_c, resolved_press_hpa) =
2521            self.resolved_atmosphere();
2522        // MBA-1136 (rank 30): base density RATIO for the local-altitude atmosphere recompute done
2523        // per-substep inside calculate_acceleration. The `air_density` / `speed_of_sound` above
2524        // stay the frozen station values, still used for the Mach-transition, pitch-damping and
2525        // precession/nutation diagnostics (which are intentionally referenced to station Mach).
2526        let base_ratio = air_density / 1.225;
2527
2528        // Wind vector (McCoy): X=downrange (head/tail wind), Y=0, Z=lateral (crosswind)
2529        // 0deg = headwind, 90deg = from the right (McCoy wind-FROM convention, matching
2530        // WindSock); wind enters drag via velocity - wind. Used when no segmented wind.
2531        // MBA-728: no shear/no segments here, so vertical_speed passes straight through
2532        // (there is no horizontal-only scaling step on this path).
2533        let wind_vector =
2534            crate::wind::wind_vector(self.wind.speed, self.wind.direction, self.wind.vertical_speed);
2535
2536        // Pitch-damping coefficients depend only on the (constant) bullet_model; compute once
2537        // instead of re-deriving them (with a to_lowercase alloc) every integration step.
2538        let pitch_coeffs = PitchDampingCoefficients::from_bullet_type(
2539            self.inputs.bullet_model.as_deref().unwrap_or("default"),
2540        );
2541
2542        // Main integration loop (X is downrange)
2543        while position.x < self.max_range
2544            && position.y > self.inputs.ground_threshold
2545            && time < TRAJECTORY_TIME_LIMIT_S
2546        {
2547            // Store trajectory point
2548            let velocity_magnitude = velocity.magnitude();
2549            let kinetic_energy =
2550                0.5 * self.inputs.bullet_mass * velocity_magnitude * velocity_magnitude;
2551
2552            self.push_trajectory_point(
2553                &mut points,
2554                TrajectoryPoint {
2555                    time,
2556                    position,
2557                    velocity_magnitude,
2558                    kinetic_energy,
2559                    drag_coefficient: None,
2560                },
2561            )?;
2562
2563            // Record Mach-transition distances (constant sea-level speed of sound, matching the
2564            // transonic_mach tracking). Each threshold is recorded once, in descending order.
2565            {
2566                let mach_here = if speed_of_sound > 0.0 {
2567                    velocity_magnitude / speed_of_sound
2568                } else {
2569                    0.0
2570                };
2571                mach_transitions.record_downward_crossings(
2572                    mach_here,
2573                    position.x,
2574                    &mut transonic_distances,
2575                );
2576            }
2577
2578            // Track max height
2579            if position.y > max_height {
2580                max_height = position.y;
2581            }
2582
2583            // Calculate pitch damping if enabled
2584            if self.inputs.enable_pitch_damping {
2585                let mach = velocity_magnitude / speed_of_sound;
2586
2587                // Track when we enter transonic
2588                if transonic_mach.is_none() && mach < 1.2 && mach > 0.8 {
2589                    transonic_mach = Some(mach);
2590                }
2591
2592                // Calculate pitch damping coefficient
2593                let pitch_damping = calculate_pitch_damping_coefficient(mach, &pitch_coeffs);
2594
2595                // Track minimum (most critical for stability)
2596                if pitch_damping < min_pitch_damping {
2597                    min_pitch_damping = pitch_damping;
2598                }
2599            }
2600
2601            // Calculate precession/nutation if enabled
2602            if self.inputs.enable_precession_nutation {
2603                if let Some(ref mut state) = angular_state {
2604                    let velocity_magnitude = velocity.magnitude();
2605                    let params = self.precession_nutation_params(
2606                        velocity_magnitude,
2607                        air_density,
2608                        speed_of_sound,
2609                    );
2610
2611                    // Update angular state
2612                    *state = calculate_combined_angular_motion(
2613                        &params,
2614                        state,
2615                        time,
2616                        self.time_step,
2617                        0.001, // Initial disturbance
2618                    );
2619
2620                    // Track maximums
2621                    if state.yaw_angle.abs() > max_yaw_angle {
2622                        max_yaw_angle = state.yaw_angle.abs();
2623                    }
2624                    if state.precession_angle.abs() > max_precession_angle {
2625                        max_precession_angle = state.precession_angle.abs();
2626                    }
2627                }
2628            }
2629
2630            // Use the same acceleration kernel as RK4/RK45 so all three solvers share ONE drag
2631            // model. solve_euler previously used a bespoke frontal-area drag (0.5*rho*Cd*A*v^2/m)
2632            // that IGNORED the ballistic coefficient entirely (diverging up to ~2.3x from the
2633            // BC-retardation RK4/RK45 path), and also omitted the Magnus/Coriolis terms.
2634            // calculate_acceleration applies BC-retardation drag, gravity, Coriolis, Magnus, wind
2635            // shear, and the zero-relative-velocity gravity-only guard.
2636            let acceleration = self.calculate_acceleration(
2637                &position,
2638                &velocity,
2639                &wind_vector,
2640                (resolved_temp_c, resolved_press_hpa, base_ratio),
2641            );
2642
2643            // Update state
2644            velocity += acceleration * self.time_step;
2645            position += velocity * self.time_step;
2646            time += self.time_step;
2647            self.validate_integration_state(&position, &velocity, time)?;
2648        }
2649
2650        let termination =
2651            self.append_terminal_endpoint(&mut points, position, velocity, time, &mut max_height)?;
2652
2653        // Get final values
2654        // MBA-1423: fill the per-point Cd here, once, rather than inside each integrator loop.
2655        // Every solver family reaches this line, so none can leave the field empty while the
2656        // others populate it. Must precede the `last_point` borrow below.
2657        self.annotate_drag_coefficients(&mut points, speed_of_sound);
2658
2659        let last_point = points.last().ok_or("No trajectory points generated")?;
2660
2661        // Create trajectory sampling data if enabled (shared helper, MBA-1403)
2662        let sampled_points = self.build_sampled_points(
2663            &points,
2664            max_height,
2665            transonic_distances,
2666            &mach_transitions,
2667        )?;
2668
2669        Ok(TrajectoryResult {
2670            max_range: last_point.position.x, // X is downrange
2671            max_height,
2672            time_of_flight: last_point.time,
2673            impact_velocity: last_point.velocity_magnitude,
2674            impact_energy: last_point.kinetic_energy,
2675            projectile_mass_kg: self.inputs.bullet_mass,
2676            line_of_sight_height_m: self.inputs.muzzle_height + self.inputs.sight_height,
2677            station_speed_of_sound_mps: speed_of_sound,
2678            termination,
2679            points,
2680            sampled_points,
2681            min_pitch_damping: if self.inputs.enable_pitch_damping {
2682                Some(min_pitch_damping)
2683            } else {
2684                None
2685            },
2686            transonic_mach,
2687            angular_state,
2688            max_yaw_angle: if self.inputs.enable_precession_nutation {
2689                Some(max_yaw_angle)
2690            } else {
2691                None
2692            },
2693            max_precession_angle: if self.inputs.enable_precession_nutation {
2694                Some(max_precession_angle)
2695            } else {
2696                None
2697            },
2698            aerodynamic_jump: aj_components,
2699            mach_1_2_distance_m: mach_transitions.mach_1_2_distance_m,
2700            mach_1_0_distance_m: mach_transitions.mach_1_0_distance_m,
2701            mach_0_9_distance_m: mach_transitions.mach_0_9_distance_m,
2702        })
2703    }
2704
2705    fn solve_rk4(&self) -> Result<TrajectoryResult, BallisticsError> {
2706        // RK4 trajectory integration for better accuracy
2707        let mut time = 0.0;
2708        // Bullet starts at the BORE position, which is muzzle_height above ground
2709        // The sight is sight_height ABOVE the bore, so we don't add sight_height here
2710        // The sight_height affects the LOS calculation and zero angle, not the starting position
2711        // cant-adjusted via initial_position (MBA-1286)
2712        let mut position = self.initial_position();
2713
2714        // Calculate initial velocity components with both elevation and azimuth
2715        // McCoy coordinate system: X=downrange, Y=vertical, Z=lateral (right)
2716        // Launch direction includes the aerodynamic-jump muzzle perturbation when enabled
2717        // (a no-op returning the bare muzzle/azimuth angles otherwise). MBA-959. Computed
2718        // once here and reused for the result so it isn't evaluated twice per solve.
2719        let aj_components = self.aerodynamic_jump_components();
2720        let (launch_elev, launch_azim) = self.launch_angles_from(aj_components.as_ref());
2721        let horizontal_velocity = self.inputs.muzzle_velocity * launch_elev.cos();
2722        let mut velocity = Vector3::new(
2723            horizontal_velocity * launch_azim.cos(), // X: downrange (forward)
2724            self.inputs.muzzle_velocity * launch_elev.sin(), // Y: vertical component
2725            horizontal_velocity * launch_azim.sin(), // Z: lateral (side deviation)
2726        );
2727
2728        let mut points = Vec::new();
2729        let mut max_height = position.y;
2730        let mut min_pitch_damping = f64::INFINITY; // Track minimum pitch damping coefficient
2731        let mut transonic_mach = None; // Track when we enter transonic
2732                                       // Downrange distances where the projectile crosses Mach 1.2 (transonic) then Mach 1.0
2733                                       // (subsonic), so the sampled trajectory output can flag those transitions
2734                                       // (trajectory_sampling::add_trajectory_flags consumes this).
2735        let mut transonic_distances: Vec<f64> = Vec::new();
2736        let mut mach_transitions = MachTransitionTracker::default();
2737
2738        // Initialize angular state for precession/nutation tracking
2739        let mut angular_state = if self.inputs.enable_precession_nutation {
2740            Some(AngularState {
2741                pitch_angle: 0.001, // Small initial disturbance
2742                yaw_angle: 0.001,
2743                pitch_rate: 0.0,
2744                yaw_rate: 0.0,
2745                precession_angle: 0.0,
2746                nutation_phase: 0.0,
2747            })
2748        } else {
2749            None
2750        };
2751        let mut max_yaw_angle = 0.0;
2752        let mut max_precession_angle = 0.0;
2753
2754        // Calculate air density
2755        let (air_density, speed_of_sound, resolved_temp_c, resolved_press_hpa) =
2756            self.resolved_atmosphere();
2757        // MBA-1136 (rank 30): base density RATIO for the local-altitude atmosphere recompute done
2758        // per-substep inside calculate_acceleration. The `air_density` / `speed_of_sound` above
2759        // stay the frozen station values, still used for the Mach-transition, pitch-damping and
2760        // precession/nutation diagnostics (which are intentionally referenced to station Mach).
2761        let base_ratio = air_density / 1.225;
2762
2763        // Wind vector (McCoy): X=downrange (head/tail wind), Y=0, Z=lateral (crosswind)
2764        // 0deg = headwind, 90deg = from the right (McCoy wind-FROM convention, matching
2765        // WindSock); wind enters drag via velocity - wind. Used when no segmented wind.
2766        // MBA-728: no shear/no segments here, so vertical_speed passes straight through
2767        // (there is no horizontal-only scaling step on this path).
2768        let wind_vector =
2769            crate::wind::wind_vector(self.wind.speed, self.wind.direction, self.wind.vertical_speed);
2770
2771        // Pitch-damping coefficients depend only on the (constant) bullet_model; compute once
2772        // instead of re-deriving them (with a to_lowercase alloc) every integration step.
2773        let pitch_coeffs = PitchDampingCoefficients::from_bullet_type(
2774            self.inputs.bullet_model.as_deref().unwrap_or("default"),
2775        );
2776
2777        // Main RK4 integration loop (X is downrange)
2778        while position.x < self.max_range
2779            && position.y > self.inputs.ground_threshold
2780            && time < TRAJECTORY_TIME_LIMIT_S
2781        {
2782            // Store trajectory point
2783            let velocity_magnitude = velocity.magnitude();
2784            let kinetic_energy =
2785                0.5 * self.inputs.bullet_mass * velocity_magnitude * velocity_magnitude;
2786
2787            self.push_trajectory_point(
2788                &mut points,
2789                TrajectoryPoint {
2790                    time,
2791                    position,
2792                    velocity_magnitude,
2793                    kinetic_energy,
2794                    drag_coefficient: None,
2795                },
2796            )?;
2797
2798            // Record Mach-transition distances (constant sea-level speed of sound, matching the
2799            // transonic_mach tracking). Each threshold is recorded once, in descending order.
2800            {
2801                let mach_here = if speed_of_sound > 0.0 {
2802                    velocity_magnitude / speed_of_sound
2803                } else {
2804                    0.0
2805                };
2806                mach_transitions.record_downward_crossings(
2807                    mach_here,
2808                    position.x,
2809                    &mut transonic_distances,
2810                );
2811            }
2812
2813            if position.y > max_height {
2814                max_height = position.y;
2815            }
2816
2817            // Calculate pitch damping if enabled (RK4 solver)
2818            if self.inputs.enable_pitch_damping {
2819                let mach = velocity_magnitude / speed_of_sound;
2820
2821                // Track when we enter transonic
2822                if transonic_mach.is_none() && mach < 1.2 && mach > 0.8 {
2823                    transonic_mach = Some(mach);
2824                }
2825
2826                // Calculate pitch damping coefficient
2827                let pitch_damping = calculate_pitch_damping_coefficient(mach, &pitch_coeffs);
2828
2829                // Track minimum (most critical for stability)
2830                if pitch_damping < min_pitch_damping {
2831                    min_pitch_damping = pitch_damping;
2832                }
2833            }
2834
2835            // Calculate precession/nutation if enabled (RK4 solver)
2836            if self.inputs.enable_precession_nutation {
2837                if let Some(ref mut state) = angular_state {
2838                    let velocity_magnitude = velocity.magnitude();
2839                    let params = self.precession_nutation_params(
2840                        velocity_magnitude,
2841                        air_density,
2842                        speed_of_sound,
2843                    );
2844
2845                    // Update angular state
2846                    *state = calculate_combined_angular_motion(
2847                        &params,
2848                        state,
2849                        time,
2850                        self.time_step,
2851                        0.001, // Initial disturbance
2852                    );
2853
2854                    // Track maximums
2855                    if state.yaw_angle.abs() > max_yaw_angle {
2856                        max_yaw_angle = state.yaw_angle.abs();
2857                    }
2858                    if state.precession_angle.abs() > max_precession_angle {
2859                        max_precession_angle = state.precession_angle.abs();
2860                    }
2861                }
2862            }
2863
2864            // RK4 method
2865            let dt = self.time_step;
2866
2867            // k1
2868            let acc1 = self.calculate_acceleration(
2869                &position,
2870                &velocity,
2871                &wind_vector,
2872                (resolved_temp_c, resolved_press_hpa, base_ratio),
2873            );
2874
2875            // k2
2876            let pos2 = position + velocity * (dt * 0.5);
2877            let vel2 = velocity + acc1 * (dt * 0.5);
2878            let acc2 = self.calculate_acceleration(
2879                &pos2,
2880                &vel2,
2881                &wind_vector,
2882                (resolved_temp_c, resolved_press_hpa, base_ratio),
2883            );
2884
2885            // k3
2886            let pos3 = position + vel2 * (dt * 0.5);
2887            let vel3 = velocity + acc2 * (dt * 0.5);
2888            let acc3 = self.calculate_acceleration(
2889                &pos3,
2890                &vel3,
2891                &wind_vector,
2892                (resolved_temp_c, resolved_press_hpa, base_ratio),
2893            );
2894
2895            // k4
2896            let pos4 = position + vel3 * dt;
2897            let vel4 = velocity + acc3 * dt;
2898            let acc4 = self.calculate_acceleration(
2899                &pos4,
2900                &vel4,
2901                &wind_vector,
2902                (resolved_temp_c, resolved_press_hpa, base_ratio),
2903            );
2904
2905            // Update position and velocity
2906            position += (velocity + vel2 * 2.0 + vel3 * 2.0 + vel4) * (dt / 6.0);
2907            velocity += (acc1 + acc2 * 2.0 + acc3 * 2.0 + acc4) * (dt / 6.0);
2908            time += dt;
2909            self.validate_integration_state(&position, &velocity, time)?;
2910        }
2911
2912        let termination =
2913            self.append_terminal_endpoint(&mut points, position, velocity, time, &mut max_height)?;
2914
2915        // Get final values
2916        // MBA-1423: fill the per-point Cd here, once, rather than inside each integrator loop.
2917        // Every solver family reaches this line, so none can leave the field empty while the
2918        // others populate it. Must precede the `last_point` borrow below.
2919        self.annotate_drag_coefficients(&mut points, speed_of_sound);
2920
2921        let last_point = points.last().ok_or("No trajectory points generated")?;
2922
2923        // Create trajectory sampling data if enabled (shared helper, MBA-1403)
2924        let sampled_points = self.build_sampled_points(
2925            &points,
2926            max_height,
2927            transonic_distances,
2928            &mach_transitions,
2929        )?;
2930
2931        Ok(TrajectoryResult {
2932            max_range: last_point.position.x, // X is downrange
2933            max_height,
2934            time_of_flight: last_point.time,
2935            impact_velocity: last_point.velocity_magnitude,
2936            impact_energy: last_point.kinetic_energy,
2937            projectile_mass_kg: self.inputs.bullet_mass,
2938            line_of_sight_height_m: self.inputs.muzzle_height + self.inputs.sight_height,
2939            station_speed_of_sound_mps: speed_of_sound,
2940            termination,
2941            points,
2942            sampled_points,
2943            min_pitch_damping: if self.inputs.enable_pitch_damping {
2944                Some(min_pitch_damping)
2945            } else {
2946                None
2947            },
2948            transonic_mach,
2949            angular_state,
2950            max_yaw_angle: if self.inputs.enable_precession_nutation {
2951                Some(max_yaw_angle)
2952            } else {
2953                None
2954            },
2955            max_precession_angle: if self.inputs.enable_precession_nutation {
2956                Some(max_precession_angle)
2957            } else {
2958                None
2959            },
2960            aerodynamic_jump: aj_components,
2961            mach_1_2_distance_m: mach_transitions.mach_1_2_distance_m,
2962            mach_1_0_distance_m: mach_transitions.mach_1_0_distance_m,
2963            mach_0_9_distance_m: mach_transitions.mach_0_9_distance_m,
2964        })
2965    }
2966
2967    fn solve_rk45(&self) -> Result<TrajectoryResult, BallisticsError> {
2968        // RK45 adaptive step size integration (Dormand-Prince method)
2969        let mut time = 0.0;
2970        // Bullet starts at the BORE position, which is muzzle_height above ground
2971        // The sight is sight_height ABOVE the bore, so we don't add sight_height here
2972        // cant-adjusted via initial_position (MBA-1286)
2973        let mut position = self.initial_position();
2974
2975        // Calculate initial velocity components
2976        // McCoy coordinate system: X=downrange, Y=vertical, Z=lateral (right)
2977        // Launch direction includes the aerodynamic-jump muzzle perturbation when enabled
2978        // (a no-op returning the bare muzzle/azimuth angles otherwise). MBA-959. Computed
2979        // once here and reused for the result so it isn't evaluated twice per solve.
2980        let aj_components = self.aerodynamic_jump_components();
2981        let (launch_elev, launch_azim) = self.launch_angles_from(aj_components.as_ref());
2982        let horizontal_velocity = self.inputs.muzzle_velocity * launch_elev.cos();
2983        let mut velocity = Vector3::new(
2984            horizontal_velocity * launch_azim.cos(), // X: downrange (forward)
2985            self.inputs.muzzle_velocity * launch_elev.sin(), // Y: vertical component
2986            horizontal_velocity * launch_azim.sin(), // Z: lateral (side deviation)
2987        );
2988
2989        let mut points = Vec::new();
2990        let mut max_height = position.y;
2991        let mut dt = 0.001; // Initial step size
2992
2993        // Air density and wind are constant for the whole solve (self.atmosphere / self.wind
2994        // are immutable); compute once instead of every iteration (mirrors solve_rk4).
2995        let (air_density, speed_of_sound, resolved_temp_c, resolved_press_hpa) =
2996            self.resolved_atmosphere();
2997        // MBA-1136 (rank 30): base density RATIO for the local-altitude atmosphere recompute done
2998        // per-substep inside calculate_acceleration. The `air_density` / `speed_of_sound` above
2999        // stay the frozen station values, still used for the Mach-transition, pitch-damping and
3000        // precession/nutation diagnostics (which are intentionally referenced to station Mach).
3001        let base_ratio = air_density / 1.225;
3002        // 0deg = headwind, 90deg = from the right (McCoy wind-FROM convention, matching
3003        // WindSock); wind enters drag via velocity - wind. Used when no segmented wind.
3004        // MBA-728: no shear/no segments here, so vertical_speed passes straight through
3005        // (there is no horizontal-only scaling step on this path).
3006        let wind_vector =
3007            crate::wind::wind_vector(self.wind.speed, self.wind.direction, self.wind.vertical_speed);
3008
3009        // Mach-transition distances for the sampled-output flags (see solve_euler/solve_rk4).
3010        let mut transonic_distances: Vec<f64> = Vec::new();
3011        let mut mach_transitions = MachTransitionTracker::default();
3012
3013        // Pitch-damping / precession diagnostics (MBA-966). Previously only the
3014        // Euler and fixed-RK4 solvers tracked these, so the default adaptive
3015        // RK45 path always reported null even with --enable-pitch-damping /
3016        // --enable-precession set. Mirror the RK4 tracking here.
3017        let mut min_pitch_damping = f64::INFINITY;
3018        let mut transonic_mach: Option<f64> = None;
3019        let pitch_coeffs = PitchDampingCoefficients::from_bullet_type(
3020            self.inputs.bullet_model.as_deref().unwrap_or("default"),
3021        );
3022        let mut angular_state = if self.inputs.enable_precession_nutation {
3023            Some(AngularState {
3024                pitch_angle: 0.001,
3025                yaw_angle: 0.001,
3026                pitch_rate: 0.0,
3027                yaw_rate: 0.0,
3028                precession_angle: 0.0,
3029                nutation_phase: 0.0,
3030            })
3031        } else {
3032            None
3033        };
3034        let mut max_yaw_angle = 0.0;
3035        let mut max_precession_angle = 0.0;
3036
3037        while position.x < self.max_range
3038            && position.y > self.inputs.ground_threshold
3039            && time < TRAJECTORY_TIME_LIMIT_S
3040        {
3041            // Store current point
3042            let velocity_magnitude = velocity.magnitude();
3043            let kinetic_energy = 0.5 * self.inputs.bullet_mass * velocity_magnitude.powi(2);
3044
3045            self.push_trajectory_point(
3046                &mut points,
3047                TrajectoryPoint {
3048                    time,
3049                    position,
3050                    velocity_magnitude,
3051                    kinetic_energy,
3052                    drag_coefficient: None,
3053                },
3054            )?;
3055
3056            // Record Mach-transition distances (constant sea-level speed of sound, matching the
3057            // transonic_mach tracking). Each threshold is recorded once, in descending order.
3058            {
3059                let mach_here = if speed_of_sound > 0.0 {
3060                    velocity_magnitude / speed_of_sound
3061                } else {
3062                    0.0
3063                };
3064                mach_transitions.record_downward_crossings(
3065                    mach_here,
3066                    position.x,
3067                    &mut transonic_distances,
3068                );
3069            }
3070
3071            if position.y > max_height {
3072                max_height = position.y;
3073            }
3074
3075            // Pitch damping (RK45 solver) — track the minimum coefficient and the
3076            // Mach at which the projectile enters the transonic band (MBA-966).
3077            if self.inputs.enable_pitch_damping {
3078                let mach = velocity_magnitude / speed_of_sound;
3079                if transonic_mach.is_none() && mach < 1.2 && mach > 0.8 {
3080                    transonic_mach = Some(mach);
3081                }
3082                let pitch_damping = calculate_pitch_damping_coefficient(mach, &pitch_coeffs);
3083                if pitch_damping < min_pitch_damping {
3084                    min_pitch_damping = pitch_damping;
3085                }
3086            }
3087
3088            // Retry the same state until the embedded error estimate accepts the
3089            // candidate. No trajectory or angular state advances on rejection.
3090            let accepted_step = self.adaptive_rk45_step(
3091                &position,
3092                &velocity,
3093                dt,
3094                &wind_vector,
3095                (resolved_temp_c, resolved_press_hpa, base_ratio),
3096            );
3097            debug_assert!(
3098                accepted_step.error <= RK45_TOLERANCE || accepted_step.used_dt <= RK45_MIN_DT
3099            );
3100
3101            // Precession / nutation advances only after the translational step
3102            // is accepted, using that accepted interval rather than a rejected
3103            // trial's dt.
3104            if self.inputs.enable_precession_nutation {
3105                if let Some(ref mut state) = angular_state {
3106                    let params = self.precession_nutation_params(
3107                        velocity_magnitude,
3108                        air_density,
3109                        speed_of_sound,
3110                    );
3111
3112                    *state = calculate_combined_angular_motion(
3113                        &params,
3114                        state,
3115                        time,
3116                        accepted_step.used_dt,
3117                        0.001,
3118                    );
3119
3120                    if state.yaw_angle.abs() > max_yaw_angle {
3121                        max_yaw_angle = state.yaw_angle.abs();
3122                    }
3123                    if state.precession_angle.abs() > max_precession_angle {
3124                        max_precession_angle = state.precession_angle.abs();
3125                    }
3126                }
3127            }
3128
3129            position = accepted_step.position;
3130            velocity = accepted_step.velocity;
3131            time += accepted_step.used_dt;
3132            self.validate_integration_state(&position, &velocity, time)?;
3133
3134            // Adapt the step size for the NEXT iteration.
3135            dt = accepted_step.next_dt;
3136        }
3137
3138        // Ensure we have at least one point
3139        if points.is_empty() {
3140            return Err(BallisticsError::from("No trajectory points calculated"));
3141        }
3142
3143        // Shared MBA-968/MBA-1218 range-crossing interpolation for all solver modes.
3144        let termination =
3145            self.append_terminal_endpoint(&mut points, position, velocity, time, &mut max_height)?;
3146
3147        // MBA-1423: see the sibling solvers — fill the per-point Cd before the borrow below.
3148        self.annotate_drag_coefficients(&mut points, speed_of_sound);
3149
3150        let last_point = points.last().unwrap();
3151
3152        // Generate sampled trajectory points if enabled (shared helper, MBA-1403)
3153        let sampled_points = self.build_sampled_points(
3154            &points,
3155            max_height,
3156            transonic_distances,
3157            &mach_transitions,
3158        )?;
3159
3160        Ok(TrajectoryResult {
3161            max_range: last_point.position.x, // X is downrange
3162            max_height,
3163            time_of_flight: last_point.time,
3164            impact_velocity: last_point.velocity_magnitude,
3165            impact_energy: last_point.kinetic_energy,
3166            projectile_mass_kg: self.inputs.bullet_mass,
3167            line_of_sight_height_m: self.inputs.muzzle_height + self.inputs.sight_height,
3168            station_speed_of_sound_mps: speed_of_sound,
3169            termination,
3170            points,
3171            sampled_points,
3172            min_pitch_damping: if self.inputs.enable_pitch_damping {
3173                Some(min_pitch_damping)
3174            } else {
3175                None
3176            },
3177            transonic_mach,
3178            angular_state,
3179            max_yaw_angle: if self.inputs.enable_precession_nutation {
3180                Some(max_yaw_angle)
3181            } else {
3182                None
3183            },
3184            max_precession_angle: if self.inputs.enable_precession_nutation {
3185                Some(max_precession_angle)
3186            } else {
3187                None
3188            },
3189            aerodynamic_jump: aj_components,
3190            mach_1_2_distance_m: mach_transitions.mach_1_2_distance_m,
3191            mach_1_0_distance_m: mach_transitions.mach_1_0_distance_m,
3192            mach_0_9_distance_m: mach_transitions.mach_0_9_distance_m,
3193        })
3194    }
3195
3196    fn adaptive_rk45_step(
3197        &self,
3198        position: &Vector3<f64>,
3199        velocity: &Vector3<f64>,
3200        initial_dt: f64,
3201        wind_vector: &Vector3<f64>,
3202        resolved_atmo: (f64, f64, f64),
3203    ) -> Rk45AcceptedStep {
3204        let mut trial_dt = initial_dt;
3205
3206        loop {
3207            let trial = self.rk45_step(
3208                position,
3209                velocity,
3210                trial_dt,
3211                wind_vector,
3212                RK45_TOLERANCE,
3213                resolved_atmo,
3214            );
3215            // A finite-but-extreme input or malformed optional curve can overflow an embedded
3216            // trial. Do not let a NaN suggested step poison `trial_dt` and retry forever: shrink
3217            // to the minimum step, return the non-finite trial there, and let the immediate
3218            // integration-state check turn it into a clean Err.
3219            let next_dt = if trial.suggested_dt.is_finite() {
3220                (RK45_SAFETY_FACTOR * trial.suggested_dt).clamp(RK45_MIN_DT, RK45_MAX_DT)
3221            } else {
3222                RK45_MIN_DT
3223            };
3224
3225            if trial.error <= RK45_TOLERANCE || trial_dt <= RK45_MIN_DT {
3226                return Rk45AcceptedStep {
3227                    position: trial.position,
3228                    velocity: trial.velocity,
3229                    used_dt: trial_dt,
3230                    next_dt,
3231                    error: trial.error,
3232                };
3233            }
3234
3235            trial_dt = next_dt;
3236        }
3237    }
3238
3239    fn rk45_step(
3240        &self,
3241        position: &Vector3<f64>,
3242        velocity: &Vector3<f64>,
3243        dt: f64,
3244        wind_vector: &Vector3<f64>,
3245        tolerance: f64,
3246        resolved_atmo: (f64, f64, f64), // (base_temp_c, base_press_hpa, base_ratio)
3247    ) -> Rk45Trial {
3248        // Dormand-Prince coefficients
3249        const A21: f64 = 1.0 / 5.0;
3250        const A31: f64 = 3.0 / 40.0;
3251        const A32: f64 = 9.0 / 40.0;
3252        const A41: f64 = 44.0 / 45.0;
3253        const A42: f64 = -56.0 / 15.0;
3254        const A43: f64 = 32.0 / 9.0;
3255        const A51: f64 = 19372.0 / 6561.0;
3256        const A52: f64 = -25360.0 / 2187.0;
3257        const A53: f64 = 64448.0 / 6561.0;
3258        const A54: f64 = -212.0 / 729.0;
3259        const A61: f64 = 9017.0 / 3168.0;
3260        const A62: f64 = -355.0 / 33.0;
3261        const A63: f64 = 46732.0 / 5247.0;
3262        const A64: f64 = 49.0 / 176.0;
3263        const A65: f64 = -5103.0 / 18656.0;
3264        const A71: f64 = 35.0 / 384.0;
3265        const A73: f64 = 500.0 / 1113.0;
3266        const A74: f64 = 125.0 / 192.0;
3267        const A75: f64 = -2187.0 / 6784.0;
3268        const A76: f64 = 11.0 / 84.0;
3269
3270        // 5th order coefficients
3271        const B1: f64 = 35.0 / 384.0;
3272        const B3: f64 = 500.0 / 1113.0;
3273        const B4: f64 = 125.0 / 192.0;
3274        const B5: f64 = -2187.0 / 6784.0;
3275        const B6: f64 = 11.0 / 84.0;
3276
3277        // 4th order coefficients for error estimation
3278        const B1_ERR: f64 = 5179.0 / 57600.0;
3279        const B3_ERR: f64 = 7571.0 / 16695.0;
3280        const B4_ERR: f64 = 393.0 / 640.0;
3281        const B5_ERR: f64 = -92097.0 / 339200.0;
3282        const B6_ERR: f64 = 187.0 / 2100.0;
3283        const B7_ERR: f64 = 1.0 / 40.0;
3284
3285        // Compute RK45 stages
3286        let k1_v = self.calculate_acceleration(position, velocity, wind_vector, resolved_atmo);
3287        let k1_p = *velocity;
3288
3289        let p2 = position + dt * A21 * k1_p;
3290        let v2 = velocity + dt * A21 * k1_v;
3291        let k2_v = self.calculate_acceleration(&p2, &v2, wind_vector, resolved_atmo);
3292        let k2_p = v2;
3293
3294        let p3 = position + dt * (A31 * k1_p + A32 * k2_p);
3295        let v3 = velocity + dt * (A31 * k1_v + A32 * k2_v);
3296        let k3_v = self.calculate_acceleration(&p3, &v3, wind_vector, resolved_atmo);
3297        let k3_p = v3;
3298
3299        let p4 = position + dt * (A41 * k1_p + A42 * k2_p + A43 * k3_p);
3300        let v4 = velocity + dt * (A41 * k1_v + A42 * k2_v + A43 * k3_v);
3301        let k4_v = self.calculate_acceleration(&p4, &v4, wind_vector, resolved_atmo);
3302        let k4_p = v4;
3303
3304        let p5 = position + dt * (A51 * k1_p + A52 * k2_p + A53 * k3_p + A54 * k4_p);
3305        let v5 = velocity + dt * (A51 * k1_v + A52 * k2_v + A53 * k3_v + A54 * k4_v);
3306        let k5_v = self.calculate_acceleration(&p5, &v5, wind_vector, resolved_atmo);
3307        let k5_p = v5;
3308
3309        let p6 = position + dt * (A61 * k1_p + A62 * k2_p + A63 * k3_p + A64 * k4_p + A65 * k5_p);
3310        let v6 = velocity + dt * (A61 * k1_v + A62 * k2_v + A63 * k3_v + A64 * k4_v + A65 * k5_v);
3311        let k6_v = self.calculate_acceleration(&p6, &v6, wind_vector, resolved_atmo);
3312        let k6_p = v6;
3313
3314        let p7 = position + dt * (A71 * k1_p + A73 * k3_p + A74 * k4_p + A75 * k5_p + A76 * k6_p);
3315        let v7 = velocity + dt * (A71 * k1_v + A73 * k3_v + A74 * k4_v + A75 * k5_v + A76 * k6_v);
3316        let k7_v = self.calculate_acceleration(&p7, &v7, wind_vector, resolved_atmo);
3317        let k7_p = v7;
3318
3319        // 5th order solution
3320        let new_pos = position + dt * (B1 * k1_p + B3 * k3_p + B4 * k4_p + B5 * k5_p + B6 * k6_p);
3321        let new_vel = velocity + dt * (B1 * k1_v + B3 * k3_v + B4 * k4_v + B5 * k5_v + B6 * k6_v);
3322
3323        // 4th order solution for error estimate
3324        let pos_err = position
3325            + dt * (B1_ERR * k1_p
3326                + B3_ERR * k3_p
3327                + B4_ERR * k4_p
3328                + B5_ERR * k5_p
3329                + B6_ERR * k6_p
3330                + B7_ERR * k7_p);
3331        let vel_err = velocity
3332            + dt * (B1_ERR * k1_v
3333                + B3_ERR * k3_v
3334                + B4_ERR * k4_v
3335                + B5_ERR * k5_v
3336                + B6_ERR * k6_v
3337                + B7_ERR * k7_v);
3338
3339        // Estimate error
3340        let error = cli_rk45_error_norm(position, velocity, &new_pos, &new_vel, &pos_err, &vel_err);
3341
3342        // Calculate new step size
3343        let dt_new = if error < tolerance {
3344            dt * (tolerance / error).powf(0.2).min(2.0)
3345        } else {
3346            dt * (tolerance / error).powf(0.25).max(0.1)
3347        };
3348
3349        Rk45Trial {
3350            position: new_pos,
3351            velocity: new_vel,
3352            suggested_dt: dt_new,
3353            error,
3354        }
3355    }
3356
3357    fn apply_cluster_bc_correction(&self, base_bc: f64, velocity_fps: f64) -> f64 {
3358        if let Some(ref cluster_bc) = self.cluster_bc {
3359            cluster_bc.apply_correction_for_drag_model(
3360                base_bc,
3361                self.inputs.caliber_inches,
3362                self.inputs.weight_grains,
3363                velocity_fps,
3364                self.inputs.bc_type,
3365            )
3366        } else {
3367            base_bc
3368        }
3369    }
3370
3371    fn calculate_acceleration(
3372        &self,
3373        position: &Vector3<f64>,
3374        velocity: &Vector3<f64>,
3375        wind_vector: &Vector3<f64>,
3376        resolved_atmo: (f64, f64, f64), // (base_temp_c, base_press_hpa, base_ratio) hoisted per-solve
3377    ) -> Vector3<f64> {
3378        // Resolve the wind at this point. Downrange-segmented wind (when supplied)
3379        // takes precedence and is sampled by downrange distance (position.x) per
3380        // step; otherwise altitude-dependent shear (if enabled); otherwise the
3381        // constant `wind_vector`. Segmented wind is not combined with shear (the
3382        // CLI/WASM front-ends reject that combination), so the order is safe.
3383        let actual_wind = if let Some(ref sock) = self.wind_sock {
3384            sock.vector_for_range_stateless(position.x)
3385        } else if self.inputs.enable_wind_shear {
3386            self.get_wind_at_altitude(position.y)
3387        } else {
3388            *wind_vector
3389        };
3390        let actual_wind =
3391            crate::derivatives::level_vector_to_shot_frame(actual_wind, self.inputs.shooting_angle);
3392
3393        let relative_velocity = velocity - actual_wind;
3394        let velocity_magnitude = relative_velocity.magnitude();
3395
3396        if velocity_magnitude < 0.001 {
3397            return self.gravity_acceleration();
3398        }
3399
3400        // MBA-1136 (rank 30): recompute the atmosphere at the LOCAL substep altitude instead of
3401        // holding the frozen station scalars for the whole flight. This mirrors what
3402        // derivatives.rs / fast_trajectory.rs already do, so all three solver families vary air
3403        // density AND speed of sound with altitude (matters on elevated / long-range shots; a
3404        // no-op at the shooter altitude, where the ratio-based density recovers the station value
3405        // exactly). base_* were resolved once per solve via resolved_atmosphere().
3406        //
3407        // `base_temp_c` / `base_press_hpa` are the STATION conditions that seed the local
3408        // atmosphere calculation below. Magnus dynamic stability consumes the resulting local
3409        // density rather than freezing a launch-density correction.
3410        let (base_temp_c, base_press_hpa, station_ratio) = resolved_atmo;
3411
3412        // MBA-1137: downrange-segmented atmosphere. When an AtmoSock is present, swap the BASE
3413        // (station-referenced) T/P/H tuple for the active zone selected by downrange distance
3414        // (position.x), recomputing the per-zone base density ratio via CIPM. That swapped base
3415        // then flows through the SAME altitude-lapse pipeline, so downrange zone selection and the
3416        // world-vertical altitude lapse compose — the zone sets the base density/humidity, and the
3417        // lapse multiplies on top of it (no double-count). When None, this is the resolved
3418        // single-station base.
3419        let (drag_base_temp_c, drag_base_press_hpa, drag_base_ratio, drag_humidity_percent) =
3420            if let Some(ref sock) = self.atmo_sock {
3421                let (zone_temp_c, zone_press_hpa, zone_humidity) = sock.atmo_for_range(position.x);
3422                let zone_base_ratio = crate::atmosphere::calculate_air_density_cimp(
3423                    zone_temp_c,
3424                    zone_press_hpa,
3425                    zone_humidity,
3426                ) / 1.225;
3427                (zone_temp_c, zone_press_hpa, zone_base_ratio, zone_humidity)
3428            } else {
3429                (
3430                    base_temp_c,
3431                    base_press_hpa,
3432                    station_ratio,
3433                    self.atmosphere.humidity,
3434                )
3435            };
3436        let local_alt = crate::atmosphere::shot_frame_altitude(
3437            self.atmosphere.altitude,
3438            position.x,
3439            position.y,
3440            self.inputs.shooting_angle,
3441        );
3442        let (air_density, speed_of_sound) = crate::atmosphere::get_local_atmosphere_humid(
3443            local_alt,
3444            self.atmosphere.altitude,
3445            drag_base_temp_c,
3446            drag_base_press_hpa,
3447            drag_base_ratio,
3448            drag_humidity_percent,
3449        );
3450
3451        // Resolve the Cd and the retardation denominator through the shared resolver. MBA-1423
3452        // reports a per-point Cd derived from these same two values, so the number a consumer
3453        // charts cannot drift from the number actually flown here.
3454        let (cd, retard_denom) = self.drag_terms(velocity_magnitude, speed_of_sound);
3455
3456        // Convert velocity to fps (still used below outside the BC lookup).
3457        let velocity_fps = velocity_magnitude * 3.28084;
3458
3459        // Use proper ballistics retardation formula
3460        // This matches the proven formula from fast_trajectory.rs
3461        // The standard retardation factor converts Cd to drag deceleration
3462        // Note: velocity_fps already calculated above for BC segment lookup
3463        let cd_to_retard = crate::constants::CD_TO_RETARD;
3464        let standard_factor = cd * cd_to_retard;
3465        let density_scale = air_density / 1.225; // Scale relative to standard air (1.225 kg/m³)
3466
3467        // Drag acceleration in ft/s² then convert to m/s²
3468        let a_drag_ft_s2 =
3469            (velocity_fps * velocity_fps) * standard_factor * density_scale / retard_denom;
3470        let a_drag_m_s2 = a_drag_ft_s2 * 0.3048; // ft/s² to m/s²
3471
3472        // Apply drag opposite to velocity direction
3473        let drag_acceleration = -a_drag_m_s2 * (relative_velocity / velocity_magnitude);
3474
3475        // Total acceleration = drag + gravity. `shooting_angle` rotates gravity into the shot
3476        // frame for inclined fire; at 0 deg this is the normal vertical-only gravity vector.
3477        let mut accel = drag_acceleration + self.gravity_acceleration();
3478
3479        // Coriolis (Earth rotation). McCoy frame: X=downrange, Y=vertical, Z=lateral,
3480        // azimuth 0 = North. McCoy frame: X=downrange, Y=vertical, Z=lateral.
3481        if self.inputs.enable_coriolis {
3482            if let Some(lat_deg) = self.inputs.latitude {
3483                let omega_earth = 7.2921159e-5_f64; // rad/s
3484                let lat = lat_deg.to_radians();
3485                let az = self.inputs.shot_azimuth; // compass bearing (0=N), NOT the aiming offset
3486                                                   // Earth's angular velocity in level downrange/up/lateral axes.
3487                                                   // Projecting Omega=(0, Ω cosφ, Ω sinφ) [local E,N,U] by azimuth gives
3488                                                   // a NEGATIVE lateral component:
3489                                                   // lateral = downrange × up points East for a North shot, and
3490                                                   // Omega·East = -Ω cosφ sin(az). The previous code dropped that sign.
3491                let omega = Vector3::new(
3492                    omega_earth * lat.cos() * az.cos(),  // X: downrange
3493                    omega_earth * lat.sin(),             // Y: vertical
3494                    -omega_earth * lat.cos() * az.sin(), // Z: lateral (MBA-938: corrected sign)
3495                );
3496                let omega = crate::derivatives::level_vector_to_shot_frame(
3497                    omega,
3498                    self.inputs.shooting_angle,
3499                );
3500                // Coriolis acceleration is the physical -2 Ω×v (MBA-938). The old +2 with
3501                // an "output-preserving relabel" justification produced left-ward drift for
3502                // a North shot in the Northern hemisphere; first principles (and the +Eötvös
3503                // lift for East shots) require -2 with the corrected omega above.
3504                accel += -2.0 * omega.cross(velocity);
3505            }
3506        }
3507
3508        // Magnus force (spinning projectile). SI units in this solver.
3509        // MBA-1134 (rank 35): the canonical empirical Litz spin-drift post-process
3510        // (apply_spin_drift) already captures the gyroscopic yaw-of-repose lateral, so the
3511        // explicit Magnus side force must NOT be added on top of it — otherwise the two lateral
3512        // models stack and double-count the drift. Suppress Magnus whenever Litz spin drift is
3513        // active. (The inverse is intentionally NOT done: Litz is not suppressed when Magnus is on.)
3514        if self.inputs.enable_magnus
3515            && !self.inputs.use_enhanced_spin_drift
3516            && self.inputs.bullet_diameter > 0.0
3517            && self.inputs.twist_rate > 0.0
3518        {
3519            let diameter_m = self.inputs.bullet_diameter;
3520            let (spin_rad_s, spin_param) = crate::spin_drift::calculate_magnus_spin_state(
3521                self.inputs.muzzle_velocity,
3522                velocity_magnitude,
3523                self.inputs.twist_rate,
3524                diameter_m,
3525            );
3526            // Mach and dynamic stability both use the LOCAL atmosphere recomputed above.
3527            let mach = velocity_magnitude / speed_of_sound;
3528
3529            // Imperial conversions for the stability / yaw-of-repose helpers.
3530            let d_in = self.inputs.bullet_diameter / 0.0254;
3531            let m_gr = self.inputs.bullet_mass / crate::constants::GRAINS_TO_KG;
3532            let l_in = if self.inputs.bullet_length > 0.0 {
3533                self.inputs.bullet_length / 0.0254
3534            } else {
3535                // MBA-1135: mass-based length estimate (was a mass-blind 4.5-caliber default).
3536                let est_m = crate::stability::estimate_bullet_length_m(
3537                    self.inputs.bullet_diameter,
3538                    self.inputs.bullet_mass,
3539                );
3540                if est_m > 0.0 {
3541                    est_m / 0.0254
3542                } else {
3543                    4.5 * d_in
3544                }
3545            };
3546            // Use current-flight Sg with the muzzle-set spin. The helper back-calculates the
3547            // effective twist from fixed spin and current airspeed, so Sg and yaw of repose grow
3548            // downrange instead of remaining tied to launch conditions.
3549            let sg = crate::spin_drift::calculate_dynamic_stability(
3550                m_gr,
3551                velocity_magnitude,
3552                spin_rad_s,
3553                d_in,
3554                l_in,
3555                air_density,
3556            );
3557
3558            // Yaw of repose (radians); zero for unstable bullets (Sg <= 1).
3559            let (yaw_rad, _) = crate::spin_drift::calculate_yaw_of_repose(
3560                sg,
3561                velocity_magnitude,
3562                spin_rad_s,
3563                0.0, // crosswind handled elsewhere
3564                0.0, // pitch rate not tracked
3565                air_density,
3566                d_in,
3567                l_in,
3568                m_gr,
3569                mach,
3570                "match",
3571                false,
3572            );
3573
3574            // Proper McCoy Magnus FORCE: F = q S C_Npa (pd/2V) sin(alpha_R).
3575            let c_np = crate::derivatives::calculate_magnus_moment_coefficient(mach);
3576            let area = std::f64::consts::PI * (diameter_m / 2.0).powi(2);
3577            let magnus_force = 0.5
3578                * air_density
3579                * velocity_magnitude.powi(2)
3580                * area
3581                * c_np
3582                * spin_param
3583                * yaw_rad.sin();
3584
3585            // The yaw of repose is lateral, so its Magnus force follows gravity projected normal
3586            // to flight (down for right-hand twist). Lateral yaw lift belongs to the separate Litz
3587            // spin-drift model and must not be synthesized from this Magnus magnitude.
3588            if magnus_force.abs() > 1e-12 {
3589                if let Some(dir) = crate::derivatives::yaw_of_repose_magnus_direction(
3590                    relative_velocity,
3591                    self.gravity_acceleration(),
3592                    self.inputs.is_twist_right,
3593                ) {
3594                    accel += (magnus_force / self.inputs.bullet_mass) * dir;
3595                }
3596            }
3597        }
3598
3599        accel
3600    }
3601
3602    /// The reference drag coefficient and the retardation denominator this solver divides by,
3603    /// at one speed.
3604    ///
3605    /// This is the single place the two are resolved. `calculate_acceleration` divides one by
3606    /// the other to produce drag; [`Self::effective_drag_coefficient`] recombines them into the
3607    /// projectile's own Cd for reporting (MBA-1423). Keeping both callers on one resolver is
3608    /// deliberate: a second copy of the BC-precedence ladder below is exactly the kind of
3609    /// duplicate that drifts silently once someone edits one of them.
3610    ///
3611    /// The denominator is a BC (lb/in²) for a G-model and the sectional density for a custom
3612    /// drag table, because that table already supplies the projectile's actual Cd.
3613    fn drag_terms(&self, velocity_magnitude: f64, speed_of_sound: f64) -> (f64, f64) {
3614        let cd = self.calculate_drag_coefficient(velocity_magnitude, speed_of_sound);
3615
3616        let velocity_fps = velocity_magnitude * 3.28084;
3617
3618        // Match the other solver families' BC precedence: enabled velocity-keyed segments first,
3619        // then legacy Mach-keyed segments, then the scalar BC. `use_bc_segments` gates velocity
3620        // tables, while explicit Mach segments remain active when it is false; derivatives.rs and
3621        // the fast solver preserve that legacy contract for callers that provide a Mach table.
3622        let (base_bc, bc_from_segments) = if let Some(segments) = self
3623            .inputs
3624            .bc_segments_data
3625            .as_ref()
3626            .filter(|segments| self.inputs.use_bc_segments && !segments.is_empty())
3627        {
3628            // Find matching segment for current velocity.
3629            (
3630                crate::bc_estimation::velocity_segment_bc(
3631                    velocity_fps,
3632                    segments,
3633                    self.inputs.bc_value,
3634                ),
3635                true,
3636            )
3637        } else if let Some(segments) = self
3638            .inputs
3639            .bc_segments
3640            .as_ref()
3641            .filter(|segments| !segments.is_empty())
3642        {
3643            (
3644                crate::derivatives::interpolated_bc(
3645                    velocity_magnitude / speed_of_sound,
3646                    segments,
3647                    Some(&self.inputs),
3648                ),
3649                true,
3650            )
3651        } else {
3652            (self.inputs.bc_value, false)
3653        };
3654
3655        // Segment tables already own the velocity-dependent BC shape. Stacking the empirical
3656        // cluster ladder on top would apply that shape twice (MBA-1175). Cluster correction is
3657        // therefore only a fallback for a scalar BC, regardless of which explicit segment
3658        // representation supplied the active value.
3659        let effective_bc = if bc_from_segments {
3660            base_bc
3661        } else {
3662            self.apply_cluster_bc_correction(base_bc, velocity_fps)
3663        };
3664        // The scalar BC is validated at the solve boundary. Retain a small denominator floor for
3665        // explicit segment tables, whose interpolated values are independent caller data.
3666        let effective_bc = effective_bc.max(1e-6);
3667
3668        // When a custom drag table is active, calculate_drag_coefficient returned the
3669        // projectile's ACTUAL Cd, so the retardation denominator must be the sectional
3670        // density (lb/in²), not a BC: Cd_own / SD == Cd_ref / BC
3671        // (see BallisticInputs::custom_drag_denominator).
3672        let retard_denom = if self.inputs.custom_drag_table.is_some() {
3673            self.inputs.custom_drag_denominator(effective_bc)
3674        } else {
3675            effective_bc
3676        };
3677
3678        (cd, retard_denom)
3679    }
3680
3681    /// The projectile's own drag coefficient at one speed — the curve a shooter would compare
3682    /// against a measured CDM trace, not the reference-table Cd (MBA-1423).
3683    ///
3684    /// A G-model Cd describes the *standard* projectile, so reporting it directly would hand a
3685    /// consumer the same G7 curve no matter which bullet was flown. Scaling by the form factor
3686    /// `SD / BC` converts it to this projectile's actual Cd, from the identity that both
3687    /// descriptions must produce the same retardation:
3688    ///
3689    /// ```text
3690    /// Cd_own / SD == Cd_ref / BC   =>   Cd_own == Cd_ref * SD / BC
3691    /// ```
3692    ///
3693    /// Because the denominator comes from the same internal resolver the integrator divides by,
3694    /// a velocity- or Mach-segmented BC
3695    /// carries into the result and its band steps appear in the reported curve. The same
3696    /// expression is already correct for a custom drag table, where the denominator *is* the
3697    /// sectional density and the scale factor collapses to 1.
3698    ///
3699    /// Returns `None` when the projectile's mass or diameter is unavailable, since sectional
3700    /// density — and therefore the projectile's own Cd — is undefined without both.
3701    pub fn effective_drag_coefficient(
3702        &self,
3703        velocity_magnitude: f64,
3704        speed_of_sound: f64,
3705    ) -> Option<f64> {
3706        if !velocity_magnitude.is_finite() || speed_of_sound <= 1e-9 {
3707            return None;
3708        }
3709        let sectional_density = self.inputs.sectional_density_lb_in2()?;
3710        let (cd, retard_denom) = self.drag_terms(velocity_magnitude, speed_of_sound);
3711        if retard_denom <= 0.0 {
3712            return None;
3713        }
3714        let effective = cd * sectional_density / retard_denom;
3715        effective.is_finite().then_some(effective)
3716    }
3717
3718    /// Fill every point's [`TrajectoryPoint::drag_coefficient`] in one pass (MBA-1423).
3719    ///
3720    /// Deliberately a pass over the finished vector rather than a value set where points are
3721    /// built: this solver constructs them in several places — terminal interpolation plus one
3722    /// loop per integrator family — and a pass covers a site added later for free.
3723    ///
3724    /// `speed_of_sound` must be the station value the result reports Mach against, so that a
3725    /// consumer plotting Cd against Mach gets a self-consistent pair. Feeding each step's local
3726    /// speed of sound instead would attribute a Cd to a Mach the document never shows.
3727    fn annotate_drag_coefficients(&self, points: &mut [TrajectoryPoint], speed_of_sound: f64) {
3728        for point in points.iter_mut() {
3729            point.drag_coefficient =
3730                self.effective_drag_coefficient(point.velocity_magnitude, speed_of_sound);
3731        }
3732    }
3733
3734    fn calculate_drag_coefficient(&self, velocity: f64, speed_of_sound: f64) -> f64 {
3735        let mach = velocity / speed_of_sound;
3736
3737        // MBA-940: a user-supplied custom drag table is the final Cd, used as-is — no G-model
3738        // lookup, no transonic shape correction, no form factor. The supplied curve already
3739        // encodes the projectile's true drag, so applying those would distort/double-count it.
3740        if let Some(ref table) = self.inputs.custom_drag_table {
3741            // MBA-1357: cd_scale is a single whole-curve drag multiplier applied here, at the
3742            // Cd lookup site. The Mach-keyed DSF table (truing_dsf.rs) is a SEPARATE, drop-only
3743            // post-processing correction applied to a solved TrajectoryResult's points after
3744            // integration finishes — it never touches this Cd/drag-force computation.
3745            return table.interpolate(mach) * self.inputs.cd_scale;
3746        }
3747
3748        // A published/measured BC already contains the projectile form factor (BC = SD / i).
3749        // Multiplying reference Cd by a second name-derived factor double-counts shape.
3750        crate::drag::get_drag_coefficient(mach, &self.inputs.bc_type)
3751    }
3752}
3753
3754// Monte Carlo parameters
3755#[derive(Debug, Clone)]
3756pub struct MonteCarloParams {
3757    pub num_simulations: usize,
3758    pub velocity_std_dev: f64,
3759    pub angle_std_dev: f64,
3760    pub bc_std_dev: f64,
3761    pub wind_speed_std_dev: f64,
3762    pub target_distance: Option<f64>,
3763    pub base_wind_speed: f64,
3764    pub base_wind_direction: f64,
3765    pub azimuth_std_dev: f64, // Horizontal aiming variation in radians
3766}
3767
3768impl Default for MonteCarloParams {
3769    fn default() -> Self {
3770        Self {
3771            num_simulations: 1000,
3772            velocity_std_dev: 1.0,
3773            angle_std_dev: 0.001,
3774            bc_std_dev: 0.01,
3775            wind_speed_std_dev: 1.0,
3776            target_distance: None,
3777            base_wind_speed: 0.0,
3778            base_wind_direction: 0.0,
3779            azimuth_std_dev: 0.001, // Default horizontal spread ~0.057 degrees
3780        }
3781    }
3782}
3783
3784// Monte Carlo results
3785#[derive(Debug, Clone)]
3786pub struct MonteCarloResults {
3787    pub ranges: Vec<f64>,
3788    pub impact_velocities: Vec<f64>,
3789    /// Deviations from the baseline point of aim at the target plane.
3790    ///
3791    /// A sample that falls short of the plane is encoded as
3792    /// `(0, TARGET_NOT_REACHED_SENTINEL_M, 0)` so it remains aligned with
3793    /// `ranges` and `impact_velocities` and still counts as a miss.
3794    pub impact_positions: Vec<Vector3<f64>>,
3795}
3796
3797/// Default hit-zone radius (meters) around the point of aim at the target plane — a 30 cm
3798/// circle. Shared by the CLI, FFI, and WASM so "hit probability" means the same thing everywhere.
3799pub const DEFAULT_HIT_RADIUS_M: f64 = 0.3;
3800
3801/// Vertical-position marker for a Monte Carlo sample that never reached the target plane.
3802///
3803/// The marker preserves the equal-length result-vector and C-ABI contract. Exclude marked
3804/// positions from target-plane dispersion statistics, but keep them in the denominator for hit
3805/// probability because they are definite misses.
3806pub const TARGET_NOT_REACHED_SENTINEL_M: f64 = -1.0e9;
3807
3808impl MonteCarloResults {
3809    /// Whether an encoded impact position represents a finite arrival at the target plane.
3810    pub fn position_reached_target(position: &Vector3<f64>) -> bool {
3811        position.iter().all(|component| component.is_finite())
3812            && position.y != TARGET_NOT_REACHED_SENTINEL_M
3813    }
3814
3815    /// Number of recorded simulations that reached the target plane.
3816    pub fn target_arrival_count(&self) -> usize {
3817        self.impact_positions
3818            .iter()
3819            .filter(|position| Self::position_reached_target(position))
3820            .count()
3821    }
3822
3823    /// Fraction of recorded simulations that fell short of (or otherwise failed to produce a
3824    /// finite position at) the target plane.
3825    pub fn target_shortfall_fraction(&self) -> f64 {
3826        if self.impact_positions.is_empty() {
3827            return 0.0;
3828        }
3829        (self.impact_positions.len() - self.target_arrival_count()) as f64
3830            / self.impact_positions.len() as f64
3831    }
3832
3833    /// Upper-median radial miss among samples that reached the target plane.
3834    ///
3835    /// This preserves the CLI's historical radial-to-baseline "CEP (approx)" convention while
3836    /// preventing the finite target-shortfall marker from becoming the median (MBA-1159).
3837    /// Returns `None` when no recorded simulation reached the target plane.
3838    pub fn target_plane_cep(&self) -> Option<f64> {
3839        let mut radial_misses: Vec<f64> = self
3840            .impact_positions
3841            .iter()
3842            .filter(|position| Self::position_reached_target(position))
3843            .map(Vector3::norm)
3844            .filter(|miss| miss.is_finite())
3845            .collect();
3846        radial_misses.sort_by(f64::total_cmp);
3847        if radial_misses.is_empty() {
3848            None
3849        } else {
3850            Some(radial_misses[radial_misses.len() / 2])
3851        }
3852    }
3853
3854    /// Fraction of simulations whose impact at the target plane lands within `hit_radius_m`
3855    /// of the point of aim. `impact_positions` are deviations from the baseline at the target
3856    /// plane (the downrange component is 0), so the vector norm is the radial miss distance.
3857    /// Samples that fall short of the target remain in the denominator and count as misses.
3858    /// Returns 0.0 when there are no samples.
3859    ///
3860    /// Single source of truth for hit probability — previously the CLI used a range-precision
3861    /// notion and the FFI a position notion with a redundant clause, so they disagreed.
3862    pub fn hit_probability(&self, hit_radius_m: f64) -> f64 {
3863        if self.impact_positions.is_empty() {
3864            return 0.0;
3865        }
3866        let hits = self
3867            .impact_positions
3868            .iter()
3869            .filter(|position| Self::position_is_hit(position, hit_radius_m))
3870            .count();
3871        hits as f64 / self.impact_positions.len() as f64
3872    }
3873
3874    /// Whether one encoded impact position is a hit inside `hit_radius_m` of the point of aim.
3875    ///
3876    /// The single source of truth for the hit predicate itself, as
3877    /// [`hit_probability`](Self::hit_probability) is for the ratio. Both that method and the
3878    /// adaptive driver ([`run_monte_carlo_adaptive_seeded`]) call this, so "hit" means the
3879    /// same thing whether it was counted over a retained result vector or streamed one trial
3880    /// at a time and then discarded.
3881    ///
3882    /// A sample that never reached the target plane is a definite miss, never a hit: the
3883    /// shortfall marker's norm is enormous, but the marker is excluded explicitly rather than
3884    /// left to depend on that.
3885    pub fn position_is_hit(position: &Vector3<f64>, hit_radius_m: f64) -> bool {
3886        Self::position_reached_target(position) && position.norm() < hit_radius_m
3887    }
3888
3889    /// Fixed-`n` Wilson companion to [`hit_probability`](Self::hit_probability): the same point
3890    /// estimate, plus a confidence interval for it and the `n` behind it.
3891    ///
3892    /// Returns `(p_hat, (ci_low, ci_high), n)`. This is a *composition* of two existing
3893    /// functions, not a second derivation of either: `p_hat` is
3894    /// [`hit_probability`](Self::hit_probability) called directly, and the bounds are
3895    /// [`wilson_interval`] over the hit count and `impact_positions.len()`. The denominator is
3896    /// therefore identical -- samples that fell short of the target plane are counted as
3897    /// misses in `n`, exactly as `hit_probability` counts them -- and the two can never drift
3898    /// apart under maintenance.
3899    ///
3900    /// # When this is the wrong interval
3901    ///
3902    /// A fixed-`n` interval is only valid if `n` was fixed *before* the data was seen. Use
3903    /// this for a run of a pre-declared `num_simulations`. If the sample count was instead
3904    /// chosen by watching the results -- stopping once the interval looked tight enough --
3905    /// this interval has no coverage guarantee at all; use [`run_monte_carlo_adaptive_seeded`],
3906    /// whose interval is anytime-valid, for that.
3907    ///
3908    /// With no samples the result is `(0.0, (0.0, 1.0), 0)`: the `0.0` that `hit_probability`
3909    /// reports, alongside the total-ignorance interval `wilson_interval` reports at `n == 0`.
3910    pub fn hit_probability_wilson(
3911        &self,
3912        hit_radius_m: f64,
3913        level: ConfidenceLevel,
3914    ) -> (f64, (f64, f64), u64) {
3915        let trials = self.impact_positions.len() as u64;
3916        let hits = self
3917            .impact_positions
3918            .iter()
3919            .filter(|position| Self::position_is_hit(position, hit_radius_m))
3920            .count() as u64;
3921        (
3922            self.hit_probability(hit_radius_m),
3923            wilson_interval(hits, trials, level),
3924            trials,
3925        )
3926    }
3927
3928    /// Fraction of simulations whose impact at the target plane lands within the axis-aligned
3929    /// rectangle `width_m` (lateral, Z) x `height_m` (vertical, Y) centered on the point of aim
3930    /// — i.e. within `width_m / 2` of center laterally AND `height_m / 2` of center vertically.
3931    ///
3932    /// This is the WEZ (Weapon Employment Zone, MBA-1317) counterpart of [`hit_probability`]'s
3933    /// circular radius for rectangular target sizes (e.g. an 18"x30" steel plate). Samples that
3934    /// fall short of the target plane remain in the denominator and count as misses, matching
3935    /// `hit_probability`'s convention. Returns 0.0 when there are no samples or when either
3936    /// dimension is non-positive.
3937    ///
3938    /// [`hit_probability`]: Self::hit_probability
3939    pub fn rect_hit_probability(&self, width_m: f64, height_m: f64) -> f64 {
3940        let dimensions_invalid = width_m.is_nan()
3941            || width_m <= 0.0
3942            || height_m.is_nan()
3943            || height_m <= 0.0;
3944        if self.impact_positions.is_empty() || dimensions_invalid {
3945            return 0.0;
3946        }
3947        let half_width = width_m / 2.0;
3948        let half_height = height_m / 2.0;
3949        let hits = self
3950            .impact_positions
3951            .iter()
3952            .filter(|position| {
3953                Self::position_reached_target(position)
3954                    && position.z.abs() <= half_width
3955                    && position.y.abs() <= half_height
3956            })
3957            .count();
3958        hits as f64 / self.impact_positions.len() as f64
3959    }
3960}
3961
3962fn wind_from_signed_speed_sample(
3963    signed_speed: f64,
3964    sampled_direction: f64,
3965    vertical_speed: f64,
3966) -> WindConditions {
3967    // The base wind's vertical component rides along un-dispersed: vertical wind is a
3968    // systematic input (MBA-728), not a sampled dispersion source. Dropping it here
3969    // would make every per-sample solve disagree with the baseline solve by the whole
3970    // vertical deflection — a phantom bias in the MC statistics.
3971    if signed_speed < 0.0 {
3972        WindConditions {
3973            speed: -signed_speed,
3974            direction: sampled_direction + std::f64::consts::PI,
3975            vertical_speed,
3976        }
3977    } else {
3978        WindConditions {
3979            speed: signed_speed,
3980            direction: sampled_direction,
3981            vertical_speed,
3982        }
3983    }
3984}
3985
3986struct MonteCarloWindSampler {
3987    speed: rand_distr::Normal<f64>,
3988    direction: rand_distr::Normal<f64>,
3989    /// Base wind's vertical component, carried into every sample un-dispersed.
3990    vertical_speed: f64,
3991}
3992
3993impl MonteCarloWindSampler {
3994    fn new(
3995        base_wind: &WindConditions,
3996        wind_speed_std_dev: f64,
3997        wind_direction_std_dev: f64,
3998    ) -> Result<Self, BallisticsError> {
3999        use rand_distr::Normal;
4000
4001        if !wind_direction_std_dev.is_finite() || wind_direction_std_dev < 0.0 {
4002            return Err("Wind direction standard deviation must be finite and non-negative".into());
4003        }
4004
4005        let speed = Normal::new(base_wind.speed, wind_speed_std_dev)
4006            .map_err(|e| format!("Invalid wind speed distribution: {e}"))?;
4007        let direction = Normal::new(base_wind.direction, wind_direction_std_dev)
4008            .map_err(|e| format!("Invalid wind direction distribution: {e}"))?;
4009        Ok(Self { speed, direction, vertical_speed: base_wind.vertical_speed })
4010    }
4011
4012    fn sample<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> WindConditions {
4013        use rand_distr::Distribution;
4014
4015        wind_from_signed_speed_sample(
4016            self.speed.sample(rng),
4017            self.direction.sample(rng),
4018            self.vertical_speed,
4019        )
4020    }
4021}
4022
4023/// One Monte Carlo trial's recorded outcome: the three quantities the legacy result vectors
4024/// hold, for one sample.
4025#[derive(Debug, Clone, Copy)]
4026struct TrialOutcome {
4027    /// Ground-impact range (m), recorded for every sample regardless of the target plane
4028    /// (MBA-967).
4029    range: f64,
4030    /// Ground-impact velocity (m/s), likewise recorded for every sample.
4031    impact_velocity: f64,
4032    /// Deviation from the baseline point of aim at the target plane, or
4033    /// `(0, TARGET_NOT_REACHED_SENTINEL_M, 0)` when this sample fell short of it.
4034    impact_position: Vector3<f64>,
4035}
4036
4037/// The per-trial context of a Monte Carlo run: the baseline solve, the resolved target plane
4038/// and the five input distributions, all built once and reused by every trial.
4039///
4040/// Extracted verbatim from the body of
4041/// [`run_monte_carlo_with_wind_and_direction_std_dev_using_rng`] so the adaptive driver
4042/// ([`run_monte_carlo_adaptive_seeded`]) runs the *identical* trial rather than a second copy
4043/// of it that could drift out of agreement.
4044///
4045/// # The draw order is a compatibility contract
4046///
4047/// [`Self::sample_one_trial`] consumes exactly six draws from the caller's RNG, in this order:
4048/// muzzle-velocity delta, muzzle angle, ballistic coefficient, azimuth, wind speed, wind
4049/// direction. Changing the count or the order shifts every subsequent sample of an
4050/// already-seeded run, so `monte_carlo_seeded_tests::legacy_seeded_estimates_are_pinned_bit_for_bit`
4051/// pins a committed seed's output bit-for-bit as the check on it.
4052///
4053/// The distributions are also *constructed* in the order the original inline code constructed
4054/// them. That is not cosmetic: construction is where an invalid standard deviation is
4055/// rejected, so the order decides which malformed parameter a caller is told about first.
4056struct MonteCarloTrialSampler {
4057    base_inputs: BallisticInputs,
4058    atmosphere: AtmosphericConditions,
4059    solver_max_range: f64,
4060    /// Resolved target plane: `params.target_distance` when the caller gave one, else the
4061    /// baseline solve's own max range.
4062    target_distance: f64,
4063    /// Baseline (undispersed) position at `target_distance`. Every trial's impact position is
4064    /// a deviation from this point.
4065    baseline_at_target: Vector3<f64>,
4066    velocity_delta_dist: rand_distr::Normal<f64>,
4067    angle_dist: rand_distr::Normal<f64>,
4068    bc_dist: rand_distr::Normal<f64>,
4069    wind_sampler: MonteCarloWindSampler,
4070    azimuth_dist: rand_distr::Normal<f64>,
4071}
4072
4073impl MonteCarloTrialSampler {
4074    /// Solves the baseline trajectory and builds the input distributions.
4075    ///
4076    /// Consumes no randomness -- every RNG draw happens in [`Self::sample_one_trial`].
4077    fn new(
4078        base_inputs: BallisticInputs,
4079        base_wind: &WindConditions,
4080        params: &MonteCarloParams,
4081        wind_direction_std_dev: f64,
4082    ) -> Result<Self, BallisticsError> {
4083        use rand_distr::Normal;
4084
4085        let atmosphere = AtmosphericConditions {
4086            temperature: base_inputs.temperature,
4087            pressure: base_inputs.pressure,
4088            humidity: base_inputs.humidity_percent(),
4089            altitude: base_inputs.altitude,
4090        };
4091        let target_hint = params
4092            .target_distance
4093            .unwrap_or(base_inputs.target_distance);
4094        let solver_max_range = target_hint.max(1000.0) * 2.0;
4095
4096        // First, calculate baseline trajectory with no variations
4097        let mut baseline_solver =
4098            TrajectorySolver::new(base_inputs.clone(), base_wind.clone(), atmosphere.clone());
4099        baseline_solver.set_max_range(solver_max_range);
4100        let baseline_result = baseline_solver.solve()?;
4101
4102        // Determine target distance: use explicit target or baseline max range
4103        let target_distance = params.target_distance.unwrap_or(baseline_result.max_range);
4104
4105        // Get baseline position at target distance (interpolated)
4106        let baseline_at_target = baseline_result
4107            .position_at_range(target_distance)
4108            .ok_or("Could not interpolate baseline at target distance")?;
4109
4110        // Create normal distributions for variations
4111        // Sample muzzle velocity as a DELTA and apply it after TrajectorySolver::new resolves the
4112        // powder-temperature model. Sampling an absolute value here let a powder curve overwrite
4113        // every draw in the constructor, collapsing the requested dispersion to zero (MBA-1176).
4114        let velocity_delta_dist = Normal::new(0.0, params.velocity_std_dev)
4115            .map_err(|e| format!("Invalid velocity distribution: {}", e))?;
4116        let angle_dist = Normal::new(base_inputs.muzzle_angle, params.angle_std_dev)
4117            .map_err(|e| format!("Invalid angle distribution: {}", e))?;
4118        let bc_dist = Normal::new(base_inputs.bc_value, params.bc_std_dev)
4119            .map_err(|e| format!("Invalid BC distribution: {}", e))?;
4120        // Direction uncertainty is an independent angular quantity in radians. Do not derive it from
4121        // wind-speed uncertainty: meters/second cannot supply an angular standard deviation.
4122        let wind_sampler = MonteCarloWindSampler::new(
4123            base_wind,
4124            params.wind_speed_std_dev,
4125            wind_direction_std_dev,
4126        )?;
4127        let azimuth_dist = Normal::new(base_inputs.azimuth_angle, params.azimuth_std_dev)
4128            .map_err(|e| format!("Invalid azimuth distribution: {}", e))?;
4129
4130        Ok(Self {
4131            base_inputs,
4132            atmosphere,
4133            solver_max_range,
4134            target_distance,
4135            baseline_at_target,
4136            velocity_delta_dist,
4137            angle_dist,
4138            bc_dist,
4139            wind_sampler,
4140            azimuth_dist,
4141        })
4142    }
4143
4144    /// Draws one trial: six RNG draws, one trajectory solve, one recorded outcome.
4145    ///
4146    /// `None` means the trial produced nothing to record -- either the solve failed, or it
4147    /// succeeded but the target plane could not be interpolated despite being within range (a
4148    /// defensive branch). Both were a bare `continue` in the original loop, i.e. the trial was
4149    /// dropped rather than counted as a miss, and callers must preserve that.
4150    ///
4151    /// All six draws happen *before* the solve, so a dropped trial still consumes exactly six
4152    /// draws and the RNG stream stays aligned with a run in which it succeeded.
4153    fn sample_one_trial<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> Option<TrialOutcome> {
4154        use rand_distr::Distribution;
4155
4156        // Create varied inputs
4157        let mut inputs = self.base_inputs.clone();
4158        let muzzle_velocity_delta = self.velocity_delta_dist.sample(&mut *rng);
4159        inputs.muzzle_angle = self.angle_dist.sample(&mut *rng);
4160        inputs.bc_value = self.bc_dist.sample(&mut *rng).max(0.01);
4161        inputs.azimuth_angle = self.azimuth_dist.sample(&mut *rng); // Add horizontal variation
4162
4163        // Create varied wind (now based on base wind conditions)
4164        let wind = self.wind_sampler.sample(&mut *rng);
4165
4166        // Run trajectory. The sampled velocity delta is applied to the SOLVER's inputs, after
4167        // TrajectorySolver::new has resolved any powder-temperature model -- see the MBA-1176
4168        // note on `velocity_delta_dist` above.
4169        let mut solver = TrajectorySolver::new(inputs, wind, self.atmosphere.clone());
4170        solver.inputs.muzzle_velocity =
4171            (solver.inputs.muzzle_velocity + muzzle_velocity_delta).max(0.0);
4172        solver.set_max_range(self.solver_max_range);
4173        // Skip failed simulations
4174        let result = solver.solve().ok()?;
4175
4176        // MBA-967: do NOT skip samples that fall short of the target. range/velocity are
4177        // recorded at GROUND IMPACT for EVERY sample, so "Mean Range" is the ground-impact
4178        // distribution — independent of target_distance and consistent with `trajectory`.
4179        // All three result vectors still grow together per sample, so the equal-length FFI
4180        // ABI (exposed under one count) is preserved.
4181        let impact_position = if result.max_range < self.target_distance {
4182            // This sample never reached the target plane -> definite miss. Keep the
4183            // encoded miss finite but far outside any practical target radius.
4184            Vector3::new(0.0, TARGET_NOT_REACHED_SENTINEL_M, 0.0)
4185        } else {
4186            // defensive: drop the whole sample (keeps the result vectors aligned)
4187            let pos_at_target = result.position_at_range(self.target_distance)?;
4188            // Deviation from baseline at the SAME target distance (McCoy): X = downrange
4189            // (0 here), Y = vertical (elevation), Z = lateral (windage). Muzzle-angle
4190            // sampling already models vertical pointing dispersion, so do not add a
4191            // second independent vertical pointing draw here.
4192            Vector3::new(
4193                0.0,
4194                pos_at_target.y - self.baseline_at_target.y,
4195                pos_at_target.z - self.baseline_at_target.z,
4196            )
4197        };
4198
4199        Some(TrialOutcome {
4200            range: result.max_range,
4201            impact_velocity: result.impact_velocity,
4202            impact_position,
4203        })
4204    }
4205}
4206
4207// Run Monte Carlo simulation (backwards compatibility)
4208pub fn run_monte_carlo(
4209    base_inputs: BallisticInputs,
4210    params: MonteCarloParams,
4211) -> Result<MonteCarloResults, BallisticsError> {
4212    run_monte_carlo_with_direction_std_dev(base_inputs, params, 0.0)
4213}
4214
4215/// Run Monte Carlo with an independent wind-direction standard deviation in radians.
4216///
4217/// The older [`run_monte_carlo`] entry point remains source compatible and delegates here with
4218/// zero direction uncertainty.
4219pub fn run_monte_carlo_with_direction_std_dev(
4220    base_inputs: BallisticInputs,
4221    params: MonteCarloParams,
4222    wind_direction_std_dev: f64,
4223) -> Result<MonteCarloResults, BallisticsError> {
4224    let base_wind = WindConditions {
4225        speed: params.base_wind_speed,
4226        direction: params.base_wind_direction,
4227        vertical_speed: 0.0,
4228    };
4229    run_monte_carlo_with_wind_and_direction_std_dev(
4230        base_inputs,
4231        base_wind,
4232        params,
4233        wind_direction_std_dev,
4234    )
4235}
4236
4237// Run Monte Carlo simulation with wind
4238pub fn run_monte_carlo_with_wind(
4239    base_inputs: BallisticInputs,
4240    base_wind: WindConditions,
4241    params: MonteCarloParams,
4242) -> Result<MonteCarloResults, BallisticsError> {
4243    run_monte_carlo_with_wind_and_direction_std_dev(base_inputs, base_wind, params, 0.0)
4244}
4245
4246/// Run Monte Carlo with explicit base wind and independent direction uncertainty in radians.
4247///
4248/// The older [`run_monte_carlo_with_wind`] entry point delegates here with zero direction
4249/// uncertainty, preserving its API while removing the former speed-to-angle unit conflation.
4250pub fn run_monte_carlo_with_wind_and_direction_std_dev(
4251    base_inputs: BallisticInputs,
4252    base_wind: WindConditions,
4253    params: MonteCarloParams,
4254    wind_direction_std_dev: f64,
4255) -> Result<MonteCarloResults, BallisticsError> {
4256    let mut rng = rand::rng();
4257    run_monte_carlo_with_wind_and_direction_std_dev_using_rng(
4258        base_inputs,
4259        base_wind,
4260        params,
4261        wind_direction_std_dev,
4262        &mut rng,
4263    )
4264}
4265
4266/// Run Monte Carlo with an explicit PRNG seed, for deterministic/reproducible output.
4267///
4268/// Otherwise identical to [`run_monte_carlo_with_wind_and_direction_std_dev`], which draws
4269/// from the process-global RNG instead. Intended for callers that need repeatable results
4270/// across runs — e.g. tests, or a WEZ (Weapon Employment Zone, MBA-1317) sweep that a caller
4271/// wants to reproduce exactly while tuning target size or wind-call error.
4272pub fn run_monte_carlo_with_wind_and_direction_std_dev_seeded(
4273    base_inputs: BallisticInputs,
4274    base_wind: WindConditions,
4275    params: MonteCarloParams,
4276    wind_direction_std_dev: f64,
4277    seed: u64,
4278) -> Result<MonteCarloResults, BallisticsError> {
4279    use rand::{rngs::StdRng, SeedableRng};
4280    let mut rng = StdRng::seed_from_u64(seed);
4281    run_monte_carlo_with_wind_and_direction_std_dev_using_rng(
4282        base_inputs,
4283        base_wind,
4284        params,
4285        wind_direction_std_dev,
4286        &mut rng,
4287    )
4288}
4289
4290fn run_monte_carlo_with_wind_and_direction_std_dev_using_rng<R: rand::Rng + ?Sized>(
4291    base_inputs: BallisticInputs,
4292    base_wind: WindConditions,
4293    params: MonteCarloParams,
4294    wind_direction_std_dev: f64,
4295    rng: &mut R,
4296) -> Result<MonteCarloResults, BallisticsError> {
4297    let mut ranges = Vec::new();
4298    let mut impact_velocities = Vec::new();
4299    let mut impact_positions = Vec::new();
4300
4301    let sampler = MonteCarloTrialSampler::new(
4302        base_inputs,
4303        &base_wind,
4304        &params,
4305        wind_direction_std_dev,
4306    )?;
4307
4308    for _ in 0..params.num_simulations {
4309        // A dropped trial pushes nothing at all, exactly as the original `continue` arms did,
4310        // so all three vectors stay equal-length (the FFI exposes them under one count) --
4311        // they are simply shorter than `num_simulations`.
4312        if let Some(outcome) = sampler.sample_one_trial(rng) {
4313            ranges.push(outcome.range);
4314            impact_velocities.push(outcome.impact_velocity);
4315            impact_positions.push(outcome.impact_position);
4316        }
4317    }
4318
4319    if ranges.is_empty() {
4320        return Err("No successful simulations".into());
4321    }
4322
4323    Ok(MonteCarloResults {
4324        ranges,
4325        impact_velocities,
4326        impact_positions,
4327    })
4328}
4329
4330/// Schema version of [`AdaptiveMcReportV1`]'s JSON wire form.
4331pub const MC_ADAPTIVE_SCHEMA_VERSION_V1: u32 = 1;
4332
4333/// The value [`AdaptiveMcReportV1::method`] always carries: Robbins' beta-binomial mixture
4334/// confidence sequence, revision 1.
4335///
4336/// Named so a consumer can branch on the estimator rather than on the schema version -- the
4337/// schema can gain fields without the statistics changing, and the statistics could be
4338/// replaced without the field set changing.
4339pub const MC_ADAPTIVE_METHOD_V1: &str = "anytime_beta_binomial_mixture_cs_v1";
4340
4341/// The four disclosures every [`AdaptiveMcReportV1`] carries, in order.
4342///
4343/// These are stated in the payload itself rather than only in this crate's documentation,
4344/// because the payload is what travels: a consumer that renders a hit probability and an
4345/// interval has everything it needs to over-claim, and these four sentences are what stop it.
4346/// In order they disclose (0) that the interval covers sampling error only, not model error;
4347/// (1) that stopping early is legitimate here specifically because the sequence is
4348/// anytime-valid; (2) that the input dispersions are independent normals with no modeled
4349/// correlation; and (3) how the continuous statistics were accumulated and which denominator
4350/// the hit probability uses.
4351///
4352/// Pinned per-index, full-string, by
4353/// `monte_carlo_seeded_tests::adaptive_report_carries_schema_method_and_all_four_assumptions`.
4354pub const MC_ADAPTIVE_ASSUMPTIONS_V1: [&str; 4] = [
4355    "Sampling uncertainty only: intervals cover Monte Carlo sampling error, not model error in the trajectory solver or its inputs.",
4356    "Anytime-valid stopping: the beta-binomial mixture confidence sequence keeps its coverage guarantee despite stopping the moment the target half-width is met.",
4357    "Input dispersions are the independent normal distributions declared in MonteCarloParams; correlations between inputs are not modeled.",
4358    "Continuous statistics are streaming Welford moments over trials that reached the target plane, reported with sample (n-1) standard deviations; hit probability's denominator includes all trials.",
4359];
4360
4361/// How precise the hit probability has to get, and how much sampling may be spent getting
4362/// there.
4363///
4364/// [`Default`] reproduces the legacy fixed-count run's sample size as the *floor*
4365/// (`min_samples: 1_000`, which is [`MonteCarloParams::default`]'s `num_simulations`) and then
4366/// keeps going, in batches, until the interval is tight enough or the ceiling is hit.
4367#[derive(Debug, Clone)]
4368pub struct McConvergence {
4369    /// Confidence level of the reported interval.
4370    pub level: ConfidenceLevel,
4371    /// Stop once the confidence sequence's half-width is at or below this, in probability
4372    /// units. `0.02` means "the hit probability is known to about +-2 percentage points".
4373    pub target_half_width: f64,
4374    /// Never stop before this many trials, even if the interval is already tight. Guards
4375    /// against an early run of all-hits or all-misses producing a narrow interval off a
4376    /// handful of trials.
4377    pub min_samples: u64,
4378    /// Never run more than this many trials, even if the interval is still wide. This is what
4379    /// bounds the wall time of an unreachable `target_half_width`.
4380    pub max_samples: u64,
4381    /// How many trials to run between convergence checks. Larger batches check less often (a
4382    /// `bounds()` call is two 200-step bisections); smaller batches can stop sooner.
4383    pub batch_size: u64,
4384}
4385
4386impl Default for McConvergence {
4387    fn default() -> Self {
4388        Self {
4389            level: ConfidenceLevel::P95,
4390            target_half_width: 0.02,
4391            min_samples: 1_000,
4392            max_samples: 100_000,
4393            batch_size: 500,
4394        }
4395    }
4396}
4397
4398impl McConvergence {
4399    /// Rejects a configuration that cannot produce a meaningful run, naming the offending
4400    /// field.
4401    ///
4402    /// Checked once up front rather than defended against inside the loop: a zero
4403    /// `batch_size` would spin forever making no progress, and a non-positive or `NaN`
4404    /// `target_half_width` can never be met, so both would surface as a hang or a silent
4405    /// max-samples cap instead of an error the caller can read. `NaN` is caught by the
4406    /// `is_finite` test -- `NaN <= 0.0` is `false`, so a bare comparison would let it through.
4407    pub fn validate(&self) -> Result<(), String> {
4408        if !self.target_half_width.is_finite() || self.target_half_width <= 0.0 {
4409            return Err(format!(
4410                "McConvergence.target_half_width must be a finite value greater than zero (got {})",
4411                self.target_half_width
4412            ));
4413        }
4414        if self.batch_size == 0 {
4415            return Err("McConvergence.batch_size must be greater than zero".to_string());
4416        }
4417        if self.max_samples == 0 {
4418            return Err("McConvergence.max_samples must be greater than zero".to_string());
4419        }
4420        if self.max_samples < self.min_samples {
4421            return Err(format!(
4422                "McConvergence.max_samples ({}) must be at least McConvergence.min_samples ({})",
4423                self.max_samples, self.min_samples
4424            ));
4425        }
4426        Ok(())
4427    }
4428}
4429
4430/// Why an adaptive run stopped.
4431#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
4432#[serde(rename_all = "snake_case")]
4433pub enum McStopReason {
4434    /// The confidence sequence reached [`McConvergence::target_half_width`]. The reported
4435    /// precision is the requested precision.
4436    TargetHalfWidthMet,
4437    /// [`McConvergence::max_samples`] was exhausted first. The interval is whatever that many
4438    /// trials bought -- read `ci_low`/`ci_high`, not just `hit_probability`.
4439    MaxSamplesReached,
4440}
4441
4442/// The result of a confidence-controlled Monte Carlo run.
4443///
4444/// Produced by [`run_monte_carlo_adaptive_seeded`]. Unlike [`MonteCarloResults`] this retains
4445/// no per-trial data at all: the continuous quantities arrive as streaming [`Welford`] moments
4446/// and the hit/miss counts as a running confidence sequence, so a 100,000-trial run costs the
4447/// same memory as a 1,000-trial one.
4448#[derive(Debug, Clone, serde::Serialize)]
4449pub struct AdaptiveMcReportV1 {
4450    /// Always [`MC_ADAPTIVE_SCHEMA_VERSION_V1`].
4451    pub schema_version: u32,
4452    /// Always [`MC_ADAPTIVE_METHOD_V1`].
4453    pub method: String,
4454    /// Always the four sentences of [`MC_ADAPTIVE_ASSUMPTIONS_V1`], in order.
4455    pub assumptions: Vec<String>,
4456    /// Confidence level of `ci_low`/`ci_high`, as a whole-number percentage.
4457    pub confidence_percent: u32,
4458    /// Point estimate `S / n`: hits over all trials, including trials that never reached the
4459    /// target plane.
4460    pub hit_probability: f64,
4461    /// Lower bound of the anytime-valid interval.
4462    pub ci_low: f64,
4463    /// Upper bound of the anytime-valid interval.
4464    pub ci_high: f64,
4465    /// Trials actually folded into the statistics (`n`).
4466    pub samples: u64,
4467    /// Trials *drawn*, including any the solver could not complete.
4468    ///
4469    /// `attempts - samples` is the drop count. It is normally zero, and equals `samples`
4470    /// whenever it is -- but without this field a run with a 40% solver-failure rate is
4471    /// indistinguishable in the payload from a clean one at the same `samples`, which is the
4472    /// one thing `samples` alone cannot tell you. `attempts` is also what
4473    /// [`McConvergence::max_samples`] caps, so [`McStopReason::MaxSamplesReached`] always has
4474    /// `attempts == max_samples` -- but the reverse does not hold: a
4475    /// [`McStopReason::TargetHalfWidthMet`] stop on the very last batch can reach the same
4476    /// equality, so `attempts == max_samples` alone does not identify the stop reason.
4477    pub attempts: u64,
4478    /// Trials that reached the target plane -- the population behind the three at-target
4479    /// statistics below, and the `n` in their `n-1` standard deviations.
4480    ///
4481    /// This is the magnitude behind the asymmetry `assumptions[3]` discloses qualitatively:
4482    /// `mean_drop_at_target_m`, `mean_wind_drift_at_target_m` and `mean_impact_velocity_mps`
4483    /// describe these `arrivals` trials, while `hit_probability` is over all `samples` (a
4484    /// trial that fell short is a definite miss, so it is in that denominator but has no
4485    /// measured position to contribute). With `arrivals` well below `samples`, the at-target
4486    /// statistics describe only part of the run and this field is what says so.
4487    ///
4488    /// The fixed-count path exposes the same information as
4489    /// [`MonteCarloResults::target_arrival_count`] and
4490    /// [`MonteCarloResults::target_shortfall_fraction`]; `samples - arrivals` is the shortfall
4491    /// count and `1 - arrivals / samples` the shortfall fraction.
4492    pub arrivals: u64,
4493    /// Why the run stopped. Serializes as `"target_half_width_met"` / `"max_samples_reached"`.
4494    pub stop_reason: McStopReason,
4495    /// Hit-zone radius the probability was computed against.
4496    pub hit_radius_m: f64,
4497    /// Resolved target plane: `params.target_distance` if given, else the baseline's max range.
4498    pub target_distance_m: f64,
4499    /// Mean ground-impact velocity over trials that reached the target plane.
4500    ///
4501    /// The velocity is the one the legacy path records: speed at *ground impact*, not at the
4502    /// target plane (MBA-967). Only the conditioning is on reaching the plane.
4503    pub mean_impact_velocity_mps: f64,
4504    /// Sample (`n-1`) standard deviation of the above. `0.0` for fewer than two such trials.
4505    pub std_impact_velocity_mps: f64,
4506    /// Mean *vertical deviation from the baseline point of aim* at the target plane, in
4507    /// meters, positive high.
4508    ///
4509    /// Named "drop" for continuity with the rest of the API, but it is a deviation from the
4510    /// undispersed baseline, not a drop from the bore line: with symmetric input dispersions
4511    /// its expectation is near zero and the informative number is
4512    /// [`std_drop_at_target_m`](Self::std_drop_at_target_m).
4513    pub mean_drop_at_target_m: f64,
4514    /// Sample (`n-1`) standard deviation of the vertical deviation -- the run's vertical
4515    /// dispersion at the target.
4516    pub std_drop_at_target_m: f64,
4517    /// Mean lateral deviation from the baseline point of aim at the target plane, in meters.
4518    /// The same "deviation, not absolute" caveat as `mean_drop_at_target_m` applies.
4519    pub mean_wind_drift_at_target_m: f64,
4520    /// Sample (`n-1`) standard deviation of the lateral deviation -- the run's horizontal
4521    /// dispersion at the target.
4522    pub std_wind_drift_at_target_m: f64,
4523}
4524
4525/// Runs a Monte Carlo hit-probability estimate that decides its own sample size, from an
4526/// explicit seed.
4527///
4528/// # What this buys over the fixed-count path
4529///
4530/// [`run_monte_carlo_with_wind_and_direction_std_dev_seeded`] runs exactly
4531/// `params.num_simulations` trials and reports a point estimate; whether that count was enough
4532/// is left to the caller to guess. This instead runs until the answer is as precise as the
4533/// caller asked for, and reports the achieved precision either way. **`params.num_simulations`
4534/// is ignored here** -- the sample count comes from `convergence`, and
4535/// [`McConvergence::min_samples`] defaults to the same `1_000` so the floor matches the legacy
4536/// default.
4537///
4538/// # Why the interval is anytime-valid
4539///
4540/// Stopping when the interval looks tight enough is optional stopping, and a fixed-`n`
4541/// interval (Wilson, Wald, anything) checked repeatedly that way has no coverage guarantee:
4542/// the error rate grows with the number of peeks. [`BernoulliConfidenceSequence`] is instead
4543/// valid at every `n` simultaneously, so a data-dependent stopping rule is legitimate. The
4544/// price is a strictly wider interval at any given `n` than the fixed-`n`
4545/// [`MonteCarloResults::hit_probability_wilson`] would report on the same counts. Paying it is
4546/// the point.
4547///
4548/// # The trial is the same trial
4549///
4550/// Each trial is `MonteCarloTrialSampler::sample_one_trial` (crate-internal), the same body
4551/// and the same six-draw sequence the legacy loop runs, and the hit test is
4552/// [`MonteCarloResults::position_is_hit`], the same predicate
4553/// [`MonteCarloResults::hit_probability`] counts with. A trial that never reached the target
4554/// plane is a definite miss and stays in the denominator, exactly as it does there. Wind
4555/// direction is not dispersed: [`MonteCarloParams`] has no direction-sigma field, so this
4556/// passes `0.0`, matching [`run_monte_carlo_with_wind`].
4557///
4558/// # Sample accounting
4559///
4560/// Trials are run in batches of [`McConvergence::batch_size`] (the last batch truncated so the
4561/// ceiling is never overshot), and the stopping rule is evaluated after each batch: stop with
4562/// [`McStopReason::TargetHalfWidthMet`] once at least `min_samples` trials are in *and* the
4563/// half-width is at or below `target_half_width`; stop with
4564/// [`McStopReason::MaxSamplesReached`] once `max_samples` trials have been attempted.
4565///
4566/// The report carries three cardinalities, and they are three different numbers:
4567///
4568/// * `attempts` -- trials drawn. This is what `max_samples` caps.
4569/// * `samples` -- trials that produced an outcome, i.e. the `n` behind `hit_probability` and
4570///   the confidence interval.
4571/// * `arrivals` -- trials that reached the target plane, i.e. the `n` behind the three
4572///   at-target statistics.
4573///
4574/// `attempts >= samples >= arrivals` always. A trial whose solve fails is dropped rather than
4575/// counted as a miss -- the legacy loop's behaviour, preserved so the two paths cannot
4576/// disagree about what a solver failure means -- but it still consumes an attempt, so it
4577/// shows up as `attempts > samples`. With no dropped trials the two are equal, which is the
4578/// normal case; when they differ, `samples` can finish below `min_samples`, and the honest
4579/// report of that is `MaxSamplesReached` with the smaller `n` and the correspondingly wider
4580/// interval. A trial that solved but fell short of the target plane is a definite miss: it is
4581/// a sample (in `hit_probability`'s denominator) but not an arrival, so it shows up as
4582/// `samples > arrivals`. A run in which *every* trial was dropped is an error, not a report.
4583///
4584/// # `hit_radius_m` is not validated
4585///
4586/// Every [`McConvergence`] field is `Err`-checked up front, but `hit_radius_m` itself is not:
4587/// a `NaN` or negative radius makes [`MonteCarloResults::position_is_hit`] false for every
4588/// trial, yielding `p = 0.0` with a tight interval and (usually) a
4589/// [`McStopReason::TargetHalfWidthMet`] stop rather than an error. This is deliberate, not an
4590/// oversight -- it matches [`MonteCarloResults::hit_probability`]'s equally lenient legacy
4591/// posture on the same input, so this path cannot diverge from the fixed-count one over how a
4592/// bad radius is treated.
4593///
4594/// # Errors
4595///
4596/// Returns `Err` if `convergence` is not usable ([`McConvergence::validate`], which names the
4597/// offending field), if the baseline solve or an input distribution is invalid, or if no trial
4598/// at all produced an outcome.
4599pub fn run_monte_carlo_adaptive_seeded(
4600    base_inputs: &BallisticInputs,
4601    base_wind: &WindConditions,
4602    params: &MonteCarloParams,
4603    convergence: &McConvergence,
4604    hit_radius_m: f64,
4605    seed: u64,
4606) -> Result<AdaptiveMcReportV1, String> {
4607    use rand::{rngs::StdRng, SeedableRng};
4608
4609    convergence.validate()?;
4610
4611    // `wind_direction_std_dev = 0.0`: MonteCarloParams carries no direction sigma, so this
4612    // matches `run_monte_carlo_with_wind`'s treatment rather than inventing one.
4613    let sampler = MonteCarloTrialSampler::new(base_inputs.clone(), base_wind, params, 0.0)
4614        .map_err(|e| e.to_string())?;
4615
4616    let mut rng = StdRng::seed_from_u64(seed);
4617    let mut hits_cs = BernoulliConfidenceSequence::new(convergence.level);
4618    let mut impact_velocity = Welford::new();
4619    let mut drop_at_target = Welford::new();
4620    let mut drift_at_target = Welford::new();
4621
4622    let mut attempts: u64 = 0;
4623    let mut stop_reason = McStopReason::MaxSamplesReached;
4624
4625    while attempts < convergence.max_samples {
4626        // Truncate the final batch so `max_samples` is a ceiling on attempts, not a threshold
4627        // the last batch may overshoot.
4628        let batch = convergence.batch_size.min(convergence.max_samples - attempts);
4629        let mut batch_hits: u64 = 0;
4630        let mut batch_trials: u64 = 0;
4631
4632        for _ in 0..batch {
4633            attempts += 1;
4634            let Some(outcome) = sampler.sample_one_trial(&mut rng) else {
4635                continue; // dropped trial: not a miss, not a sample (see the legacy loop)
4636            };
4637            batch_trials += 1;
4638            if MonteCarloResults::position_is_hit(&outcome.impact_position, hit_radius_m) {
4639                batch_hits += 1;
4640            }
4641            // Continuous statistics are conditioned on arrival: a shortfall marker is a
4642            // placeholder, not a measured position, and folding it in would drag the moments
4643            // toward TARGET_NOT_REACHED_SENTINEL_M. It still counts as a miss above.
4644            if MonteCarloResults::position_reached_target(&outcome.impact_position) {
4645                impact_velocity.push(outcome.impact_velocity);
4646                drop_at_target.push(outcome.impact_position.y);
4647                drift_at_target.push(outcome.impact_position.z);
4648            }
4649        }
4650
4651        hits_cs.update_batch(batch_hits, batch_trials);
4652
4653        if hits_cs.trials() >= convergence.min_samples
4654            && hits_cs.half_width() <= convergence.target_half_width
4655        {
4656            stop_reason = McStopReason::TargetHalfWidthMet;
4657            break;
4658        }
4659    }
4660
4661    let samples = hits_cs.trials();
4662    if samples == 0 {
4663        return Err("No successful simulations".to_string());
4664    }
4665    let (ci_low, ci_high) = hits_cs.bounds();
4666
4667    Ok(AdaptiveMcReportV1 {
4668        schema_version: MC_ADAPTIVE_SCHEMA_VERSION_V1,
4669        method: MC_ADAPTIVE_METHOD_V1.to_string(),
4670        assumptions: MC_ADAPTIVE_ASSUMPTIONS_V1
4671            .iter()
4672            .map(|s| s.to_string())
4673            .collect(),
4674        confidence_percent: convergence.level.as_percent(),
4675        hit_probability: hits_cs.successes() as f64 / samples as f64,
4676        ci_low,
4677        ci_high,
4678        samples,
4679        attempts,
4680        // All three at-target accumulators are fed under one guard, in one block, so their
4681        // counts are equal by construction; reading the population off one of them binds this
4682        // field to the actual Welford `n` rather than to a parallel counter that could drift.
4683        arrivals: drop_at_target.count(),
4684        stop_reason,
4685        hit_radius_m,
4686        target_distance_m: sampler.target_distance,
4687        mean_impact_velocity_mps: impact_velocity.mean(),
4688        std_impact_velocity_mps: impact_velocity.sample_std(),
4689        mean_drop_at_target_m: drop_at_target.mean(),
4690        std_drop_at_target_m: drop_at_target.sample_std(),
4691        mean_wind_drift_at_target_m: drift_at_target.mean(),
4692        std_wind_drift_at_target_m: drift_at_target.sample_std(),
4693    })
4694}
4695
4696// Calculate zero angle for a target
4697pub fn calculate_zero_angle(
4698    inputs: BallisticInputs,
4699    target_distance: f64,
4700    target_height: f64,
4701) -> Result<f64, BallisticsError> {
4702    calculate_zero_angle_with_conditions(
4703        inputs,
4704        target_distance,
4705        target_height,
4706        WindConditions::default(),
4707        AtmosphericConditions::default(),
4708    )
4709}
4710
4711pub fn calculate_zero_angle_with_conditions(
4712    inputs: BallisticInputs,
4713    target_distance: f64,
4714    target_height: f64,
4715    wind: WindConditions,
4716    atmosphere: AtmosphericConditions,
4717) -> Result<f64, BallisticsError> {
4718    let mut solver = TrajectorySolver::new(inputs, wind, atmosphere);
4719    solver.calculate_and_set_zero_angle(target_distance, target_height, ZeroTargetFrame::SightLine)
4720}
4721
4722/// [`calculate_zero_angle_with_conditions`] for a presence-aware caller that has already
4723/// resolved station temperature/pressure (MBA-1397; e.g. reduced a declared QNH via
4724/// [`crate::atmosphere::resolve_station_conditions_with_pressure_mode`]). Unlike the base
4725/// function, `atmosphere`'s temperature/pressure are trusted as-is and never re-interpreted
4726/// through the legacy default-sentinel heuristic.
4727pub fn calculate_zero_angle_with_resolved_conditions(
4728    inputs: BallisticInputs,
4729    target_distance: f64,
4730    target_height: f64,
4731    wind: WindConditions,
4732    atmosphere: AtmosphericConditions,
4733) -> Result<f64, BallisticsError> {
4734    let mut solver = TrajectorySolver::new_with_resolved_station_atmosphere(inputs, wind, atmosphere);
4735    solver.calculate_and_set_zero_angle(target_distance, target_height, ZeroTargetFrame::SightLine)
4736}
4737
4738/// Generous solve envelope for [`calculate_zero_range_from_angle_with_conditions`] /
4739/// [`calculate_zero_range_from_angle_with_resolved_conditions`] (MBA-1402): a "zero" bore angle
4740/// is a near-horizontal shot, so its far line-of-sight crossing sits well inside this even at
4741/// extended small-arms ranges. Double the engine's own default 1000 m solve envelope
4742/// ([`TrajectorySolver::new`]) rather than something scaled to an (unknown, being solved for)
4743/// target distance; `solve()` still stops at ground impact well before this in the typical
4744/// case, so the larger envelope costs effectively nothing.
4745pub const ZERO_RANGE_FROM_ANGLE_MAX_RANGE_M: f64 = 2000.0;
4746
4747/// Solve the zero RANGE(S) that a fixed bore angle produces. Runs the trajectory at
4748/// `zero_angle_rad` and returns BOTH line-of-sight crossings it finds, as
4749/// [`ZeroCrossings`] — a rifle sighted above the bore generally crosses a level line of
4750/// sight twice on a rising shot (near, ascending, close to the muzzle; far, descending past
4751/// the apex).
4752///
4753/// **This is NOT the exact inverse of [`calculate_zero_angle_with_conditions`].** A single
4754/// bore angle generally implies two valid zero distances (the classic 25/300-yard
4755/// battle-zero relationship is exactly this: one angle, two zeros), and
4756/// [`calculate_zero_angle_with_conditions`]'s own choice of root depends on which target
4757/// distance it was asked to solve for. Round-tripping a solved angle back through this
4758/// function recovers the ORIGINAL distance as one of the two returned crossings, not
4759/// necessarily as `far_m` specifically — for short/flat zeros the forward solver's answer is
4760/// often the NEAR crossing.
4761pub fn calculate_zero_range_from_angle_with_conditions(
4762    inputs: BallisticInputs,
4763    zero_angle_rad: f64,
4764    target_height: f64,
4765    wind: WindConditions,
4766    atmosphere: AtmosphericConditions,
4767) -> Result<ZeroCrossings, BallisticsError> {
4768    let mut solver = TrajectorySolver::new(inputs, wind, atmosphere);
4769    solver.set_max_range(ZERO_RANGE_FROM_ANGLE_MAX_RANGE_M);
4770    solver.find_zero_range(zero_angle_rad, target_height, ZeroTargetFrame::SightLine)
4771}
4772
4773/// [`calculate_zero_range_from_angle_with_conditions`] for a presence-aware caller that has
4774/// already resolved station temperature/pressure — same relationship as
4775/// [`calculate_zero_angle_with_resolved_conditions`] has to
4776/// [`calculate_zero_angle_with_conditions`] (MBA-1397 pattern). See that function's doc
4777/// comment for why this returns both crossings rather than a single "the" zero range.
4778pub fn calculate_zero_range_from_angle_with_resolved_conditions(
4779    inputs: BallisticInputs,
4780    zero_angle_rad: f64,
4781    target_height: f64,
4782    wind: WindConditions,
4783    atmosphere: AtmosphericConditions,
4784) -> Result<ZeroCrossings, BallisticsError> {
4785    let mut solver = TrajectorySolver::new_with_resolved_station_atmosphere(inputs, wind, atmosphere);
4786    solver.set_max_range(ZERO_RANGE_FROM_ANGLE_MAX_RANGE_M);
4787    solver.find_zero_range(zero_angle_rad, target_height, ZeroTargetFrame::SightLine)
4788}
4789
4790/// What a BC estimate is fit against.
4791#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4792pub enum BcFitMode {
4793    /// Data points are `(distance_m, drop_m)` — the classic drop-curve fit.
4794    Drop,
4795    /// Data points are `(distance_m, velocity_mps)` — a velocity-retention fit,
4796    /// which is immune to zero / sight-height / launch-angle error.
4797    Velocity,
4798}
4799
4800/// The result of a single BC fit (one drag model, one fit basis).
4801#[derive(Debug, Clone, Copy)]
4802pub struct BcEstimate {
4803    /// The estimated ballistic coefficient.
4804    pub bc: f64,
4805    /// RMS residual across the data points, in fit units (meters of drop, or m/s of speed).
4806    pub rms_error: f64,
4807    /// Which standard drag model this BC is referenced to.
4808    pub drag_model: DragModel,
4809    /// Whether the fit was against drop or velocity data.
4810    pub mode: BcFitMode,
4811    /// True if the best fit landed at the edge of the physical BC search range — i.e. the
4812    /// data did not pin down an interior optimum (too sparse/short-range, or wrong units /
4813    /// atmosphere / zero). The reported `bc` is then a floor/ceiling, not a real estimate.
4814    pub at_bound: bool,
4815}
4816
4817/// Interpolate the fitted quantity (drop in meters, or speed in m/s) at a downrange
4818/// distance from a solved trajectory. `None` if the trajectory never reaches `target_dist`.
4819///
4820/// `drop_offset` is subtracted-from convention: for `Drop` the returned value is
4821/// `drop_offset - y`. With `drop_offset = 0` this is bore-referenced drop (flat fire);
4822/// with `drop_offset = sight_height` and a zeroed trajectory it is drop below the
4823/// (horizontal) line of sight — i.e. dope-card drop.
4824fn fit_value_at(
4825    points: &[TrajectoryPoint],
4826    target_dist: f64,
4827    mode: BcFitMode,
4828    drop_offset: f64,
4829) -> Option<f64> {
4830    let val = |p: &TrajectoryPoint| match mode {
4831        BcFitMode::Drop => drop_offset - p.position.y,
4832        BcFitMode::Velocity => p.velocity_magnitude,
4833    };
4834    for i in 0..points.len() {
4835        if points[i].position.x >= target_dist {
4836            if i == 0 {
4837                return Some(val(&points[0]));
4838            }
4839            let p1 = &points[i - 1];
4840            let p2 = &points[i];
4841            let dx = p2.position.x - p1.position.x;
4842            if dx.abs() < 1e-9 {
4843                return Some(val(p2));
4844            }
4845            let t = (target_dist - p1.position.x) / dx;
4846            return Some(val(p1) + t * (val(p2) - val(p1)));
4847        }
4848    }
4849    None
4850}
4851
4852fn fit_residual_sse(
4853    trajectory: &[TrajectoryPoint],
4854    observations: &[(f64, f64)],
4855    mode: BcFitMode,
4856    drop_offset: f64,
4857) -> Option<f64> {
4858    if observations.is_empty() {
4859        return None;
4860    }
4861    let mut total = 0.0;
4862    for (target_dist, target_val) in observations {
4863        // Scores are comparable only when every candidate contains every residual term.
4864        // Reject a trajectory that terminates before even one observation (MBA-1178).
4865        let value = fit_value_at(trajectory, *target_dist, mode, drop_offset)?;
4866        let error = value - target_val;
4867        total += error * error;
4868    }
4869    Some(total)
4870}
4871
4872/// Estimate a BC by fitting a simulated trajectory to measured data, for a chosen drag
4873/// model (G1, G7, …) and fit basis (drop or velocity). Uses a coarse 0.01 sweep over
4874/// plausible BCs followed by a 0.001 local refine around the coarse best.
4875///
4876/// `points` are `(distance_m, value_m_or_mps)` where the second element is drop in meters
4877/// (`BcFitMode::Drop`) or remaining speed in m/s (`BcFitMode::Velocity`).
4878///
4879/// The fit runs under `atmosphere` — BC is only meaningful relative to the air density the
4880/// data was measured at, so this must match the conditions the drop/velocity came from
4881/// (pass ICAO standard for a standard-atmosphere dope card).
4882///
4883/// `zero_range` selects the drop reference frame (ignored for velocity fits):
4884/// - `None` → **bore-referenced**: flat 0° fire, drop below the extended bore axis.
4885/// - `Some(range_m)` → **sight/dope-card-referenced**: the trajectory is zeroed at
4886///   `range_m` (using `sight_height`), and drop is measured below the horizontal line of
4887///   sight — i.e. exactly what a dope card zeroed at that range prints.
4888#[allow(clippy::too_many_arguments)] // Public compatibility API; grouping would be breaking.
4889pub fn estimate_bc_fit(
4890    velocity: f64,
4891    mass: f64,
4892    diameter: f64,
4893    points: &[(f64, f64)],
4894    drag_model: DragModel,
4895    mode: BcFitMode,
4896    atmosphere: AtmosphericConditions,
4897    zero_range: Option<f64>,
4898    sight_height: f64,
4899) -> Result<BcEstimate, BallisticsError> {
4900    if points.is_empty() {
4901        return Err(BallisticsError::from(
4902            "No data points provided for BC estimation.".to_string(),
4903        ));
4904    }
4905    let max_dist = points.iter().map(|(d, _)| *d).fold(0.0_f64, f64::max);
4906    // For a zeroed drop fit, drop is below the horizontal LOS which sits `sight_height`
4907    // above the bore at the muzzle: drop = sight_height - y. Bore-referenced fits use 0.
4908    let drop_offset = if zero_range.is_some() { sight_height } else { 0.0 };
4909
4910    // Sum of squared residuals for a trial BC; None unless the solve reaches ALL data points.
4911    let sse = |bc_value: f64| -> Option<f64> {
4912        let mut inputs = BallisticInputs {
4913            muzzle_velocity: velocity,
4914            bc_value,
4915            bc_type: drag_model,
4916            bullet_mass: mass,
4917            bullet_diameter: diameter,
4918            sight_height,
4919            ..Default::default()
4920        };
4921        // Zeroed fit: tilt the bore so the bullet crosses LOS at the zero range, so the
4922        // downrange drops match a dope card zeroed there. Bore fit leaves muzzle_angle = 0.
4923        if let Some(zr) = zero_range {
4924            // MBA-1130: zero to the LINE OF SIGHT (y = sight_height) at the zero range,
4925            // not the bore line (y = 0). Drop is measured as `drop_offset - y` with
4926            // drop_offset = sight_height, so a bore-referenced zero left drop != 0 at the
4927            // zero range and the drop-fit no longer round-tripped to the true BC. This
4928            // matches how range-table / come-up / dope-card generation zero.
4929            let za = calculate_zero_angle_with_conditions(
4930                inputs.clone(),
4931                zr,
4932                sight_height,
4933                WindConditions::default(),
4934                atmosphere.clone(),
4935            )
4936            .ok()?;
4937            inputs.muzzle_angle = za;
4938        }
4939        let mut solver =
4940            TrajectorySolver::new(inputs, WindConditions::default(), atmosphere.clone());
4941        solver.set_max_range(max_dist * 1.5);
4942        let result = solver.solve().ok()?;
4943        fit_residual_sse(&result.points, points, mode, drop_offset)
4944    };
4945
4946    // Physical BC search range, per drag model. Real G7 BCs top out well under 0.5 (0.7 is
4947    // a generous ceiling); G1 BCs run higher. Keeping G7 out of G1 territory means a fit
4948    // that runs to the ceiling reports a sane bound, not a nonsensical 1.2.
4949    let (bc_min, bc_max) = match drag_model {
4950        DragModel::G7 => (0.05, 0.70),
4951        _ => (0.10, 1.20),
4952    };
4953
4954    // Coarse sweep across the physical range.
4955    let mut best_bc = f64::NAN;
4956    let mut best_sse = f64::MAX;
4957    let mut bc = bc_min;
4958    while bc <= bc_max + 1e-9 {
4959        if let Some(s) = sse(bc) {
4960            if s < best_sse {
4961                best_sse = s;
4962                best_bc = bc;
4963            }
4964        }
4965        bc += 0.01;
4966    }
4967    if !best_bc.is_finite() {
4968        return Err(BallisticsError::from(
4969            "Unable to estimate BC from provided data. Check that the values and units are correct."
4970                .to_string(),
4971        ));
4972    }
4973
4974    // Local refine at 0.001 resolution around the coarse best (kept within the range).
4975    let lo = (best_bc - 0.01).max(bc_min);
4976    let hi = (best_bc + 0.01).min(bc_max);
4977    let mut bc = lo;
4978    while bc <= hi + 1e-9 {
4979        if let Some(s) = sse(bc) {
4980            if s < best_sse {
4981                best_sse = s;
4982                best_bc = bc;
4983            }
4984        }
4985        bc += 0.001;
4986    }
4987
4988    // A solution sitting on the search boundary means the data didn't determine an interior
4989    // optimum — the fit ran to the floor/ceiling. Flag it so callers don't trust the number.
4990    let at_bound = best_bc <= bc_min + 0.011 || best_bc >= bc_max - 0.011;
4991    // fit_residual_sse rejects partial trajectories, so best_sse contains exactly one residual
4992    // per input point and this denominator is also the honest matched-point count.
4993    let rms_error = (best_sse / points.len() as f64).sqrt();
4994    Ok(BcEstimate {
4995        bc: best_bc,
4996        rms_error,
4997        drag_model,
4998        mode,
4999        at_bound,
5000    })
5001}
5002
5003/// Estimate a G1 BC from a drop curve. Back-compatible wrapper over [`estimate_bc_fit`];
5004/// `points` are `(distance_m, drop_m)`.
5005pub fn estimate_bc_from_trajectory(
5006    velocity: f64,
5007    mass: f64,
5008    diameter: f64,
5009    points: &[(f64, f64)], // (distance, drop) pairs
5010) -> Result<f64, BallisticsError> {
5011    estimate_bc_fit(
5012        velocity,
5013        mass,
5014        diameter,
5015        points,
5016        DragModel::G1,
5017        BcFitMode::Drop,
5018        AtmosphericConditions::default(),
5019        None,
5020        0.05,
5021    )
5022    .map(|e| e.bc)
5023}
5024
5025// Add rand dependencies for Monte Carlo
5026use rand;
5027use rand_distr;
5028
5029#[cfg(test)]
5030mod mba737_powder_resolution_tests {
5031    use super::*;
5032
5033    #[test]
5034    fn linear_model_cold_powder_subtracts() {
5035        // 0.5486 m/s per degC (1 fps/degF), shot day 10 C below the 21.1 C reference.
5036        let v = resolve_powder_adjusted_velocity(823.0, 11.1, true, 0.5486, 21.1, None, None);
5037        assert!((v - (823.0 + 0.5486 * (11.1 - 21.1))).abs() < 1e-12);
5038        assert!(v < 823.0);
5039    }
5040
5041    #[test]
5042    fn linear_model_hot_powder_adds() {
5043        let v = resolve_powder_adjusted_velocity(823.0, 31.1, true, 0.5486, 21.1, None, None);
5044        assert!((v - (823.0 + 0.5486 * 10.0)).abs() < 1e-12);
5045    }
5046
5047    #[test]
5048    fn disabled_flag_is_passthrough() {
5049        let v = resolve_powder_adjusted_velocity(823.0, 40.0, false, 0.5486, 21.1, None, None);
5050        assert_eq!(v, 823.0);
5051    }
5052
5053    #[test]
5054    fn curve_overrides_linear_and_interpolates_at_powder_temp() {
5055        let curve = [(4.4, 798.6), (21.1, 823.0), (37.8, 841.2)];
5056        // Explicit powder temp decouples from ambient: interpolate at 4.4 C, not 30 C.
5057        let v = resolve_powder_adjusted_velocity(823.0, 30.0, true, 99.0, 21.1, Some(&curve), Some(4.4));
5058        assert!((v - 798.6).abs() < 1e-9);
5059    }
5060
5061    #[test]
5062    fn curve_falls_back_to_ambient_and_clamps() {
5063        let curve = [(4.4, 798.6), (37.8, 841.2)];
5064        // Ambient far below the coldest measured point: clamp, no extrapolation.
5065        let v = resolve_powder_adjusted_velocity(823.0, -40.0, true, 1.0, 21.1, Some(&curve), None);
5066        assert!((v - 798.6).abs() < 1e-9);
5067        let v_hot = resolve_powder_adjusted_velocity(823.0, 60.0, true, 1.0, 21.1, Some(&curve), None);
5068        assert!((v_hot - 841.2).abs() < 1e-9);
5069    }
5070
5071    #[test]
5072    fn empty_curve_suppresses_linear_fallback() {
5073        // Historical `else if` semantics: Some-but-empty curve means NO adjustment.
5074        let v = resolve_powder_adjusted_velocity(823.0, 40.0, true, 0.5486, 21.1, Some(&[]), None);
5075        assert_eq!(v, 823.0);
5076    }
5077
5078    #[test]
5079    fn sweep_huge_range_errors_instead_of_overflowing() {
5080        // Review finding: the old count math saturated the usize cast and the +1
5081        // panicked (debug) or wrapped to zero rows (release), bypassing the cap.
5082        assert!(parse_powder_sweep("0:1e20:1").is_err());
5083        assert!(parse_powder_sweep("0:1e308:1e-3").is_err());
5084    }
5085
5086    #[test]
5087    fn sweep_fractional_step_keeps_end_row() {
5088        // 0.3/0.1 floats to 2.9999999999999996; the END row must survive the floor.
5089        let rows = parse_powder_sweep("0:0.3:0.1").unwrap();
5090        assert_eq!(rows.len(), 4);
5091        assert!((rows[3] - 0.3).abs() < 1e-9);
5092    }
5093
5094    #[test]
5095    fn solver_and_helper_agree_on_linear_model() {
5096        // The solve() seam must fly exactly what the helper reports (MBA-737 contract).
5097        let inputs = BallisticInputs {
5098            use_powder_sensitivity: true,
5099            powder_temp_sensitivity: 0.5486,
5100            powder_temp: 21.1,
5101            temperature: 4.4,
5102            ..Default::default()
5103        };
5104        let expected = resolve_powder_adjusted_velocity(
5105            inputs.muzzle_velocity,
5106            inputs.temperature,
5107            true,
5108            0.5486,
5109            21.1,
5110            None,
5111            None,
5112        );
5113        let solver = TrajectorySolver::new(
5114            inputs,
5115            WindConditions::default(),
5116            AtmosphericConditions::default(),
5117        );
5118        assert!((solver.inputs.muzzle_velocity - expected).abs() < 1e-12);
5119    }
5120}
5121
5122#[cfg(test)]
5123mod mba1302_solver_seam_tests {
5124    use super::*;
5125    use crate::wind::WindSegment;
5126
5127    #[test]
5128    fn authoritative_station_atmosphere_preserves_explicit_standard_values_at_altitude() {
5129        let atmosphere = AtmosphericConditions {
5130            temperature: 15.0,
5131            pressure: 1013.25,
5132            humidity: 50.0,
5133            altitude: 2_000.0,
5134        };
5135        let legacy = TrajectorySolver::new(
5136            BallisticInputs::default(),
5137            WindConditions::default(),
5138            atmosphere.clone(),
5139        );
5140        let authoritative = TrajectorySolver::new_with_resolved_station_atmosphere(
5141            BallisticInputs::default(),
5142            WindConditions::default(),
5143            atmosphere,
5144        );
5145
5146        let (legacy_density, _, legacy_temp_c, legacy_pressure_hpa) = legacy.resolved_atmosphere();
5147        let (authoritative_density, _, authoritative_temp_c, authoritative_pressure_hpa) =
5148            authoritative.resolved_atmosphere();
5149        let (icao_temp_k, icao_pressure_pa) =
5150            crate::atmosphere::calculate_icao_standard_atmosphere(2_000.0);
5151        let (expected_authoritative_density, _) =
5152            crate::atmosphere::calculate_atmosphere(2_000.0, Some(15.0), Some(1013.25), 50.0);
5153
5154        assert!((legacy_temp_c - (icao_temp_k - 273.15)).abs() < 1e-12);
5155        assert!((legacy_pressure_hpa - icao_pressure_pa / 100.0).abs() < 1e-12);
5156        assert_eq!(authoritative_temp_c.to_bits(), 15.0_f64.to_bits());
5157        assert_eq!(authoritative_pressure_hpa.to_bits(), 1013.25_f64.to_bits());
5158        assert_eq!(
5159            authoritative_density.to_bits(),
5160            expected_authoritative_density.to_bits()
5161        );
5162        assert!(
5163            (authoritative_density - legacy_density).abs() > 0.1,
5164            "explicit standard values at altitude must differ from ICAO-at-altitude: explicit={authoritative_density}, ICAO={legacy_density}"
5165        );
5166    }
5167
5168    /// MBA-1397: the CLI/WASM `--pressure-type` mechanism precomputes station conditions via
5169    /// `atmosphere::resolve_station_conditions_with_pressure_mode` and constructs the solver
5170    /// with `new_with_resolved_station_atmosphere` UNCONDITIONALLY (not only for `Qnh`), to
5171    /// avoid re-deriving through the legacy sentinel a second time. This must be bit-for-bit
5172    /// equivalent to the historical `TrajectorySolver::new` (LegacyDefaultSentinels) path for
5173    /// every NON-ambiguous input -- i.e. for `PressureReferenceMode::Absolute`, precomputing
5174    /// and using the Authoritative constructor must reproduce `TrajectorySolver::new` exactly,
5175    /// which is the bit-level guarantee the CLI/WASM byte-identical-output tests rely on.
5176    #[test]
5177    fn precomputed_absolute_resolution_via_authoritative_matches_legacy_new() {
5178        for (temperature, pressure, altitude) in [
5179            (15.0, 1013.25, 0.0),   // sea-level default
5180            (15.0, 1013.25, 2000.0), // sentinel: omitted-pressure-at-altitude
5181            (-5.0, 850.0, 2000.0),  // explicit non-default station values
5182            (22.0, 950.0, 500.0),
5183        ] {
5184            let atmosphere = AtmosphericConditions {
5185                temperature,
5186                pressure,
5187                humidity: 50.0,
5188                altitude,
5189            };
5190            let legacy = TrajectorySolver::new(
5191                BallisticInputs::default(),
5192                WindConditions::default(),
5193                atmosphere.clone(),
5194            );
5195
5196            let (resolved_temp_c, resolved_pressure_hpa) =
5197                crate::atmosphere::resolve_station_conditions_with_pressure_mode(
5198                    temperature,
5199                    pressure,
5200                    altitude,
5201                    crate::atmosphere::PressureReferenceMode::Absolute,
5202                );
5203            let precomputed_atmosphere = AtmosphericConditions {
5204                temperature: resolved_temp_c,
5205                pressure: resolved_pressure_hpa,
5206                humidity: 50.0,
5207                altitude,
5208            };
5209            let precomputed = TrajectorySolver::new_with_resolved_station_atmosphere(
5210                BallisticInputs::default(),
5211                WindConditions::default(),
5212                precomputed_atmosphere,
5213            );
5214
5215            let (legacy_density, legacy_sos, legacy_temp_c, legacy_pressure_hpa) =
5216                legacy.resolved_atmosphere();
5217            let (pre_density, pre_sos, pre_temp_c, pre_pressure_hpa) =
5218                precomputed.resolved_atmosphere();
5219
5220            assert_eq!(
5221                legacy_temp_c.to_bits(),
5222                pre_temp_c.to_bits(),
5223                "temperature=({temperature}, {pressure}, {altitude})"
5224            );
5225            assert_eq!(
5226                legacy_pressure_hpa.to_bits(),
5227                pre_pressure_hpa.to_bits(),
5228                "pressure=({temperature}, {pressure}, {altitude})"
5229            );
5230            assert_eq!(legacy_density.to_bits(), pre_density.to_bits());
5231            assert_eq!(legacy_sos.to_bits(), pre_sos.to_bits());
5232        }
5233    }
5234
5235    fn configured_euler_zero(vertical_wind_mps: f64, time_step_s: f64) -> TrajectorySolver {
5236        let inputs = BallisticInputs {
5237            muzzle_velocity: 800.0,
5238            bc_value: 0.5,
5239            bc_type: DragModel::G7,
5240            bullet_mass: 0.0109,
5241            bullet_diameter: 0.00782,
5242            bullet_length: 0.0309,
5243            sight_height: 0.05,
5244            ground_threshold: -100.0,
5245            use_rk4: false,
5246            use_adaptive_rk45: false,
5247            ..BallisticInputs::default()
5248        };
5249        let mut solver = TrajectorySolver::new_with_resolved_station_atmosphere(
5250            inputs,
5251            WindConditions::default(),
5252            AtmosphericConditions::default(),
5253        );
5254        solver.set_max_range(300.0);
5255        solver.set_time_step(time_step_s);
5256        if vertical_wind_mps != 0.0 {
5257            solver.set_wind_segments(vec![WindSegment {
5258                speed_kmh: 0.0,
5259                angle_deg: 0.0,
5260                until_m: 400.0,
5261                vertical_mps: vertical_wind_mps,
5262            }]);
5263        }
5264        solver
5265    }
5266
5267    #[test]
5268    fn inclined_shot_zeroes_like_a_level_rifle() {
5269        // MBA-1412: since MBA-1302, zero_trial_height_at converted trial heights into the
5270        // gravity frame (shot_frame_altitude adds d*sin(shooting_angle) ~ 9 m at 5.71deg /
5271        // 100 yd) while find_zero_angle compared against a sight-frame target height, so ANY
5272        // inclined shot failed to bracket. A zero is a property of a level rifle's sight
5273        // geometry (same doctrine as MBA-1286's cant handling): the trial must solve level.
5274        const ZERO_DISTANCE_M: f64 = 91.44; // 100 yd
5275        const SIGHT_HEIGHT_M: f64 = 0.0381; // 1.5 in
5276
5277        let inputs = BallisticInputs {
5278            bc_value: 0.5,
5279            bullet_mass: 150.0 * 0.06479891 / 1000.0,
5280            muzzle_velocity: 2700.0 * 0.3048,
5281            sight_height: SIGHT_HEIGHT_M,
5282            ..Default::default()
5283        };
5284
5285        let mut level = inputs.clone();
5286        level.shooting_angle = 0.0;
5287        let level_angle = TrajectorySolver::new(level, Default::default(), Default::default())
5288            .find_zero_angle(ZERO_DISTANCE_M, SIGHT_HEIGHT_M, ZeroTargetFrame::SightLine)
5289            .expect("level zero must solve");
5290
5291        let mut inclined = inputs;
5292        inclined.shooting_angle = 5.71_f64.to_radians();
5293        let inclined_angle =
5294            TrajectorySolver::new(inclined, Default::default(), Default::default())
5295                .find_zero_angle(ZERO_DISTANCE_M, SIGHT_HEIGHT_M, ZeroTargetFrame::SightLine)
5296                .expect("MBA-1412: a 5.71 deg incline at a 100 yd zero must be solvable");
5297
5298        assert!(
5299            (inclined_angle - level_angle).abs() < 1e-9,
5300            "zeroing is level-rifle sight geometry; incline must not move the solved zero: \
5301             level={level_angle}, inclined={inclined_angle}"
5302        );
5303    }
5304
5305    #[test]
5306    fn configured_zero_keeps_segments_method_and_time_step_then_sets_base_angle() {
5307        const TARGET_DISTANCE_M: f64 = 150.0;
5308        const TARGET_HEIGHT_M: f64 = 0.05;
5309
5310        // A deliberately coarse Euler step makes an accidental reset to the historical 1 ms
5311        // zeroing step observable, while remaining stable and physically meaningful.
5312        let mut segmented = configured_euler_zero(-10.0, 0.02);
5313        let coarse_height = segmented
5314            .zero_trial_height_at(0.0, TARGET_DISTANCE_M, ZeroTargetFrame::SightLine)
5315            .expect("coarse configured trial")
5316            .expect("coarse trial reaches target");
5317        let mut fine = segmented.clone();
5318        fine.set_time_step(0.001);
5319        let fine_height = fine
5320            .zero_trial_height_at(0.0, TARGET_DISTANCE_M, ZeroTargetFrame::SightLine)
5321            .expect("fine configured trial")
5322            .expect("fine trial reaches target");
5323        assert!(
5324            (coarse_height - fine_height).abs() > 1e-5,
5325            "configured Euler step must affect zero trials: coarse={coarse_height}, fine={fine_height}"
5326        );
5327
5328        let segmented_angle = segmented
5329            .calculate_and_set_zero_angle(TARGET_DISTANCE_M, TARGET_HEIGHT_M, ZeroTargetFrame::SightLine)
5330            .expect("segmented zero");
5331        assert_eq!(
5332            segmented.inputs.muzzle_angle.to_bits(),
5333            segmented_angle.to_bits(),
5334            "successful zero must install its angle on the configured solver"
5335        );
5336        assert_eq!(segmented.time_step.to_bits(), 0.02_f64.to_bits());
5337        assert_eq!(segmented.max_range.to_bits(), 300.0_f64.to_bits());
5338        assert!(segmented.wind_sock.is_some());
5339        assert_eq!(
5340            segmented.station_atmosphere_resolution,
5341            StationAtmosphereResolution::Authoritative
5342        );
5343        let zero_height = segmented
5344            .zero_trial_height_at(segmented_angle, TARGET_DISTANCE_M, ZeroTargetFrame::SightLine)
5345            .expect("verify segmented zero")
5346            .expect("zeroed trial reaches target");
5347        assert!(
5348            (zero_height - TARGET_HEIGHT_M).abs() < 0.0001,
5349            "configured zero missed target: height={zero_height}"
5350        );
5351
5352        let mut calm = configured_euler_zero(0.0, 0.02);
5353        let calm_angle = calm
5354            .calculate_and_set_zero_angle(TARGET_DISTANCE_M, TARGET_HEIGHT_M, ZeroTargetFrame::SightLine)
5355            .expect("calm zero");
5356        assert!(
5357            (segmented_angle - calm_angle).abs() > 1e-5,
5358            "segmented vertical wind must participate in zero trials: segmented={segmented_angle}, calm={calm_angle}"
5359        );
5360    }
5361}
5362
5363#[cfg(test)]
5364mod result_sanity_tests {
5365    use super::*;
5366
5367    fn default_solver() -> TrajectorySolver {
5368        TrajectorySolver::new(
5369            BallisticInputs::default(),
5370            WindConditions::default(),
5371            AtmosphericConditions::default(),
5372        )
5373    }
5374
5375    fn minimal_result() -> TrajectoryResult {
5376        TrajectoryResult {
5377            max_range: 100.0,
5378            max_height: 1.0,
5379            time_of_flight: 0.5,
5380            impact_velocity: 700.0,
5381            impact_energy: 2450.0,
5382            projectile_mass_kg: 0.01,
5383            line_of_sight_height_m: 1.5,
5384            station_speed_of_sound_mps: 340.0,
5385            termination: TrajectoryTermination::MaxRange,
5386            points: vec![],
5387            sampled_points: None,
5388            min_pitch_damping: None,
5389            transonic_mach: None,
5390            angular_state: None,
5391            max_yaw_angle: None,
5392            max_precession_angle: None,
5393            aerodynamic_jump: None,
5394            mach_1_2_distance_m: None,
5395            mach_1_0_distance_m: None,
5396            mach_0_9_distance_m: None,
5397        }
5398    }
5399
5400    #[test]
5401    fn mba1293_negative_scalars_fail_the_result_postcondition() {
5402        let solver = default_solver();
5403        solver
5404            .validate_result_sanity(&minimal_result())
5405            .expect("a sane result must pass");
5406
5407        for (name, mutate) in [
5408            ("max_range", (|r| r.max_range = -50.588) as fn(&mut TrajectoryResult)),
5409            ("time_of_flight", |r| r.time_of_flight = -1.0),
5410            ("impact_velocity", |r| r.impact_velocity = -700.0),
5411            ("impact_energy", |r| r.impact_energy = -1.0),
5412        ] {
5413            let mut result = minimal_result();
5414            mutate(&mut result);
5415            let error = solver
5416                .validate_result_sanity(&result)
5417                .expect_err("negative scalar must fail");
5418            assert!(
5419                error.to_string().contains(name),
5420                "error for {name} did not name the field: {error}"
5421            );
5422        }
5423    }
5424
5425    #[test]
5426    fn mba1293_speed_budget_bounds_legitimate_states_and_rejects_divergence() {
5427        let solver = default_solver();
5428        let mv = solver.inputs.muzzle_velocity;
5429
5430        // A state at muzzle speed is always inside the budget.
5431        let position = Vector3::new(10.0, 0.0, 0.0);
5432        solver
5433            .validate_integration_state(&position, &Vector3::new(mv, 0.0, 0.0), 0.01)
5434            .expect("muzzle-speed state must pass");
5435
5436        // The MBA-1293 explosion (13x the muzzle speed) must be rejected as divergence.
5437        let error = solver
5438            .validate_integration_state(&position, &Vector3::new(-13.0 * mv, 0.0, 0.0), 0.01)
5439            .expect_err("13x muzzle speed must fail the budget");
5440        assert!(error.to_string().contains("diverged"), "{error}");
5441
5442        // The budget grows with gravity's g*t so long lobbed arcs never trip it.
5443        let after_fall = mv + crate::constants::G_ACCEL_MPS2 * 60.0;
5444        solver
5445            .validate_integration_state(&position, &Vector3::new(0.0, -after_fall, 0.0), 60.0)
5446            .expect("gravity-accelerated speed within g*t must pass");
5447    }
5448}
5449
5450#[cfg(test)]
5451mod trajectory_point_budget_tests {
5452    use super::*;
5453    use crate::MAX_TRAJECTORY_SAMPLES;
5454
5455    fn solver_with_budget(
5456        use_rk4: bool,
5457        use_adaptive_rk45: bool,
5458        point_budget: usize,
5459        max_range: f64,
5460    ) -> TrajectorySolver {
5461        let inputs = BallisticInputs {
5462            use_rk4,
5463            use_adaptive_rk45,
5464            ground_threshold: f64::NEG_INFINITY,
5465            ..BallisticInputs::default()
5466        };
5467        let mut solver = TrajectorySolver::new(
5468            inputs,
5469            WindConditions::default(),
5470            AtmosphericConditions::default(),
5471        );
5472        solver.max_trajectory_points = point_budget;
5473        solver.set_max_range(max_range);
5474        solver.set_time_step(0.001);
5475        solver
5476    }
5477
5478    #[test]
5479    fn mba1283_every_solver_errors_instead_of_exceeding_point_budget() {
5480        for (mode, use_rk4, use_adaptive_rk45) in [
5481            ("Euler", false, false),
5482            ("RK4", true, false),
5483            ("RK45", true, true),
5484        ] {
5485            let error = solver_with_budget(use_rk4, use_adaptive_rk45, 3, 10.0)
5486                .solve()
5487                .expect_err("a solve requiring more than three points must fail");
5488            assert!(
5489                error.to_string().contains("point limit of 3"),
5490                "unexpected {mode} point-budget error: {error}"
5491            );
5492        }
5493    }
5494
5495    #[test]
5496    fn mba1283_interpolated_endpoint_counts_toward_point_budget() {
5497        for (mode, use_rk4, use_adaptive_rk45) in [
5498            ("Euler", false, false),
5499            ("RK4", true, false),
5500            ("RK45", true, true),
5501        ] {
5502            let result = solver_with_budget(use_rk4, use_adaptive_rk45, 2, 0.1)
5503                .solve()
5504                .expect("the initial point plus exact endpoint fit a two-point budget");
5505            assert_eq!(result.points.len(), 2, "unexpected {mode} point count");
5506
5507            let error = solver_with_budget(use_rk4, use_adaptive_rk45, 1, 0.1)
5508                .solve()
5509                .expect_err("the exact endpoint must not exceed a one-point budget");
5510            assert!(
5511                error.to_string().contains("point limit of 1"),
5512                "unexpected {mode} endpoint-budget error: {error}"
5513            );
5514        }
5515    }
5516
5517    #[test]
5518    fn mba1299_every_solver_preflights_the_sample_budget() {
5519        for (mode, use_rk4, use_adaptive_rk45) in [
5520            ("Euler", false, false),
5521            ("RK4", true, false),
5522            ("RK45", true, true),
5523        ] {
5524            let inputs = BallisticInputs {
5525                use_rk4,
5526                use_adaptive_rk45,
5527                enable_trajectory_sampling: true,
5528                sample_interval: 1.0,
5529                ground_threshold: f64::NEG_INFINITY,
5530                ..BallisticInputs::default()
5531            };
5532            let mut solver = TrajectorySolver::new(
5533                inputs,
5534                WindConditions::default(),
5535                AtmosphericConditions::default(),
5536            );
5537            solver.set_max_range(MAX_TRAJECTORY_SAMPLES as f64);
5538            // If validation does not reject the sample grid before dispatch, the first attempted
5539            // integration point produces a distinct point-budget error.
5540            solver.max_trajectory_points = 0;
5541
5542            let error = solver
5543                .solve()
5544                .expect_err("an over-limit sample grid must fail before integration");
5545            assert!(
5546                error
5547                    .to_string()
5548                    .contains("trajectory sample limit of 250000 exceeded"),
5549                "unexpected {mode} sample-budget error: {error}"
5550            );
5551        }
5552    }
5553
5554    #[test]
5555    fn mba1299_normal_sampling_does_not_change_solver_results() {
5556        for (mode, use_rk4, use_adaptive_rk45) in [
5557            ("Euler", false, false),
5558            ("RK4", true, false),
5559            ("RK45", true, true),
5560        ] {
5561            let solve = |enable_trajectory_sampling| {
5562                let inputs = BallisticInputs {
5563                    use_rk4,
5564                    use_adaptive_rk45,
5565                    enable_trajectory_sampling,
5566                    sample_interval: 0.5,
5567                    ground_threshold: f64::NEG_INFINITY,
5568                    ..BallisticInputs::default()
5569                };
5570                let mut solver = TrajectorySolver::new(
5571                    inputs,
5572                    WindConditions::default(),
5573                    AtmosphericConditions::default(),
5574                );
5575                solver.set_max_range(2.0);
5576                solver.solve().expect("normal short-range solve")
5577            };
5578
5579            let baseline = solve(false);
5580            let sampled = solve(true);
5581            for (field, left, right) in [
5582                ("max_range", baseline.max_range, sampled.max_range),
5583                ("max_height", baseline.max_height, sampled.max_height),
5584                (
5585                    "time_of_flight",
5586                    baseline.time_of_flight,
5587                    sampled.time_of_flight,
5588                ),
5589                (
5590                    "impact_velocity",
5591                    baseline.impact_velocity,
5592                    sampled.impact_velocity,
5593                ),
5594                (
5595                    "impact_energy",
5596                    baseline.impact_energy,
5597                    sampled.impact_energy,
5598                ),
5599            ] {
5600                assert_eq!(
5601                    left.to_bits(),
5602                    right.to_bits(),
5603                    "{mode} sampling changed {field}"
5604                );
5605            }
5606            assert_eq!(baseline.points.len(), sampled.points.len());
5607            for (index, (left, right)) in baseline
5608                .points
5609                .iter()
5610                .zip(&sampled.points)
5611                .enumerate()
5612            {
5613                assert_eq!(left.time.to_bits(), right.time.to_bits(), "{mode} point {index}");
5614                assert_eq!(
5615                    left.position.map(f64::to_bits),
5616                    right.position.map(f64::to_bits),
5617                    "{mode} point {index} position"
5618                );
5619                assert_eq!(
5620                    left.velocity_magnitude.to_bits(),
5621                    right.velocity_magnitude.to_bits(),
5622                    "{mode} point {index} velocity"
5623                );
5624                assert_eq!(
5625                    left.kinetic_energy.to_bits(),
5626                    right.kinetic_energy.to_bits(),
5627                    "{mode} point {index} energy"
5628                );
5629            }
5630            assert!(baseline.sampled_points.is_none());
5631            let samples = sampled
5632                .sampled_points
5633                .expect("sampling-enabled solve should return observations");
5634            assert_eq!(
5635                samples
5636                    .iter()
5637                    .map(|sample| sample.distance_m)
5638                    .collect::<Vec<_>>(),
5639                vec![0.0, 0.5, 1.0, 1.5, 2.0],
5640                "{mode} normal sampling grid changed"
5641            );
5642        }
5643    }
5644}
5645
5646#[cfg(test)]
5647mod monte_carlo_result_tests {
5648    use super::*;
5649
5650    fn make_results(impact_positions: Vec<Vector3<f64>>) -> MonteCarloResults {
5651        let count = impact_positions.len();
5652        MonteCarloResults {
5653            ranges: vec![500.0; count],
5654            impact_velocities: vec![300.0; count],
5655            impact_positions,
5656        }
5657    }
5658
5659    #[test]
5660    fn target_plane_cep_excludes_shortfall_markers() {
5661        let mut positions: Vec<Vector3<f64>> = (1..=5)
5662            .map(|radius| Vector3::new(0.0, radius as f64, 0.0))
5663            .collect();
5664        positions.extend(
5665            (0..5).map(|_| Vector3::new(0.0, TARGET_NOT_REACHED_SENTINEL_M, 0.0)),
5666        );
5667        let results = make_results(positions);
5668
5669        assert_eq!(results.target_arrival_count(), 5);
5670        assert_eq!(results.target_shortfall_fraction(), 0.5);
5671        assert_eq!(results.target_plane_cep(), Some(3.0));
5672
5673        let one_shortfall = make_results(vec![
5674            Vector3::new(0.0, 1.0, 0.0),
5675            Vector3::new(0.0, 2.0, 0.0),
5676            Vector3::new(0.0, 3.0, 0.0),
5677            Vector3::new(0.0, 4.0, 0.0),
5678            Vector3::new(0.0, 5.0, 0.0),
5679            Vector3::new(0.0, TARGET_NOT_REACHED_SENTINEL_M, 0.0),
5680        ]);
5681        assert_eq!(one_shortfall.target_plane_cep(), Some(3.0));
5682    }
5683
5684    #[test]
5685    fn all_shortfalls_have_no_cep_but_still_count_as_misses() {
5686        let all_shortfalls = make_results(vec![
5687            Vector3::new(0.0, TARGET_NOT_REACHED_SENTINEL_M, 0.0),
5688            Vector3::new(0.0, TARGET_NOT_REACHED_SENTINEL_M, 0.0),
5689        ]);
5690        assert_eq!(all_shortfalls.target_arrival_count(), 0);
5691        assert_eq!(all_shortfalls.target_shortfall_fraction(), 1.0);
5692        assert_eq!(all_shortfalls.target_plane_cep(), None);
5693        assert_eq!(all_shortfalls.hit_probability(0.3), 0.0);
5694
5695        let one_hit_one_shortfall = make_results(vec![
5696            Vector3::new(0.0, 0.1, 0.0),
5697            Vector3::new(0.0, TARGET_NOT_REACHED_SENTINEL_M, 0.0),
5698        ]);
5699        assert_eq!(one_hit_one_shortfall.hit_probability(0.3), 0.5);
5700    }
5701
5702    // MBA-1317: WEZ rectangular hit probability.
5703    #[test]
5704    fn rect_hit_probability_checks_independent_axis_halves() {
5705        let results = make_results(vec![
5706            // Inside a 0.4 (lateral) x 0.6 (vertical) box: half-width 0.2, half-height 0.3.
5707            Vector3::new(0.0, 0.1, 0.1),
5708            // On the lateral edge (exactly half-width) -> counts as a hit ("<=").
5709            Vector3::new(0.0, 0.0, 0.2),
5710            // Outside laterally (just past half-width).
5711            Vector3::new(0.0, 0.0, 0.201),
5712            // Outside vertically (just past half-height).
5713            Vector3::new(0.0, 0.301, 0.0),
5714            // Shortfall marker: stays in the denominator, never a hit.
5715            Vector3::new(0.0, TARGET_NOT_REACHED_SENTINEL_M, 0.0),
5716        ]);
5717        // 2 hits out of 5 samples.
5718        assert!((results.rect_hit_probability(0.4, 0.6) - 0.4).abs() < 1e-12);
5719    }
5720
5721    #[test]
5722    fn rect_hit_probability_matches_circular_hit_probability_for_a_centered_hit() {
5723        let results = make_results(vec![Vector3::new(0.0, 0.0, 0.0)]);
5724        assert_eq!(results.rect_hit_probability(0.5, 0.5), 1.0);
5725        assert_eq!(results.hit_probability(0.3), 1.0);
5726    }
5727
5728    #[test]
5729    fn rect_hit_probability_is_zero_for_empty_or_nonpositive_dimensions() {
5730        let empty = make_results(vec![]);
5731        assert_eq!(empty.rect_hit_probability(1.0, 1.0), 0.0);
5732
5733        let results = make_results(vec![Vector3::new(0.0, 0.0, 0.0)]);
5734        assert_eq!(results.rect_hit_probability(0.0, 1.0), 0.0);
5735        assert_eq!(results.rect_hit_probability(1.0, 0.0), 0.0);
5736        assert_eq!(results.rect_hit_probability(-1.0, 1.0), 0.0);
5737    }
5738}
5739
5740#[cfg(test)]
5741mod monte_carlo_seeded_tests {
5742    use super::*;
5743
5744    /// Shared fixture for the seeded Monte Carlo tests: the crate defaults at an explicit
5745    /// 800 m/s muzzle velocity in still air.
5746    ///
5747    /// The brief for this task assumed the module already had such a helper; it did not (every
5748    /// test above restated the same two literals inline), so it is introduced here and the
5749    /// adaptive-driver tests below share it. The existing tests keep their own inline fixtures
5750    /// deliberately: rewriting them to call this helper would change nothing about what they
5751    /// assert but would put unrelated churn in the same commit as a bit-for-bit pin.
5752    fn seeded_test_fixture() -> (BallisticInputs, WindConditions) {
5753        (
5754            BallisticInputs {
5755                muzzle_velocity: 800.0,
5756                ..BallisticInputs::default()
5757            },
5758            WindConditions::default(),
5759        )
5760    }
5761
5762    /// Dispersions for the adaptive-driver tests: a 300 m shot with small pointing and wind
5763    /// error, so almost every trial lands inside `DEFAULT_HIT_RADIUS_M` of the baseline.
5764    ///
5765    /// Tuned for *test wall time*, deliberately. A confidence sequence's half-width scales
5766    /// with `sqrt(p(1-p) * log(n) / n)`, so a hit probability near `1` reaches the default
5767    /// `0.02` target inside `min_samples` (1000 trials) while a `p` near `0.5` would need
5768    /// roughly 4-5x as many -- and every trial is a full trajectory solve, run unoptimised
5769    /// under `cargo test`. It stays a little short of a degenerate `p == 1`: a handful of
5770    /// misses in 1000 keeps the hit *counting* under test rather than trivially saturated.
5771    fn loose_params() -> MonteCarloParams {
5772        MonteCarloParams {
5773            num_simulations: 1, // deliberately absurd: the adaptive driver must ignore it
5774            velocity_std_dev: 3.0,
5775            angle_std_dev: 3.5e-4,
5776            bc_std_dev: 0.01,
5777            wind_speed_std_dev: 1.0,
5778            target_distance: Some(300.0),
5779            base_wind_speed: 0.0,
5780            base_wind_direction: 0.0,
5781            azimuth_std_dev: 3.5e-4,
5782        }
5783    }
5784
5785    /// Params whose target plane sits *inside* the ground-impact scatter, so some trials
5786    /// arrive at it and some fall short.
5787    ///
5788    /// The pin fixture records ground impact between 1907 m and 1936 m for this projectile, so
5789    /// a 1920 m plane splits the run. That split is the point: with `loose_params()` every
5790    /// trial arrives, which makes `arrivals`, `samples` and `attempts` numerically identical
5791    /// and therefore useless for catching a report that populates one of them from another.
5792    fn mixed_arrival_params() -> MonteCarloParams {
5793        MonteCarloParams {
5794            num_simulations: 1,
5795            target_distance: Some(1920.0),
5796            ..MonteCarloParams::default()
5797        }
5798    }
5799
5800    /// THE bit-for-bit compatibility contract for the legacy seeded Monte Carlo path
5801    /// (Plan C spec 9.5).
5802    ///
5803    /// Every literal below was captured by running this exact fixture against the tree at
5804    /// commit 5a421bf ("fix(decision-support): close the last three Plan B branch-review
5805    /// gaps"), i.e. the last commit before any Plan C change touched `src/cli_api.rs`, and
5806    /// printed with `{:?}` (shortest round-tripping form, so the pasted literal reproduces the
5807    /// captured `f64` to the bit).
5808    ///
5809    /// It exists to be run BEFORE and AFTER the per-trial body is extracted into
5810    /// [`MonteCarloTrialSampler::sample_one_trial`]. The extraction is only legitimate if the
5811    /// sequence and count of RNG draws per trial is unchanged, and that is not something the
5812    /// type system can check: a reordered or added draw shifts every subsequent sample and
5813    /// shows up here as a mismatch. If this test fails after a refactor of the trial loop, the
5814    /// refactor is wrong -- do not re-capture the literals.
5815    #[test]
5816    fn legacy_seeded_estimates_are_pinned_bit_for_bit() {
5817        let (inputs, wind) = seeded_test_fixture();
5818        let params = MonteCarloParams {
5819            num_simulations: 200,
5820            target_distance: Some(500.0),
5821            ..MonteCarloParams::default()
5822        };
5823
5824        let results = run_monte_carlo_with_wind_and_direction_std_dev_seeded(
5825            inputs,
5826            wind,
5827            params,
5828            0.01,
5829            0x1352_5EED,
5830        )
5831        .expect("seeded legacy run");
5832
5833        // Every trial is recorded: no solve failed and no target-plane interpolation was
5834        // skipped, so the three vectors are all 200 long. This is asserted, not assumed --
5835        // an extraction that started dropping trials would otherwise shorten the vectors
5836        // while the first three entries below still matched.
5837        assert_eq!(results.ranges.len(), 200, "ranges length");
5838        assert_eq!(results.impact_velocities.len(), 200, "impact_velocities length");
5839        assert_eq!(results.impact_positions.len(), 200, "impact_positions length");
5840
5841        // 28 hits in 200 trials.
5842        assert_eq!(
5843            results.hit_probability(DEFAULT_HIT_RADIUS_M).to_bits(),
5844            0.14_f64.to_bits(),
5845            "hit_probability = {:?}",
5846            results.hit_probability(DEFAULT_HIT_RADIUS_M)
5847        );
5848
5849        let expected_ranges: [f64; 3] =
5850            [1907.972891143359, 1936.408435469319, 1912.8150447617645];
5851        let expected_velocities: [f64; 3] =
5852            [238.6187151542299, 239.91923651600106, 243.14112455427164];
5853        let expected_positions: [(f64, f64, f64); 3] = [
5854            (0.0, -0.0643556039548101, 0.7344970252014579),
5855            (0.0, 0.5769422971539162, 0.27227201756386726),
5856            (0.0, -0.7440425792472842, 0.1541804446282822),
5857        ];
5858
5859        for (i, expected) in expected_ranges.iter().enumerate() {
5860            assert_eq!(
5861                results.ranges[i].to_bits(),
5862                expected.to_bits(),
5863                "ranges[{i}] = {:?}, pinned {expected:?}",
5864                results.ranges[i]
5865            );
5866        }
5867        for (i, expected) in expected_velocities.iter().enumerate() {
5868            assert_eq!(
5869                results.impact_velocities[i].to_bits(),
5870                expected.to_bits(),
5871                "impact_velocities[{i}] = {:?}, pinned {expected:?}",
5872                results.impact_velocities[i]
5873            );
5874        }
5875        for (i, (x, y, z)) in expected_positions.iter().enumerate() {
5876            let actual = results.impact_positions[i];
5877            assert_eq!(actual.x.to_bits(), x.to_bits(), "impact_positions[{i}].x = {:?}", actual.x);
5878            assert_eq!(actual.y.to_bits(), y.to_bits(), "impact_positions[{i}].y = {:?}", actual.y);
5879            assert_eq!(actual.z.to_bits(), z.to_bits(), "impact_positions[{i}].z = {:?}", actual.z);
5880        }
5881    }
5882
5883    #[test]
5884    fn seeded_runs_are_deterministic_and_match_the_using_rng_path() {
5885        let inputs = BallisticInputs {
5886            muzzle_velocity: 800.0,
5887            ..BallisticInputs::default()
5888        };
5889        let params = MonteCarloParams {
5890            num_simulations: 64,
5891            target_distance: Some(200.0),
5892            ..MonteCarloParams::default()
5893        };
5894
5895        let a = run_monte_carlo_with_wind_and_direction_std_dev_seeded(
5896            inputs.clone(),
5897            WindConditions::default(),
5898            params.clone(),
5899            0.01,
5900            42,
5901        )
5902        .expect("seeded run a");
5903        let b = run_monte_carlo_with_wind_and_direction_std_dev_seeded(
5904            inputs,
5905            WindConditions::default(),
5906            params,
5907            0.01,
5908            42,
5909        )
5910        .expect("seeded run b");
5911
5912        assert_eq!(a.ranges.len(), b.ranges.len());
5913        for (ra, rb) in a.ranges.iter().zip(b.ranges.iter()) {
5914            assert_eq!(ra.to_bits(), rb.to_bits());
5915        }
5916        for (pa, pb) in a.impact_positions.iter().zip(b.impact_positions.iter()) {
5917            assert_eq!(pa.x.to_bits(), pb.x.to_bits());
5918            assert_eq!(pa.y.to_bits(), pb.y.to_bits());
5919            assert_eq!(pa.z.to_bits(), pb.z.to_bits());
5920        }
5921    }
5922
5923    #[test]
5924    fn different_seeds_generally_produce_different_draws() {
5925        let inputs = BallisticInputs {
5926            muzzle_velocity: 800.0,
5927            ..BallisticInputs::default()
5928        };
5929        let params = MonteCarloParams {
5930            num_simulations: 32,
5931            velocity_std_dev: 5.0,
5932            target_distance: Some(200.0),
5933            ..MonteCarloParams::default()
5934        };
5935
5936        let a = run_monte_carlo_with_wind_and_direction_std_dev_seeded(
5937            inputs.clone(),
5938            WindConditions::default(),
5939            params.clone(),
5940            0.0,
5941            1,
5942        )
5943        .expect("seeded run a");
5944        let b = run_monte_carlo_with_wind_and_direction_std_dev_seeded(
5945            inputs,
5946            WindConditions::default(),
5947            params,
5948            0.0,
5949            2,
5950        )
5951        .expect("seeded run b");
5952
5953        assert_ne!(a.impact_velocities, b.impact_velocities);
5954    }
5955
5956    #[test]
5957    fn adaptive_stops_at_target_half_width_on_an_easy_case() {
5958        let (inputs, wind) = seeded_test_fixture();
5959        let conv = McConvergence {
5960            target_half_width: 0.05,
5961            ..Default::default()
5962        };
5963        let r = run_monte_carlo_adaptive_seeded(
5964            &inputs,
5965            &wind,
5966            &loose_params(),
5967            &conv,
5968            DEFAULT_HIT_RADIUS_M,
5969            0x1352_ADA9,
5970        )
5971        .unwrap();
5972
5973        assert_eq!(r.stop_reason, McStopReason::TargetHalfWidthMet);
5974        assert!(
5975            (r.ci_high - r.ci_low) / 2.0 <= 0.05 + 1e-12,
5976            "half-width {} exceeds the requested 0.05",
5977            (r.ci_high - r.ci_low) / 2.0
5978        );
5979        assert!(r.samples >= conv.min_samples, "stopped below min_samples");
5980        assert!(r.samples < conv.max_samples, "did not actually stop early");
5981        assert!(r.samples.is_multiple_of(conv.batch_size) || r.samples == conv.min_samples);
5982        assert!(r.ci_low <= r.hit_probability && r.hit_probability <= r.ci_high);
5983
5984        // The report must describe the run it actually did, not the params it ignored.
5985        assert_eq!(r.hit_radius_m, DEFAULT_HIT_RADIUS_M);
5986        assert_eq!(r.target_distance_m, 300.0);
5987        assert_eq!(r.confidence_percent, 95);
5988        // `num_simulations` is 1 in `loose_params`; if it were honoured we would see 1 sample.
5989        assert!(
5990            r.samples > 1,
5991            "params.num_simulations must be ignored by the adaptive driver"
5992        );
5993        // The streaming moments ran over trials that reached the plane: a 300 m shot at
5994        // 800 m/s is still supersonic, and the dispersions are nonzero, so both must be too.
5995        assert!(
5996            r.mean_impact_velocity_mps > 0.0,
5997            "no impact velocity accumulated"
5998        );
5999        assert!(
6000            r.std_drop_at_target_m > 0.0 && r.std_wind_drift_at_target_m > 0.0,
6001            "dispersion collapsed: drop sd {} drift sd {}",
6002            r.std_drop_at_target_m,
6003            r.std_wind_drift_at_target_m
6004        );
6005    }
6006
6007    #[test]
6008    fn adaptive_caps_at_max_samples_on_an_impossible_target() {
6009        let (inputs, wind) = seeded_test_fixture();
6010        let conv = McConvergence {
6011            target_half_width: 1e-6,
6012            max_samples: 3_000,
6013            batch_size: 500,
6014            min_samples: 1_000,
6015            level: ConfidenceLevel::P95,
6016        };
6017        let r = run_monte_carlo_adaptive_seeded(
6018            &inputs,
6019            &wind,
6020            &loose_params(),
6021            &conv,
6022            DEFAULT_HIT_RADIUS_M,
6023            7,
6024        )
6025        .unwrap();
6026
6027        assert_eq!(r.stop_reason, McStopReason::MaxSamplesReached);
6028        assert_eq!(r.samples, 3_000);
6029    }
6030
6031    /// The adaptive middle: a stop that is decided by the DATA, not by either bound.
6032    ///
6033    /// Every other stopping test lands on a boundary -- the easy case and the determinism case
6034    /// both stop at exactly `min_samples`, and the impossible case runs to `max_samples`. None
6035    /// of them would notice if the half-width check were, say, only consulted on the first
6036    /// batch. Here `min_samples` is 0 and `max_samples` is far away, so the sample count is
6037    /// whatever the confidence sequence decides it is, and the assertions pin that it landed
6038    /// strictly inside both bounds after more than one batch.
6039    #[test]
6040    fn adaptive_stops_between_the_floor_and_the_ceiling() {
6041        let (inputs, wind) = seeded_test_fixture();
6042        let conv = McConvergence {
6043            level: ConfidenceLevel::P95,
6044            target_half_width: 0.03,
6045            min_samples: 0,
6046            max_samples: 10_000,
6047            batch_size: 100,
6048        };
6049        let r = run_monte_carlo_adaptive_seeded(
6050            &inputs,
6051            &wind,
6052            &loose_params(),
6053            &conv,
6054            DEFAULT_HIT_RADIUS_M,
6055            0x1352_5A1D,
6056        )
6057        .unwrap();
6058
6059        assert_eq!(r.stop_reason, McStopReason::TargetHalfWidthMet);
6060        assert!(r.samples > 0);
6061        assert!(
6062            r.samples.is_multiple_of(conv.batch_size),
6063            "samples {} is not a whole number of batches",
6064            r.samples
6065        );
6066        assert!(
6067            r.samples > conv.min_samples,
6068            "stopped on the floor, not on the data"
6069        );
6070        assert!(
6071            r.samples < conv.max_samples,
6072            "ran to the ceiling, so nothing adaptive was exercised"
6073        );
6074        assert!(
6075            r.samples > conv.batch_size,
6076            "stopped on the very first look ({} samples); the multi-batch path is untested",
6077            r.samples
6078        );
6079        assert!((r.ci_high - r.ci_low) / 2.0 <= 0.03 + 1e-12);
6080        assert!(r.ci_low <= r.hit_probability && r.hit_probability <= r.ci_high);
6081        assert_eq!(r.attempts, r.samples, "no trial should have been dropped");
6082    }
6083
6084    /// The final batch is truncated so `max_samples` is a hard ceiling, not a threshold the
6085    /// last batch overshoots.
6086    ///
6087    /// `750 = 500 + 250`, so the second batch must run short. With a `max_samples` that is a
6088    /// whole multiple of `batch_size` -- as in every other test here -- the
6089    /// `batch_size.min(max_samples - attempts)` clamp never actually clamps, and a driver that
6090    /// ignored it entirely would pass. This one would report 1000.
6091    #[test]
6092    fn adaptive_runs_a_truncated_final_batch_up_to_max_samples() {
6093        let (inputs, wind) = seeded_test_fixture();
6094        let conv = McConvergence {
6095            level: ConfidenceLevel::P95,
6096            target_half_width: 1e-6,
6097            min_samples: 0,
6098            max_samples: 750,
6099            batch_size: 500,
6100        };
6101        let r = run_monte_carlo_adaptive_seeded(
6102            &inputs,
6103            &wind,
6104            &loose_params(),
6105            &conv,
6106            DEFAULT_HIT_RADIUS_M,
6107            0x1352_7B10,
6108        )
6109        .unwrap();
6110
6111        assert_eq!(r.stop_reason, McStopReason::MaxSamplesReached);
6112        assert_eq!(
6113            r.samples, 750,
6114            "the 250-trial final batch did not run, or was not truncated"
6115        );
6116        assert_eq!(r.attempts, 750);
6117        assert!(!r.samples.is_multiple_of(conv.batch_size));
6118    }
6119
6120    #[test]
6121    fn adaptive_is_deterministic_for_a_seed() {
6122        let (inputs, wind) = seeded_test_fixture();
6123        let conv = McConvergence::default();
6124        let a = run_monte_carlo_adaptive_seeded(
6125            &inputs,
6126            &wind,
6127            &loose_params(),
6128            &conv,
6129            DEFAULT_HIT_RADIUS_M,
6130            99,
6131        )
6132        .unwrap();
6133        let b = run_monte_carlo_adaptive_seeded(
6134            &inputs,
6135            &wind,
6136            &loose_params(),
6137            &conv,
6138            DEFAULT_HIT_RADIUS_M,
6139            99,
6140        )
6141        .unwrap();
6142
6143        assert_eq!(a.hit_probability.to_bits(), b.hit_probability.to_bits());
6144        assert_eq!(a.samples, b.samples);
6145        assert_eq!(a.ci_low.to_bits(), b.ci_low.to_bits());
6146        assert_eq!(a.ci_high.to_bits(), b.ci_high.to_bits());
6147        // The streaming moments have to be reproducible too, not just the hit counts: they
6148        // are the part that would drift if the trial body consumed draws inconsistently.
6149        assert_eq!(
6150            a.mean_impact_velocity_mps.to_bits(),
6151            b.mean_impact_velocity_mps.to_bits()
6152        );
6153        assert_eq!(
6154            a.std_drop_at_target_m.to_bits(),
6155            b.std_drop_at_target_m.to_bits()
6156        );
6157    }
6158
6159    #[test]
6160    fn adaptive_report_carries_schema_method_and_all_four_assumptions() {
6161        let (inputs, wind) = seeded_test_fixture();
6162        // Nothing here depends on the statistics converging, so keep it to one batch. The
6163        // fixture is the mixed-arrival one so the three cardinalities come out DISTINCT --
6164        // see the assertions below.
6165        let conv = McConvergence {
6166            min_samples: 0,
6167            max_samples: 50,
6168            batch_size: 50,
6169            target_half_width: 1.0,
6170            level: ConfidenceLevel::P90,
6171        };
6172        let r = run_monte_carlo_adaptive_seeded(
6173            &inputs,
6174            &wind,
6175            &mixed_arrival_params(),
6176            &conv,
6177            DEFAULT_HIT_RADIUS_M,
6178            0x1352_D0C5,
6179        )
6180        .unwrap();
6181
6182        assert_eq!(r.schema_version, MC_ADAPTIVE_SCHEMA_VERSION_V1);
6183        assert_eq!(r.schema_version, 1);
6184        assert_eq!(r.method, "anytime_beta_binomial_mixture_cs_v1");
6185        assert_eq!(r.confidence_percent, 90);
6186
6187        // The three cardinalities, pinned against each other rather than each against 50.
6188        // `attempts` and `samples` are both 50 here (nothing was dropped), but `arrivals` is
6189        // strictly smaller because the 1920 m plane sits inside the ground-impact scatter --
6190        // so a report that populated `arrivals` from `samples` (or vice versa) fails here,
6191        // which it could not if all three were the same number.
6192        assert_eq!(r.attempts, 50, "one full batch was drawn");
6193        assert_eq!(r.samples, 50, "no trial was dropped by the solver");
6194        assert!(
6195            r.arrivals > 0 && r.arrivals < r.samples,
6196            "fixture must split the run: arrivals {} of samples {}",
6197            r.arrivals,
6198            r.samples
6199        );
6200        // ...and the at-target statistics really are the `arrivals` population: two or more
6201        // arrivals is what makes a Bessel-corrected standard deviation defined at all.
6202        assert!(r.arrivals >= 2, "arrivals {} too few for a sample sd", r.arrivals);
6203        assert!(r.std_drop_at_target_m > 0.0 && r.std_impact_velocity_mps > 0.0);
6204        // The ordering invariant the doc comments promise.
6205        assert!(r.attempts >= r.samples && r.samples >= r.arrivals);
6206
6207        // Length AND per-index full-string equality against literals restated here character
6208        // for character. Deliberately NOT compared against MC_ADAPTIVE_ASSUMPTIONS_V1: that
6209        // would be circular, passing for any edit to the constant. `contains()` is likewise
6210        // not a pin -- a substring probe survives a sentence being reworded, truncated, or
6211        // having its meaning inverted around the matched word.
6212        assert_eq!(r.assumptions.len(), 4, "exactly four assumptions expected");
6213        assert_eq!(
6214            r.assumptions[0],
6215            "Sampling uncertainty only: intervals cover Monte Carlo sampling error, not model error in the trajectory solver or its inputs."
6216        );
6217        assert_eq!(
6218            r.assumptions[1],
6219            "Anytime-valid stopping: the beta-binomial mixture confidence sequence keeps its coverage guarantee despite stopping the moment the target half-width is met."
6220        );
6221        assert_eq!(
6222            r.assumptions[2],
6223            "Input dispersions are the independent normal distributions declared in MonteCarloParams; correlations between inputs are not modeled."
6224        );
6225        assert_eq!(
6226            r.assumptions[3],
6227            "Continuous statistics are streaming Welford moments over trials that reached the target plane, reported with sample (n-1) standard deviations; hit probability's denominator includes all trials."
6228        );
6229
6230        // The stop reason is a snake_case string on the wire, not a variant name or an index.
6231        assert_eq!(
6232            serde_json::to_string(&McStopReason::TargetHalfWidthMet).unwrap(),
6233            "\"target_half_width_met\""
6234        );
6235        assert_eq!(
6236            serde_json::to_string(&McStopReason::MaxSamplesReached).unwrap(),
6237            "\"max_samples_reached\""
6238        );
6239    }
6240
6241    #[test]
6242    fn adaptive_rejects_nonsense_convergence() {
6243        let (inputs, wind) = seeded_test_fixture();
6244        let run = |conv: McConvergence| {
6245            run_monte_carlo_adaptive_seeded(
6246                &inputs,
6247                &wind,
6248                &loose_params(),
6249                &conv,
6250                DEFAULT_HIT_RADIUS_M,
6251                1,
6252            )
6253            .unwrap_err()
6254        };
6255
6256        for bad_width in [0.0, -0.01, f64::NAN] {
6257            let err = run(McConvergence {
6258                target_half_width: bad_width,
6259                ..Default::default()
6260            });
6261            assert!(
6262                err.contains("target_half_width"),
6263                "error must name the field, got: {err}"
6264            );
6265        }
6266
6267        let err = run(McConvergence {
6268            batch_size: 0,
6269            ..Default::default()
6270        });
6271        assert!(err.contains("batch_size"), "got: {err}");
6272
6273        let err = run(McConvergence {
6274            min_samples: 5_000,
6275            max_samples: 1_000,
6276            ..Default::default()
6277        });
6278        assert!(err.contains("max_samples"), "got: {err}");
6279        assert!(err.contains("min_samples"), "got: {err}");
6280
6281        let err = run(McConvergence {
6282            max_samples: 0,
6283            min_samples: 0,
6284            ..Default::default()
6285        });
6286        assert!(err.contains("max_samples"), "got: {err}");
6287
6288        // Validation happens before any trajectory work: a rejected config costs no solves.
6289        let err = McConvergence {
6290            batch_size: 0,
6291            ..Default::default()
6292        }
6293        .validate()
6294        .unwrap_err();
6295        assert!(err.contains("batch_size"));
6296    }
6297
6298    #[test]
6299    fn wilson_companion_matches_hit_probability_and_wilson_interval() {
6300        let (inputs, wind) = seeded_test_fixture();
6301        let params = MonteCarloParams {
6302            num_simulations: 128,
6303            target_distance: Some(500.0),
6304            ..MonteCarloParams::default()
6305        };
6306        let results = run_monte_carlo_with_wind_and_direction_std_dev_seeded(
6307            inputs,
6308            wind,
6309            params,
6310            0.01,
6311            0x1352_C0DE,
6312        )
6313        .expect("seeded legacy run");
6314
6315        for level in [
6316            ConfidenceLevel::P90,
6317            ConfidenceLevel::P95,
6318            ConfidenceLevel::P99,
6319        ] {
6320            let (p_hat, (lo, hi), n) =
6321                results.hit_probability_wilson(DEFAULT_HIT_RADIUS_M, level);
6322
6323            // The companion is a composition, not a re-derivation: p_hat must be the very
6324            // number `hit_probability` returns, bit for bit.
6325            assert_eq!(
6326                p_hat.to_bits(),
6327                results.hit_probability(DEFAULT_HIT_RADIUS_M).to_bits()
6328            );
6329            assert_eq!(n, results.impact_positions.len() as u64);
6330
6331            // ...and the bounds must be `wilson_interval` over the same counts. The hit count
6332            // is recomputed here from the shared predicate rather than taken from the
6333            // companion, so a wrong denominator (e.g. excluding target shortfalls) fails.
6334            let hits = results
6335                .impact_positions
6336                .iter()
6337                .filter(|p| MonteCarloResults::position_is_hit(p, DEFAULT_HIT_RADIUS_M))
6338                .count() as u64;
6339            let (want_lo, want_hi) = wilson_interval(hits, n, level);
6340            assert_eq!(lo.to_bits(), want_lo.to_bits());
6341            assert_eq!(hi.to_bits(), want_hi.to_bits());
6342            assert!(lo <= p_hat && p_hat <= hi, "interval excludes p_hat");
6343        }
6344
6345        // Empty results: hit_probability's 0.0 alongside wilson_interval's n == 0 ignorance.
6346        let empty = MonteCarloResults {
6347            ranges: Vec::new(),
6348            impact_velocities: Vec::new(),
6349            impact_positions: Vec::new(),
6350        };
6351        assert_eq!(
6352            empty.hit_probability_wilson(DEFAULT_HIT_RADIUS_M, ConfidenceLevel::P95),
6353            (0.0, (0.0, 1.0), 0)
6354        );
6355    }
6356}
6357
6358#[cfg(test)]
6359mod monte_carlo_powder_curve_tests {
6360    use super::*;
6361    use rand::{rngs::StdRng, SeedableRng};
6362
6363    #[test]
6364    fn powder_curve_preserves_sampled_muzzle_velocity_dispersion() {
6365        let inputs = BallisticInputs {
6366            muzzle_velocity: 700.0,
6367            powder_temp_curve: Some(vec![(15.0, 800.0)]),
6368            powder_curve_temp_c: Some(15.0),
6369            ..BallisticInputs::default()
6370        };
6371        let params = MonteCarloParams {
6372            num_simulations: 16,
6373            velocity_std_dev: 20.0,
6374            angle_std_dev: 1e-12,
6375            bc_std_dev: 1e-12,
6376            wind_speed_std_dev: 1e-12,
6377            target_distance: Some(100.0),
6378            azimuth_std_dev: 1e-12,
6379            ..MonteCarloParams::default()
6380        };
6381
6382        let mut rng = StdRng::seed_from_u64(0x5EED_1176);
6383        let results = run_monte_carlo_with_wind_and_direction_std_dev_using_rng(
6384            inputs,
6385            WindConditions::default(),
6386            params,
6387            0.0,
6388            &mut rng,
6389        )
6390        .expect("Monte Carlo solve");
6391        let min_velocity = results
6392            .impact_velocities
6393            .iter()
6394            .copied()
6395            .fold(f64::INFINITY, f64::min);
6396        let max_velocity = results
6397            .impact_velocities
6398            .iter()
6399            .copied()
6400            .fold(f64::NEG_INFINITY, f64::max);
6401
6402        assert!(
6403            max_velocity - min_velocity > 1.0,
6404            "20 m/s muzzle spread collapsed after curve resolution: impact-velocity span={} m/s",
6405            max_velocity - min_velocity
6406        );
6407    }
6408}
6409
6410#[cfg(test)]
6411mod monte_carlo_wind_sampling_tests {
6412    use super::*;
6413    use rand::{rngs::StdRng, SeedableRng};
6414
6415    #[test]
6416    fn wind_speed_sigma_does_not_change_seeded_direction_draws() {
6417        let base_wind = WindConditions {
6418            speed: 100.0,
6419            direction: 0.37,
6420            vertical_speed: 0.0,
6421        };
6422        let narrow_speed = MonteCarloWindSampler::new(&base_wind, 0.5, 0.2).unwrap();
6423        let wide_speed = MonteCarloWindSampler::new(&base_wind, 4.0, 0.2).unwrap();
6424        let mut narrow_rng = StdRng::seed_from_u64(0x5EED_1223);
6425        let mut wide_rng = StdRng::seed_from_u64(0x5EED_1223);
6426        let mut speed_changed = false;
6427
6428        for _ in 0..32 {
6429            let narrow = narrow_speed.sample(&mut narrow_rng);
6430            let wide = wide_speed.sample(&mut wide_rng);
6431            assert!(narrow.speed > 0.0 && wide.speed > 0.0);
6432            assert_eq!(narrow.direction.to_bits(), wide.direction.to_bits());
6433            speed_changed |= narrow.speed.to_bits() != wide.speed.to_bits();
6434        }
6435        assert!(
6436            speed_changed,
6437            "different speed sigmas must still vary speed draws"
6438        );
6439    }
6440
6441    #[test]
6442    fn zero_direction_sigma_has_no_angular_jitter() {
6443        let base_wind = WindConditions {
6444            speed: 100.0,
6445            direction: 0.37,
6446            vertical_speed: 0.0,
6447        };
6448        let sampler = MonteCarloWindSampler::new(&base_wind, 4.0, 0.0).unwrap();
6449        let mut rng = StdRng::seed_from_u64(0x5EED_1223);
6450        let mut speed_changed = false;
6451
6452        for _ in 0..32 {
6453            let wind = sampler.sample(&mut rng);
6454            speed_changed |= wind.speed.to_bits() != base_wind.speed.to_bits();
6455            assert_eq!(wind.direction.to_bits(), base_wind.direction.to_bits());
6456        }
6457        assert!(speed_changed, "speed uncertainty should remain active");
6458    }
6459
6460    #[test]
6461    fn direction_sigma_controls_seeded_angular_spread_in_radians() {
6462        let base_wind = WindConditions {
6463            speed: 100.0,
6464            direction: 0.37,
6465            vertical_speed: 0.0,
6466        };
6467        let narrow = MonteCarloWindSampler::new(&base_wind, 4.0, 0.1).unwrap();
6468        let wide = MonteCarloWindSampler::new(&base_wind, 4.0, 0.2).unwrap();
6469        let mut narrow_rng = StdRng::seed_from_u64(0x5EED_1223);
6470        let mut wide_rng = StdRng::seed_from_u64(0x5EED_1223);
6471        let mut nonzero_direction_draw = false;
6472
6473        for _ in 0..32 {
6474            let narrow_wind = narrow.sample(&mut narrow_rng);
6475            let wide_wind = wide.sample(&mut wide_rng);
6476            assert_eq!(narrow_wind.speed.to_bits(), wide_wind.speed.to_bits());
6477
6478            let narrow_delta = narrow_wind.direction - base_wind.direction;
6479            let wide_delta = wide_wind.direction - base_wind.direction;
6480            assert!((wide_delta - 2.0 * narrow_delta).abs() < 1e-12);
6481            nonzero_direction_draw |= narrow_delta.abs() > 1e-6;
6482        }
6483        assert!(
6484            nonzero_direction_draw,
6485            "positive radians sigma must vary direction"
6486        );
6487    }
6488
6489    #[test]
6490    fn direction_sigma_rejects_negative_or_nonfinite_values() {
6491        let base_wind = WindConditions::default();
6492        for sigma in [-0.1, f64::NAN, f64::INFINITY] {
6493            assert!(MonteCarloWindSampler::new(&base_wind, 1.0, sigma).is_err());
6494        }
6495    }
6496
6497    #[test]
6498    fn base_vertical_wind_rides_into_every_mc_sample() {
6499        // MBA-728: vertical wind is a systematic input, not a dispersion source —
6500        // every sampled wind must carry the base vertical un-dispersed. (Before
6501        // this fix, samples dropped it, biasing the whole MC cloud vs the baseline.)
6502        use rand::SeedableRng;
6503        let base_wind = WindConditions { vertical_speed: 4.2, ..Default::default() };
6504        let sampler = MonteCarloWindSampler::new(&base_wind, 1.0, 0.2).unwrap();
6505        let mut rng = rand::rngs::StdRng::seed_from_u64(7);
6506        for _ in 0..32 {
6507            let w = sampler.sample(&mut rng);
6508            assert_eq!(w.vertical_speed, 4.2);
6509        }
6510    }
6511
6512    #[test]
6513    fn negative_speed_sample_reverses_wind_direction() {
6514        let direction = 0.25;
6515        let signed_speed = -2.5;
6516        let wind = wind_from_signed_speed_sample(signed_speed, direction, 0.0);
6517        let positive_wind = wind_from_signed_speed_sample(2.5, direction, 0.0);
6518
6519        assert_eq!(wind.speed, 2.5);
6520        assert!(
6521            (wind.direction - (direction + std::f64::consts::PI)).abs() < f64::EPSILON,
6522            "negative speed must reverse direction by pi: got {}",
6523            wind.direction
6524        );
6525        assert_eq!(positive_wind.speed, 2.5);
6526        assert_eq!(positive_wind.direction, direction);
6527
6528        let normalized_x = -wind.speed * wind.direction.cos();
6529        let normalized_z = -wind.speed * wind.direction.sin();
6530        let signed_x = -signed_speed * direction.cos();
6531        let signed_z = -signed_speed * direction.sin();
6532        assert!((normalized_x - signed_x).abs() < 1e-12);
6533        assert!((normalized_z - signed_z).abs() < 1e-12);
6534    }
6535}
6536
6537#[cfg(test)]
6538mod bc_fit_objective_tests {
6539    use super::*;
6540
6541    fn velocity_point(range_m: f64, velocity_mps: f64) -> TrajectoryPoint {
6542        TrajectoryPoint {
6543            time: 0.0,
6544            position: Vector3::new(range_m, 0.0, 0.0),
6545            velocity_magnitude: velocity_mps,
6546            kinetic_energy: 0.0,
6547            drag_coefficient: None,
6548        }
6549    }
6550
6551    #[test]
6552    fn candidate_that_misses_an_observation_has_no_score() {
6553        let trajectory = vec![velocity_point(0.0, 800.0), velocity_point(100.0, 700.0)];
6554        let observations = vec![(50.0, 750.0), (150.0, 600.0)];
6555
6556        assert!(
6557            fit_residual_sse(&trajectory, &observations, BcFitMode::Velocity, 0.0).is_none(),
6558            "a candidate that reaches only one of two observations must not compete on partial SSE"
6559        );
6560
6561        let complete_observations = vec![(50.0, 740.0), (100.0, 680.0)];
6562        assert_eq!(
6563            fit_residual_sse(
6564                &trajectory,
6565                &complete_observations,
6566                BcFitMode::Velocity,
6567                0.0,
6568            ),
6569            Some(500.0)
6570        );
6571    }
6572}
6573
6574#[cfg(test)]
6575mod cluster_bc_reference_space_tests {
6576    use super::*;
6577
6578    fn acceleration_at_1100_fps(inputs: BallisticInputs) -> Vector3<f64> {
6579        let solver = TrajectorySolver::new(
6580            inputs,
6581            WindConditions::default(),
6582            AtmosphericConditions::default(),
6583        );
6584        let position = Vector3::zeros();
6585        let velocity = Vector3::new(1100.0 / 3.28084, 0.0, 0.0);
6586        let (density, _, temp_c, pressure_hpa) = solver.resolved_atmosphere();
6587        solver.calculate_acceleration(
6588            &position,
6589            &velocity,
6590            &Vector3::zeros(),
6591            (temp_c, pressure_hpa, density / 1.225),
6592        )
6593    }
6594
6595    #[test]
6596    fn solver_passes_g7_reference_model_to_cluster_classifier() {
6597        let inputs = BallisticInputs {
6598            bc_value: 0.190,
6599            bc_type: DragModel::G7,
6600            bullet_mass: 77.0 * crate::constants::GRAINS_TO_KG,
6601            bullet_diameter: 0.224 * 0.0254,
6602            use_cluster_bc: true,
6603            ..BallisticInputs::default()
6604        };
6605
6606        let solver = TrajectorySolver::new(
6607            inputs,
6608            WindConditions::default(),
6609            AtmosphericConditions::default(),
6610        );
6611        let corrected = solver.apply_cluster_bc_correction(0.190, 2800.0);
6612
6613        assert!(
6614            (corrected / 0.190 - 1.004).abs() < 1e-12,
6615            "solver selected the wrong G7 cluster multiplier: {}",
6616            corrected / 0.190
6617        );
6618    }
6619
6620    #[test]
6621    fn velocity_bc_segments_are_not_cluster_corrected_twice() {
6622        let segmented_clustered = BallisticInputs {
6623            bc_value: 0.5,
6624            bc_type: DragModel::G7,
6625            use_bc_segments: true,
6626            bc_segments_data: Some(vec![
6627                crate::BCSegmentData {
6628                    velocity_min: 0.0,
6629                    velocity_max: 1_600.0,
6630                    bc_value: 0.4,
6631                },
6632                crate::BCSegmentData {
6633                    velocity_min: 1_600.0,
6634                    velocity_max: 5_000.0,
6635                    bc_value: 0.45,
6636                },
6637            ]),
6638            use_cluster_bc: true,
6639            ..BallisticInputs::default()
6640        };
6641        let mut segmented_only = segmented_clustered.clone();
6642        segmented_only.use_cluster_bc = false;
6643        let mut constant_clustered = segmented_clustered.clone();
6644        constant_clustered.bc_value = 0.4;
6645        constant_clustered.bc_segments_data = None;
6646
6647        let stacked = acceleration_at_1100_fps(segmented_clustered);
6648        let segment_only = acceleration_at_1100_fps(segmented_only);
6649        let cluster_only = acceleration_at_1100_fps(constant_clustered);
6650
6651        assert!(
6652            (stacked.x - segment_only.x).abs() < 1e-12,
6653            "segment BC already owns the velocity shape: stacked ax={} segment-only ax={}",
6654            stacked.x,
6655            segment_only.x
6656        );
6657        assert!(
6658            (cluster_only.x - segment_only.x).abs() > 1e-6,
6659            "cluster correction must remain active for a constant BC"
6660        );
6661    }
6662
6663    #[test]
6664    fn mach_bc_segments_are_not_cluster_corrected_twice() {
6665        let mach_segmented_clustered = BallisticInputs {
6666            bc_value: 0.5,
6667            bc_type: DragModel::G7,
6668            use_bc_segments: false,
6669            bc_segments: Some(vec![(0.5, 0.3), (1.5, 0.5)]),
6670            use_cluster_bc: true,
6671            ..BallisticInputs::default()
6672        };
6673        let mut mach_segmented_only = mach_segmented_clustered.clone();
6674        mach_segmented_only.use_cluster_bc = false;
6675
6676        let stacked = acceleration_at_1100_fps(mach_segmented_clustered);
6677        let segment_only = acceleration_at_1100_fps(mach_segmented_only);
6678
6679        assert!(
6680            (stacked.x - segment_only.x).abs() < 1e-12,
6681            "Mach segment BC already owns the velocity shape: stacked ax={} segment-only ax={}",
6682            stacked.x,
6683            segment_only.x
6684        );
6685    }
6686}
6687
6688#[cfg(test)]
6689mod velocity_bc_flag_tests {
6690    use super::*;
6691
6692    fn acceleration_at_600_mps(inputs: BallisticInputs) -> Vector3<f64> {
6693        let solver = TrajectorySolver::new(
6694            inputs,
6695            WindConditions::default(),
6696            AtmosphericConditions::default(),
6697        );
6698        let (density, _, temp_c, pressure_hpa) = solver.resolved_atmosphere();
6699        solver.calculate_acceleration(
6700            &Vector3::zeros(),
6701            &Vector3::new(600.0, 0.0, 0.0),
6702            &Vector3::zeros(),
6703            (temp_c, pressure_hpa, density / 1.225),
6704        )
6705    }
6706
6707    #[test]
6708    fn velocity_bc_data_requires_opt_in_in_trajectory_solver() {
6709        let scalar_inputs = BallisticInputs {
6710            bc_value: 0.5,
6711            bc_type: DragModel::G7,
6712            ..BallisticInputs::default()
6713        };
6714        let mut disabled_inputs = scalar_inputs.clone();
6715        disabled_inputs.bc_segments_data = Some(vec![crate::BCSegmentData {
6716            velocity_min: 0.0,
6717            velocity_max: 4_000.0,
6718            bc_value: 0.46,
6719        }]);
6720        disabled_inputs.use_bc_segments = false;
6721        let mut enabled_inputs = disabled_inputs.clone();
6722        enabled_inputs.use_bc_segments = true;
6723        let mut mach_only_inputs = scalar_inputs.clone();
6724        mach_only_inputs.bc_segments = Some(vec![(0.0, 0.4), (3.0, 0.4)]);
6725        let mut disabled_with_both = mach_only_inputs.clone();
6726        disabled_with_both.bc_segments_data = disabled_inputs.bc_segments_data.clone();
6727
6728        let scalar = acceleration_at_600_mps(scalar_inputs);
6729        let disabled = acceleration_at_600_mps(disabled_inputs);
6730        let enabled = acceleration_at_600_mps(enabled_inputs);
6731        let mach_only = acceleration_at_600_mps(mach_only_inputs);
6732        let disabled_with_both = acceleration_at_600_mps(disabled_with_both);
6733
6734        assert_eq!(
6735            disabled.x.to_bits(),
6736            scalar.x.to_bits(),
6737            "a populated velocity table must not change drag while use_bc_segments is false"
6738        );
6739        assert!(
6740            enabled.x < disabled.x - 1.0,
6741            "enabling the lower BC table must increase drag: disabled ax={} enabled ax={}",
6742            disabled.x,
6743            enabled.x
6744        );
6745        assert_eq!(
6746            disabled_with_both.x.to_bits(),
6747            mach_only.x.to_bits(),
6748            "disabling velocity data must fall through to an explicit Mach table"
6749        );
6750    }
6751}
6752
6753#[cfg(test)]
6754mod mach_bc_segment_tests {
6755    use super::*;
6756
6757    #[test]
6758    fn trajectory_solver_interpolates_explicit_mach_bc_segments() {
6759        let segmented_inputs = BallisticInputs {
6760            bc_value: 0.8,
6761            use_bc_segments: false,
6762            bc_segments: Some(vec![(1.0, 0.2), (2.0, 0.4)]),
6763            bc_segments_data: None,
6764            ..BallisticInputs::default()
6765        };
6766
6767        let mut expected_inputs = segmented_inputs.clone();
6768        expected_inputs.bc_value = 0.3;
6769        expected_inputs.bc_segments = None;
6770
6771        let atmosphere = AtmosphericConditions::default();
6772        let segmented_solver = TrajectorySolver::new(
6773            segmented_inputs,
6774            WindConditions::default(),
6775            atmosphere.clone(),
6776        );
6777        let expected_solver = TrajectorySolver::new(
6778            expected_inputs,
6779            WindConditions::default(),
6780            atmosphere,
6781        );
6782        let position = Vector3::zeros();
6783        let (density, _, temp_c, pressure_hpa) = segmented_solver.resolved_atmosphere();
6784        let (_, local_speed_of_sound) = crate::atmosphere::get_local_atmosphere_humid(
6785            segmented_solver.atmosphere.altitude,
6786            segmented_solver.atmosphere.altitude,
6787            temp_c,
6788            pressure_hpa,
6789            density / 1.225,
6790            segmented_solver.atmosphere.humidity,
6791        );
6792        let velocity = Vector3::new(1.5 * local_speed_of_sound, 0.0, 0.0);
6793        let resolved_atmo = (temp_c, pressure_hpa, density / 1.225);
6794
6795        let segmented_acceleration = segmented_solver.calculate_acceleration(
6796            &position,
6797            &velocity,
6798            &Vector3::zeros(),
6799            resolved_atmo,
6800        );
6801        let expected_acceleration = expected_solver.calculate_acceleration(
6802            &position,
6803            &velocity,
6804            &Vector3::zeros(),
6805            resolved_atmo,
6806        );
6807
6808        assert!(
6809            (segmented_acceleration.x - expected_acceleration.x).abs() < 1e-12,
6810            "Mach 1.5 must interpolate BC 0.3: segmented ax={} expected ax={}",
6811            segmented_acceleration.x,
6812            expected_acceleration.x
6813        );
6814    }
6815}
6816
6817#[cfg(test)]
6818mod custom_drag_table_validation_tests {
6819    use super::*;
6820
6821    #[test]
6822    fn solve_accepts_zero_bc_when_custom_table_present() {
6823        let inputs = BallisticInputs {
6824            bc_value: 0.0, // ignored when a table is set
6825            bullet_mass: 0.0106,
6826            bullet_diameter: 0.00782,
6827            muzzle_velocity: 850.0,
6828            custom_drag_table: Some(crate::drag::DragTable::new(
6829                vec![0.5, 1.0, 2.0, 3.0],
6830                vec![0.23, 0.40, 0.30, 0.26],
6831            )),
6832            ..BallisticInputs::default()
6833        };
6834        let solver = TrajectorySolver::new(inputs, WindConditions::default(), AtmosphericConditions::default());
6835        // Must not error on the bc_value gate.
6836        assert!(solver.solve().is_ok());
6837    }
6838
6839    #[test]
6840    fn solve_still_requires_bc_without_table() {
6841        let inputs = BallisticInputs {
6842            bc_value: 0.0,
6843            bullet_mass: 0.0106,
6844            bullet_diameter: 0.00782,
6845            muzzle_velocity: 850.0,
6846            ..BallisticInputs::default()
6847        };
6848        let solver = TrajectorySolver::new(inputs, WindConditions::default(), AtmosphericConditions::default());
6849        assert!(solver.solve().is_err());
6850    }
6851}
6852
6853/// MBA-1356: cd_scale — a whole-curve multiplier on the custom-deck Cd.
6854#[cfg(test)]
6855mod cd_scale_tests {
6856    use super::*;
6857
6858    fn deck() -> crate::drag::DragTable {
6859        crate::drag::DragTable::new(vec![0.5, 1.0, 2.0, 3.0], vec![0.23, 0.40, 0.30, 0.26])
6860    }
6861
6862    fn deck_inputs(cd_scale: f64) -> BallisticInputs {
6863        BallisticInputs {
6864            bullet_mass: 0.0106,
6865            bullet_diameter: 0.00782,
6866            muzzle_velocity: 850.0,
6867            custom_drag_table: Some(deck()),
6868            cd_scale,
6869            ..BallisticInputs::default()
6870        }
6871    }
6872
6873    #[test]
6874    fn default_cd_scale_is_one() {
6875        assert_eq!(BallisticInputs::default().cd_scale, 1.0);
6876    }
6877
6878    /// (a) Default invariance: omitting `cd_scale` (picked up from `..Default::default()`)
6879    /// must be byte-identical to explicitly setting `1.0`, on the custom-deck Cd itself.
6880    #[test]
6881    fn cd_scale_absent_is_byte_identical_to_explicit_one() {
6882        let omitted = BallisticInputs {
6883            bullet_mass: 0.0106,
6884            bullet_diameter: 0.00782,
6885            muzzle_velocity: 850.0,
6886            custom_drag_table: Some(deck()),
6887            ..BallisticInputs::default()
6888        };
6889        let explicit = BallisticInputs {
6890            cd_scale: 1.0,
6891            ..omitted.clone()
6892        };
6893
6894        let solver_omitted =
6895            TrajectorySolver::new(omitted, WindConditions::default(), AtmosphericConditions::default());
6896        let solver_explicit =
6897            TrajectorySolver::new(explicit, WindConditions::default(), AtmosphericConditions::default());
6898
6899        let cd_omitted = solver_omitted.calculate_drag_coefficient(700.0, 340.0);
6900        let cd_explicit = solver_explicit.calculate_drag_coefficient(700.0, 340.0);
6901        assert_eq!(
6902            cd_omitted.to_bits(),
6903            cd_explicit.to_bits(),
6904            "default cd_scale must be bit-identical to an explicit 1.0"
6905        );
6906
6907        // And a full custom-deck solve (the existing pre-MBA-1356 test surface) must still
6908        // succeed unchanged with the field simply absent from the literal.
6909        let result = solver_omitted.solve();
6910        assert!(result.is_ok(), "existing custom-deck solves must pass unchanged");
6911    }
6912
6913    /// The custom-deck interpolation site multiplies the deck's Cd by `cd_scale` exactly.
6914    #[test]
6915    fn cd_scale_multiplies_the_interpolated_cd_exactly() {
6916        let velocity = 700.0;
6917        let speed_of_sound = 340.0;
6918        let mach = velocity / speed_of_sound;
6919        let expected_unscaled = deck().interpolate(mach);
6920
6921        for &scale in &[0.90, 1.0, 1.10, 1.5] {
6922            let solver = TrajectorySolver::new(
6923                deck_inputs(scale),
6924                WindConditions::default(),
6925                AtmosphericConditions::default(),
6926            );
6927            let cd = solver.calculate_drag_coefficient(velocity, speed_of_sound);
6928            assert!(
6929                (cd - expected_unscaled * scale).abs() < 1e-12,
6930                "scale={scale}: cd={cd} expected={}",
6931                expected_unscaled * scale
6932            );
6933        }
6934    }
6935
6936    /// (b) Scale-direction test, cli_api (RK4/RK45) solver path: a higher cd_scale means more
6937    /// drag, so the solve loses more velocity (and correspondingly drops more) over the same
6938    /// downrange distance; a lower cd_scale loses less.
6939    #[test]
6940    fn cd_scale_direction_on_cli_api_solver() {
6941        let solve = |scale: f64| {
6942            TrajectorySolver::new(
6943                deck_inputs(scale),
6944                WindConditions::default(),
6945                AtmosphericConditions::default(),
6946            )
6947            .solve()
6948            .expect("custom-deck solve should succeed")
6949        };
6950
6951        let baseline = solve(1.0);
6952        let scaled_up = solve(1.10);
6953        let scaled_down = solve(0.90);
6954
6955        assert!(
6956            scaled_up.impact_velocity < baseline.impact_velocity,
6957            "cd_scale=1.10 must increase drag -> lower impact velocity: base={} up={}",
6958            baseline.impact_velocity,
6959            scaled_up.impact_velocity
6960        );
6961        assert!(
6962            scaled_down.impact_velocity > baseline.impact_velocity,
6963            "cd_scale=0.90 must decrease drag -> higher impact velocity: base={} down={}",
6964            baseline.impact_velocity,
6965            scaled_down.impact_velocity
6966        );
6967    }
6968
6969    /// (d) `validate_for_solve` rejects a non-finite or non-positive `cd_scale`.
6970    #[test]
6971    fn validate_for_solve_rejects_invalid_cd_scale() {
6972        for bad in [0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
6973            let solver = TrajectorySolver::new(
6974                deck_inputs(bad),
6975                WindConditions::default(),
6976                AtmosphericConditions::default(),
6977            );
6978            assert!(
6979                solver.solve().is_err(),
6980                "cd_scale={bad} must be rejected by validate_for_solve"
6981            );
6982        }
6983    }
6984
6985    /// `require_positive("cd_scale", ...)` is unconditional in `validate_for_solve` (see the
6986    /// comment there) — it must reject an invalid scale even with NO custom drag table present,
6987    /// not just on the deck path the other tests in this module exercise. Otherwise a caller
6988    /// that sets an invalid `cd_scale` without ever touching `custom_drag_table` would slip
6989    /// through unvalidated (the field would simply go unread on this path, but the validation
6990    /// gate itself must not silently skip it).
6991    #[test]
6992    fn validate_for_solve_rejects_invalid_cd_scale_without_a_custom_drag_table() {
6993        for bad in [0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
6994            let inputs = BallisticInputs {
6995                bc_value: 0.5,
6996                bc_type: crate::DragModel::G1,
6997                bullet_mass: 0.0106,
6998                bullet_diameter: 0.00782,
6999                muzzle_velocity: 850.0,
7000                cd_scale: bad,
7001                ..BallisticInputs::default()
7002            };
7003            assert!(inputs.custom_drag_table.is_none(), "precondition: no custom deck");
7004            let solver = TrajectorySolver::new(
7005                inputs,
7006                WindConditions::default(),
7007                AtmosphericConditions::default(),
7008            );
7009            assert!(
7010                solver.solve().is_err(),
7011                "cd_scale={bad} must be rejected by validate_for_solve even without a custom \
7012                 drag table"
7013            );
7014        }
7015    }
7016
7017    /// cd_scale must be inert on the standard G-model/BC path (no custom_drag_table): the
7018    /// scale is read only inside the `custom_drag_table` branch, so a scale far from 1.0 must
7019    /// not perturb a plain G1/G7 solve at all.
7020    #[test]
7021    fn cd_scale_is_inert_without_a_custom_drag_table() {
7022        let make = |cd_scale: f64| BallisticInputs {
7023            bc_value: 0.5,
7024            bc_type: crate::DragModel::G1,
7025            bullet_mass: 0.0106,
7026            bullet_diameter: 0.00782,
7027            muzzle_velocity: 850.0,
7028            cd_scale,
7029            ..BallisticInputs::default()
7030        };
7031        let solver_neutral = TrajectorySolver::new(
7032            make(1.0),
7033            WindConditions::default(),
7034            AtmosphericConditions::default(),
7035        );
7036        let solver_far = TrajectorySolver::new(
7037            make(1.5),
7038            WindConditions::default(),
7039            AtmosphericConditions::default(),
7040        );
7041        let cd_neutral = solver_neutral.calculate_drag_coefficient(700.0, 340.0);
7042        let cd_far = solver_far.calculate_drag_coefficient(700.0, 340.0);
7043        assert_eq!(
7044            cd_neutral.to_bits(),
7045            cd_far.to_bits(),
7046            "cd_scale must not affect the G-model/BC drag path"
7047        );
7048    }
7049
7050    /// (c) Cross-solver consistency: cli_api (RK4/RK45), derivatives-driven, and fast_trajectory
7051    /// all shift together (same relative direction) under cd_scale != 1.0 on the same deck.
7052    #[test]
7053    fn cd_scale_shifts_all_three_solver_paths_in_the_same_direction() {
7054        // --- cli_api ---
7055        let cli_solve = |scale: f64| {
7056            TrajectorySolver::new(
7057                deck_inputs(scale),
7058                WindConditions::default(),
7059                AtmosphericConditions::default(),
7060            )
7061            .solve()
7062            .expect("cli_api custom-deck solve should succeed")
7063        };
7064        let cli_baseline = cli_solve(1.0);
7065        let cli_scaled = cli_solve(1.10);
7066        assert!(
7067            cli_scaled.impact_velocity < cli_baseline.impact_velocity,
7068            "cli_api: cd_scale=1.10 must lower impact velocity"
7069        );
7070
7071        // --- derivatives (the RK4/RK45 generic integrator's kernel) ---
7072        let derivatives_accel_x = |scale: f64| {
7073            let inputs = deck_inputs(scale);
7074            crate::derivatives::compute_derivatives(
7075                nalgebra::Vector3::zeros(),
7076                nalgebra::Vector3::new(700.0, 0.0, 0.0),
7077                &inputs,
7078                nalgebra::Vector3::zeros(),
7079                (1.225, 340.0, 0.0, 0.0),
7080                inputs.bc_value,
7081                None,
7082                0.0,
7083                None,
7084            )[3]
7085        };
7086        let deriv_baseline = derivatives_accel_x(1.0);
7087        let deriv_scaled = derivatives_accel_x(1.10);
7088        assert!(
7089            deriv_scaled < deriv_baseline,
7090            "derivatives: cd_scale=1.10 must make x-acceleration more negative (more drag): \
7091             base={deriv_baseline} scaled={deriv_scaled}"
7092        );
7093
7094        // --- fast_trajectory (fast_integrate) ---
7095        let fast_final_speed = |scale: f64| {
7096            let inputs = deck_inputs(scale);
7097            let wind_sock = crate::wind::WindSock::new(vec![]);
7098            let params = crate::fast_trajectory::FastIntegrationParams {
7099                horiz: 500.0,
7100                vert: 0.0,
7101                initial_state: [0.0, 0.0, 0.0, 850.0, 0.0, 0.0],
7102                t_span: (0.0, 5.0),
7103                atmo_params: (0.0, 15.0, 1013.25, 1.0),
7104                atmo_sock: None,
7105            };
7106            let solution = crate::fast_trajectory::fast_integrate(&inputs, &wind_sock, params);
7107            assert!(solution.success, "fast_integrate must succeed for scale={scale}");
7108            let last = solution.t.len() - 1;
7109            let (vx, vy, vz) = (
7110                solution.y[3][last],
7111                solution.y[4][last],
7112                solution.y[5][last],
7113            );
7114            (vx * vx + vy * vy + vz * vz).sqrt()
7115        };
7116        let fast_baseline = fast_final_speed(1.0);
7117        let fast_scaled = fast_final_speed(1.10);
7118        assert!(
7119            fast_scaled < fast_baseline,
7120            "fast_trajectory: cd_scale=1.10 must lower final speed: base={fast_baseline} scaled={fast_scaled}"
7121        );
7122    }
7123}
7124
7125#[cfg(test)]
7126mod humid_local_mach_tests {
7127    use super::*;
7128
7129    fn solver_with_station_humidity(humidity_percent: f64) -> TrajectorySolver {
7130        let inputs = BallisticInputs {
7131            custom_drag_table: Some(crate::drag::DragTable::new(vec![0.5, 1.5], vec![0.1, 1.1])),
7132            ..BallisticInputs::default()
7133        };
7134        TrajectorySolver::new(
7135            inputs,
7136            WindConditions::default(),
7137            AtmosphericConditions {
7138                temperature: 30.0,
7139                pressure: 1013.25,
7140                humidity: humidity_percent,
7141                altitude: 0.0,
7142            },
7143        )
7144    }
7145
7146    fn acceleration(solver: &TrajectorySolver, base_ratio: f64) -> Vector3<f64> {
7147        solver.calculate_acceleration(
7148            &Vector3::zeros(),
7149            &Vector3::new(350.0, 0.0, 0.0),
7150            &Vector3::zeros(),
7151            (30.0, 1013.25, base_ratio),
7152        )
7153    }
7154
7155    #[test]
7156    fn local_mach_uses_station_humidity_when_density_is_held_constant() {
7157        let dry = acceleration(&solver_with_station_humidity(0.0), 1.0);
7158        let humid = acceleration(&solver_with_station_humidity(100.0), 1.0);
7159
7160        assert!(
7161            humid.x > dry.x,
7162            "humid sound speed should lower Mach and drag on the rising test curve: dry ax={} humid ax={}",
7163            dry.x,
7164            humid.x
7165        );
7166    }
7167
7168    #[test]
7169    fn active_atmosphere_zone_uses_zone_humidity_instead_of_station_humidity() {
7170        let zone_humidity = 80.0;
7171        let zone_ratio =
7172            crate::atmosphere::calculate_air_density_cimp(30.0, 1013.25, zone_humidity) / 1.225;
7173        let station_solver = solver_with_station_humidity(zone_humidity);
7174        let mut zoned_solver = solver_with_station_humidity(0.0);
7175        zoned_solver.set_atmo_segments(vec![(30.0, 1013.25, zone_humidity, 1_000.0)]);
7176
7177        let station = acceleration(&station_solver, zone_ratio);
7178        let zoned = acceleration(&zoned_solver, zone_ratio);
7179
7180        assert!(
7181            (zoned - station).norm() < 1e-12,
7182            "active zone T/P/RH should override the station atmosphere: station={station:?} zoned={zoned:?}"
7183        );
7184    }
7185}
7186
7187#[cfg(test)]
7188mod inclined_atmosphere_frame_tests {
7189    use super::*;
7190
7191    fn expected_shot_frame_vector(level: Vector3<f64>, angle: f64) -> Vector3<f64> {
7192        let (sin_angle, cos_angle) = angle.sin_cos();
7193        Vector3::new(
7194            level.x * cos_angle + level.y * sin_angle,
7195            -level.x * sin_angle + level.y * cos_angle,
7196            level.z,
7197        )
7198    }
7199
7200    #[test]
7201    fn inclined_positions_at_same_world_altitude_have_same_solver_acceleration() {
7202        let angle = std::f64::consts::FRAC_PI_6;
7203        let inputs = BallisticInputs {
7204            shooting_angle: angle,
7205            ..BallisticInputs::default()
7206        };
7207        let atmosphere = AtmosphericConditions {
7208            altitude: 100.0,
7209            ..AtmosphericConditions::default()
7210        };
7211        let solver = TrajectorySolver::new(inputs, WindConditions::default(), atmosphere);
7212        let (density, _, temp_c, pressure_hpa) = solver.resolved_atmosphere();
7213        let resolved_atmo = (temp_c, pressure_hpa, density / 1.225);
7214        let velocity = Vector3::new(600.0, 0.0, 0.0);
7215        let along_slant = Vector3::new(1_000.0, 0.0, 0.0);
7216        let across_slant = Vector3::new(0.0, 500.0 / angle.cos(), 0.0);
7217
7218        let a = solver.calculate_acceleration(
7219            &along_slant,
7220            &velocity,
7221            &Vector3::zeros(),
7222            resolved_atmo,
7223        );
7224        let b = solver.calculate_acceleration(
7225            &across_slant,
7226            &velocity,
7227            &Vector3::zeros(),
7228            resolved_atmo,
7229        );
7230
7231        assert!(
7232            (a - b).norm() < 1e-10,
7233            "solver acceleration differs at equal world altitude: {a:?} vs {b:?}"
7234        );
7235    }
7236
7237    #[test]
7238    fn inclined_headwind_is_rotated_into_solver_frame() {
7239        let angle = std::f64::consts::FRAC_PI_6;
7240        let inputs = BallisticInputs {
7241            shooting_angle: angle,
7242            ..BallisticInputs::default()
7243        };
7244        let solver = TrajectorySolver::new(
7245            inputs,
7246            WindConditions::default(),
7247            AtmosphericConditions::default(),
7248        );
7249        let level_headwind = Vector3::new(-100.0, 0.0, 0.0);
7250        let velocity = expected_shot_frame_vector(level_headwind, angle);
7251        let (density, _, temp_c, pressure_hpa) = solver.resolved_atmosphere();
7252        let actual = solver.calculate_acceleration(
7253            &Vector3::zeros(),
7254            &velocity,
7255            &level_headwind,
7256            (temp_c, pressure_hpa, density / 1.225),
7257        );
7258
7259        assert!(
7260            (actual - solver.gravity_acceleration()).norm() < 1e-12,
7261            "co-moving horizontal wind must leave only shot-frame gravity: {actual:?}"
7262        );
7263    }
7264
7265    #[test]
7266    fn inclined_coriolis_is_rotated_into_solver_frame() {
7267        let angle = std::f64::consts::FRAC_PI_6;
7268        let latitude_deg = 45.0_f64;
7269        let shot_azimuth = 0.4_f64;
7270        let velocity = Vector3::new(600.0, 20.0, 5.0);
7271        let base_inputs = BallisticInputs {
7272            shooting_angle: angle,
7273            latitude: Some(latitude_deg),
7274            shot_azimuth,
7275            ..BallisticInputs::default()
7276        };
7277        let acceleration = |enable_coriolis| {
7278            let mut inputs = base_inputs.clone();
7279            inputs.enable_coriolis = enable_coriolis;
7280            let solver = TrajectorySolver::new(
7281                inputs,
7282                WindConditions::default(),
7283                AtmosphericConditions::default(),
7284            );
7285            let (density, _, temp_c, pressure_hpa) = solver.resolved_atmosphere();
7286            solver.calculate_acceleration(
7287                &Vector3::zeros(),
7288                &velocity,
7289                &Vector3::zeros(),
7290                (temp_c, pressure_hpa, density / 1.225),
7291            )
7292        };
7293
7294        let omega_earth = 7.2921159e-5_f64;
7295        let latitude = latitude_deg.to_radians();
7296        let level_omega = Vector3::new(
7297            omega_earth * latitude.cos() * shot_azimuth.cos(),
7298            omega_earth * latitude.sin(),
7299            -omega_earth * latitude.cos() * shot_azimuth.sin(),
7300        );
7301        let expected = -2.0 * expected_shot_frame_vector(level_omega, angle).cross(&velocity);
7302        let actual = acceleration(true) - acceleration(false);
7303
7304        assert!(
7305            (actual - expected).norm() < 1e-12,
7306            "inclined Coriolis mismatch: actual={actual:?}, expected={expected:?}"
7307        );
7308    }
7309}
7310
7311#[cfg(test)]
7312mod terminal_range_interpolation_tests {
7313    use super::*;
7314
7315    #[test]
7316    fn terminal_finalizer_selects_the_earliest_crossed_boundary() {
7317        let inputs = BallisticInputs {
7318            ground_threshold: 0.0,
7319            ..BallisticInputs::default()
7320        };
7321        let mut solver = TrajectorySolver::new(
7322            inputs,
7323            WindConditions::default(),
7324            AtmosphericConditions::default(),
7325        );
7326        solver.set_max_range(120.0);
7327
7328        let previous_speed = 700.0;
7329        let mut points = vec![TrajectoryPoint {
7330            time: 99.0,
7331            position: Vector3::new(90.0, 1.0, -1.0),
7332            velocity_magnitude: previous_speed,
7333            kinetic_energy: 0.5 * solver.inputs.bullet_mass * previous_speed.powi(2),
7334            drag_coefficient: None,
7335        }];
7336        let mut max_height = 1.0;
7337        let termination = solver
7338            .append_terminal_endpoint(
7339                &mut points,
7340                Vector3::new(130.0, -3.0, 3.0),
7341                Vector3::new(600.0, 0.0, 0.0),
7342                101.0,
7343                &mut max_height,
7344            )
7345            .expect("the final step brackets supported boundaries");
7346
7347        assert_eq!(termination, TrajectoryTermination::GroundThreshold);
7348        assert_eq!(points.len(), 2);
7349        let terminal = points.last().expect("terminal point");
7350        assert_eq!(terminal.time, 99.5);
7351        assert_eq!(terminal.position, Vector3::new(100.0, 0.0, 0.0));
7352        assert_eq!(terminal.velocity_magnitude, 675.0);
7353        assert_eq!(
7354            terminal.kinetic_energy,
7355            0.5 * solver.inputs.bullet_mass * 675.0_f64.powi(2)
7356        );
7357
7358        // At x=100 the range and ground crossings tie; physical ground impact wins explicitly.
7359        solver.set_max_range(100.0);
7360        let mut tied_points = vec![points[0].clone()];
7361        assert_eq!(
7362            solver
7363                .append_terminal_endpoint(
7364                    &mut tied_points,
7365                    Vector3::new(130.0, -3.0, 3.0),
7366                    Vector3::new(600.0, 0.0, 0.0),
7367                    101.0,
7368                    &mut max_height,
7369                )
7370                .expect("tied boundaries remain a valid terminal"),
7371            TrajectoryTermination::GroundThreshold
7372        );
7373    }
7374
7375    #[test]
7376    fn sub_ulp_terminal_crossing_replaces_instead_of_duplicating_range() {
7377        let ground_threshold = f64::from_bits(1.0_f64.to_bits() - 1);
7378        let inputs = BallisticInputs {
7379            ground_threshold,
7380            ..BallisticInputs::default()
7381        };
7382        let mut solver = TrajectorySolver::new(
7383            inputs,
7384            WindConditions::default(),
7385            AtmosphericConditions::default(),
7386        );
7387        solver.set_max_range(1_000.0);
7388
7389        let speed = 700.0;
7390        let mut points = vec![TrajectoryPoint {
7391            time: 0.0,
7392            position: Vector3::new(100.0, 1.0, 0.0),
7393            velocity_magnitude: speed,
7394            kinetic_energy: 0.5 * solver.inputs.bullet_mass * speed.powi(2),
7395            drag_coefficient: None,
7396        }];
7397        let mut max_height = 1.0;
7398        let termination = solver
7399            .append_terminal_endpoint(
7400                &mut points,
7401                Vector3::new(101.0, 0.0, 0.0),
7402                Vector3::new(699.0, 0.0, 0.0),
7403                1.0,
7404                &mut max_height,
7405            )
7406            .expect("sub-ULP ground crossing remains representable as one terminal state");
7407
7408        assert_eq!(termination, TrajectoryTermination::GroundThreshold);
7409        assert_eq!(points.len(), 1);
7410        assert_eq!(points[0].position.x, 100.0);
7411        assert_eq!(points[0].position.y.to_bits(), ground_threshold.to_bits());
7412        assert!(points[0].time > 0.0);
7413    }
7414
7415    #[test]
7416    fn every_solver_appends_an_exact_max_range_endpoint() {
7417        let target_range = 0.1;
7418        let modes = [
7419            ("Euler", false, false),
7420            ("RK4", true, false),
7421            ("RK45", true, true),
7422        ];
7423
7424        for (name, use_rk4, use_adaptive_rk45) in modes {
7425            let inputs = BallisticInputs {
7426                use_rk4,
7427                use_adaptive_rk45,
7428                ground_threshold: f64::NEG_INFINITY,
7429                enable_trajectory_sampling: true,
7430                sample_interval: target_range,
7431                ..BallisticInputs::default()
7432            };
7433            let mut solver = TrajectorySolver::new(
7434                inputs,
7435                WindConditions::default(),
7436                AtmosphericConditions::default(),
7437            );
7438            solver.set_max_range(target_range);
7439
7440            let result = solver.solve().expect("short-range solve should succeed");
7441            let terminal = result.points.last().expect("terminal point is missing");
7442            let muzzle = result.points.first().expect("muzzle point is missing");
7443
7444            assert_eq!(result.termination, TrajectoryTermination::MaxRange);
7445            assert_eq!(
7446                terminal.position.x.to_bits(),
7447                target_range.to_bits(),
7448                "{name} did not terminate exactly at max_range"
7449            );
7450            assert_eq!(result.max_range.to_bits(), target_range.to_bits());
7451            assert!(
7452                result.time_of_flight > 0.0 && result.time_of_flight < solver.time_step,
7453                "{name} terminal time was not interpolated within the crossing step: {}",
7454                result.time_of_flight
7455            );
7456            assert_eq!(result.time_of_flight.to_bits(), terminal.time.to_bits());
7457            assert_eq!(
7458                result.impact_velocity.to_bits(),
7459                terminal.velocity_magnitude.to_bits()
7460            );
7461            assert_eq!(
7462                result.impact_energy.to_bits(),
7463                terminal.kinetic_energy.to_bits()
7464            );
7465            let expected_energy = 0.5 * solver.inputs.bullet_mass * result.impact_velocity.powi(2);
7466            assert!((result.impact_energy - expected_energy).abs() < 1e-12);
7467            assert!(terminal.velocity_magnitude < muzzle.velocity_magnitude);
7468            assert!(terminal.kinetic_energy < muzzle.kinetic_energy);
7469
7470            let terminal_sample = result
7471                .sampled_points
7472                .as_ref()
7473                .and_then(|samples| samples.last())
7474                .expect("terminal trajectory sample is missing");
7475            assert_eq!(
7476                terminal_sample.distance_m.to_bits(),
7477                target_range.to_bits(),
7478                "{name} sampling did not include max_range"
7479            );
7480            assert_eq!(
7481                terminal_sample.time_s.to_bits(),
7482                result.time_of_flight.to_bits()
7483            );
7484            assert_eq!(
7485                terminal_sample.velocity_mps.to_bits(),
7486                result.impact_velocity.to_bits()
7487            );
7488            assert!((terminal_sample.energy_j - result.impact_energy).abs() < 1e-12);
7489        }
7490    }
7491}
7492
7493#[cfg(test)]
7494mod precession_inertia_wiring_tests {
7495    use super::*;
7496
7497    #[test]
7498    fn solver_uses_projectile_specific_moments_of_inertia() {
7499        let mass_kg = 55.0 * crate::constants::GRAINS_TO_KG;
7500        let caliber_m = 0.224 * 0.0254;
7501        let length_m = 0.75 * 0.0254;
7502        let inputs = BallisticInputs {
7503            bullet_mass: mass_kg,
7504            bullet_diameter: caliber_m,
7505            bullet_length: length_m,
7506            muzzle_velocity: 800.0,
7507            twist_rate: 7.0,
7508            enable_precession_nutation: true,
7509            use_rk4: false,
7510            use_adaptive_rk45: false,
7511            ..BallisticInputs::default()
7512        };
7513        let mut solver = TrajectorySolver::new(
7514            inputs,
7515            WindConditions::default(),
7516            AtmosphericConditions::default(),
7517        );
7518        solver.set_max_range(0.1);
7519
7520        let (air_density, speed_of_sound, _, _) = solver.resolved_atmosphere();
7521        let velocity_mps = solver.inputs.muzzle_velocity;
7522        let velocity_fps = velocity_mps * 3.28084;
7523        let twist_rate_ft = solver.inputs.twist_rate / 12.0;
7524        let spin_rate_rad_s = (velocity_fps / twist_rate_ft) * 2.0 * std::f64::consts::PI;
7525        let initial_state = AngularState {
7526            pitch_angle: 0.001,
7527            yaw_angle: 0.001,
7528            pitch_rate: 0.0,
7529            yaw_rate: 0.0,
7530            precession_angle: 0.0,
7531            nutation_phase: 0.0,
7532        };
7533        let params = PrecessionNutationParams {
7534            mass_kg,
7535            caliber_m,
7536            length_m,
7537            spin_rate_rad_s,
7538            spin_inertia: crate::spin_decay::calculate_moment_of_inertia(
7539                mass_kg, caliber_m, length_m, "ogive",
7540            ),
7541            transverse_inertia: crate::pitch_damping::calculate_transverse_moment_of_inertia(
7542                mass_kg, caliber_m, length_m, "ogive",
7543            ),
7544            velocity_mps,
7545            air_density_kg_m3: air_density,
7546            mach: velocity_mps / speed_of_sound,
7547            pitch_damping_coeff: PitchDampingCoefficients::default().subsonic,
7548            nutation_damping_factor: 0.05,
7549        };
7550        let expected = calculate_combined_angular_motion(
7551            &params,
7552            &initial_state,
7553            0.0,
7554            solver.time_step,
7555            0.001,
7556        );
7557        let actual = solver
7558            .solve()
7559            .expect("one-step solve should succeed")
7560            .angular_state
7561            .expect("precession/nutation was enabled");
7562
7563        assert!(
7564            (actual.precession_angle - expected.precession_angle).abs() < 1e-15,
7565            "precession phase used the wrong inertia: actual={}, expected={}",
7566            actual.precession_angle,
7567            expected.precession_angle
7568        );
7569        assert!(
7570            (actual.nutation_phase - expected.nutation_phase).abs() < 1e-15,
7571            "nutation phase used the wrong inertia: actual={}, expected={}",
7572            actual.nutation_phase,
7573            expected.nutation_phase
7574        );
7575    }
7576}
7577
7578#[cfg(test)]
7579mod form_factor_drag_tests {
7580    use super::*;
7581
7582    fn acceleration_with_form_factor_flag(enabled: bool) -> Vector3<f64> {
7583        let inputs = BallisticInputs {
7584            bc_value: 0.462,
7585            bc_type: DragModel::G1,
7586            bullet_model: Some("168gr SMK Match".to_string()),
7587            use_form_factor: enabled,
7588            ..BallisticInputs::default()
7589        };
7590        let solver = TrajectorySolver::new(
7591            inputs,
7592            WindConditions::default(),
7593            AtmosphericConditions::default(),
7594        );
7595        let (density, _, temp_c, pressure_hpa) = solver.resolved_atmosphere();
7596        solver.calculate_acceleration(
7597            &Vector3::zeros(),
7598            &Vector3::new(600.0, 0.0, 0.0),
7599            &Vector3::zeros(),
7600            (temp_c, pressure_hpa, density / 1.225),
7601        )
7602    }
7603
7604    #[test]
7605    fn measured_bc_drag_does_not_apply_name_based_form_factor_again() {
7606        let baseline = acceleration_with_form_factor_flag(false);
7607        let flagged = acceleration_with_form_factor_flag(true);
7608
7609        assert!(
7610            (flagged - baseline).norm() < 1e-12,
7611            "published BC already encodes form factor: baseline={baseline:?} flagged={flagged:?}"
7612        );
7613    }
7614}
7615
7616#[cfg(test)]
7617mod rk45_adaptivity_tests {
7618    use super::*;
7619
7620    #[test]
7621    fn cli_rk45_error_norm_scales_components_independently() {
7622        let position = Vector3::new(1.0e9, 0.0, 0.0);
7623        let velocity = Vector3::new(800.0, 0.0, 0.0);
7624        let fifth_position = position;
7625        let fifth_velocity = velocity;
7626        let fourth_position = position;
7627        let fourth_velocity = Vector3::new(800.0, 1.0e-3, 0.0);
7628
7629        let error = cli_rk45_error_norm(
7630            &position,
7631            &velocity,
7632            &fifth_position,
7633            &fifth_velocity,
7634            &fourth_position,
7635            &fourth_velocity,
7636        );
7637        let expected = 1.0e-3 / 6.0_f64.sqrt();
7638
7639        assert!(
7640            (error - expected).abs() <= 1e-15,
7641            "large downrange position masked a velocity-component error: {error}"
7642        );
7643    }
7644
7645    fn discontinuous_wind_solver() -> TrajectorySolver {
7646        let inputs = BallisticInputs::default();
7647        let mut solver = TrajectorySolver::new(
7648            inputs,
7649            WindConditions::default(),
7650            AtmosphericConditions::default(),
7651        );
7652        solver.set_wind_segments(vec![
7653            crate::wind::WindSegment::new(0.0, 90.0, 4.0),
7654            crate::wind::WindSegment::new(1_000.0, 90.0, 10_000.0),
7655        ]);
7656        solver
7657    }
7658
7659    #[test]
7660    fn rk45_retries_discontinuous_trial_before_advancing() {
7661        let solver = discontinuous_wind_solver();
7662        let position = Vector3::new(0.0, solver.inputs.muzzle_height, 0.0);
7663        let velocity = Vector3::new(solver.inputs.muzzle_velocity, 0.0, 0.0);
7664        let (density, _, temp_c, pressure_hpa) = solver.resolved_atmosphere();
7665        let resolved_atmo = (temp_c, pressure_hpa, density / 1.225);
7666        let dt = 0.01;
7667
7668        let rejected_trial = solver.rk45_step(
7669            &position,
7670            &velocity,
7671            dt,
7672            &Vector3::zeros(),
7673            RK45_TOLERANCE,
7674            resolved_atmo,
7675        );
7676        assert!(
7677            rejected_trial.error > RK45_TOLERANCE,
7678            "discontinuous full step must exceed tolerance, got {}",
7679            rejected_trial.error
7680        );
7681
7682        let accepted = solver.adaptive_rk45_step(
7683            &position,
7684            &velocity,
7685            dt,
7686            &Vector3::zeros(),
7687            resolved_atmo,
7688        );
7689        assert!(accepted.used_dt < dt, "oversized trial was not retried");
7690        assert!(
7691            accepted.error <= RK45_TOLERANCE || accepted.used_dt <= RK45_MIN_DT,
7692            "accepted error {} exceeds tolerance at dt {}",
7693            accepted.error,
7694            accepted.used_dt
7695        );
7696
7697        let accepted_trial = solver.rk45_step(
7698            &position,
7699            &velocity,
7700            accepted.used_dt,
7701            &Vector3::zeros(),
7702            RK45_TOLERANCE,
7703            resolved_atmo,
7704        );
7705        assert_eq!(accepted.position, accepted_trial.position);
7706        assert_eq!(accepted.velocity, accepted_trial.velocity);
7707        assert!((RK45_MIN_DT..=RK45_MAX_DT).contains(&accepted.next_dt));
7708    }
7709}
7710
7711#[cfg(test)]
7712mod ground_termination_tests {
7713    use super::*;
7714    use crate::trajectory_observation::TrajectoryObservationFlag;
7715
7716    #[test]
7717    fn every_solver_reports_one_exact_early_ground_endpoint() {
7718        for (name, use_rk4, use_adaptive_rk45) in [
7719            ("Euler", false, false),
7720            ("RK4", true, false),
7721            ("RK45", true, true),
7722        ] {
7723            let inputs = BallisticInputs {
7724                muzzle_height: 1.0,
7725                muzzle_angle: -0.2,
7726                ground_threshold: 0.0,
7727                use_rk4,
7728                use_adaptive_rk45,
7729                ..BallisticInputs::default()
7730            };
7731            let mut solver = TrajectorySolver::new(
7732                inputs,
7733                WindConditions::default(),
7734                AtmosphericConditions::default(),
7735            );
7736            solver.set_max_range(1_000.0);
7737
7738            let result = solver.solve().expect("early-ground solve should succeed");
7739            let terminal = result.points.last().expect("terminal point is missing");
7740
7741            assert_eq!(result.termination, TrajectoryTermination::GroundThreshold);
7742            assert_eq!(terminal.position.y.to_bits(), 0.0_f64.to_bits());
7743            assert!(
7744                terminal.position.x < 1_000.0,
7745                "{name} incorrectly reached max range"
7746            );
7747            assert_eq!(result.max_range.to_bits(), terminal.position.x.to_bits());
7748            assert_eq!(
7749                result
7750                    .points
7751                    .iter()
7752                    .filter(|point| point.position.y == 0.0)
7753                    .count(),
7754                1,
7755                "{name} did not retain exactly one ground endpoint"
7756            );
7757
7758            let observations = result
7759                .sample_observations(1.0, 100)
7760                .expect("checked early-ground sampling should succeed");
7761            assert!(observations[..observations.len() - 1]
7762                .iter()
7763                .all(|observation| observation.distance_m < terminal.position.x));
7764            let terminal_observation = observations.last().expect("terminal observation");
7765            assert_eq!(
7766                terminal_observation.distance_m.to_bits(),
7767                terminal.position.x.to_bits()
7768            );
7769            assert!(terminal_observation
7770                .flags
7771                .contains(&TrajectoryObservationFlag::Terminal));
7772            assert!(terminal_observation
7773                .flags
7774                .contains(&TrajectoryObservationFlag::GroundThreshold));
7775            assert_eq!(
7776                observations
7777                    .iter()
7778                    .filter(|observation| observation
7779                        .flags
7780                        .contains(&TrajectoryObservationFlag::Terminal))
7781                    .count(),
7782                1,
7783                "{name} repeated the terminal observation"
7784            );
7785        }
7786    }
7787
7788    // Regression lock for the unified ground termination: solve_euler/solve_rk4/solve_rk45 all
7789    // loop while `position.y > ground_threshold` (default -100.0), so they agree with RK45. A
7790    // lofted shot that returns to launch level before reaching max_range must keep descending to
7791    // the -100 m floor instead of stopping at y = 0 — and RK4-fixed and RK45 must behave the same.
7792    #[test]
7793    fn rk4_and_rk45_descend_to_ground_threshold() {
7794        for adaptive in [false, true] {
7795            let inputs = BallisticInputs {
7796                muzzle_angle: 0.1, // ~5.7 deg: arcs up, then descends past launch level
7797                use_rk4: true,
7798                use_adaptive_rk45: adaptive,
7799                ..BallisticInputs::default()
7800            };
7801            assert_eq!(
7802                inputs.ground_threshold, -100.0,
7803                "default ground_threshold is -100 m"
7804            );
7805
7806            let mut solver = TrajectorySolver::new(
7807                inputs,
7808                WindConditions::default(),
7809                AtmosphericConditions::default(),
7810            );
7811            // Huge max range: termination must be driven by ground_threshold, not the range cap.
7812            solver.set_max_range(1.0e7);
7813
7814            let result = solver.solve().expect("solve should succeed");
7815            let final_y = result
7816                .points
7817                .last()
7818                .expect("trajectory has points")
7819                .position
7820                .y;
7821            assert!(
7822                final_y < -1.0,
7823                "adaptive_rk45={adaptive}: final y = {final_y} m; a lofted shot should descend \
7824                 past launch level toward the ground_threshold floor, not stop at y = 0"
7825            );
7826        }
7827    }
7828}
7829
7830#[cfg(test)]
7831mod magnus_stability_tests {
7832    use super::*;
7833
7834    #[test]
7835    fn yaw_of_repose_magnus_force_is_vertical_and_twist_signed() {
7836        let acceleration = |enable_magnus, is_twist_right| {
7837            let inputs = BallisticInputs {
7838                muzzle_velocity: 822.96,
7839                bullet_mass: 168.0 * crate::constants::GRAINS_TO_KG,
7840                bullet_diameter: 0.308 * 0.0254,
7841                bullet_length: 1.215 * 0.0254,
7842                twist_rate: 10.0,
7843                is_twist_right,
7844                enable_magnus,
7845                ..BallisticInputs::default()
7846            };
7847            let solver = TrajectorySolver::new(
7848                inputs,
7849                WindConditions::default(),
7850                AtmosphericConditions::default(),
7851            );
7852            let (density, _, temp_c, pressure_hpa) = solver.resolved_atmosphere();
7853            solver.calculate_acceleration(
7854                &Vector3::zeros(),
7855                &Vector3::new(822.96, 0.0, 0.0),
7856                &Vector3::zeros(),
7857                (temp_c, pressure_hpa, density / 1.225),
7858            )
7859        };
7860
7861        let baseline = acceleration(false, true);
7862        let right_twist = acceleration(true, true) - baseline;
7863        let left_twist = acceleration(true, false) - baseline;
7864
7865        assert!(
7866            right_twist.y < 0.0,
7867            "right-hand Magnus must point down, got {right_twist:?}"
7868        );
7869        assert!(
7870            left_twist.y > 0.0,
7871            "left-hand Magnus must point up, got {left_twist:?}"
7872        );
7873        assert!((right_twist.y + left_twist.y).abs() < 1e-12);
7874        assert!(right_twist.x.abs() < 1e-12 && right_twist.z.abs() < 1e-12);
7875        assert!(left_twist.x.abs() < 1e-12 && left_twist.z.abs() < 1e-12);
7876    }
7877
7878    #[test]
7879    fn magnus_uses_velocity_corrected_muzzle_stability_gate() {
7880        let muzzle_velocity = 1_400.0 / 3.28084;
7881        let inputs = BallisticInputs {
7882            muzzle_velocity,
7883            bullet_mass: 168.0 * crate::constants::GRAINS_TO_KG,
7884            bullet_diameter: 0.308 * 0.0254,
7885            bullet_length: 1.215 * 0.0254,
7886            twist_rate: 15.0,
7887            enable_magnus: true,
7888            ..BallisticInputs::default()
7889        };
7890        let solver = TrajectorySolver::new(
7891            inputs.clone(),
7892            WindConditions::default(),
7893            AtmosphericConditions::default(),
7894        );
7895
7896        let bare_sg = crate::spin_drift::miller_stability(0.308, 168.0, 15.0, 1.215);
7897        let canonical_sg = solver.effective_spin_drift_sg();
7898        assert!(bare_sg > 1.0, "test requires bare Sg above the Magnus gate");
7899        assert!(
7900            canonical_sg < 1.0,
7901            "velocity-corrected Sg must be below the gate, got {canonical_sg}"
7902        );
7903
7904        let (density, _, temp_c, pressure_hpa) = solver.resolved_atmosphere();
7905        let acceleration = solver.calculate_acceleration(
7906            &Vector3::zeros(),
7907            &Vector3::new(muzzle_velocity, 0.0, 0.0),
7908            &Vector3::zeros(),
7909            (temp_c, pressure_hpa, density / 1.225),
7910        );
7911        let mut baseline_inputs = inputs;
7912        baseline_inputs.enable_magnus = false;
7913        let baseline_solver = TrajectorySolver::new(
7914            baseline_inputs,
7915            WindConditions::default(),
7916            AtmosphericConditions::default(),
7917        );
7918        let baseline = baseline_solver.calculate_acceleration(
7919            &Vector3::zeros(),
7920            &Vector3::new(muzzle_velocity, 0.0, 0.0),
7921            &Vector3::zeros(),
7922            (temp_c, pressure_hpa, density / 1.225),
7923        );
7924
7925        assert_eq!(
7926            acceleration, baseline,
7927            "canonical Sg below 1 must suppress every Magnus acceleration component"
7928        );
7929    }
7930
7931    #[test]
7932    fn magnus_force_grows_as_fixed_spin_projectile_slows() {
7933        let inputs = BallisticInputs {
7934            muzzle_velocity: 800.0,
7935            bullet_mass: 168.0 * crate::constants::GRAINS_TO_KG,
7936            bullet_diameter: 0.308 * 0.0254,
7937            bullet_length: 1.215 * 0.0254,
7938            twist_rate: 12.0,
7939            enable_magnus: true,
7940            ..BallisticInputs::default()
7941        };
7942
7943        let magnus_acceleration = |speed_mps| {
7944            let evaluate = |enable_magnus| {
7945                let mut run_inputs = inputs.clone();
7946                run_inputs.enable_magnus = enable_magnus;
7947                let solver = TrajectorySolver::new(
7948                    run_inputs,
7949                    WindConditions::default(),
7950                    AtmosphericConditions::default(),
7951                );
7952                let (density, _, temp_c, pressure_hpa) = solver.resolved_atmosphere();
7953                solver
7954                    .calculate_acceleration(
7955                        &Vector3::zeros(),
7956                        &Vector3::new(speed_mps, 0.0, 0.0),
7957                        &Vector3::zeros(),
7958                        (temp_c, pressure_hpa, density / 1.225),
7959                    )
7960                    .y
7961            };
7962            (evaluate(true) - evaluate(false)).abs()
7963        };
7964
7965        let fast = magnus_acceleration(200.0);
7966        let slow = magnus_acceleration(100.0);
7967        let ratio = slow / fast;
7968        let expected_ratio = 2.0_f64.powf(5.0 / 3.0);
7969
7970        assert!(fast > 0.0 && slow > 0.0, "fast={fast}, slow={slow}");
7971        assert!(
7972            (ratio - expected_ratio).abs() < 1e-3,
7973            "fixed-spin Magnus acceleration must grow downrange; slow/fast={ratio}, \
7974             expected={expected_ratio}"
7975        );
7976    }
7977}
7978
7979#[cfg(test)]
7980mod coriolis_direction_tests {
7981    use super::*;
7982    use std::f64::consts::FRAC_PI_2;
7983
7984    #[test]
7985    fn supersonic_crossing_flags_a_positive_range_sample() {
7986        // A supersonic shot that slows past Mach 1 must flag a sampled point as a Mach
7987        // transition. The underlying transonic_distances were a Vec::new() TODO, so this
7988        // flag was NEVER set regardless of trajectory — this is the regression guard.
7989        use crate::trajectory_sampling::TrajectoryFlag;
7990
7991        for (solver_name, use_rk4, use_adaptive_rk45) in [
7992            ("Euler", false, false),
7993            ("RK4", true, false),
7994            ("RK45", true, true),
7995        ] {
7996            let inputs = BallisticInputs {
7997                muzzle_velocity: 850.0,
7998                bc_value: 0.2,
7999                bc_type: DragModel::G7,
8000                muzzle_angle: 0.03,
8001                enable_trajectory_sampling: true,
8002                sample_interval: 50.0,
8003                use_rk4,
8004                use_adaptive_rk45,
8005                ..BallisticInputs::default()
8006            };
8007            let mut solver = TrajectorySolver::new(
8008                inputs,
8009                WindConditions::default(),
8010                AtmosphericConditions::default(),
8011            );
8012            solver.set_max_range(2000.0);
8013            let samples = solver
8014                .solve()
8015                .expect("supersonic solve should succeed")
8016                .sampled_points
8017                .expect("sampling was enabled");
8018            let flagged_distances: Vec<_> = samples
8019                .iter()
8020                .filter(|sample| sample.flags.contains(&TrajectoryFlag::MachTransition))
8021                .map(|sample| sample.distance_m)
8022                .collect();
8023
8024            assert!(
8025                !flagged_distances.is_empty()
8026                    && flagged_distances.iter().all(|distance| *distance > 0.0),
8027                "{solver_name} must flag genuine crossings only at positive range: {flagged_distances:?}"
8028            );
8029        }
8030    }
8031
8032    #[test]
8033    fn subsonic_launch_does_not_flag_a_muzzle_transition() {
8034        use crate::trajectory_sampling::TrajectoryFlag;
8035
8036        for (solver_name, use_rk4, use_adaptive_rk45) in [
8037            ("Euler", false, false),
8038            ("RK4", true, false),
8039            ("RK45", true, true),
8040        ] {
8041            let inputs = BallisticInputs {
8042                muzzle_velocity: 250.0,
8043                muzzle_angle: 0.02,
8044                enable_trajectory_sampling: true,
8045                sample_interval: 25.0,
8046                use_rk4,
8047                use_adaptive_rk45,
8048                ..BallisticInputs::default()
8049            };
8050            let mut solver = TrajectorySolver::new(
8051                inputs,
8052                WindConditions::default(),
8053                AtmosphericConditions::default(),
8054            );
8055            solver.set_max_range(300.0);
8056            let samples = solver
8057                .solve()
8058                .expect("subsonic solve should succeed")
8059                .sampled_points
8060                .expect("sampling was enabled");
8061
8062            assert!(
8063                samples
8064                    .iter()
8065                    .all(|sample| !sample.flags.contains(&TrajectoryFlag::MachTransition)),
8066                "{solver_name} marked a Mach transition for a launch already below Mach 1"
8067            );
8068        }
8069    }
8070
8071    #[test]
8072    fn mach_transition_tracker_requires_a_downward_crossing() {
8073        fn record(mach_values: &[f64]) -> Vec<f64> {
8074            let mut tracker = MachTransitionTracker::default();
8075            let mut distances = Vec::new();
8076            for (index, mach) in mach_values.iter().copied().enumerate() {
8077                tracker.record_downward_crossings(mach, index as f64 * 10.0, &mut distances);
8078            }
8079            distances
8080        }
8081
8082        assert!(record(&[0.9, 0.8, 0.7]).is_empty());
8083        assert_eq!(record(&[1.1, 1.05, 0.99]), vec![20.0]);
8084        assert_eq!(record(&[1.2, 1.19, 1.0, 0.99]), vec![10.0, 30.0]);
8085        assert_eq!(record(&[0.9, 1.3, 1.1, 0.9, 1.3, 0.8]), vec![20.0, 30.0]);
8086        assert!(record(&[1.3, f64::NAN, 1.1]).is_empty());
8087    }
8088
8089    #[test]
8090    fn mach_transition_tracker_labels_0_9_without_touching_the_flat_vec() {
8091        // MBA-1405: the tracker gains a third (0.9) threshold, but it must NEVER be appended
8092        // to the flat `distances` Vec — only its own labeled field. Reuses the exact input
8093        // sequences pinned by `mach_transition_tracker_requires_a_downward_crossing` above (the
8094        // pre-change flat-Vec behavior for those sequences) and additionally asserts the
8095        // labeled fields.
8096        fn record(mach_values: &[f64]) -> (Vec<f64>, MachTransitionTracker) {
8097            let mut tracker = MachTransitionTracker::default();
8098            let mut distances = Vec::new();
8099            for (index, mach) in mach_values.iter().copied().enumerate() {
8100                tracker.record_downward_crossings(mach, index as f64 * 10.0, &mut distances);
8101            }
8102            (distances, tracker)
8103        }
8104
8105        // Already at/below 1.2 and 1.0 at the muzzle (never crosses those downward from
8106        // above), but DOES cross 0.9 downward at x=10 (previous_mach 0.9 >= 0.9, mach 0.8 < 0.9).
8107        let (distances, tracker) = record(&[0.9, 0.8, 0.7]);
8108        assert!(distances.is_empty()); // flat Vec unchanged (pinned pre-change value)
8109        assert_eq!(tracker.mach_1_2_distance_m, None);
8110        assert_eq!(tracker.mach_1_0_distance_m, None);
8111        assert_eq!(tracker.mach_0_9_distance_m, Some(10.0));
8112
8113        // Crosses 1.0 only (never reaches 1.2 from above, never reaches 0.9).
8114        let (distances, tracker) = record(&[1.1, 1.05, 0.99]);
8115        assert_eq!(distances, vec![20.0]);
8116        assert_eq!(tracker.mach_1_2_distance_m, None);
8117        assert_eq!(tracker.mach_1_0_distance_m, Some(20.0));
8118        assert_eq!(tracker.mach_0_9_distance_m, None);
8119
8120        // Crosses 1.2 then 1.0, never reaches 0.9 (lowest sample is 0.99).
8121        let (distances, tracker) = record(&[1.2, 1.19, 1.0, 0.99]);
8122        assert_eq!(distances, vec![10.0, 30.0]); // flat Vec unchanged
8123        assert_eq!(tracker.mach_1_2_distance_m, Some(10.0));
8124        assert_eq!(tracker.mach_1_0_distance_m, Some(30.0));
8125        assert_eq!(tracker.mach_0_9_distance_m, None);
8126
8127        // Crosses 1.2, then 1.0, then 0.9 — the flat Vec must be EXACTLY {20.0, 30.0} as
8128        // before (0.9 crossing at x=50.0 must NOT appear in it).
8129        let (distances, tracker) = record(&[0.9, 1.3, 1.1, 0.9, 1.3, 0.8]);
8130        assert_eq!(distances, vec![20.0, 30.0]); // flat Vec unchanged (pinned pre-change value)
8131        assert_eq!(tracker.mach_1_2_distance_m, Some(20.0));
8132        assert_eq!(tracker.mach_1_0_distance_m, Some(30.0));
8133        assert_eq!(tracker.mach_0_9_distance_m, Some(50.0));
8134        assert!(
8135            tracker.mach_1_2_distance_m < tracker.mach_1_0_distance_m
8136                && tracker.mach_1_0_distance_m < tracker.mach_0_9_distance_m,
8137            "labeled crossings must be strictly increasing downrange"
8138        );
8139
8140        // NAN resets tracking exactly as before; no labels set either.
8141        let (distances, tracker) = record(&[1.3, f64::NAN, 1.1]);
8142        assert!(distances.is_empty());
8143        assert_eq!(tracker.mach_1_2_distance_m, None);
8144        assert_eq!(tracker.mach_1_0_distance_m, None);
8145        assert_eq!(tracker.mach_0_9_distance_m, None);
8146    }
8147
8148    #[test]
8149    fn humidity_percent_converts_and_clamps() {
8150        // MBA-722: BallisticInputs.humidity is a 0-1 fraction; the helper yields 0-100 percent.
8151        let mut i = BallisticInputs {
8152            humidity: 0.5,
8153            ..BallisticInputs::default()
8154        };
8155        assert!((i.humidity_percent() - 50.0).abs() < 1e-9, "0.5 -> 50%");
8156        i.humidity = 0.0;
8157        assert_eq!(i.humidity_percent(), 0.0);
8158        i.humidity = 1.0;
8159        assert_eq!(i.humidity_percent(), 100.0);
8160        i.humidity = 1.5; // out of range -> clamped, never > 100
8161        assert_eq!(i.humidity_percent(), 100.0);
8162    }
8163
8164    /// Vertical position (m) at a given downrange `range_m`, for a shot fired along
8165    /// compass bearing `shot_azimuth` (radians, 0=N) with Coriolis enabled.
8166    fn vertical_at(shot_azimuth: f64, range_m: f64) -> f64 {
8167        let inputs = BallisticInputs {
8168            muzzle_velocity: 800.0,
8169            bc_value: 0.5,
8170            bc_type: DragModel::G7,
8171            muzzle_angle: 0.02, // ~20 mrad so it carries well past range_m
8172            enable_coriolis: true,
8173            latitude: Some(45.0),
8174            shot_azimuth,
8175            ground_threshold: f64::NEG_INFINITY, // never terminate early
8176            ..BallisticInputs::default()
8177        };
8178        let mut solver = TrajectorySolver::new(
8179            inputs,
8180            WindConditions::default(),
8181            AtmosphericConditions::default(),
8182        );
8183        solver.set_max_range(range_m + 50.0);
8184        let r = solver.solve().expect("solve");
8185        let pts = &r.points;
8186        for i in 1..pts.len() {
8187            if pts[i].position.x >= range_m {
8188                let p1 = &pts[i - 1];
8189                let p2 = &pts[i];
8190                let t = (range_m - p1.position.x) / (p2.position.x - p1.position.x);
8191                return p1.position.y + t * (p2.position.y - p1.position.y);
8192            }
8193        }
8194        panic!("range {range_m} not reached");
8195    }
8196
8197    /// Regression for the shot-direction Coriolis bug: the Eötvös vertical term
8198    /// `a_up = +2Ω cosφ v_east` lifts an EAST shot and depresses a WEST shot, so at a
8199    /// common range east must sit HIGHER than west, with north in between. Before the
8200    /// fix, `--shot-direction` never reached the solver and E/W/N were identical.
8201    #[test]
8202    fn eotvos_east_higher_than_west() {
8203        let range = 600.0;
8204        let east = vertical_at(FRAC_PI_2, range); // 90° E
8205        let west = vertical_at(3.0 * FRAC_PI_2, range); // 270° W
8206        let north = vertical_at(0.0, range); // 0° N
8207        assert!(
8208            east > west,
8209            "east ({east:.5}) must be higher than west ({west:.5}) at {range} m (Eötvös)"
8210        );
8211        assert!(
8212            east > north && north > west,
8213            "north ({north:.5}) must lie between east ({east:.5}) and west ({west:.5})"
8214        );
8215        assert!(
8216            (east - west) > 1e-3,
8217            "E-W vertical separation ({:.6} m) should be physically meaningful, not FP noise",
8218            east - west
8219        );
8220    }
8221
8222    /// MBA-1405: labeled Mach-crossing distances on `TrajectoryResult`, pinned exactly against
8223    /// a capture of the (pre-change) flat `transonic_distances` Vec taken from this same
8224    /// muzzle_velocity=850/bc=0.2 G7/angle=0.03/max_range=2000 scenario, for all three solver
8225    /// paths. Because `MachTransitionTracker::record_downward_crossings` writes the labeled
8226    /// field and pushes to the flat Vec from the SAME `downrange_m` value at the SAME crossing,
8227    /// these pinned labels ARE the flat-Vec content for the 1.2/1.0 thresholds — proving the
8228    /// flat Vec is untouched by the 0.9 addition.
8229    #[test]
8230    fn labeled_mach_crossings_match_pinned_pre_change_flat_vec_across_solvers() {
8231        // (solver_name, use_rk4, use_adaptive_rk45, expected mach_1_2, expected mach_1_0)
8232        let cases = [
8233            ("Euler", false, false, 670.9878683238721_f64, 805.5274119916264_f64),
8234            ("RK4", true, false, 671.7257336844475_f64, 805.933409072171_f64),
8235            ("RK45", true, true, 672.4905711917901_f64, 806.5709746782849_f64),
8236        ];
8237
8238        for (solver_name, use_rk4, use_adaptive_rk45, expected_1_2, expected_1_0) in cases {
8239            let inputs = BallisticInputs {
8240                muzzle_velocity: 850.0,
8241                bc_value: 0.2,
8242                bc_type: DragModel::G7,
8243                muzzle_angle: 0.03,
8244                use_rk4,
8245                use_adaptive_rk45,
8246                ..BallisticInputs::default()
8247            };
8248            let mut solver = TrajectorySolver::new(
8249                inputs,
8250                WindConditions::default(),
8251                AtmosphericConditions::default(),
8252            );
8253            solver.set_max_range(2000.0);
8254            let result = solver.solve().expect("solve should succeed");
8255
8256            assert_eq!(
8257                result.mach_1_2_distance_m,
8258                Some(expected_1_2),
8259                "{solver_name}: mach_1_2_distance_m must match the pinned pre-change flat-Vec value"
8260            );
8261            assert_eq!(
8262                result.mach_1_0_distance_m,
8263                Some(expected_1_0),
8264                "{solver_name}: mach_1_0_distance_m must match the pinned pre-change flat-Vec value"
8265            );
8266
8267            let mach_1_2 = result.mach_1_2_distance_m.expect("crosses 1.2");
8268            let mach_1_0 = result.mach_1_0_distance_m.expect("crosses 1.0");
8269            let mach_0_9 = result
8270                .mach_0_9_distance_m
8271                .expect("this trajectory also goes past 0.9 within 2000 m");
8272            assert!(
8273                mach_1_2 < mach_1_0 && mach_1_0 < mach_0_9,
8274                "{solver_name}: labeled crossings must be strictly increasing downrange \
8275                 (1.2={mach_1_2}, 1.0={mach_1_0}, 0.9={mach_0_9})"
8276            );
8277        }
8278    }
8279
8280    /// A trajectory that terminates while still well above Mach 1.2 must leave all three
8281    /// labeled crossings `None` (there is nothing to cross), across all three solver paths.
8282    #[test]
8283    fn labeled_mach_crossings_are_none_for_a_fully_supersonic_trajectory() {
8284        for (solver_name, use_rk4, use_adaptive_rk45) in [
8285            ("Euler", false, false),
8286            ("RK4", true, false),
8287            ("RK45", true, true),
8288        ] {
8289            let inputs = BallisticInputs {
8290                muzzle_velocity: 850.0,
8291                bc_value: 0.2,
8292                bc_type: DragModel::G7,
8293                muzzle_angle: 0.03,
8294                use_rk4,
8295                use_adaptive_rk45,
8296                ..BallisticInputs::default()
8297            };
8298            let mut solver = TrajectorySolver::new(
8299                inputs,
8300                WindConditions::default(),
8301                AtmosphericConditions::default(),
8302            );
8303            // Well short of the ~671 m downward 1.2 crossing measured for this load.
8304            solver.set_max_range(200.0);
8305            let result = solver.solve().expect("solve should succeed");
8306
8307            assert_eq!(
8308                result.mach_1_2_distance_m, None,
8309                "{solver_name}: must not report a 1.2 crossing that never happens"
8310            );
8311            assert_eq!(
8312                result.mach_1_0_distance_m, None,
8313                "{solver_name}: must not report a 1.0 crossing that never happens"
8314            );
8315            assert_eq!(
8316                result.mach_0_9_distance_m, None,
8317                "{solver_name}: must not report a 0.9 crossing that never happens"
8318            );
8319        }
8320    }
8321}
8322
8323#[cfg(test)]
8324mod cant_tests {
8325    use super::*;
8326
8327    fn base_inputs() -> BallisticInputs {
8328        BallisticInputs {
8329            muzzle_velocity: 800.0,
8330            bc_value: 0.5,
8331            bc_type: DragModel::G7,
8332            bullet_mass: 0.0109,
8333            bullet_diameter: 0.00782,
8334            bullet_length: 0.0309,
8335            sight_height: 0.05,
8336            twist_rate: 10.0,
8337            use_rk4: true,
8338            ..BallisticInputs::default()
8339        }
8340    }
8341
8342    fn solve_with(inputs: BallisticInputs, max_range: f64) -> TrajectoryResult {
8343        let mut s = TrajectorySolver::new(
8344            inputs,
8345            WindConditions::default(),
8346            AtmosphericConditions::default(),
8347        );
8348        s.set_max_range(max_range);
8349        s.solve().expect("solve")
8350    }
8351
8352    /// Interpolate (y, z) at downrange x.
8353    fn yz_at(result: &TrajectoryResult, x: f64) -> (f64, f64) {
8354        let pts = &result.points;
8355        for i in 1..pts.len() {
8356            if pts[i].position.x >= x {
8357                let (p1, p2) = (&pts[i - 1], &pts[i]);
8358                let dx = p2.position.x - p1.position.x;
8359                let t = if dx.abs() < 1e-12 { 0.0 } else { (x - p1.position.x) / dx };
8360                return (
8361                    p1.position.y + t * (p2.position.y - p1.position.y),
8362                    p1.position.z + t * (p2.position.z - p1.position.z),
8363                );
8364            }
8365        }
8366        panic!("trajectory never reached {x} m");
8367    }
8368
8369    #[test]
8370    fn cant_sign_clockwise_up_offset_goes_right_and_low() {
8371        // Upward zero offset + clockwise cant => POI right (+z) and low vs un-canted.
8372        let mut level = base_inputs();
8373        level.muzzle_angle = 0.003; // ~10 MOA up
8374        let mut canted = level.clone();
8375        canted.cant_angle = 10f64.to_radians();
8376
8377        let (y0, z0) = yz_at(&solve_with(level, 400.0), 300.0);
8378        let (y1, z1) = yz_at(&solve_with(canted, 400.0), 300.0);
8379        assert!(z1 > z0 + 0.01, "clockwise cant must move POI right: z0={z0} z1={z1}");
8380        assert!(y1 < y0 - 0.001, "clockwise cant must move POI low: y0={y0} y1={y1}");
8381    }
8382
8383    #[test]
8384    fn pure_cant_shows_bore_offset_near_range() {
8385        // No aim offset: the only lateral source near the muzzle is the swung bore,
8386        // z0 = -sight_height*sin(cant) (left of the aim plane for clockwise cant).
8387        let mut i = base_inputs();
8388        i.muzzle_angle = 0.0;
8389        i.cant_angle = 10f64.to_radians();
8390        let sh = i.sight_height;
8391        let r = solve_with(i, 60.0);
8392        let first = &r.points[1]; // just past the muzzle
8393        let expected = -sh * 10f64.to_radians().sin();
8394        assert!(
8395            (first.position.z - expected).abs() < 0.005,
8396            "near-muzzle lateral {} should be ~bore offset {expected}",
8397            first.position.z
8398        );
8399    }
8400
8401    #[test]
8402    fn zero_angle_is_independent_of_cant() {
8403        let a = base_inputs();
8404        let mut b = base_inputs();
8405        b.cant_angle = 15f64.to_radians();
8406        let za = calculate_zero_angle(a.clone(), 100.0, 0.0).expect("zero a");
8407        let zb = calculate_zero_angle(b.clone(), 100.0, 0.0).expect("zero b");
8408        assert_eq!(za.to_bits(), zb.to_bits(), "zeroing must ignore cant: {za} vs {zb}");
8409        // silence unused warnings
8410        let _ = (a.cant_angle, b.cant_angle);
8411    }
8412
8413    #[test]
8414    fn nonfinite_cant_is_rejected() {
8415        let mut i = base_inputs();
8416        i.cant_angle = f64::NAN;
8417        let s = TrajectorySolver::new(i, WindConditions::default(), AtmosphericConditions::default());
8418        assert!(s.solve().is_err());
8419    }
8420
8421    #[test]
8422    fn incline_and_cant_compose_without_breaking() {
8423        // 15-degree incline + 10-degree cant: finite result, cant still pushes right.
8424        let mut flat = base_inputs();
8425        flat.muzzle_angle = 0.003;
8426        flat.shooting_angle = 15f64.to_radians();
8427        let mut canted = flat.clone();
8428        canted.cant_angle = 10f64.to_radians();
8429        let (_, z_flat) = yz_at(&solve_with(flat, 400.0), 300.0);
8430        let (_, z_cant) = yz_at(&solve_with(canted, 400.0), 300.0);
8431        assert!(z_cant > z_flat, "cant must still deflect right on an incline");
8432    }
8433}
8434
8435#[cfg(test)]
8436mod vertical_wind_tests {
8437    use super::*;
8438
8439    fn base_inputs() -> BallisticInputs {
8440        BallisticInputs {
8441            muzzle_velocity: 800.0,
8442            bc_value: 0.5,
8443            bc_type: DragModel::G7,
8444            bullet_mass: 0.0109,
8445            bullet_diameter: 0.00782,
8446            bullet_length: 0.0309,
8447            sight_height: 0.05,
8448            twist_rate: 10.0,
8449            use_rk4: true,
8450            ..BallisticInputs::default()
8451        }
8452    }
8453
8454    /// Interpolate trajectory height (McCoy Y) at downrange distance `x`.
8455    fn y_at(result: &TrajectoryResult, x: f64) -> f64 {
8456        let pts = &result.points;
8457        for i in 1..pts.len() {
8458            if pts[i].position.x >= x {
8459                let (p1, p2) = (&pts[i - 1], &pts[i]);
8460                let dx = p2.position.x - p1.position.x;
8461                let t = if dx.abs() < 1e-12 { 0.0 } else { (x - p1.position.x) / dx };
8462                return p1.position.y + t * (p2.position.y - p1.position.y);
8463            }
8464        }
8465        panic!("trajectory never reached {x} m");
8466    }
8467
8468    fn solve_with(inputs: BallisticInputs, wind: WindConditions, max_range: f64) -> TrajectoryResult {
8469        let mut s = TrajectorySolver::new(inputs, wind, AtmosphericConditions::default());
8470        s.set_max_range(max_range);
8471        s.solve().expect("solve")
8472    }
8473
8474    #[test]
8475    fn updraft_raises_poi_downrange() {
8476        // No shear, no segments: this exercises the constant-wind sites in
8477        // solve_euler/solve_rk4/solve_rk45 directly (MBA-728).
8478        let calm_inputs = base_inputs();
8479        let calm_wind = WindConditions::default();
8480        let updraft = WindConditions {
8481            vertical_speed: 5.0,
8482            ..Default::default()
8483        };
8484
8485        let calm = solve_with(calm_inputs.clone(), calm_wind, 500.0);
8486        let updraft_result = solve_with(calm_inputs, updraft, 500.0);
8487
8488        let y_calm = y_at(&calm, 400.0);
8489        let y_updraft = y_at(&updraft_result, 400.0);
8490        assert!(
8491            y_updraft > y_calm,
8492            "5 m/s updraft must raise POI at 400m: calm={y_calm}, updraft={y_updraft}"
8493        );
8494    }
8495
8496    #[test]
8497    fn zero_vertical_is_default_and_finite_required() {
8498        assert_eq!(WindConditions::default().vertical_speed, 0.0);
8499
8500        let inputs = base_inputs();
8501        let wind = WindConditions {
8502            vertical_speed: f64::NAN,
8503            ..Default::default()
8504        };
8505        let s = TrajectorySolver::new(inputs, wind, AtmosphericConditions::default());
8506        assert!(
8507            s.solve().is_err(),
8508            "NaN wind.vertical_speed must be rejected by validate_for_solve"
8509        );
8510    }
8511}
8512
8513/// MBA-1365: declare whether a BC is ICAO- or Army-Standard-Metro-referenced.
8514#[cfg(test)]
8515mod bc_reference_standard_tests {
8516    use super::*;
8517
8518    fn base_inputs() -> BallisticInputs {
8519        BallisticInputs {
8520            muzzle_velocity: 800.0,
8521            bc_value: 0.5,
8522            bc_type: DragModel::G7,
8523            bullet_mass: 0.0109,
8524            bullet_diameter: 0.00782,
8525            bullet_length: 0.0309,
8526            sight_height: 0.05,
8527            twist_rate: 10.0,
8528            use_rk4: true,
8529            ..BallisticInputs::default()
8530        }
8531    }
8532
8533    /// Interpolate trajectory height (McCoy Y) and speed at downrange distance `x`.
8534    fn y_and_speed_at(result: &TrajectoryResult, x: f64) -> (f64, f64) {
8535        let pts = &result.points;
8536        for i in 1..pts.len() {
8537            if pts[i].position.x >= x {
8538                let (p1, p2) = (&pts[i - 1], &pts[i]);
8539                let dx = p2.position.x - p1.position.x;
8540                let t = if dx.abs() < 1e-12 {
8541                    0.0
8542                } else {
8543                    (x - p1.position.x) / dx
8544                };
8545                return (
8546                    p1.position.y + t * (p2.position.y - p1.position.y),
8547                    p1.velocity_magnitude + t * (p2.velocity_magnitude - p1.velocity_magnitude),
8548                );
8549            }
8550        }
8551        panic!("trajectory never reached {x} m");
8552    }
8553
8554    // ---- The constant itself -----------------------------------------------------------
8555
8556    #[test]
8557    fn asm_to_icao_ratio_matches_documented_value() {
8558        assert!(
8559            (crate::constants::ASM_TO_ICAO_BC - 0.98237).abs() < 1e-5,
8560            "ASM_TO_ICAO_BC = {} must equal 0.98237 to 5 decimal places",
8561            crate::constants::ASM_TO_ICAO_BC
8562        );
8563        // Derived from the two named densities, not a bare literal. (The ratio being < 1.0
8564        // — a denser reference atmosphere implying a numerically smaller ICAO-equivalent
8565        // BC — is already established by the 0.98237 check above; a bare `assert!` on a
8566        // const-only comparison here would be compiled away, so it isn't repeated.)
8567        assert_eq!(
8568            crate::constants::ASM_TO_ICAO_BC,
8569            crate::constants::ASM_DENSITY_LB_FT3 / crate::constants::ICAO_DENSITY_LB_FT3
8570        );
8571    }
8572
8573    // ---- Default / byte-identical --------------------------------------------------------
8574
8575    #[test]
8576    fn default_bc_reference_standard_is_icao() {
8577        assert_eq!(
8578            BallisticInputs::default().bc_reference_standard,
8579            BcReferenceStandard::Icao
8580        );
8581    }
8582
8583    /// RED (pre-MBA-1365) would not compile at all — there was no field to normalize.
8584    /// GREEN: with the field defaulted to `Icao`, `TrajectorySolver::new` must never
8585    /// touch `bc_value` — bit-for-bit, not just approximately — so every existing
8586    /// caller that never sets this field is byte-identical to today.
8587    #[test]
8588    fn icao_reference_leaves_bc_value_bit_identical() {
8589        let raw_bc: f64 = 0.4372911; // an arbitrary, non-round value
8590        let inputs = BallisticInputs {
8591            bc_value: raw_bc,
8592            bc_reference_standard: BcReferenceStandard::Icao,
8593            ..base_inputs()
8594        };
8595        let solver = TrajectorySolver::new(inputs, WindConditions::default(), AtmosphericConditions::default());
8596        assert_eq!(solver.inputs.bc_value.to_bits(), raw_bc.to_bits());
8597    }
8598
8599    #[test]
8600    fn default_inputs_solve_is_unaffected_by_the_new_field_existing() {
8601        // A solve built entirely from BallisticInputs::default() (which now carries
8602        // bc_reference_standard: Icao) must match a solve of an equivalent struct that
8603        // never mentions the field at all in its literal (relying on ..default()).
8604        let a = TrajectorySolver::new(base_inputs(), WindConditions::default(), AtmosphericConditions::default())
8605            .solve()
8606            .expect("solve a");
8607        let b = TrajectorySolver::new(
8608            BallisticInputs { ..base_inputs() },
8609            WindConditions::default(),
8610            AtmosphericConditions::default(),
8611        )
8612        .solve()
8613        .expect("solve b");
8614        assert_eq!(a.impact_velocity.to_bits(), b.impact_velocity.to_bits());
8615        assert_eq!(a.max_range.to_bits(), b.max_range.to_bits());
8616    }
8617
8618    // ---- ArmyStandardMetro normalization --------------------------------------------------
8619
8620    #[test]
8621    fn army_standard_metro_scales_bc_value_by_exactly_the_derived_ratio() {
8622        let raw_bc = 0.5;
8623        let inputs = BallisticInputs {
8624            bc_value: raw_bc,
8625            bc_reference_standard: BcReferenceStandard::ArmyStandardMetro,
8626            ..base_inputs()
8627        };
8628        let solver = TrajectorySolver::new(inputs, WindConditions::default(), AtmosphericConditions::default());
8629        assert_eq!(
8630            solver.inputs.bc_value,
8631            raw_bc * crate::constants::ASM_TO_ICAO_BC
8632        );
8633    }
8634
8635    #[test]
8636    fn army_standard_metro_scales_mach_keyed_bc_segments() {
8637        let inputs = BallisticInputs {
8638            bc_reference_standard: BcReferenceStandard::ArmyStandardMetro,
8639            bc_segments: Some(vec![(0.5, 0.40), (1.5, 0.30)]),
8640            ..base_inputs()
8641        };
8642        let solver = TrajectorySolver::new(inputs, WindConditions::default(), AtmosphericConditions::default());
8643        let segments = solver.inputs.bc_segments.as_ref().expect("segments");
8644        assert_eq!(segments[0], (0.5, 0.40 * crate::constants::ASM_TO_ICAO_BC));
8645        assert_eq!(segments[1], (1.5, 0.30 * crate::constants::ASM_TO_ICAO_BC));
8646    }
8647
8648    #[test]
8649    fn army_standard_metro_scales_velocity_keyed_bc_segments_data() {
8650        let inputs = BallisticInputs {
8651            bc_reference_standard: BcReferenceStandard::ArmyStandardMetro,
8652            bc_segments_data: Some(vec![
8653                crate::BCSegmentData {
8654                    velocity_min: 0.0,
8655                    velocity_max: 500.0,
8656                    bc_value: 0.40,
8657                },
8658                crate::BCSegmentData {
8659                    velocity_min: 500.0,
8660                    velocity_max: 900.0,
8661                    bc_value: 0.45,
8662                },
8663            ]),
8664            ..base_inputs()
8665        };
8666        let solver = TrajectorySolver::new(inputs, WindConditions::default(), AtmosphericConditions::default());
8667        let segments = solver.inputs.bc_segments_data.as_ref().expect("segments");
8668        assert_eq!(segments[0].bc_value, 0.40 * crate::constants::ASM_TO_ICAO_BC);
8669        assert_eq!(segments[1].bc_value, 0.45 * crate::constants::ASM_TO_ICAO_BC);
8670        // Non-BC fields must be untouched.
8671        assert_eq!(segments[0].velocity_min, 0.0);
8672        assert_eq!(segments[1].velocity_max, 900.0);
8673    }
8674
8675    /// Empirically verify the drag DIRECTION (not just the arithmetic): declaring the
8676    /// SAME raw BC number as Army-Standard-Metro must produce MORE drop and LOWER
8677    /// remaining velocity downrange than declaring it ICAO, because the normalized
8678    /// (smaller) BC feeds MORE drag into the ICAO-calibrated retardation formula.
8679    #[test]
8680    fn army_standard_metro_moves_impact_in_the_more_drag_direction() {
8681        let solve_at = |standard: BcReferenceStandard| {
8682            let inputs = BallisticInputs {
8683                bc_value: 0.475,
8684                bc_reference_standard: standard,
8685                ..base_inputs()
8686            };
8687            let mut solver =
8688                TrajectorySolver::new(inputs, WindConditions::default(), AtmosphericConditions::default());
8689            solver.set_max_range(500.0);
8690            solver.solve().expect("solve")
8691        };
8692
8693        let icao = solve_at(BcReferenceStandard::Icao);
8694        let asm = solve_at(BcReferenceStandard::ArmyStandardMetro);
8695
8696        let (y_icao, v_icao) = y_and_speed_at(&icao, 400.0);
8697        let (y_asm, v_asm) = y_and_speed_at(&asm, 400.0);
8698
8699        assert!(
8700            y_asm < y_icao,
8701            "ArmyStandardMetro must drop MORE (lower y) at 400m than Icao for the same raw \
8702             bc_value: icao_y={y_icao}, asm_y={y_asm}"
8703        );
8704        assert!(
8705            v_asm < v_icao,
8706            "ArmyStandardMetro must retain LESS velocity at 400m than Icao for the same raw \
8707             bc_value: icao_v={v_icao}, asm_v={v_asm}"
8708        );
8709    }
8710
8711    // ---- Downstream inheritance: Monte Carlo ----------------------------------------------
8712
8713    /// Monte Carlo must inherit the exact same normalization with zero duplicated math:
8714    /// with every std-dev pinned to 0 (so every sample is deterministically the base
8715    /// input, unperturbed), a single-sample MC run must match a plain direct solve of the
8716    /// identical base inputs bit-for-bit.
8717    #[test]
8718    fn monte_carlo_inherits_the_normalized_bc_reference() {
8719        let base_inputs_asm = BallisticInputs {
8720            bc_value: 0.475,
8721            bc_reference_standard: BcReferenceStandard::ArmyStandardMetro,
8722            ..base_inputs()
8723        };
8724        let wind = WindConditions::default();
8725
8726        // Match run_monte_carlo_with_wind_and_direction_std_dev_using_rng's own
8727        // solver_max_range derivation exactly (target_hint.max(1000.0) * 2.0, with
8728        // target_hint = base_inputs.target_distance since MonteCarloParams.target_distance
8729        // is None below) — otherwise the two solves integrate to different caps and a
8730        // level, non-ground-impacting shot legitimately reports a different max_range.
8731        let mut direct_solver =
8732            TrajectorySolver::new(base_inputs_asm.clone(), wind.clone(), AtmosphericConditions::default());
8733        direct_solver.set_max_range(base_inputs_asm.target_distance.max(1000.0) * 2.0);
8734        let direct = direct_solver.solve().expect("direct solve");
8735
8736        let mc_params = MonteCarloParams {
8737            num_simulations: 1,
8738            velocity_std_dev: 0.0,
8739            angle_std_dev: 0.0,
8740            bc_std_dev: 0.0,
8741            wind_speed_std_dev: 0.0,
8742            target_distance: None,
8743            base_wind_speed: 0.0,
8744            base_wind_direction: 0.0,
8745            azimuth_std_dev: 0.0,
8746        };
8747        let mc = run_monte_carlo_with_wind_and_direction_std_dev_seeded(
8748            base_inputs_asm,
8749            wind,
8750            mc_params,
8751            0.0,
8752            42,
8753        )
8754        .expect("monte carlo");
8755
8756        assert_eq!(mc.ranges.len(), 1);
8757        assert_eq!(
8758            mc.ranges[0].to_bits(),
8759            direct.max_range.to_bits(),
8760            "a zero-dispersion single MC sample must match a plain solve of the same \
8761             ASM-referenced inputs bit-for-bit"
8762        );
8763        assert_eq!(
8764            mc.impact_velocities[0].to_bits(),
8765            direct.impact_velocity.to_bits()
8766        );
8767    }
8768
8769    // ---- Downstream inheritance: estimate-bc fitting --------------------------------------
8770
8771    /// `estimate_bc_fit` always builds its internal search trials from
8772    /// `BallisticInputs { ..Default::default() }`, which defaults to `Icao` — so a fitted
8773    /// BC is always ICAO-referenced regardless of any other configuration in the process.
8774    /// Prove it by generating synthetic drop data from a KNOWN Icao-referenced bc_value and
8775    /// confirming the fit recovers that same value (not an ASM-shifted one).
8776    #[test]
8777    fn estimate_bc_fit_recovers_an_icao_referenced_bc() {
8778        let known_bc = 0.475;
8779        let velocity = 800.0;
8780        let mass = 0.0109;
8781        let diameter = 0.00782;
8782        let atmosphere = AtmosphericConditions::default();
8783
8784        let synth_inputs = BallisticInputs {
8785            muzzle_velocity: velocity,
8786            bc_value: known_bc,
8787            bc_type: DragModel::G7,
8788            bullet_mass: mass,
8789            bullet_diameter: diameter,
8790            bullet_length: 0.0309,
8791            sight_height: 0.05,
8792            twist_rate: 10.0,
8793            use_rk4: true,
8794            bc_reference_standard: BcReferenceStandard::Icao,
8795            ..BallisticInputs::default()
8796        };
8797        let mut solver = TrajectorySolver::new(synth_inputs, WindConditions::default(), atmosphere.clone());
8798        solver.set_max_range(500.0);
8799        let trajectory = solver.solve().expect("synthetic solve");
8800
8801        let points: Vec<(f64, f64)> = [100.0, 200.0, 300.0, 400.0]
8802            .iter()
8803            .map(|&d| {
8804                let (y, _) = {
8805                    let pts = &trajectory.points;
8806                    let mut found = None;
8807                    for i in 1..pts.len() {
8808                        if pts[i].position.x >= d {
8809                            let (p1, p2) = (&pts[i - 1], &pts[i]);
8810                            let dx = p2.position.x - p1.position.x;
8811                            let t = if dx.abs() < 1e-12 {
8812                                0.0
8813                            } else {
8814                                (d - p1.position.x) / dx
8815                            };
8816                            found = Some((
8817                                p1.position.y + t * (p2.position.y - p1.position.y),
8818                                0.0,
8819                            ));
8820                            break;
8821                        }
8822                    }
8823                    found.expect("trajectory reached observation distance")
8824                };
8825                (d, -y) // drop is positive-down
8826            })
8827            .collect();
8828
8829        let estimate = estimate_bc_fit(
8830            velocity,
8831            mass,
8832            diameter,
8833            &points,
8834            DragModel::G7,
8835            BcFitMode::Drop,
8836            atmosphere,
8837            None,
8838            0.05,
8839        )
8840        .expect("fit should converge");
8841
8842        assert!(
8843            (estimate.bc - known_bc).abs() < 0.02,
8844            "fit should recover the known ICAO-referenced bc={known_bc}, got {}",
8845            estimate.bc
8846        );
8847    }
8848
8849    // ---- Custom drag table: documented inert behavior -------------------------------------
8850
8851    #[test]
8852    fn custom_drag_table_makes_bc_reference_standard_numerically_inert() {
8853        let table = crate::drag::DragTable::try_new(vec![0.5, 1.0, 2.0, 3.0], vec![0.3, 0.4, 0.3, 0.2])
8854            .expect("valid table");
8855
8856        let solve_with = |standard: BcReferenceStandard| {
8857            let inputs = BallisticInputs {
8858                bc_value: 0.5, // irrelevant once a custom drag table is active
8859                bc_reference_standard: standard,
8860                custom_drag_table: Some(table.clone()),
8861                ..base_inputs()
8862            };
8863            let mut solver =
8864                TrajectorySolver::new(inputs, WindConditions::default(), AtmosphericConditions::default());
8865            solver.set_max_range(500.0);
8866            solver.solve().expect("solve")
8867        };
8868
8869        let icao = solve_with(BcReferenceStandard::Icao);
8870        let asm = solve_with(BcReferenceStandard::ArmyStandardMetro);
8871
8872        assert_eq!(
8873            icao.impact_velocity.to_bits(),
8874            asm.impact_velocity.to_bits(),
8875            "a custom drag table must make bc_reference_standard fully inert"
8876        );
8877        assert_eq!(icao.max_range.to_bits(), asm.max_range.to_bits());
8878    }
8879
8880    #[test]
8881    fn custom_drag_table_inert_warning_fires_only_for_army_standard_metro_with_a_table() {
8882        let table = crate::drag::DragTable::try_new(vec![0.5, 1.0, 2.0], vec![0.3, 0.4, 0.3])
8883            .expect("valid table");
8884
8885        // No table: never warns, regardless of the declared standard.
8886        let no_table_icao = base_inputs();
8887        assert!(no_table_icao.bc_reference_standard_inert_warning().is_none());
8888        let no_table_asm = BallisticInputs {
8889            bc_reference_standard: BcReferenceStandard::ArmyStandardMetro,
8890            ..base_inputs()
8891        };
8892        assert!(no_table_asm.bc_reference_standard_inert_warning().is_none());
8893
8894        // Table + Icao: no conversion was ever going to apply, so no warning either.
8895        let table_icao = BallisticInputs {
8896            custom_drag_table: Some(table.clone()),
8897            ..base_inputs()
8898        };
8899        assert!(table_icao.bc_reference_standard_inert_warning().is_none());
8900
8901        // Table + ArmyStandardMetro: the one case that is actually inert -> warn.
8902        let table_asm = BallisticInputs {
8903            custom_drag_table: Some(table),
8904            bc_reference_standard: BcReferenceStandard::ArmyStandardMetro,
8905            ..base_inputs()
8906        };
8907        let warning = table_asm
8908            .bc_reference_standard_inert_warning()
8909            .expect("must warn");
8910        assert!(warning.contains("--bc-reference"));
8911        assert!(warning.contains("--drag-table"));
8912    }
8913}
8914
8915/// MBA-1423: the per-point effective drag coefficient.
8916///
8917/// These pin the DEFINITION (the projectile's own Cd, form-factor scaled) rather than the
8918/// plumbing, because the plumbing being present is not the risk — reporting a plausible number
8919/// that is not the one flown is.
8920#[cfg(test)]
8921mod effective_drag_coefficient_tests {
8922    use super::*;
8923
8924    fn inputs_175gr_g7() -> BallisticInputs {
8925        let mut inputs = BallisticInputs {
8926            bc_value: 0.243,
8927            bc_type: DragModel::G7,
8928            muzzle_velocity: 823.0,
8929            ..Default::default()
8930        };
8931        // Set the SI fields: TrajectorySolver::new re-derives caliber_inches/weight_grains
8932        // from bullet_diameter/bullet_mass, so setting only the imperial pair would be
8933        // silently overwritten by the SI defaults (a 154gr .30, not a 175gr .308).
8934        inputs.bullet_mass = 175.0 * crate::constants::GRAINS_TO_KG;
8935        inputs.bullet_diameter = 0.308 * 0.0254;
8936        inputs.weight_grains = 175.0;
8937        inputs.caliber_inches = 0.308;
8938        inputs
8939    }
8940
8941    fn solver(inputs: BallisticInputs) -> TrajectorySolver {
8942        TrajectorySolver::new(
8943            inputs,
8944            WindConditions::default(),
8945            AtmosphericConditions::default(),
8946        )
8947    }
8948
8949    /// The reported Cd is the projectile's own, i.e. the reference Cd scaled by the form factor
8950    /// SD/BC — not the reference table value itself, which would be identical for every bullet
8951    /// sharing a drag model and so useless for charting a specific load.
8952    #[test]
8953    fn reports_the_projectiles_own_cd_not_the_reference_tables() {
8954        let inputs = inputs_175gr_g7();
8955        let sd = inputs.sectional_density_lb_in2().expect("SD");
8956        let solver = solver(inputs);
8957
8958        let sos = 340.0;
8959        let velocity = 800.0;
8960        let mach = velocity / sos;
8961
8962        let reference = crate::drag::get_drag_coefficient(mach, &DragModel::G7);
8963        let reported = solver
8964            .effective_drag_coefficient(velocity, sos)
8965            .expect("mass and diameter are set");
8966
8967        let expected = reference * sd / 0.243;
8968        assert!(
8969            (reported - expected).abs() < 1e-12,
8970            "reported {reported} != Cd_ref * SD / BC {expected}"
8971        );
8972        // The form factor here is > 1, so the two genuinely differ: a test that passed with
8973        // `reported == reference` would not be testing anything.
8974        assert!(
8975            (reported - reference).abs() > 1e-6,
8976            "form factor collapsed to 1; this fixture no longer distinguishes the two values"
8977        );
8978    }
8979
8980    /// A custom drag table already supplies the projectile's actual Cd and divides by sectional
8981    /// density, so the form-factor scale must collapse to exactly 1 and pass the curve through.
8982    #[test]
8983    fn a_custom_drag_table_passes_through_unscaled() {
8984        let mut inputs = inputs_175gr_g7();
8985        inputs.custom_drag_table = Some(crate::drag::DragTable::new(
8986            vec![0.5, 3.0],
8987            vec![0.15, 0.40],
8988        ));
8989        let solver = solver(inputs);
8990
8991        let sos = 340.0;
8992        let velocity = 0.9 * sos;
8993        let table_value = solver
8994            .inputs
8995            .custom_drag_table
8996            .as_ref()
8997            .expect("table")
8998            .interpolate(0.9);
8999
9000        let reported = solver
9001            .effective_drag_coefficient(velocity, sos)
9002            .expect("mass and diameter are set");
9003        assert!(
9004            (reported - table_value).abs() < 1e-12,
9005            "custom table Cd {table_value} was rescaled to {reported}"
9006        );
9007    }
9008
9009    /// The band step a segmented BC produces is the whole reason this field exists: it is the
9010    /// one feature of a real load's drag curve a consumer cannot reconstruct from a published BC.
9011    #[test]
9012    fn a_velocity_segmented_bc_steps_the_reported_cd() {
9013        let mut inputs = inputs_175gr_g7();
9014        inputs.use_bc_segments = true;
9015        inputs.bc_segments_data = Some(vec![
9016            crate::BCSegmentData { velocity_min: 2400.0, velocity_max: 4000.0, bc_value: 0.243 },
9017            crate::BCSegmentData { velocity_min: 0.0, velocity_max: 2400.0, bc_value: 0.200 },
9018        ]);
9019        let solver = solver(inputs);
9020
9021        let sos = 340.0;
9022        // Straddle the 2400 fps boundary (fps -> m/s).
9023        let above = solver.effective_drag_coefficient(2500.0 / 3.28084, sos).expect("cd");
9024        let below = solver.effective_drag_coefficient(2300.0 / 3.28084, sos).expect("cd");
9025
9026        // Lower BC below the boundary means MORE drag for the same reference curve.
9027        assert!(
9028            below > above,
9029            "expected the 0.200 band to report a higher Cd than the 0.243 band; got {below} vs {above}"
9030        );
9031    }
9032
9033    /// Sectional density is undefined without both mass and diameter, and so is the projectile's
9034    /// own Cd. Reporting the reference value there would be a silently wrong number.
9035    #[test]
9036    fn is_absent_when_sectional_density_is_unknown() {
9037        let mut inputs = inputs_175gr_g7();
9038        inputs.weight_grains = 0.0;
9039        inputs.bullet_mass = 0.0;
9040        let solver = solver(inputs);
9041        assert!(solver.effective_drag_coefficient(800.0, 340.0).is_none());
9042    }
9043
9044    /// MBA-1427: the emit rule the browser terminal applies, pinned natively because the WASM
9045    /// emit site is cfg-gated out of every native build and so is never executed by CI. Three
9046    /// cases, and the third is the contract: absent — not null — when sectional density is
9047    /// unknown, even with the flag set.
9048    #[test]
9049    fn the_json_emit_rule_is_flag_gated_and_absent_when_cd_is_unknown() {
9050        let mut point = TrajectoryPoint {
9051            time: 0.0,
9052            position: nalgebra::Vector3::new(0.0, 0.0, 0.0),
9053            velocity_magnitude: 800.0,
9054            kinetic_energy: 3000.0,
9055            drag_coefficient: Some(0.31),
9056        };
9057        assert_eq!(point.drag_coefficient_json_value(true), Some(0.31));
9058        assert_eq!(
9059            point.drag_coefficient_json_value(false),
9060            None,
9061            "without the flag the key must not exist, so default JSON stays byte-identical"
9062        );
9063        point.drag_coefficient = None;
9064        assert_eq!(
9065            point.drag_coefficient_json_value(true),
9066            None,
9067            "unknown sectional density must yield an ABSENT key, not null"
9068        );
9069    }
9070
9071    /// Every solver family runs the same post-pass, so none may leave the field empty.
9072    #[test]
9073    fn every_point_of_a_solved_trajectory_carries_the_value() {
9074        let mut solver = solver(inputs_175gr_g7());
9075        solver.set_max_range(300.0);
9076        let result = solver.solve().expect("solve");
9077        assert!(!result.points.is_empty());
9078        assert!(
9079            result.points.iter().all(|p| p.drag_coefficient.is_some()),
9080            "the post-integration pass missed at least one point"
9081        );
9082    }
9083}