Skip to main content

ballistics_engine/
cli_api.rs

1// CLI API module - provides simplified interfaces for command-line tool
2use crate::atmosphere::{
3    AtmosphereError, KernelAtmosphere, PressureReferenceMode, RelativeHumidity, StationAir,
4    StationAtmospherePresence, StationOrigin, StationPressureOrigin, DEFAULT_HUMIDITY_PERCENT,
5};
6use crate::cluster_bc::ClusterBCDegradation;
7use crate::gravity::Gravity;
8use crate::mc_stats::{wilson_interval, BernoulliConfidenceSequence, ConfidenceLevel, Welford};
9use crate::pitch_damping::{calculate_pitch_damping_coefficient, PitchDampingCoefficients};
10use crate::precession_nutation::{
11    calculate_combined_angular_motion, projectile_moments_of_inertia, AngularState,
12    PrecessionNutationParams,
13};
14use crate::trajectory_observation::{bracket_param, Bracket, TrajectoryTermination};
15use crate::trajectory_sampling::{
16    projected_sample_count, sample_trajectory, TrajectoryData, TrajectoryOutputs, TrajectorySample,
17};
18use crate::wind_shear::WindShearModel;
19use crate::DragModel;
20use nalgebra::{Vector3, Vector6};
21use std::error::Error;
22use std::fmt;
23
24/// Unit system for CLI-style inputs and outputs.
25///
26/// The single crate-wide unit-system selector, shared by the CLI binary
27/// (`--units`), the truing core ([`crate::truing`]) and the WEZ sweep core
28/// ([`crate::wez`]). It only selects how user-facing quantities are
29/// interpreted and displayed; the solver itself always works in SI.
30///
31/// Variant order (Metric first) is load-bearing for the CLI: clap lists
32/// `--units` possible values in declaration order.
33#[derive(Debug, Clone, Copy, PartialEq)]
34#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
35pub enum UnitSystem {
36    /// Metric units (velocity in m/s, mass in grams, distance in meters, diameter in mm, Celsius)
37    Metric,
38    /// Imperial units (velocity in fps, mass in grains, distance in yards, diameter in inches, Fahrenheit)
39    Imperial,
40}
41
42// Output format for results
43#[derive(Debug, Clone, Copy, PartialEq)]
44pub enum OutputFormat {
45    Table,
46    Json,
47    Csv,
48}
49
50/// Which standard atmosphere a ballistic coefficient's numeric value is referenced to
51/// (MBA-1365).
52///
53/// A BC is not a pure property of the bullet — it also encodes an assumed reference air
54/// density. This engine's retardation constant ([`crate::constants::CD_TO_RETARD`]) is
55/// calibrated against the ICAO Standard Atmosphere's sea-level density
56/// ([`crate::constants::ICAO_DENSITY_LB_FT3`]), which most modern published BCs already
57/// assume. Some vendors (notably Sierra, Hornady, and Barnes for many bullets) instead
58/// publish BCs referenced to the older, denser Army Standard Metro atmosphere
59/// ([`crate::constants::ASM_DENSITY_LB_FT3`]). Feeding an ASM-referenced BC into this
60/// engine as if it were ICAO-referenced under-predicts drag by about 1.8% — declaring
61/// `ArmyStandardMetro` here corrects for that exactly once, at input normalization (see
62/// [`crate::constants::ASM_TO_ICAO_BC`] and `TrajectorySolver::new`).
63///
64/// Does not apply when a custom drag table (`BallisticInputs::custom_drag_table`) is flown as
65/// the projectile's own curve: that path divides by sectional density, not a BC value, so no
66/// BC reference conversion is physically meaningful there (see
67/// `BallisticInputs::bc_reference_standard_inert_warning`). A table flown as a reference curve
68/// (`BallisticInputs::custom_drag_reference`) divides by the BC exactly as a built-in model
69/// does, so the conversion applies to it as it does to a G-model.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
71#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
72pub enum BcReferenceStandard {
73    /// The ICAO Standard Atmosphere reference density — matches this engine's
74    /// retardation constant. The default; byte-identical to pre-MBA-1365 behavior.
75    #[default]
76    Icao,
77    /// The (older) Army Standard Metro reference density used by some vendor-published
78    /// BCs (e.g. many Sierra/Hornady/Barnes bullets).
79    ArmyStandardMetro,
80}
81
82/// Shared text for the MBA-1365 "`--bc-reference army-standard-metro` is inert" warning —
83/// single source of truth for every surface that can trigger it (native CLI, WASM,
84/// [`BallisticInputs::bc_reference_standard_inert_warning`]) so the wording can't drift.
85pub const BC_REFERENCE_STANDARD_INERT_WARNING: &str =
86    "warning: --bc-reference army-standard-metro has no effect together with a custom drag \
87     table (--drag-table): the deck's Cd is divided by sectional density, not a BC value, so \
88     no BC-reference conversion applies";
89
90// Error type for CLI operations
91#[derive(Debug)]
92pub struct BallisticsError {
93    message: String,
94    atmosphere: Option<crate::atmosphere::AtmosphereError>,
95}
96
97impl BallisticsError {
98    /// The atmosphere refusal behind this error, when a solve refused its air: today, air that
99    /// cannot exist aloft ([`crate::AtmosphereErrorReason::AirAloftBelowAbsoluteZero`]), which a
100    /// trajectory kernel finds only in flight. A surface that names its readings states it in its
101    /// own words with [`crate::AtmosphereError::refusal_in`]; the message is its `Display`.
102    pub fn atmosphere_error(&self) -> Option<&crate::atmosphere::AtmosphereError> {
103        self.atmosphere.as_ref()
104    }
105
106    /// This error as a terminal (the native CLI, the browser terminal) states it, as it states
107    /// every refusal of its air ([`AtmosphericConditions::air_refusal_named`]): a refusal of air
108    /// that cannot exist aloft names the temperature by `temperature_label` (the flag, saved
109    /// profile field or CSV column it came from), in the run's `units`, with the height in feet
110    /// or metres:
111    ///
112    /// ```text
113    /// --temperature = -441.67 °F: the air aloft would fall below absolute zero: from this
114    /// temperature the standard lapse reaches 0 K at 5049 ft above mean sea level, which this
115    /// flight reaches (check the temperature and its unit)
116    /// ```
117    ///
118    /// Any other error, and one already stated in a terminal's words, is returned unchanged;
119    /// [`Self::atmosphere_error`] still carries the refusal.
120    pub fn in_terminal_words(mut self, units: UnitSystem, temperature_label: &str) -> Self {
121        if let Some(error) = &self.atmosphere {
122            if error.reason() == crate::AtmosphereErrorReason::AirAloftBelowAbsoluteZero
123                && self.message == error.to_string()
124            {
125                self.message = format!(
126                    "{temperature_label} = {}: {}",
127                    terminal_temperature_text(error.value(), units),
128                    error.explanation_in(terminal_altitude_unit(units))
129                );
130            }
131        }
132        self
133    }
134}
135
136impl fmt::Display for BallisticsError {
137    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
138        write!(f, "{}", self.message)
139    }
140}
141
142impl Error for BallisticsError {
143    fn source(&self) -> Option<&(dyn Error + 'static)> {
144        self.atmosphere
145            .as_ref()
146            .map(|error| error as &(dyn Error + 'static))
147    }
148}
149
150impl From<String> for BallisticsError {
151    fn from(msg: String) -> Self {
152        BallisticsError {
153            message: msg,
154            atmosphere: None,
155        }
156    }
157}
158
159impl From<&str> for BallisticsError {
160    fn from(msg: &str) -> Self {
161        BallisticsError {
162            message: msg.to_string(),
163            atmosphere: None,
164        }
165    }
166}
167
168impl From<crate::atmosphere::AtmosphereError> for BallisticsError {
169    fn from(error: crate::atmosphere::AtmosphereError) -> Self {
170        BallisticsError {
171            message: error.to_string(),
172            atmosphere: Some(error),
173        }
174    }
175}
176
177/// Which plane sampled drop values are referenced to (MBA-1403).
178///
179/// See [`BallisticInputs::drops_reference`]. This is an output-mode toggle for the
180/// trajectory sampler, not new plane machinery: the solver implements incline as gravity
181/// rotation into the shot frame, so sampled drop is already perpendicular to the LOS and
182/// the JBM-equivalent "target" mode is a `1 / cos(shooting_angle)` reference transform
183/// plus relabeling.
184#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
185pub enum DropsReference {
186    /// Drop measured perpendicular to the line of sight (the historical default).
187    #[default]
188    Los,
189    /// Drop measured vertically in the target plane (JBM's "target plane" reference):
190    /// the LOS-perpendicular drop scaled by `1 / cos(shooting_angle)`.
191    Target,
192}
193
194// Ballistic input parameters - MBA-151 Reconciled Structure
195// Unified structure used by both ballistics-engine and ballistics_rust
196// Duplicates removed, all necessary fields included
197#[derive(Debug, Clone)]
198pub struct BallisticInputs {
199    // Core ballistics parameters (using intuitive names)
200    pub bc_value: f64,      // Ballistic coefficient (G1, G7, etc.)
201    pub bc_type: DragModel, // Drag model (G1, G7, G8, etc.)
202    /// Which standard atmosphere `bc_value`/`bc_segments`/`bc_segments_data` are
203    /// referenced to (MBA-1365). `Icao` (the default) is a no-op; `ArmyStandardMetro`
204    /// is converted to the ICAO reference exactly once, in `TrajectorySolver::new`,
205    /// before any retardation math runs. See [`BcReferenceStandard`].
206    pub bc_reference_standard: BcReferenceStandard,
207    pub bullet_mass: f64,     // kg
208    pub muzzle_velocity: f64, // m/s
209    pub bullet_diameter: f64, // meters
210    pub bullet_length: f64,   // meters
211
212    // Targeting and positioning
213    pub muzzle_angle: f64,    // radians (launch angle)
214    pub target_distance: f64, // meters
215    pub azimuth_angle: f64, // horizontal aiming angle in radians (small aim offset within the shot frame)
216    /// Compass bearing the shot is fired ALONG, radians, 0 = North, π/2 = East.
217    /// Used only by the Coriolis model (Earth-rotation depends on which way downrange
218    /// points relative to true North). Distinct from `azimuth_angle`, which is the
219    /// small horizontal *aiming* offset and rotates the launch velocity.
220    pub shot_azimuth: f64,
221    pub shooting_angle: f64, // uphill/downhill angle in radians
222    /// Rifle cant angle in radians about the line of sight — positive = clockwise from the
223    /// shooter's view (top of the scope tips right). Rotates the sight-frame aim offsets
224    /// (`muzzle_angle`, `azimuth_angle`) about the LOS and swings the bore's sight-height
225    /// offset laterally, producing the classic canted-rifle POI error (right-and-low for
226    /// clockwise cant with an upward zero). Zeroing always solves un-canted ("zero level,
227    /// fire canted"). NOTE: treats `muzzle_angle` as a sight-frame offset — the standard
228    /// zero-then-fire usage; a raw gravity-frame launch angle would not rotate physically.
229    /// 0.0 = level rifle (bit-identical to pre-cant behavior). (MBA-1286)
230    pub cant_angle: f64,
231    pub sight_height: f64, // meters above bore
232    /// Lateral offset between the sight axis and the bore axis, meters (MBA-1396;
233    /// offset-mounted optics): positive = the sight sits RIGHT of the bore, so the bore
234    /// starts LEFT of the line of sight (initial lateral position `z -= offset`). When a
235    /// zero is solved, a windage-zero convergence term of `offset / zero_distance` is
236    /// added to `azimuth_angle` (see [`BallisticInputs::windage_zero_bias_rad`]) so the
237    /// trajectory crosses the LOS laterally at the zero range — matching AB/JBM/Shooter,
238    /// not a constant parallel offset. Without a zero solve (an explicit muzzle angle),
239    /// only the physical displacement applies. Distinct from `zero_poi_horizontal_m`,
240    /// which is an angular ZERO-STATE bias, not mount geometry. 0.0 (the default) is
241    /// byte-identical to pre-MBA-1396 behavior.
242    pub sight_offset_lateral_m: f64,
243    pub muzzle_height: f64, // meters above ground
244    pub target_height: f64, // meters above ground for zeroing
245    /// Deliberate vertical point-of-impact offset AT THE ZERO RANGE, meters (MBA-1359;
246    /// Kestrel "zero height" semantics): positive = the rifle is deliberately zeroed to
247    /// impact HIGH by this much at the zero distance. Applied POST-solve by
248    /// `calculate_and_set_zero_angle` as a constant angular bias of
249    /// `zero_poi_vertical_m / zero_distance` on the solved elevation — the zero trials
250    /// themselves always solve perfect convergence, and the small-angle addition is
251    /// identical in both zero target frames. 0.0 (the default) is byte-identical to
252    /// pre-MBA-1359 behavior.
253    pub zero_poi_vertical_m: f64,
254    /// Deliberate horizontal point-of-impact offset AT THE ZERO RANGE, meters (MBA-1359;
255    /// Kestrel "zero offset" semantics): positive = impacts RIGHT by this much at the
256    /// zero distance. Applied POST-solve as an azimuth bias of
257    /// `zero_poi_horizontal_m / zero_distance` when a zero is solved — see
258    /// [`BallisticInputs::windage_zero_bias_rad`]. 0.0 (the default) is neutral.
259    pub zero_poi_horizontal_m: f64,
260    pub ground_threshold: f64, // meters below which to stop
261
262    // Environmental conditions
263    pub altitude: f64,    // meters
264    pub temperature: f64, // Celsius
265    pub pressure: f64,    // millibars/hPa
266    /// Relative humidity, PERCENT, `0..=100` (50.0 = 50 %): the unit of
267    /// [`AtmosphericConditions::humidity`] and of every atmosphere function, so it passes
268    /// between them unconverted. Default [`DEFAULT_HUMIDITY_PERCENT`]. A sensor reading within
269    /// [`crate::HUMIDITY_SENSOR_TOLERANCE_PERCENT`] of the range flies as the end it reads as.
270    ///
271    /// A [`TrajectorySolver`] flies its [`AtmosphericConditions`] and sets this field from it.
272    /// The entry points that take inputs alone (the `run_monte_carlo*` family and
273    /// [`crate::monte_carlo::solve_trajectory_for_monte_carlo`]) fly this value.
274    ///
275    /// 0.50.0 renamed it from `humidity`, a 0-1 FRACTION. The `humidity_percent()` accessor
276    /// that converted that fraction is kept for one release, deprecated, and returns this field.
277    /// To migrate, write the percent, or convert a fraction with
278    /// [`crate::RelativeHumidity::try_fraction`].
279    pub humidity_percent: f64,
280    pub latitude: Option<f64>, // degrees
281
282    // Wind conditions
283    pub wind_speed: f64, // m/s
284    pub wind_angle: f64, // radians (0=headwind, PI/2=from right)
285
286    // Bullet characteristics
287    pub twist_rate: f64,               // inches per turn
288    pub is_twist_right: bool,          // right-hand twist
289    pub caliber_inches: f64,           // diameter in inches
290    pub weight_grains: f64,            // mass in grains
291    pub manufacturer: Option<String>,  // Bullet manufacturer
292    pub bullet_model: Option<String>,  // Bullet model name
293    pub bullet_id: Option<String>,     // Unique bullet identifier
294    pub bullet_cluster: Option<usize>, // BC cluster ID for cluster_bc module
295
296    // Integration method selection
297    pub use_rk4: bool,           // Use RK4 integration instead of Euler
298    pub use_adaptive_rk45: bool, // Use RK45 adaptive step size integration
299
300    // Advanced effects flags
301    pub enable_advanced_effects: bool,
302    pub enable_magnus: bool,   // Magnus force (independent of Coriolis)
303    pub enable_coriolis: bool, // Coriolis deflection (requires latitude)
304    pub use_powder_sensitivity: bool,
305    pub powder_temp_sensitivity: f64, // m/s per degree Celsius
306    pub powder_temp: f64,             // Celsius
307    /// Optional measured powder-temperature -> muzzle-velocity curve, as
308    /// (temperature_celsius, muzzle_velocity_m_s) points sorted ascending by
309    /// temperature. When present it supersedes the linear `powder_temp_sensitivity`
310    /// model: the muzzle velocity is interpolated from this table at the ambient
311    /// `temperature` (clamped to the endpoints — no extrapolation beyond measured
312    /// data). This is the data-driven, non-linear alternative to the constant slope.
313    pub powder_temp_curve: Option<Vec<(f64, f64)>>,
314    /// Temperature (Celsius) at which to interpolate `powder_temp_curve` — the POWDER
315    /// temperature, which may differ from the ambient `temperature` (air). `None` uses
316    /// `temperature`. Decouples the velocity lookup from the air-density temperature.
317    pub powder_curve_temp_c: Option<f64>,
318    pub tipoff_yaw: f64,            // radians
319    pub tipoff_decay_distance: f64, // meters
320    /// Quadratic yaw-drag coefficient CD_delta2 (per rad^2, actual-Cd space) applied
321    /// additively to the tip-off yaw: CD = CD0 + CD_delta2 * delta^2 (McCoy, Modern
322    /// Exterior Ballistics). Literature values for spitzer rifle bullets run ~4-20
323    /// per rad^2 (7.62 M80 ~= 9.6); the default 7.5 is a documented mid-range
324    /// constant. Only active when `tipoff_yaw` is nonzero (MBA-1227).
325    pub cd_delta2: f64,
326    /// Enables velocity-keyed `bc_segments_data`. Explicit Mach-keyed `bc_segments` retain their
327    /// legacy behavior and remain active when this flag is false.
328    ///
329    /// An empty `bc_segments_data` is the same as `None`. With the flag on and no velocity
330    /// ladder, every solver flies a non-empty Mach `bc_segments` table. Without one,
331    /// `TrajectorySolver` and `fast_trajectory::fast_integrate` fly the scalar BC, while the RK45
332    /// kernel behind `fast_integrate_with_segments` /
333    /// `trajectory_integration::integrate_trajectory` / `derivatives::compute_derivatives`
334    /// auto-estimates a ladder when `bc_segments` is `None` (MBA-955, legacy opt-in).
335    pub use_bc_segments: bool,
336    pub bc_segments: Option<Vec<(f64, f64)>>, // Mach-BC pairs
337    pub bc_segments_data: Option<Vec<crate::BCSegmentData>>, // Velocity-BC segments
338    pub use_enhanced_spin_drift: bool,
339    /// Legacy compatibility flag. Name-derived "form factors" are intentionally not multiplied
340    /// into reference Cd when `bc_value` is already the retardation denominator (MBA-1184).
341    pub use_form_factor: bool,
342    pub enable_wind_shear: bool,
343    pub wind_shear_model: String,
344    pub enable_trajectory_sampling: bool,
345    pub sample_interval: f64, // meters
346    /// Which plane sampled drop values are referenced to (MBA-1403). The default
347    /// [`DropsReference::Los`] keeps the historical behavior (drop perpendicular to the
348    /// line of sight) byte-identical; [`DropsReference::Target`] reports drop as vertical
349    /// in the target plane — the LOS-perpendicular drop scaled by
350    /// `1 / cos(shooting_angle)` (JBM's "target plane" checkbox) — and, when a non-zero
351    /// `target_height` is supplied, slopes the sampler's LOS datum toward it. This is an
352    /// OUTPUT-mode toggle: the solved trajectory itself is unchanged, and zero-solve
353    /// `target_height` semantics are untouched.
354    pub drops_reference: DropsReference,
355    pub enable_pitch_damping: bool,
356    pub enable_precession_nutation: bool,
357    // MBA-959: apply aerodynamic jump as a muzzle launch-angle perturbation.
358    // EXPERIMENTAL — the underlying model is heuristic and not yet validated; default OFF.
359    pub enable_aerodynamic_jump: bool,
360    pub use_cluster_bc: bool, // Use cluster-based BC degradation
361
362    // Custom drag model support
363    /// A caller-supplied Cd-vs-Mach curve that replaces the `bc_type` G-model curve at every
364    /// drag site (MBA-940). It is used as-is: no transonic correction and no form factor is
365    /// applied to it, and outside its Mach range the nearest end value is held. What the curve
366    /// describes, and so what it is divided by, is decided by [`Self::custom_drag_reference`]:
367    ///
368    /// * `false` (the default): the projectile's OWN drag coefficient, divided by its
369    ///   sectional density. `bc_value` and any BC segments are unused for drag. This is the
370    ///   only reading the CLI's `--drag-table`, the WASM terminal, the array FFI and saved
371    ///   profiles have, and solve-json v1's `kind: "projectile"`.
372    /// * `true`: a REFERENCE curve, such as an airgun pellet law, that the BCs were measured
373    ///   against, divided by the resolved BC exactly as a built-in model's curve is.
374    ///
375    /// See [`Self::custom_drag_denominator`].
376    pub custom_drag_table: Option<crate::drag::DragTable>,
377    /// Whole-curve multiplier applied to the custom deck's interpolated Cd (MBA-1356):
378    /// `Cd_used = table.interpolate(mach) * cd_scale`. Meaningful only alongside
379    /// `custom_drag_table` — it is read at the three custom-deck interpolation sites in
380    /// cli_api.rs/derivatives.rs/fast_trajectory.rs and left untouched on the standard
381    /// G-model/BC path (those users true their drag via `--bc-adjustment` instead; scaling
382    /// a G-model's reference table too would double-count). It multiplies the curve before
383    /// the division, under either reading of [`Self::custom_drag_reference`]. solve-json v1's
384    /// `kind: "reference"` table without a BC ladder is installed as the own-curve path with
385    /// `cd_scale = SD / BC`, which flies `Cd_ref / BC`; with a ladder it is installed with
386    /// `custom_drag_reference` set and `cd_scale = 1.0` instead, since one whole-curve scale
387    /// cannot carry a BC that changes from band to band. Default `1.0` is neutral
388    /// (byte-identical to the pre-MBA-1356 behavior). Validated finite and > 0 by
389    /// `validate_for_solve`.
390    pub cd_scale: f64,
391    /// Whether `custom_drag_table` is a REFERENCE curve that the BCs were measured against
392    /// (`true`), rather than the projectile's own Cd (`false`, the default). Inert without a
393    /// table.
394    ///
395    /// When set, the drag sites in cli_api.rs, derivatives.rs and fast_trajectory.rs divide the
396    /// table's Cd (times `cd_scale`) by the BC each of them has already resolved for the current
397    /// speed, exactly as they divide a built-in model's Cd: a velocity ladder's band BC
398    /// (`bc_segments_data` under `use_bc_segments`, selected and smoothstep-blended by
399    /// `velocity_segment_bc`), a Mach-keyed `bc_segments` BC, or the scalar `bc_value` in an
400    /// interior gap or without a ladder. The BC matters again on this path, so
401    /// `validate_for_solve` requires a finite positive `bc_value`, and an `ArmyStandardMetro`
402    /// `bc_reference_standard` is converted exactly as it is for a built-in model.
403    ///
404    /// solve-json v1 sets it for a `kind: "reference"` `projectile.drag_table` sent with a
405    /// `projectile.bc_segments` ladder; no other front end sets it. Every path that copies a
406    /// table between input structs must carry it alongside `cd_scale`
407    /// (`TrajectoryParams::custom_drag_reference`): dropped beside `cd_scale = 1.0`, it would fly
408    /// the reference curve as the projectile's own Cd over sectional density, wrong by the
409    /// projectile's whole form factor (the MBA-1356 dropped-field class).
410    pub custom_drag_reference: bool,
411
412    // Legacy field for compatibility
413    pub bc_type_str: Option<String>,
414}
415
416impl BallisticInputs {
417    /// The humidity as a percent: 0.49.0's accessor, which converted the 0-1 fraction field
418    /// `humidity` to a percent. Since 0.50.0 the `humidity_percent` field is that percent, so
419    /// this returns the field unchanged, and a caller that only read the accessor still compiles,
420    /// for one release.
421    ///
422    /// 0.49.0's accessor also clamped into 0-100. 0.50.0 clamps a humidity nowhere: a value
423    /// beyond the sensor band ([`crate::HUMIDITY_SENSOR_TOLERANCE_PERCENT`]) is returned as
424    /// stored, and the solve refuses it. From 0 to 100 the two accessors return the same percent.
425    #[deprecated(
426        since = "0.50.0",
427        note = "read the `humidity_percent` field, which is the percent itself since 0.50.0"
428    )]
429    pub fn humidity_percent(&self) -> f64 {
430        self.humidity_percent
431    }
432
433    /// Azimuth bias (radians) a zero solved at `zero_distance_m` applies to the launch
434    /// direction. Two independent terms share this one convergence point:
435    /// * MBA-1359 — the deliberate horizontal POI offset at the zero range
436    ///   (`zero_poi_horizontal_m`), an angular zero-state bias;
437    /// * MBA-1396 — the lateral sight-mount offset (`sight_offset_lateral_m`): the bore
438    ///   starts `offset` left of the LOS (see `initial_position`), so the windage zero
439    ///   steers `offset / zero_distance` right to cross the LOS at the zero range.
440    ///
441    /// `calculate_and_set_zero_angle` applies this to its OWN solver's `azimuth_angle`;
442    /// callers that copy a solved zero angle onto separate flight inputs (the CLI/WASM
443    /// auto-zero paths) must add this to their flight `azimuth_angle` themselves — the
444    /// returned elevation angle cannot carry it. Returns exactly `0.0` when both offsets
445    /// are `0.0` or `zero_distance_m` is not positive, so default inputs stay
446    /// byte-identical.
447    pub fn windage_zero_bias_rad(&self, zero_distance_m: f64) -> f64 {
448        if zero_distance_m > 0.0 {
449            (self.zero_poi_horizontal_m + self.sight_offset_lateral_m) / zero_distance_m
450        } else {
451            0.0
452        }
453    }
454
455    /// Sectional density in lb/in²: `weight_grains / 7000 / diameter_in²`.
456    ///
457    /// Derived from the imperial mirror fields (`weight_grains` / `caliber_inches`), falling
458    /// back to the SI `bullet_mass` (kg) / `bullet_diameter` (meters) for SI-only callers
459    /// (mirrors the fallbacks in derivatives.rs). `None` when neither source is usable.
460    pub fn sectional_density_lb_in2(&self) -> Option<f64> {
461        let weight_gr = if self.weight_grains > 0.0 {
462            self.weight_grains
463        } else {
464            self.bullet_mass / crate::constants::GRAINS_TO_KG // kg -> grains
465        };
466        let diameter_in = if self.caliber_inches > 0.0 {
467            self.caliber_inches
468        } else {
469            self.bullet_diameter / 0.0254 // meters -> inches
470        };
471        if weight_gr > 0.0 && diameter_in > 0.0 {
472            Some(weight_gr / 7000.0 / (diameter_in * diameter_in))
473        } else {
474            None
475        }
476    }
477
478    /// Retardation denominator to use when `custom_drag_table` is active.
479    ///
480    /// `resolved_bc` is the BC the calling drag site has already resolved for the current
481    /// speed, by the same precedence it applies to a built-in model: a velocity ladder's band
482    /// BC, else a Mach-segment BC, else the scalar `bc_value`.
483    ///
484    /// * **Reference curve** ([`Self::custom_drag_reference`]): returns `resolved_bc`, the very
485    ///   denominator a built-in model divides by, so the table flies `Cd_ref / BC` and a BC
486    ///   ladder's band BCs reach it.
487    /// * **The projectile's own curve** (the default): the table supplies the projectile's
488    ///   ACTUAL drag coefficient, so the point-mass retardation formula must divide it by the
489    ///   projectile's SECTIONAL DENSITY (lb/in²), not by a ballistic coefficient: BC = SD / i
490    ///   (form factor i vs the reference projectile), and with the projectile's own curve
491    ///   i == 1, so Cd_own / SD == Cd_ref / BC. Dividing the curve's Cd by `bc_value` made
492    ///   custom-table trajectories wrongly scale with whatever BC happened to be set. Falls back
493    ///   to `resolved_bc` (with a one-time stderr warning) when mass/diameter are unavailable,
494    ///   so degenerate inputs degrade to the old behavior instead of panicking.
495    pub fn custom_drag_denominator(&self, resolved_bc: f64) -> f64 {
496        if self.custom_drag_reference {
497            return resolved_bc;
498        }
499        match self.sectional_density_lb_in2() {
500            Some(sd) => sd,
501            None => {
502                static WARN_ONCE: std::sync::Once = std::sync::Once::new();
503                WARN_ONCE.call_once(|| {
504                    eprintln!(
505                        "Warning: custom drag table active but bullet mass/diameter are \
506                         unavailable; falling back to bc_value for the retardation denominator"
507                    );
508                });
509                resolved_bc
510            }
511        }
512    }
513
514    /// Whether a declared `bc_reference_standard` is inert on this configuration
515    /// (MBA-1365), and if so, the message explaining why.
516    ///
517    /// A custom drag table (`custom_drag_table`) flown as the projectile's own curve supplies
518    /// its actual Cd and divides by sectional density, not by a BC value (see
519    /// `custom_drag_denominator`), so an `ArmyStandardMetro` reference has no physical effect
520    /// once such a table is active. A table flown as a reference curve
521    /// (`custom_drag_reference`) divides by the BC like a built-in model, so the conversion
522    /// is meaningful there and this returns `None`. Pure and side-effect-free — same shape as
523    /// `main.rs`'s `adjustment_unit_noop_warning` (MBA-1414) — so each surface decides how to
524    /// surface it: the native CLI prints it to stderr once per run, while the WASM browser
525    /// terminal (no visible stderr) splices it into its table-output text instead.
526    pub fn bc_reference_standard_inert_warning(&self) -> Option<&'static str> {
527        if self.custom_drag_table.is_some()
528            && !self.custom_drag_reference
529            && matches!(
530                self.bc_reference_standard,
531                BcReferenceStandard::ArmyStandardMetro
532            )
533        {
534            Some(BC_REFERENCE_STANDARD_INERT_WARNING)
535        } else {
536            None
537        }
538    }
539
540    /// Apply every input-conditioning step integration requires, exactly once (MBA-1415).
541    ///
542    /// **Every public entry point into integration must call this**, not just
543    /// [`TrajectorySolver::new`]. `fast_trajectory::fast_integrate` and
544    /// `fast_integrate_with_segments` are `pub` and are called directly by the Python
545    /// binding, so conditioning that lives only in the solver constructor is invisible to
546    /// those consumers: the caller sets a field, gets no error, and the value is silently
547    /// ignored. That exact shape has already cost this project twice — MBA-1296 (a dropped
548    /// field that zeroed Coriolis in production) and the MBA-1356 review catch
549    /// (`cd_scale` dropped by the segmented fast path). Adding a step here rather than at a
550    /// call site is what keeps the next one from repeating it.
551    ///
552    /// **Idempotent**, and it must stay that way: Monte Carlo builds a solver per sample, and
553    /// the fast entry points may receive inputs that already passed through a solver. Each
554    /// step below is either an absolute override (derived fields, powder-resolved velocity) or
555    /// self-disarming (the BC conversion rewrites `bc_reference_standard` to the reference it
556    /// just converted into, so a second call finds nothing to do). A step that scales a value
557    /// in place without disarming itself would double-apply silently — do not add one.
558    pub fn normalize_for_solve(&mut self) {
559        // MBA-1365: normalize a declared Army-Standard-Metro BC reference to the ICAO
560        // reference this engine's retardation constant (CD_TO_RETARD) is calibrated against,
561        // before any retardation math runs. Every BC representation on these inputs (the
562        // scalar, explicit Mach segments, and velocity segments) is a real BC and gets the
563        // same treatment. `Icao` (the default) takes this branch never, so callers that never
564        // set the field are byte-identical to pre-MBA-1365 behavior. A custom drag table flown
565        // as the projectile's own curve divides by sectional density rather than a BC, so the
566        // conversion is physically inert there — see `bc_reference_standard_inert_warning`,
567        // which callers surface at their own display sites (native stderr / WASM table text)
568        // from their OWN copy of the inputs, before this runs. A table flown as a reference
569        // curve (`custom_drag_reference`) divides by these same BCs, so it needs the conversion
570        // exactly as a built-in model does.
571        if matches!(
572            self.bc_reference_standard,
573            BcReferenceStandard::ArmyStandardMetro
574        ) {
575            self.bc_value *= crate::constants::ASM_TO_ICAO_BC;
576            if let Some(segments) = self.bc_segments.as_mut() {
577                for (_mach, bc) in segments.iter_mut() {
578                    *bc *= crate::constants::ASM_TO_ICAO_BC;
579                }
580            }
581            if let Some(segments) = self.bc_segments_data.as_mut() {
582                for segment in segments.iter_mut() {
583                    segment.bc_value *= crate::constants::ASM_TO_ICAO_BC;
584                }
585            }
586            // Disarm: these BC values are now ICAO-referenced, which is simply true, and it
587            // makes a second call a no-op instead of a silent second scaling.
588            self.bc_reference_standard = BcReferenceStandard::Icao;
589        }
590
591        // Derived imperial fields, recomputed from the canonical SI values. These are an
592        // absolute override, NOT a fallback: a caller that sets only `caliber_inches` /
593        // `weight_grains` and leaves the SI fields at their defaults has those imperial values
594        // overwritten here. SI is authoritative on these inputs.
595        self.caliber_inches = self.bullet_diameter / 0.0254;
596        self.weight_grains = self.bullet_mass / crate::constants::GRAINS_TO_KG;
597
598        // Resolve the muzzle velocity for the ambient temperature before integration. A
599        // measured powder-temperature -> velocity curve (data-driven, non-linear) takes
600        // precedence when supplied; otherwise fall back to the linear powder-temperature-
601        // sensitivity model (MBA-963). Both operate in canonical SI (Celsius, m/s), so every
602        // solver built from these inputs — the main trajectory AND the zero-angle search —
603        // sees the same temperature-resolved velocity. In particular, when a zero solve passes
604        // the zero-day temperature, the curve automatically yields the zero-day velocity.
605        // (The curve interpolates at the POWDER temperature — powder_curve_temp_c, falling
606        // back to ambient. Air temperature still drives density separately; this only sets the
607        // velocity. Absolute override, so applying it twice is a no-op.)
608        self.muzzle_velocity = resolve_powder_adjusted_velocity(
609            self.muzzle_velocity,
610            self.temperature,
611            self.use_powder_sensitivity,
612            self.powder_temp_sensitivity,
613            self.powder_temp,
614            self.powder_temp_curve.as_deref(),
615            self.powder_curve_temp_c,
616        );
617    }
618}
619
620impl Default for BallisticInputs {
621    fn default() -> Self {
622        let mass_kg = 0.01;
623        let diameter_m = 0.00762;
624        let bc = 0.5;
625        let muzzle_angle_rad = 0.0;
626        let bc_type = DragModel::G1;
627
628        Self {
629            // Core ballistics parameters
630            bc_value: bc,
631            bc_type,
632            bc_reference_standard: BcReferenceStandard::Icao,
633            bullet_mass: mass_kg,
634            muzzle_velocity: 800.0,
635            bullet_diameter: diameter_m,
636            // MBA-1135: mass-based length estimate so the default is self-consistent with the
637            // default mass/diameter (was a mass-blind 4.5-caliber literal). The twist default below
638            // stays a fixed 1:12" per the ticket (a constant is a sensible velocity-agnostic default).
639            bullet_length: crate::stability::estimate_bullet_length_m(diameter_m, mass_kg),
640
641            // Targeting and positioning
642            muzzle_angle: muzzle_angle_rad,
643            target_distance: 100.0,
644            azimuth_angle: 0.0,
645            shot_azimuth: 0.0,
646            shooting_angle: 0.0,
647            cant_angle: 0.0,
648            sight_height: 0.05,
649            sight_offset_lateral_m: 0.0, // Sight directly above the bore (MBA-1396)
650            muzzle_height: 0.0,          // Default 0 - height is in sight_height
651            target_height: 0.0,          // Target at ground level by default
652            zero_poi_vertical_m: 0.0,    // No deliberate POI offset at the zero range (MBA-1359)
653            zero_poi_horizontal_m: 0.0,
654            ground_threshold: -100.0, // Effectively disable ground detection (allow bullet to drop 100m below start)
655
656            // Environmental conditions
657            altitude: 0.0,
658            temperature: 15.0,
659            pressure: 1013.25, // Standard sea level pressure (millibars)
660            humidity_percent: DEFAULT_HUMIDITY_PERCENT,
661            latitude: None,
662
663            // Wind conditions
664            wind_speed: 0.0,
665            wind_angle: 0.0,
666
667            // Bullet characteristics
668            twist_rate: 12.0, // 1:12" typical
669            is_twist_right: true,
670            caliber_inches: diameter_m / 0.0254, // Convert to inches
671            weight_grains: mass_kg / crate::constants::GRAINS_TO_KG, // Convert to grains
672            manufacturer: None,
673            bullet_model: None,
674            bullet_id: None,
675            bullet_cluster: None,
676
677            // Integration method selection
678            use_rk4: true,           // Use Runge-Kutta methods by default
679            use_adaptive_rk45: true, // Default to RK45 adaptive for best accuracy
680
681            // Advanced effects (disabled by default)
682            enable_advanced_effects: false,
683            enable_magnus: false,
684            enable_coriolis: false,
685            use_powder_sensitivity: false,
686            powder_temp_sensitivity: 0.0,
687            powder_temp: 15.0,
688            powder_temp_curve: None,
689            powder_curve_temp_c: None,
690            tipoff_yaw: 0.0,
691            tipoff_decay_distance: 50.0,
692            cd_delta2: 7.5,
693            use_bc_segments: false,
694            bc_segments: None,
695            bc_segments_data: None,
696            use_enhanced_spin_drift: false,
697            use_form_factor: false,
698            enable_wind_shear: false,
699            wind_shear_model: "none".to_string(),
700            enable_trajectory_sampling: false,
701            sample_interval: 10.0,                // Default 10 meter intervals
702            drops_reference: DropsReference::Los, // historical LOS-perpendicular drops
703            enable_pitch_damping: false,
704            enable_precession_nutation: false,
705            enable_aerodynamic_jump: false,
706            use_cluster_bc: false, // Disabled by default for backward compatibility
707
708            // Custom drag model support
709            custom_drag_table: None,
710            cd_scale: 1.0,
711            custom_drag_reference: false,
712
713            // Legacy field for compatibility
714            bc_type_str: None,
715        }
716    }
717}
718
719/// Interpolate a muzzle velocity (m/s) from a measured powder-temperature curve at
720/// `temp_c` (Celsius). `curve` is `(temperature_celsius, velocity_m_s)` points; it is
721/// sorted ascending by temperature before use. Values below the first point or above
722/// the last are CLAMPED to the endpoint velocity (no extrapolation beyond measured
723/// data), and segments are linearly interpolated. A single point yields a constant.
724pub fn interpolate_powder_temp_curve(curve: &[(f64, f64)], temp_c: f64) -> f64 {
725    debug_assert!(!curve.is_empty());
726    if curve.is_empty() {
727        return 0.0;
728    }
729    // Defensive: accept unsorted input by sorting a local copy only when needed.
730    // Callers (CLI/WASM parsers) already sort, so the common path is a no-op scan.
731    let mut sorted;
732    let pts: &[(f64, f64)] = if curve.windows(2).all(|w| w[0].0 <= w[1].0) {
733        curve
734    } else {
735        sorted = curve.to_vec();
736        sorted.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
737        &sorted
738    };
739    let n = pts.len();
740    if temp_c <= pts[0].0 {
741        return pts[0].1; // clamp below the coldest measured point
742    }
743    if temp_c >= pts[n - 1].0 {
744        return pts[n - 1].1; // clamp above the hottest measured point
745    }
746    for i in 1..n {
747        let (t0, v0) = pts[i - 1];
748        let (t1, v1) = pts[i];
749        if temp_c <= t1 {
750            let span = t1 - t0;
751            if span.abs() < f64::EPSILON {
752                return v1; // coincident temps: avoid divide-by-zero, take the upper
753            }
754            let f = (temp_c - t0) / span;
755            return v0 + f * (v1 - v0);
756        }
757    }
758    pts[n - 1].1
759}
760
761/// Parse a `--sweep START:END:STEP` temperature range (display units) for the
762/// `powder` command — ONE parser shared by the native CLI and WASM so their
763/// validation cannot drift. Returns the
764/// inclusive row temperatures. Guarded: STEP must be positive, END >= START, and the
765/// row count is capped so a typo can't emit an unbounded table.
766pub fn parse_powder_sweep(s: &str) -> Result<Vec<f64>, String> {
767    const MAX_SWEEP_ROWS: usize = 500;
768    let parts: Vec<&str> = s.split(':').collect();
769    if parts.len() != 3 {
770        return Err(format!(
771            "Invalid --sweep '{}': expected START:END:STEP (e.g. \"20:110:10\")",
772            s
773        ));
774    }
775    let parse = |p: &str, name: &str| -> Result<f64, String> {
776        p.trim()
777            .parse::<f64>()
778            .map_err(|_| format!("Invalid --sweep {}: '{}' is not a number", name, p.trim()))
779    };
780    let start = parse(parts[0], "START")?;
781    let end = parse(parts[1], "END")?;
782    let step = parse(parts[2], "STEP")?;
783    if !step.is_finite() || step <= 0.0 {
784        return Err(format!("Invalid --sweep STEP {}: must be positive", step));
785    }
786    if !start.is_finite() || !end.is_finite() || end < start {
787        return Err(format!(
788            "Invalid --sweep range {}:{}: END must be >= START",
789            start, end
790        ));
791    }
792    // Row count computed and bounds-checked in f64 BEFORE the usize cast: a huge
793    // range would saturate the cast and overflow the `+ 1` (panic under
794    // overflow-checks, wrap-to-zero in release — silently bypassing this cap).
795    // The epsilon keeps a fractional STEP whose quotient lands a hair below an
796    // integer (e.g. 0:0.3:0.1 -> 2.9999999999999996) from dropping the END row.
797    let n_f = ((end - start) / step + 1e-9).floor();
798    if !n_f.is_finite() || n_f + 1.0 > MAX_SWEEP_ROWS as f64 {
799        return Err(format!(
800            "--sweep would produce more than {} rows; use a larger STEP",
801            MAX_SWEEP_ROWS
802        ));
803    }
804    let n = n_f as usize + 1;
805    // Index-multiplied (not accumulated) so float drift can't drop the END row.
806    Ok((0..n).map(|i| start + step * i as f64).collect())
807}
808
809/// Resolve the powder-temperature-adjusted muzzle velocity (m/s) — the velocity the
810/// solver actually flies. A non-empty measured `powder_temp_curve` takes precedence
811/// (interpolated at `powder_curve_temp_c`, falling back to the ambient
812/// `ambient_temperature_c`; clamped at the endpoints) and REPLACES the nominal
813/// velocity; otherwise, when `use_powder_sensitivity` is set, the linear model adds
814/// `sensitivity x (ambient - reference)` to it. All inputs canonical SI (Celsius,
815/// m/s). This is the single shared implementation behind the trajectory solve, the
816/// `powder` CLI/WASM command (MBA-737), and anything else that must agree with them.
817pub fn resolve_powder_adjusted_velocity(
818    nominal_velocity_mps: f64,
819    ambient_temperature_c: f64,
820    use_powder_sensitivity: bool,
821    powder_temp_sensitivity_mps_per_c: f64,
822    powder_reference_temp_c: f64,
823    powder_temp_curve: Option<&[(f64, f64)]>,
824    powder_curve_temp_c: Option<f64>,
825) -> f64 {
826    if let Some(curve) = powder_temp_curve {
827        if !curve.is_empty() {
828            let lookup_c = powder_curve_temp_c.unwrap_or(ambient_temperature_c);
829            return interpolate_powder_temp_curve(curve, lookup_c);
830        }
831        // A supplied-but-empty curve has always suppressed the linear fallback
832        // (the historical `else if`); preserve that exactly.
833        return nominal_velocity_mps;
834    }
835    if use_powder_sensitivity {
836        let temp_delta_c = ambient_temperature_c - powder_reference_temp_c;
837        return nominal_velocity_mps + powder_temp_sensitivity_mps_per_c * temp_delta_c;
838    }
839    nominal_velocity_mps
840}
841
842// Wind conditions
843#[derive(Debug, Clone)]
844pub struct WindConditions {
845    pub speed: f64, // m/s
846    // radians, wind-FROM convention: 0 = headwind, PI/2 = from the right,
847    // PI = tailwind, 3*PI/2 = from the left (matches WindSock / the bindings).
848    pub direction: f64,
849    /// Vertical wind component, m/s. POSITIVE = UPDRAFT (raises POI downrange); negative =
850    /// downdraft. Default 0.0. Enters the wind vector via [`crate::wind::wind_vector`]'s third
851    /// argument (MBA-728). Boundary-layer shear scales horizontal wind only — vertical passes
852    /// through unscaled wherever shear is applied on top of this. This scalar field (like
853    /// [`WindConditions::speed`]/[`WindConditions::direction`]) is ignored once downrange wind
854    /// segments are set on the solver — each [`crate::wind::WindSegment`] carries its own
855    /// `vertical_mps` instead.
856    pub vertical_speed: f64,
857}
858
859impl Default for WindConditions {
860    fn default() -> Self {
861        Self {
862            speed: 0.0,
863            direction: 0.0,
864            vertical_speed: 0.0,
865        }
866    }
867}
868
869// Atmospheric conditions
870#[derive(Debug, Clone)]
871pub struct AtmosphericConditions {
872    pub temperature: f64, // Celsius
873    pub pressure: f64,    // hPa
874    /// Relative humidity, PERCENT, `0..=100`, the same unit as
875    /// [`BallisticInputs::humidity_percent`]. Default [`DEFAULT_HUMIDITY_PERCENT`]. A sensor
876    /// reading within [`crate::HUMIDITY_SENSOR_TOLERANCE_PERCENT`] of the range (101.7 in fog)
877    /// flies as the end it reads as; a value beyond that is refused by the solve.
878    pub humidity: f64,
879    pub altitude: f64, // meters
880}
881
882impl AtmosphericConditions {
883    /// The station temperature (°C) and absolute pressure (hPa) a solve of these conditions
884    /// flies, after the presence rule: a reading `presence` marks as supplied flies as given,
885    /// an omitted default at a real altitude flies the ICAO standard value there.
886    pub fn resolved_station(&self, presence: StationAtmospherePresence) -> (f64, f64) {
887        crate::atmosphere::resolve_station_conditions_with_presence(
888            self.temperature,
889            self.pressure,
890            self.altitude,
891            PressureReferenceMode::Absolute,
892            presence,
893        )
894    }
895
896    /// The station air a solve of these conditions flies, built exactly as
897    /// [`TrajectorySolver`] builds it: the humidity through [`RelativeHumidity::try_percent`],
898    /// the temperature and pressure through [`Self::resolved_station`], the air through
899    /// [`StationAir::new`].
900    ///
901    /// For a surface that refuses air up front, before any work, in its own words
902    /// ([`AtmosphereError::refusal_in`]): whatever this refuses, every solve of these
903    /// conditions refuses, and whatever it accepts, a solve flies.
904    pub fn station_air(
905        &self,
906        presence: StationAtmospherePresence,
907    ) -> Result<StationAir, AtmosphereError> {
908        let humidity = RelativeHumidity::try_percent(self.humidity)?;
909        let (temperature_c, pressure_hpa) = self.resolved_station(presence);
910        StationAir::new(self.altitude, temperature_c, pressure_hpa, humidity)
911    }
912
913    /// Where the station pressure a solve of these conditions flies comes from, by the
914    /// presence rule [`Self::resolved_station`] applies: the standard pressure at the altitude
915    /// when `presence` marks the pressure omitted and it is the sea-level default at a real
916    /// altitude, the reading otherwise ([`StationOrigin::resolving`]). These conditions hold a
917    /// station pressure, never a QNH, and the temperature is a reading: a caller that reduced a
918    /// QNH or flies a density altitude's station states its own origin to
919    /// [`Self::air_refusal_from`].
920    pub fn station_origin(&self, presence: StationAtmospherePresence) -> StationOrigin {
921        StationOrigin::resolving(
922            self.pressure,
923            self.altitude,
924            PressureReferenceMode::Absolute,
925            presence,
926        )
927    }
928
929    /// [`Self::air_refusal`] for a terminal (the native CLI, the browser terminal): every reading
930    /// is named by its flag, which is also its path (`labels`: humidity, temperature, pressure,
931    /// altitude, e.g. `["--humidity", "--temperature", "--pressure", "--altitude"]`, or where a
932    /// reading came from: `--location CSV column TEMP`, `profile 'p' field pressure`), the
933    /// humidity is the percent the command flies, and the station temperature, pressure and
934    /// every altitude are stated in the run's `units` (°F, inHg and ft, or °C, hPa and m):
935    /// `--humidity = 100 at 212 °F and 29.92 inHg: no such air exists: ...`,
936    /// `profile 'p' field pressure = -1 inHg: pressure must be greater than 0`.
937    pub fn air_refusal_named(
938        &self,
939        presence: StationAtmospherePresence,
940        units: UnitSystem,
941        labels: [&str; 4],
942    ) -> Option<crate::atmosphere::AirRefusal> {
943        self.air_refusal_named_from(presence, self.station_origin(presence), units, labels)
944    }
945
946    /// [`Self::air_refusal_named`] for a terminal that resolved the station itself (a QNH
947    /// reduced, a density altitude's derived triple) and so knows where its readings came from
948    /// better than `presence` can say: `origin`, which decides whether a station pressure outside
949    /// the troposphere is blamed on the pressure, the altitude or a density altitude, carries the
950    /// QNH as it was typed, and says whether a density altitude gave the temperature.
951    pub fn air_refusal_named_from(
952        &self,
953        presence: StationAtmospherePresence,
954        origin: StationOrigin,
955        units: UnitSystem,
956        labels: [&str; 4],
957    ) -> Option<crate::atmosphere::AirRefusal> {
958        self.air_refusal_from(
959            presence,
960            origin,
961            labels.map(crate::atmosphere::AirField::named),
962            self.humidity,
963            terminal_air_units(units),
964        )
965    }
966
967    /// The station a density altitude gives, as a terminal flies it, or its refusal in the
968    /// terminal's words ([`crate::atmosphere::station_for_density_altitude`], the one rule):
969    /// `--density-altitude = 200000 ft: no air has this density altitude: ...`.
970    ///
971    /// `labels` name the readings as [`Self::air_refusal_named`]'s do; a terminal that flies a
972    /// density altitude names its altitude (and its pressure) by the density altitude's own
973    /// label, and its temperature too unless one was given (`explicit_temperature_c`, °C, the
974    /// temperature the density altitude is re-solved around). `humidity` is the percent the
975    /// station flies; the result is checked as any station is afterwards.
976    pub fn for_density_altitude_named(
977        density_altitude_m: f64,
978        explicit_temperature_c: Option<f64>,
979        humidity: f64,
980        units: UnitSystem,
981        labels: [&str; 4],
982    ) -> Result<Self, crate::atmosphere::AirRefusal> {
983        match crate::atmosphere::station_for_density_altitude(
984            density_altitude_m,
985            explicit_temperature_c,
986        ) {
987            Ok((altitude, temperature, pressure)) => Ok(Self {
988                temperature,
989                pressure,
990                humidity,
991                altitude,
992            }),
993            Err(error) => {
994                let units = terminal_air_units(units);
995                let [humidity_field, temperature, pressure, altitude] =
996                    labels.map(crate::atmosphere::AirField::named);
997                let temperature_c = explicit_temperature_c.unwrap_or(f64::NAN);
998                Err(error.refusal_in(
999                    &crate::atmosphere::AirSpelling {
1000                        humidity: humidity_field,
1001                        temperature,
1002                        pressure,
1003                        altitude,
1004                        humidity_sent: humidity,
1005                        temperature_text: units.temperature.text(temperature_c),
1006                        temperature_unit: units.temperature,
1007                        temperature_origin: StationOrigin::density_altitude(
1008                            explicit_temperature_c.is_some(),
1009                        )
1010                        .temperature,
1011                        pressure_text: String::new(),
1012                        pressure_origin: StationPressureOrigin::DensityAltitude,
1013                        qnh_text: None,
1014                        altitude_unit: units.altitude,
1015                    },
1016                    density_altitude_m,
1017                    temperature_c,
1018                    f64::NAN,
1019                ))
1020            }
1021        }
1022    }
1023
1024    /// [`Self::station_air`] refused in a surface's words, or `None` when the air flies: every
1025    /// reason a station is refused for (a humidity outside the sensor band, a temperature at or
1026    /// below absolute zero, a pressure at or below 0, a reading that is not finite, air that
1027    /// cannot exist), each at the reading to blame.
1028    ///
1029    /// `fields` name the surface's readings (humidity, temperature, pressure, altitude);
1030    /// `humidity_sent` is the humidity as it was given there; `units` are the units the surface
1031    /// states the resolved station temperature (°C), pressure (hPa) and every altitude in. Where
1032    /// the pressure came from is [`Self::station_origin`].
1033    pub fn air_refusal(
1034        &self,
1035        presence: StationAtmospherePresence,
1036        fields: [crate::atmosphere::AirField<'_>; 4],
1037        humidity_sent: f64,
1038        units: crate::atmosphere::AirUnits,
1039    ) -> Option<crate::atmosphere::AirRefusal> {
1040        self.air_refusal_from(
1041            presence,
1042            self.station_origin(presence),
1043            fields,
1044            humidity_sent,
1045            units,
1046        )
1047    }
1048
1049    /// [`Self::air_refusal`] with the readings' `origin` stated by a caller that resolved the
1050    /// station itself (a QNH reduced, or a density altitude's station, before these conditions
1051    /// were built): a refusal names the QNH as it was given ([`StationOrigin::qnh_hpa`], in
1052    /// `units`), never the station pressure reduced from it as if it had been given, and a
1053    /// temperature a density altitude gave as that density altitude's.
1054    ///
1055    /// A QNH that is itself no pressure (not finite, or at or below 0) is refused as the
1056    /// reading it is, `pressure = -1 inHg: pressure must be greater than 0`, rather than as the
1057    /// NaN it reduces to.
1058    pub fn air_refusal_from(
1059        &self,
1060        presence: StationAtmospherePresence,
1061        origin: StationOrigin,
1062        fields: [crate::atmosphere::AirField<'_>; 4],
1063        humidity_sent: f64,
1064        units: crate::atmosphere::AirUnits,
1065    ) -> Option<crate::atmosphere::AirRefusal> {
1066        let error = self.station_air(presence).err()?;
1067        let (temperature_c, pressure_hpa) = self.resolved_station(presence);
1068        let [humidity, temperature, pressure, altitude] = fields;
1069        let spelling = crate::atmosphere::AirSpelling {
1070            humidity,
1071            temperature,
1072            pressure,
1073            altitude,
1074            humidity_sent,
1075            temperature_text: units.temperature.text(temperature_c),
1076            temperature_unit: units.temperature,
1077            temperature_origin: origin.temperature,
1078            pressure_text: units.pressure.text(pressure_hpa),
1079            pressure_origin: origin.pressure,
1080            qnh_text: origin.qnh_hpa.map(|qnh_hpa| units.pressure.text(qnh_hpa)),
1081            altitude_unit: units.altitude,
1082        };
1083        // The pressure the station refuses is the QNH's reduction: a QNH that is no pressure is
1084        // refused as the reading it is.
1085        if let (Some(qnh_hpa), "pressure_hpa") = (origin.qnh_hpa, error.field()) {
1086            if let Err(qnh_error) = crate::atmosphere::check_station_pressure_hpa(qnh_hpa) {
1087                return Some(qnh_error.refusal_in(
1088                    &crate::atmosphere::AirSpelling {
1089                        pressure_text: units.pressure.text(qnh_hpa),
1090                        pressure_origin: StationPressureOrigin::Reading,
1091                        qnh_text: None,
1092                        ..spelling
1093                    },
1094                    self.altitude,
1095                    temperature_c,
1096                    qnh_hpa,
1097                ));
1098            }
1099        }
1100        Some(error.refusal_in(&spelling, self.altitude, temperature_c, pressure_hpa))
1101    }
1102}
1103
1104/// The units a terminal (the native CLI, the browser terminal) states its station air in, by
1105/// the run's `units`: °F, inHg and feet, or °C, hPa and metres.
1106fn terminal_air_units(units: UnitSystem) -> crate::atmosphere::AirUnits {
1107    match units {
1108        UnitSystem::Imperial => crate::atmosphere::AirUnits::IMPERIAL,
1109        UnitSystem::Metric => crate::atmosphere::AirUnits::METRIC,
1110    }
1111}
1112
1113/// A station temperature, °C, as a terminal (the native CLI, the browser terminal) states it in
1114/// a refusal: in °F or °C by the run's `units`, `"-441.67 °F"`.
1115fn terminal_temperature_text(temperature_c: f64, units: UnitSystem) -> String {
1116    match units {
1117        UnitSystem::Imperial => {
1118            crate::atmosphere::reading_text(temperature_c * 9.0 / 5.0 + 32.0, "°F")
1119        }
1120        UnitSystem::Metric => crate::atmosphere::reading_text(temperature_c, "°C"),
1121    }
1122}
1123
1124/// The unit a terminal states an altitude in, by the run's `units`: feet, or metres.
1125fn terminal_altitude_unit(units: UnitSystem) -> crate::atmosphere::AltitudeUnit {
1126    match units {
1127        UnitSystem::Imperial => crate::atmosphere::AltitudeUnit::Feet,
1128        UnitSystem::Metric => crate::atmosphere::AltitudeUnit::Meters,
1129    }
1130}
1131
1132impl Default for AtmosphericConditions {
1133    fn default() -> Self {
1134        Self {
1135            temperature: 15.0,
1136            pressure: 1013.25,
1137            humidity: DEFAULT_HUMIDITY_PERCENT,
1138            altitude: 0.0,
1139        }
1140    }
1141}
1142
1143// Trajectory point data
1144#[derive(Debug, Clone)]
1145pub struct TrajectoryPoint {
1146    pub time: f64,
1147    pub position: Vector3<f64>,
1148    pub velocity_magnitude: f64,
1149    pub kinetic_energy: f64,
1150    /// The projectile's own drag coefficient at this point (MBA-1423).
1151    ///
1152    /// Filled in one pass after integration finishes, not at the sites that build this struct,
1153    /// so a solver family added later cannot silently omit it. `None` when sectional density is
1154    /// unavailable — see [`TrajectorySolver::effective_drag_coefficient`] for the definition and
1155    /// why this is the projectile's Cd rather than the reference table's.
1156    pub drag_coefficient: Option<f64>,
1157}
1158
1159impl TrajectoryPoint {
1160    /// The value `--with-drag-coefficient` emits for this point, or `None` when the JSON key
1161    /// must be ABSENT — flag off, or sectional density unknown (MBA-1427).
1162    ///
1163    /// Host-compilable on purpose. The browser terminal's emit site lives in `src/wasm.rs`,
1164    /// which is `cfg(target_arch = "wasm32")`-gated out of every native build — CI never
1165    /// executes a line of it. Keeping the gating rule here means a native test can pin the
1166    /// absent-not-null contract even though the surface that applies it only compiles for wasm.
1167    pub fn drag_coefficient_json_value(&self, with_drag_coefficient: bool) -> Option<f64> {
1168        if with_drag_coefficient {
1169            self.drag_coefficient
1170        } else {
1171            None
1172        }
1173    }
1174}
1175
1176// Trajectory result
1177#[derive(Debug, Clone)]
1178pub struct TrajectoryResult {
1179    pub max_range: f64,
1180    pub max_height: f64,
1181    pub time_of_flight: f64,
1182    pub impact_velocity: f64,
1183    pub impact_energy: f64,
1184    /// Projectile mass used to derive full-state observation energy.
1185    pub projectile_mass_kg: f64,
1186    /// Height of the horizontal line of sight in the solver's ground-referenced frame.
1187    pub line_of_sight_height_m: f64,
1188    /// Station speed of sound used for Mach observations and transition flags.
1189    pub station_speed_of_sound_mps: f64,
1190    /// Explicit reason the integration stopped; consumers must not infer this from the endpoint.
1191    pub termination: TrajectoryTermination,
1192    pub points: Vec<TrajectoryPoint>,
1193    pub sampled_points: Option<Vec<TrajectorySample>>, // Trajectory samples at regular intervals
1194    pub min_pitch_damping: Option<f64>, // Minimum pitch damping coefficient (for stability warning)
1195    pub transonic_mach: Option<f64>,    // Mach number when entering transonic regime
1196    pub angular_state: Option<AngularState>, // Final angular state if precession/nutation enabled
1197    pub max_yaw_angle: Option<f64>,     // Maximum yaw angle during flight (radians)
1198    pub max_precession_angle: Option<f64>, // Maximum precession angle (radians)
1199    // MBA-959: aerodynamic-jump components applied at the muzzle (None unless
1200    // enable_aerodynamic_jump). EXPERIMENTAL.
1201    pub aerodynamic_jump: Option<crate::aerodynamic_jump::AerodynamicJumpComponents>,
1202    /// Downrange distance (m) of the downward Mach 1.2 crossing (station speed of sound),
1203    /// populated identically by all three solver paths (Euler/RK4/RK45). `None` if the
1204    /// trajectory never crosses 1.2 while descending (e.g. launched already below 1.2, or the
1205    /// solve terminates while still above it). MBA-1405: feeds `mv_calibration_window`.
1206    pub mach_1_2_distance_m: Option<f64>,
1207    /// Downrange distance (m) of the downward Mach 1.0 crossing. `None` if the trajectory
1208    /// never goes subsonic within the solve. MBA-1405: the far edge of the MV calibration
1209    /// window (`mv_calibration_window`) is this distance.
1210    pub mach_1_0_distance_m: Option<f64>,
1211    /// Downrange distance (m) of the downward Mach 0.9 crossing. `None` if the trajectory
1212    /// never crosses 0.9 while descending. MBA-1405: feeds `dsf_window_start`. NOTE: unlike
1213    /// the 1.2/1.0 crossings, this one is intentionally NOT reflected in the historical flat
1214    /// `transonic_distances` Vec threaded through
1215    /// [`crate::trajectory_sampling::TrajectoryData`] — existing consumers of that Vec
1216    /// interpret it strictly as `{1.2, 1.0}`, so this field is the only place the 0.9
1217    /// crossing is recorded.
1218    pub mach_0_9_distance_m: Option<f64>,
1219}
1220
1221const RK45_TOLERANCE: f64 = 1e-6;
1222const RK45_SAFETY_FACTOR: f64 = 0.9;
1223const RK45_MAX_DT: f64 = 0.01;
1224const RK45_MIN_DT: f64 = 1e-6;
1225const TRAJECTORY_TIME_LIMIT_S: f64 = 100.0;
1226
1227/// Hard ceiling for points retained by a single [`TrajectorySolver`] result.
1228///
1229/// The cap applies across Euler, fixed RK4, and adaptive RK45, including the exact terminal
1230/// endpoint. Solves that would exceed it return [`BallisticsError`] instead of
1231/// truncating or growing their point buffer without bound.
1232pub const MAX_TRAJECTORY_POINTS: usize = 250_000;
1233
1234/// Pack the CLI solver's split position/velocity vectors into the shared six-component RK45 norm.
1235fn cli_rk45_error_norm(
1236    position: &Vector3<f64>,
1237    velocity: &Vector3<f64>,
1238    fifth_position: &Vector3<f64>,
1239    fifth_velocity: &Vector3<f64>,
1240    fourth_position: &Vector3<f64>,
1241    fourth_velocity: &Vector3<f64>,
1242) -> f64 {
1243    let pack_state = |position: &Vector3<f64>, velocity: &Vector3<f64>| {
1244        Vector6::new(
1245            position.x, position.y, position.z, velocity.x, velocity.y, velocity.z,
1246        )
1247    };
1248    let state = pack_state(position, velocity);
1249    let fifth_order = pack_state(fifth_position, fifth_velocity);
1250    let fourth_order = pack_state(fourth_position, fourth_velocity);
1251
1252    crate::trajectory_integration::rk45_error_norm(&state, &fifth_order, &fourth_order)
1253}
1254
1255struct Rk45Trial {
1256    position: Vector3<f64>,
1257    velocity: Vector3<f64>,
1258    suggested_dt: f64,
1259    error: f64,
1260}
1261
1262struct Rk45AcceptedStep {
1263    position: Vector3<f64>,
1264    velocity: Vector3<f64>,
1265    used_dt: f64,
1266    next_dt: f64,
1267    error: f64,
1268}
1269
1270/// Tracks the downward (decelerating) Mach crossings of a solved trajectory.
1271///
1272/// `record_downward_crossings` is called once per integration step from all three solver
1273/// paths (Euler/RK4/RK45). It both (a) appends to the historical flat `distances` Vec — used
1274/// unchanged by [`crate::trajectory_sampling`] to flag sampled points — and (b) records each
1275/// threshold's exact crossing distance on `self`, for callers that want the labeled value
1276/// directly (MBA-1405) rather than positionally decoding the flat Vec.
1277///
1278/// IMPORTANT: only the historical 1.2/1.0 thresholds are appended to `distances`. The 0.9
1279/// threshold added for MBA-1405 is recorded ONLY on `self.mach_0_9_distance_m` — existing
1280/// consumers of the flat Vec interpret it strictly as `{mach_1_2, mach_1_0}` (in that order,
1281/// when present), so appending a third entry would silently corrupt their positional
1282/// assumptions.
1283#[derive(Default)]
1284struct MachTransitionTracker {
1285    previous_mach: Option<f64>,
1286    crossed_transonic: bool,
1287    crossed_subsonic: bool,
1288    crossed_narrow: bool,
1289    /// Downrange distance (m) of the downward Mach 1.2 crossing, once seen. Mirrors the first
1290    /// flat-Vec entry.
1291    mach_1_2_distance_m: Option<f64>,
1292    /// Downrange distance (m) of the downward Mach 1.0 crossing, once seen. Mirrors the second
1293    /// flat-Vec entry.
1294    mach_1_0_distance_m: Option<f64>,
1295    /// Downrange distance (m) of the downward Mach 0.9 crossing, once seen. NOT reflected in
1296    /// the flat Vec (see struct docs).
1297    mach_0_9_distance_m: Option<f64>,
1298}
1299
1300impl MachTransitionTracker {
1301    fn record_downward_crossings(&mut self, mach: f64, downrange_m: f64, distances: &mut Vec<f64>) {
1302        if !mach.is_finite() {
1303            self.previous_mach = None;
1304            return;
1305        }
1306
1307        if let Some(previous_mach) = self.previous_mach {
1308            if !self.crossed_transonic && previous_mach >= 1.2 && mach < 1.2 {
1309                self.crossed_transonic = true;
1310                distances.push(downrange_m);
1311                self.mach_1_2_distance_m = Some(downrange_m);
1312            }
1313            if !self.crossed_subsonic && previous_mach >= 1.0 && mach < 1.0 {
1314                self.crossed_subsonic = true;
1315                distances.push(downrange_m);
1316                self.mach_1_0_distance_m = Some(downrange_m);
1317            }
1318            if !self.crossed_narrow && previous_mach >= 0.9 && mach < 0.9 {
1319                self.crossed_narrow = true;
1320                // Intentionally NOT pushed to `distances` — see struct docs.
1321                self.mach_0_9_distance_m = Some(downrange_m);
1322            }
1323        }
1324        self.previous_mach = Some(mach);
1325    }
1326}
1327
1328impl TrajectoryResult {
1329    /// Interpolate position at a given downrange distance (X coordinate, McCoy).
1330    /// Returns the interpolated (x, y, z) position at that range.
1331    /// If the target range exceeds the trajectory, returns the last point.
1332    pub fn position_at_range(&self, target_range: f64) -> Option<Vector3<f64>> {
1333        if self.points.is_empty() {
1334            return None;
1335        }
1336
1337        // Find the two points that bracket the target range
1338        for i in 0..self.points.len() - 1 {
1339            let p1 = &self.points[i];
1340            let p2 = &self.points[i + 1];
1341
1342            // Check if target range is between these two points (X is downrange)
1343            if p1.position.x <= target_range && p2.position.x >= target_range {
1344                // Linear interpolation factor
1345                let dx = p2.position.x - p1.position.x;
1346                if dx.abs() < 1e-10 {
1347                    return Some(p1.position);
1348                }
1349                let t = (target_range - p1.position.x) / dx;
1350
1351                // Interpolate Y and Z, use exact target_range for X
1352                return Some(Vector3::new(
1353                    target_range,
1354                    p1.position.y + t * (p2.position.y - p1.position.y),
1355                    p1.position.z + t * (p2.position.z - p1.position.z),
1356                ));
1357            }
1358        }
1359
1360        // Target range is beyond trajectory - return last point
1361        self.points.last().map(|p| p.position)
1362    }
1363}
1364
1365// Trajectory solver
1366#[derive(Clone)]
1367pub struct TrajectorySolver {
1368    gravity: Gravity,
1369    inputs: BallisticInputs,
1370    wind: WindConditions,
1371    atmosphere: AtmosphericConditions,
1372    /// Which of `atmosphere`'s temperature and pressure the caller supplied (0.49.0). A field
1373    /// that is not supplied keeps the legacy default-sentinel rule; see
1374    /// [`crate::atmosphere::resolve_station_conditions_with_presence`].
1375    station_presence: StationAtmospherePresence,
1376    max_range: f64,
1377    time_step: f64,
1378    max_trajectory_points: usize,
1379    cluster_bc: Option<ClusterBCDegradation>,
1380    /// Geometry-derived `(longitudinal, transverse)` moments used by angular diagnostics.
1381    precession_nutation_inertias: (f64, f64),
1382    /// Optional downrange-segmented wind. When `Some`, the per-step wind vector is
1383    /// looked up by downrange distance from this `WindSock` and the scalar `wind`
1384    /// field is ignored. When `None`, the constant `wind` vector is used (default),
1385    /// so a non-segmented solve is numerically identical to pre-feature behavior.
1386    wind_sock: Option<crate::wind::WindSock>,
1387    /// Optional downrange-segmented atmosphere (MBA-1137). When `Some`, the per-substep local
1388    /// atmosphere recompute samples the base (station-referenced) temperature/pressure/humidity by
1389    /// downrange distance from this `AtmoSock`, then feeds them through the SAME altitude-lapse
1390    /// pipeline as a single-station solve — so the downrange zone and the vertical altitude lapse
1391    /// compose without double-counting. When `None` (default), the resolved single-station
1392    /// conditions are used.
1393    atmo_sock: Option<crate::atmosphere::AtmoSock>,
1394}
1395
1396/// Which frame a zero solve's `target_height_m` lives in (MBA-1412).
1397///
1398/// `SightLine`: the classic zero contract — the height is sight geometry (typically the sight
1399/// height) and the rifle zeroes LEVEL, per the MBA-1286 doctrine that a zero is a property of a
1400/// level rifle; `shooting_angle` applies to the subsequent shot only. Used by
1401/// `calculate_zero_angle_with_conditions` and every legacy surface behind it (bindings, WASM,
1402/// FFI, CLI).
1403///
1404/// `WorldVertical`: solve-json v1's documented contract (docs/SOLVE_JSON_V1.md) — the height is
1405/// an absolute world-vertical height above the ground datum; inclined zeroing projects the
1406/// shot-frame trajectory into the world frame (MBA-1302 behavior, unchanged).
1407#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1408pub(crate) enum ZeroTargetFrame {
1409    SightLine,
1410    WorldVertical,
1411}
1412
1413/// Both line-of-sight crossings a single fixed bore angle can produce (Tier 2 whole-branch
1414/// review, C2): a rifle whose sight sits above its bore generally crosses a level line of
1415/// sight TWICE on a rising shot — an ascending "near zero" close to the muzzle, and a
1416/// descending "far zero" past the apex. The classic 25/300-yard battle-zero pairing is one
1417/// bore angle producing both. `TrajectorySolver`'s internal `find_zero_range` and the public
1418/// `calculate_zero_range_from_angle_*` functions return both rather than silently choosing
1419/// one, because `find_zero_angle`'s own choice of root depends on the target distance it was
1420/// asked to solve for — the forward and inverse solvers are NOT a single-valued pair.
1421///
1422/// Either field may be `None` when the solved envelope doesn't reach that crossing (e.g. a
1423/// short `--max-range` that stops before the far crossing, or a target height high enough
1424/// that the trajectory never rises to it at all). At least one is always `Some` on `Ok`.
1425#[derive(Debug, Clone, Copy, PartialEq)]
1426pub struct ZeroCrossings {
1427    /// Downrange distance (meters) of the near, ascending crossing, if the solved envelope
1428    /// reaches it.
1429    pub near_m: Option<f64>,
1430    /// Downrange distance (meters) of the far, descending crossing -- what "sighted in at D
1431    /// yards" conventionally means -- if the solved envelope reaches it.
1432    pub far_m: Option<f64>,
1433}
1434
1435impl TrajectorySolver {
1436    /// Construct a solver from a presence-blind [`AtmosphericConditions`].
1437    ///
1438    /// Presence-blind: a bare `f64` cannot say whether it was supplied, so at an altitude above
1439    /// 1 m a temperature within 0.1 °C of 15 °C or a pressure within 0.5 hPa of 1013.25 hPa is
1440    /// read as omitted and the ICAO standard value at that altitude is flown instead. A caller
1441    /// that knows which values were supplied uses [`Self::new_with_station_presence`]; this is
1442    /// that constructor with [`StationAtmospherePresence::NEITHER`].
1443    pub fn new(
1444        inputs: BallisticInputs,
1445        wind: WindConditions,
1446        atmosphere: AtmosphericConditions,
1447    ) -> Self {
1448        Self::new_with_station_presence(
1449            inputs,
1450            wind,
1451            atmosphere,
1452            StationAtmospherePresence::NEITHER,
1453        )
1454    }
1455
1456    /// Construct a solver that knows which of `atmosphere`'s temperature and pressure the
1457    /// caller supplied (0.49.0).
1458    ///
1459    /// A supplied value flies as given, whatever its value: a typed 15 °C or 1013.25 hPa at
1460    /// altitude is a reading, not a default. An omitted value keeps the legacy rule of
1461    /// [`Self::new`], so [`StationAtmospherePresence::NEITHER`] is bit-identical to it and
1462    /// [`StationAtmospherePresence::BOTH`] to [`Self::new_with_resolved_station_atmosphere`].
1463    /// The pressure is absolute station pressure; reduce a QNH first, or resolve the pair with
1464    /// [`crate::atmosphere::resolve_station_conditions_with_presence`] in
1465    /// [`PressureReferenceMode::Qnh`] and pass the result with `BOTH`.
1466    pub fn new_with_station_presence(
1467        inputs: BallisticInputs,
1468        wind: WindConditions,
1469        atmosphere: AtmosphericConditions,
1470        station_presence: StationAtmospherePresence,
1471    ) -> Self {
1472        Self::new_with_station_presence_and_gravity(
1473            inputs,
1474            wind,
1475            atmosphere,
1476            station_presence,
1477            Gravity::EARTH,
1478        )
1479    }
1480
1481    /// Construct a solver from station temperature and pressure that a presence-aware service
1482    /// has already resolved. Unlike [`Self::new`], exact sea-level standard values remain
1483    /// authoritative at nonzero altitude rather than acting as legacy omission sentinels.
1484    ///
1485    /// `pub` (MBA-1397; was `pub(crate)`): a QNH-aware caller (native CLI, WASM) that has
1486    /// already resolved the station air, for example with
1487    /// [`crate::atmosphere::resolve_station_conditions_with_presence`] (which reduces a declared
1488    /// altimeter setting to station pressure), needs this constructor too, and those callers
1489    /// live in a different crate (`src/main.rs` is a separate binary crate over the library).
1490    /// It is [`Self::new_with_station_presence`] with [`StationAtmospherePresence::BOTH`].
1491    pub fn new_with_resolved_station_atmosphere(
1492        inputs: BallisticInputs,
1493        wind: WindConditions,
1494        atmosphere: AtmosphericConditions,
1495    ) -> Self {
1496        Self::new_with_station_presence(inputs, wind, atmosphere, StationAtmospherePresence::BOTH)
1497    }
1498
1499    fn new_with_station_presence_and_gravity(
1500        mut inputs: BallisticInputs,
1501        wind: WindConditions,
1502        atmosphere: AtmosphericConditions,
1503        station_presence: StationAtmospherePresence,
1504        gravity: Gravity,
1505    ) -> Self {
1506        // MBA-1415: every input-conditioning step lives in one shared, idempotent helper that
1507        // the fast_integrate* entry points call too. Keeping it out of this constructor is the
1508        // point: conditioning that lives only here is invisible to the external bindings that
1509        // call the fast path directly.
1510        inputs.normalize_for_solve();
1511        // The atmosphere is what a solve flies, so its humidity wins and the inputs then say
1512        // the same thing. Copied as given; an out-of-range value is the solve's to judge.
1513        inputs.humidity_percent = atmosphere.humidity;
1514
1515        // Initialize cluster BC if enabled
1516        let cluster_bc = if inputs.use_cluster_bc {
1517            Some(ClusterBCDegradation::new())
1518        } else {
1519            None
1520        };
1521        let precession_nutation_inertias = projectile_moments_of_inertia(
1522            inputs.bullet_mass,
1523            inputs.bullet_diameter,
1524            inputs.bullet_length,
1525        );
1526
1527        Self {
1528            gravity,
1529            inputs,
1530            wind,
1531            atmosphere,
1532            station_presence,
1533            max_range: 1000.0,
1534            time_step: 0.001,
1535            max_trajectory_points: MAX_TRAJECTORY_POINTS,
1536            cluster_bc,
1537            precession_nutation_inertias,
1538            wind_sock: None,
1539            atmo_sock: None,
1540        }
1541    }
1542
1543    pub fn set_max_range(&mut self, range: f64) {
1544        self.max_range = range;
1545    }
1546
1547    pub fn set_time_step(&mut self, step: f64) {
1548        self.time_step = step;
1549    }
1550
1551    /// Calculate a level-rifle zero with this solver's configured atmosphere, wind (including
1552    /// downrange segments), effects, integration method, and time step, then install the resulting
1553    /// muzzle angle on this solver. The solver is mutated only after a zero has converged.
1554    pub(crate) fn calculate_and_set_zero_angle(
1555        &mut self,
1556        target_distance_m: f64,
1557        target_height_m: f64,
1558        frame: ZeroTargetFrame,
1559    ) -> Result<f64, BallisticsError> {
1560        let angle = self.find_zero_angle(target_distance_m, target_height_m, frame)?;
1561        // MBA-1359: a deliberate POI offset at the zero range (Kestrel ZH/ZO) is an angular
1562        // bias ON the solved angle, applied post-solve so the zero trials above still solve
1563        // perfect convergence. The small-angle addition is frame-independent (identical in
1564        // SightLine and WorldVertical), and with both offsets at their 0.0 defaults the
1565        // additions below are exact no-ops (byte-identical). The returned angle carries the
1566        // vertical bias so auto-zero callers that copy it onto flight inputs inherit it; the
1567        // horizontal bias lands on THIS solver's azimuth_angle — separate flight inputs must
1568        // add `windage_zero_bias_rad` themselves.
1569        let angle = if target_distance_m > 0.0 {
1570            angle + self.inputs.zero_poi_vertical_m / target_distance_m
1571        } else {
1572            angle
1573        };
1574        self.inputs.muzzle_angle = angle;
1575        self.apply_windage_zero_bias(target_distance_m);
1576        Ok(angle)
1577    }
1578
1579    /// Apply just the windage-zero convergence bias (see
1580    /// [`BallisticInputs::windage_zero_bias_rad`]) to this solver's azimuth, for a zero at
1581    /// `target_distance_m`, without searching for or installing an elevation.
1582    ///
1583    /// Used by [`Self::calculate_and_set_zero_angle`] above as part of a full zero search, and
1584    /// by solve_v1's round-trip re-solve path (0.33.0 decision-support Task 2) on its own: when
1585    /// an explicit `muzzle_angle_rad` already carries the correct elevation (round-tripped from
1586    /// a previous `resolved_request`, which bakes any `zero_poi_vertical_m` bias into that
1587    /// angle already), the elevation search does not run, but the windage term is a SEPARATE
1588    /// quantity that depends only on `zero_distance_m` -- not on whether the elevation was
1589    /// searched for or supplied directly -- so it must still be applied here or an
1590    /// offset-mounted sight / deliberate horizontal zero bias would silently stop converging
1591    /// once a request round-trips.
1592    pub(crate) fn apply_windage_zero_bias(&mut self, target_distance_m: f64) {
1593        self.inputs.azimuth_angle += self.inputs.windage_zero_bias_rad(target_distance_m);
1594    }
1595
1596    fn find_zero_angle(
1597        &self,
1598        target_distance_m: f64,
1599        target_height_m: f64,
1600        frame: ZeroTargetFrame,
1601    ) -> Result<f64, BallisticsError> {
1602        // Binary search for the angle that hits the target. The bracket starts at [0, 0.2] rad
1603        // and widens downward for a target below where a level bore lands, or upward for one
1604        // beyond the initial top angle.
1605        let mut low_angle = 0.0;
1606        let mut high_angle = 0.2; // about 11 degrees
1607        let tolerance = 1e-7;
1608        let max_iterations = 60;
1609
1610        // MBA-194: validate the initial bracket before starting the binary search.
1611        let low_height = self.zero_trial_height_at(low_angle, target_distance_m, frame)?;
1612        let high_height = self.zero_trial_height_at(high_angle, target_distance_m, frame)?;
1613
1614        match (low_height, high_height) {
1615            (Some(low_height), Some(high_height)) => {
1616                let low_error = low_height - target_height_m;
1617                let high_error = high_height - target_height_m;
1618
1619                if low_error > 0.0 && high_error > 0.0 {
1620                    // Both angles overshoot: the target sits below where a level bore lands
1621                    // (a shooter above the target), so the bore must point below horizontal.
1622                    // The search used to stop at 0 rad and fail. Lower the bottom of the
1623                    // bracket in the same steps the undershoot branch raises the top, down to
1624                    // 45 degrees. A trial that ends short of the target distance (the ground
1625                    // stop) is below the target too, exactly as the bisection below treats it.
1626                    //
1627                    // A trial that flies into air that cannot exist aloft ends the search with
1628                    // that refusal: no zero exists in air that exists that way, and "the target
1629                    // is below the trajectory" would name the wrong cause.
1630                    let mut expanded = false;
1631                    for multiplier in [1.0, 2.0, 3.0, 4.0] {
1632                        let new_low = (-0.2_f64 * multiplier).max(-0.785);
1633                        match self.zero_trial_height_at(new_low, target_distance_m, frame) {
1634                            Ok(Some(height)) if height - target_height_m > 0.0 => {}
1635                            Ok(_) => {
1636                                high_angle = low_angle;
1637                                low_angle = new_low;
1638                                expanded = true;
1639                                break;
1640                            }
1641                            Err(error) if error.atmosphere_error().is_some() => return Err(error),
1642                            Err(_) => {}
1643                        }
1644                    }
1645                    if !expanded {
1646                        return Err("Cannot find zero angle: target is below the trajectory even at the steepest downward angle".into());
1647                    }
1648                } else if low_error < 0.0 && high_error < 0.0 {
1649                    // Both angles undershoot. Preserve the historical expansion up to 45 degrees.
1650                    // A steeper trial that climbs into air that cannot exist aloft ends the
1651                    // search with that refusal, not "beyond effective range".
1652                    let mut expanded = false;
1653                    for multiplier in [2.0, 3.0, 4.0] {
1654                        let new_high = (high_angle * multiplier).min(0.785);
1655                        match self.zero_trial_height_at(new_high, target_distance_m, frame) {
1656                            Ok(Some(height)) if height - target_height_m > 0.0 => {
1657                                high_angle = new_high;
1658                                expanded = true;
1659                                break;
1660                            }
1661                            Err(error) if error.atmosphere_error().is_some() => return Err(error),
1662                            _ => {}
1663                        }
1664                        if new_high >= 0.785 {
1665                            break;
1666                        }
1667                    }
1668                    if !expanded {
1669                        return Err("Cannot find zero angle: target beyond effective range even at maximum angle".into());
1670                    }
1671                }
1672            }
1673            (None, Some(_)) => {
1674                // The low angle does not reach the target while the high angle does; the search
1675                // will raise the low end until it reaches a valid trajectory.
1676            }
1677            (Some(_), None) => {
1678                return Err(
1679                    "Cannot find zero angle: high angle trajectory doesn't reach target distance"
1680                        .into(),
1681                );
1682            }
1683            (None, None) => {
1684                return Err(
1685                    "Cannot find zero angle: trajectory cannot reach target distance at any angle"
1686                        .into(),
1687                );
1688            }
1689        }
1690
1691        for _ in 0..max_iterations {
1692            let mid_angle = (low_angle + high_angle) / 2.0;
1693            match self.zero_trial_height_at(mid_angle, target_distance_m, frame)? {
1694                Some(height) => {
1695                    let error = height - target_height_m;
1696                    // MBA-193: height accuracy is the primary convergence criterion. At 0.1 mm,
1697                    // short-range zero-day atmosphere differences remain observable.
1698                    if error.abs() < 0.0001 {
1699                        return Ok(mid_angle);
1700                    }
1701
1702                    // Only use angle tolerance after precision is exhausted and the remaining
1703                    // height error is still practically acceptable.
1704                    if (high_angle - low_angle).abs() < tolerance {
1705                        if error.abs() < 0.01 {
1706                            return Ok(mid_angle);
1707                        }
1708                        return Err("Zero angle did not converge: residual height error too large (target not reachable / not bracketed)".into());
1709                    }
1710
1711                    if error > 0.0 {
1712                        high_angle = mid_angle;
1713                    } else {
1714                        low_angle = mid_angle;
1715                    }
1716                }
1717                None => {
1718                    low_angle = mid_angle;
1719                    if (high_angle - low_angle).abs() < tolerance {
1720                        return Err("Trajectory cannot reach target distance - angle converged without valid solution".into());
1721                    }
1722                }
1723            }
1724        }
1725
1726        Err("Failed to find zero angle".into())
1727    }
1728
1729    /// Solve one zero-angle trial without losing any solver configuration. Only the trial clone's
1730    /// launch angle, level-rifle convention, and integration range differ from the final solve.
1731    fn zero_trial_height_at(
1732        &self,
1733        angle_rad: f64,
1734        target_distance_m: f64,
1735        frame: ZeroTargetFrame,
1736    ) -> Result<Option<f64>, BallisticsError> {
1737        let mut trial = self.clone();
1738        trial.inputs.muzzle_angle = angle_rad;
1739        // MBA-959: zero on the bare bore so aerodynamic jump remains an additive fire-time POI
1740        // shift rather than being silently absorbed by the zero search.
1741        trial.inputs.enable_aerodynamic_jump = false;
1742        // MBA-1286: a zero is a property of a level rifle's sight geometry. Cant is applied only
1743        // to the subsequent shot.
1744        trial.inputs.cant_angle = 0.0;
1745        // MBA-1412: in the SightLine contract the incline is likewise a shot-time condition,
1746        // not sight geometry. MBA-1302 left it in the trial while shot_frame_altitude lifted
1747        // heights into the gravity frame, adding d*sin(shooting_angle) (~9 m at 5.71 deg /
1748        // 100 yd) against a sight-frame target height, so no inclined legacy caller could
1749        // bracket. Zero level; shoot inclined. solve-json v1's WorldVertical contract keeps
1750        // the MBA-1302 projection (its callers supply world-frame heights).
1751        if frame == ZeroTargetFrame::SightLine {
1752            trial.inputs.shooting_angle = 0.0;
1753        }
1754        trial.set_max_range(target_distance_m * 2.0);
1755        let result = trial.solve()?;
1756
1757        for (index, point) in result.points.iter().enumerate() {
1758            if point.position.x >= target_distance_m {
1759                let shot_y_m = if index == 0 {
1760                    point.position.y
1761                } else {
1762                    let previous = &result.points[index - 1];
1763                    let span = point.position.x - previous.position.x;
1764                    let fraction = (target_distance_m - previous.position.x) / span;
1765                    previous.position.y + fraction * (point.position.y - previous.position.y)
1766                };
1767                return Ok(Some(crate::atmosphere::shot_frame_altitude(
1768                    0.0,
1769                    target_distance_m,
1770                    shot_y_m,
1771                    trial.inputs.shooting_angle,
1772                )));
1773            }
1774        }
1775        Ok(None)
1776    }
1777
1778    /// Inverse of [`Self::find_zero_angle`] (MBA-1402), corrected by the Tier 2 whole-branch
1779    /// review (C2): given a FIXED bore angle rather than searching for one, run that
1780    /// trajectory and locate the downrange distance(s) where it crosses `target_height_m` —
1781    /// the zero RANGE(S) a stored/portable bore angle implies under THESE conditions. Hornady
1782    /// and Kestrel 4DOF treat the zero angle as the portable quantity (captured once, then
1783    /// reusable independent of the day it was solved); this is what makes that value usable
1784    /// again.
1785    ///
1786    /// A rifle whose sight sits above the bore generally crosses a level line of sight TWICE
1787    /// on a rising shot: once ascending, close to the muzzle (the "near zero"), and once
1788    /// descending past the apex (the "far zero"). Both are equally real zero ranges for the
1789    /// SAME bore angle — this is the classic 25/300-yard battle-zero relationship: a rifle
1790    /// zeroed at 25 yd (the near crossing of its bore angle) is, for the same angle, ALSO
1791    /// zeroed again around 300 yd (the far crossing). [`Self::find_zero_angle`]'s own choice
1792    /// of root depends on which target distance it was asked to solve for, so this is not a
1793    /// single-valued inverse of that function — it is this function's job to report both
1794    /// roots it can find rather than silently pick one and call it "the" zero range.
1795    ///
1796    /// Returns [`ZeroCrossings`] with the near (first ascending, error negative → positive)
1797    /// and far (descending, error positive → negative) crossings independently, either of
1798    /// which may be absent if the solved envelope doesn't reach it (e.g. `--max-range` too
1799    /// short to reach the far crossing, or an angle so shallow / a target height so high that
1800    /// the near crossing never happens). Errors only when NEITHER crossing is found. Each
1801    /// crossing distance is linearly interpolated between its two bracketing sample points,
1802    /// mirroring `zero_trial_height_at`'s own height-at-a-known-distance interpolation in the
1803    /// other direction.
1804    fn find_zero_range(
1805        &self,
1806        angle_rad: f64,
1807        target_height_m: f64,
1808        frame: ZeroTargetFrame,
1809    ) -> Result<ZeroCrossings, BallisticsError> {
1810        let mut trial = self.clone();
1811        trial.inputs.muzzle_angle = angle_rad;
1812        // Mirrors zero_trial_height_at's trial setup exactly (MBA-959 / MBA-1286 / MBA-1412),
1813        // so both directions apply the same conventions.
1814        trial.inputs.enable_aerodynamic_jump = false;
1815        trial.inputs.cant_angle = 0.0;
1816        if frame == ZeroTargetFrame::SightLine {
1817            trial.inputs.shooting_angle = 0.0;
1818        }
1819        let result = trial.solve()?;
1820
1821        // The height-above-target-height error is, for a normal flat-fire trajectory,
1822        // unimodal: it starts below the line of sight (bore below sight), rises through it
1823        // ONCE (ascending -- the near zero), continues to the apex, then falls back through
1824        // it ONCE more (descending -- the far zero) before diverging away for good. So at
1825        // most one ascending and one descending crossing exist; classify each sign change by
1826        // direction rather than by position (first/last) so a near-only trajectory (solved
1827        // range too short to reach the far crossing) is never mislabeled as "far".
1828        let mut near_crossing: Option<f64> = None;
1829        let mut far_crossing: Option<f64> = None;
1830        let mut previous: Option<(f64, f64)> = None; // (downrange_m, height_error_m)
1831        for point in &result.points {
1832            let height = crate::atmosphere::shot_frame_altitude(
1833                0.0,
1834                point.position.x,
1835                point.position.y,
1836                trial.inputs.shooting_angle,
1837            );
1838            let error = height - target_height_m;
1839            if let Some((prev_x, prev_error)) = previous {
1840                if prev_error == 0.0 {
1841                    // An exact touch is itself a crossing; assign it to whichever slot is
1842                    // still open (near first, since it can only occur before far).
1843                    if near_crossing.is_none() {
1844                        near_crossing = Some(prev_x);
1845                    } else {
1846                        far_crossing = Some(prev_x);
1847                    }
1848                }
1849                if prev_error * error < 0.0 {
1850                    let fraction = prev_error / (prev_error - error);
1851                    let crossing = prev_x + fraction * (point.position.x - prev_x);
1852                    if prev_error < 0.0 && error > 0.0 {
1853                        // Ascending: the near zero. Keep only the first one found.
1854                        if near_crossing.is_none() {
1855                            near_crossing = Some(crossing);
1856                        }
1857                    } else {
1858                        // Descending: the far zero.
1859                        far_crossing = Some(crossing);
1860                    }
1861                }
1862            }
1863            previous = Some((point.position.x, error));
1864        }
1865        // The loop above only resolves a point once a later point makes it `previous`; catch
1866        // the trajectory's very last sampled point landing exactly on the line too.
1867        if let Some((last_x, last_error)) = previous {
1868            if last_error == 0.0 {
1869                if near_crossing.is_none() {
1870                    near_crossing = Some(last_x);
1871                } else {
1872                    far_crossing = Some(last_x);
1873                }
1874            }
1875        }
1876
1877        if near_crossing.is_none() && far_crossing.is_none() {
1878            return Err(BallisticsError::from(
1879                "Cannot find zero range: this angle never crosses the target height within the \
1880                 solved range (angle too shallow to reach it, or both crossings lie beyond \
1881                 the solver's max range)."
1882                    .to_string(),
1883            ));
1884        }
1885
1886        Ok(ZeroCrossings {
1887            near_m: near_crossing,
1888            far_m: far_crossing,
1889        })
1890    }
1891
1892    /// Equivalent horizontal range for an inclined shot (MBA-1395): the flat-fire range
1893    /// whose ANGULAR elevation correction — relative to the SAME dialed zero — equals the
1894    /// inclined solution's angular correction at `target_range_m`. This is the
1895    /// "shoot-to" range SIG BDX (AMR), Leica (EHR), and Gunwerks BR2 report so users of
1896    /// fixed BDC turrets/reticles can dial as if the shot were flat, computed by an
1897    /// inverse lookup over one flat re-solve (McDonald's Sierra inclined-fire treatment /
1898    /// Litz) rather than the rifleman's-rule cosine approximation, which matches LINEAR
1899    /// drop and accumulates error at long range.
1900    ///
1901    /// The solver's current state IS the inclined solution: `muzzle_angle` carries the
1902    /// solved zero and `shooting_angle` the look angle. The flat reference clones the
1903    /// solver and zeroes only `shooting_angle` (the WASM auto-zero flat-clone precedent),
1904    /// keeping the zero, wind, atmosphere, and integration configuration identical, so
1905    /// both angular corrections are measured against the same zero.
1906    ///
1907    /// Returns `None` where the inverse is ill-defined instead of guessing:
1908    /// - `target_range_m <= zero_distance_m` (inside the zero, no BDC correction exists);
1909    /// - the inclined correction at the target is not positive (bullet at/above the LOS);
1910    /// - either solve fails, or the flat solve cannot bracket the correction.
1911    ///
1912    /// Past the zero range the flat correction is monotone in range, so a plain bisection
1913    /// over the flat solve's interpolated corrections converges; the answer is refined to
1914    /// centimeter level, far below any display precision.
1915    pub fn equivalent_horizontal_range(
1916        &self,
1917        target_range_m: f64,
1918        zero_distance_m: f64,
1919    ) -> Option<f64> {
1920        if !target_range_m.is_finite() || !zero_distance_m.is_finite() {
1921            return None;
1922        }
1923        if target_range_m <= zero_distance_m || target_range_m <= 0.0 {
1924            return None;
1925        }
1926
1927        // Height of the bullet path at a downrange distance, linearly interpolated
1928        // between integration points (mirrors zero_trial_height_at's interpolation).
1929        // In the shot frame the LOS is the x-axis, so drop below the LOS is
1930        // `los_height - y` for the inclined and flat solves alike.
1931        fn path_y_at(points: &[TrajectoryPoint], distance_m: f64) -> Option<f64> {
1932            match bracket_param(points.len(), |i| points[i].position.x, distance_m) {
1933                // Below the first point: clamp to it (mirrors zero_trial_height_at's
1934                // interpolation, which the doc comment above promises). Fewer than two points
1935                // is not a case a real solved trajectory reaches; treat it like Above (no
1936                // extrapolation) rather than guessing.
1937                Bracket::Below => Some(points[0].position.y),
1938                Bracket::Above | Bracket::Degenerate => None,
1939                Bracket::Inside { lo, t } => {
1940                    let hi = lo + 1;
1941                    Some(
1942                        points[lo].position.y + t * (points[hi].position.y - points[lo].position.y),
1943                    )
1944                }
1945            }
1946        }
1947
1948        // Inclined solution's angular correction at the target (radians, small-angle:
1949        // drop below the LOS divided by range). Sampling is display-side only — turn it
1950        // off in both internal solves.
1951        let mut inclined = self.clone();
1952        inclined.inputs.enable_trajectory_sampling = false;
1953        let inclined_result = inclined.solve().ok()?;
1954        let los_height = inclined_result.line_of_sight_height_m;
1955        let inclined_drop = los_height - path_y_at(&inclined_result.points, target_range_m)?;
1956        let correction = inclined_drop / target_range_m;
1957        if correction <= 0.0 {
1958            return None;
1959        }
1960
1961        // One flat re-solve against the same zero.
1962        let mut flat = self.clone();
1963        flat.inputs.enable_trajectory_sampling = false;
1964        flat.inputs.shooting_angle = 0.0;
1965        let flat_result = flat.solve().ok()?;
1966        let flat_correction_at = |range_m: f64| -> Option<f64> {
1967            Some((los_height - path_y_at(&flat_result.points, range_m)?) / range_m)
1968        };
1969
1970        // Bracket, then bisect. Gravity's along-LOS component only shrinks under a look
1971        // angle, so the flat correction at the true range bounds the inclined one from
1972        // above and the equivalent range lies in (zero_distance, target_range]. The flat
1973        // clone can strike the ground SHORT of the inclined terminal (an uphill shot
1974        // stays airborne longer), so the upper bracket is additionally capped at the
1975        // flat solve's own terminal distance — the shoot-to range is shorter than the
1976        // true range, so the cap does not exclude the root.
1977        let flat_terminal_m = flat_result.points.last().map(|p| p.position.x)?;
1978        let mut low = zero_distance_m.max(1.0);
1979        let mut high = target_range_m.min(flat_terminal_m);
1980        if high <= low {
1981            return None;
1982        }
1983        if flat_correction_at(low)? - correction > 0.0 {
1984            return None; // no bracket below
1985        }
1986        if flat_correction_at(high)? - correction < 0.0 {
1987            return None; // no bracket above (correction not reachable flat)
1988        }
1989        for _ in 0..60 {
1990            let mid = 0.5 * (low + high);
1991            let error = flat_correction_at(mid)? - correction;
1992            if error.abs() == 0.0 {
1993                return Some(mid);
1994            }
1995            if error < 0.0 {
1996                low = mid;
1997            } else {
1998                high = mid;
1999            }
2000            if high - low < 0.01 {
2001                break;
2002            }
2003        }
2004        Some(0.5 * (low + high))
2005    }
2006
2007    /// Reject malformed state before it reaches an integration loop.
2008    ///
2009    /// `new` resolves powder-temperature velocity overrides and refreshes the imperial mirror
2010    /// fields, so validation belongs here: it sees the effective muzzle velocity, covers values
2011    /// changed through solver setters, and applies uniformly to Euler, RK4, and RK45.
2012    fn validate_for_solve(&self) -> Result<(), BallisticsError> {
2013        let require_finite = |name: &str, value: f64| {
2014            if value.is_finite() {
2015                Ok(())
2016            } else {
2017                Err(BallisticsError::from(format!("{name} must be finite")))
2018            }
2019        };
2020        let require_positive = |name: &str, value: f64| {
2021            if value.is_finite() && value > 0.0 {
2022                Ok(())
2023            } else {
2024                Err(BallisticsError::from(format!(
2025                    "{name} must be finite and greater than zero"
2026                )))
2027            }
2028        };
2029
2030        // These four quantities are required by every point-mass solve. In particular, validate
2031        // muzzle_velocity after `new` has applied a measured curve or linear powder correction.
2032        // A custom drag table flown as the projectile's own curve supplies the actual Cd and
2033        // divides by sectional density, so bc_value is physically ignored there (see
2034        // custom_drag_denominator). A table flown as a reference curve (custom_drag_reference)
2035        // divides by the BC exactly as a G-model does, so bc_value is required in every case but
2036        // the own-curve one; mass + diameter are always required (they drive the SD denominator
2037        // when an own-curve table is set).
2038        if self.inputs.custom_drag_table.is_none() || self.inputs.custom_drag_reference {
2039            require_positive("bc_value", self.inputs.bc_value)?;
2040        }
2041        require_positive("bullet_mass", self.inputs.bullet_mass)?;
2042        require_positive("bullet_diameter", self.inputs.bullet_diameter)?;
2043        require_positive("muzzle_velocity", self.inputs.muzzle_velocity)?;
2044        // MBA-1356: cd_scale multiplies the custom-deck Cd; a non-finite or non-positive value
2045        // would zero/invert drag or poison integration with NaN. Required unconditionally (not
2046        // gated on custom_drag_table) since the default (1.0) is always valid and a caller could
2047        // set an invalid scale without ever setting a table. The [0.5, 2.0] "unusual" range is a
2048        // CLI-level warning (Task 2), not a hard engine rule.
2049        require_positive("cd_scale", self.inputs.cd_scale)?;
2050
2051        require_finite("muzzle_angle", self.inputs.muzzle_angle)?;
2052        require_finite("azimuth_angle", self.inputs.azimuth_angle)?;
2053        require_finite("shooting_angle", self.inputs.shooting_angle)?;
2054        require_finite("cant_angle", self.inputs.cant_angle)?;
2055        require_finite("muzzle_height", self.inputs.muzzle_height)?;
2056
2057        // MBA-1359: a deliberate zero POI offset is a small linear offset at the zero range
2058        // (fractions of an inch to a few inches). |1 m| is far beyond any plausible
2059        // deliberate offset and almost certainly a unit error (inches/cm passed as meters).
2060        for (name, value) in [
2061            ("zero_poi_vertical_m", self.inputs.zero_poi_vertical_m),
2062            ("zero_poi_horizontal_m", self.inputs.zero_poi_horizontal_m),
2063        ] {
2064            require_finite(name, value)?;
2065            if value.abs() >= 1.0 {
2066                return Err(BallisticsError::from(format!(
2067                    "{name} must be smaller than 1.0 m in magnitude (it is a linear POI \
2068                     offset at the zero range, in meters)"
2069                )));
2070            }
2071        }
2072
2073        // MBA-1396: a lateral sight-mount offset is physically bounded by rail/mount
2074        // geometry (an inch or two). |0.5 m| is almost certainly a unit error
2075        // (inches/mm passed as meters).
2076        require_finite("sight_offset_lateral_m", self.inputs.sight_offset_lateral_m)?;
2077        if self.inputs.sight_offset_lateral_m.abs() >= 0.5 {
2078            return Err(BallisticsError::from(
2079                "sight_offset_lateral_m must be smaller than 0.5 m in magnitude (it is \
2080                 the lateral sight-to-bore mount offset, in meters)",
2081            ));
2082        }
2083
2084        // Negative infinity is the documented ignore-ground sentinel. NaN and positive infinity
2085        // make the loop condition meaningless and are rejected.
2086        if !(self.inputs.ground_threshold.is_finite()
2087            || self.inputs.ground_threshold == f64::NEG_INFINITY)
2088        {
2089            return Err(BallisticsError::from(
2090                "ground_threshold must be finite or negative infinity",
2091            ));
2092        }
2093
2094        match &self.wind_sock {
2095            Some(wind_sock) => wind_sock
2096                .validate_segments()
2097                .map_err(BallisticsError::from)?,
2098            None => {
2099                require_finite("wind.speed", self.wind.speed)?;
2100                require_finite("wind.direction", self.wind.direction)?;
2101                require_finite("wind.vertical_speed", self.wind.vertical_speed)?;
2102            }
2103        }
2104
2105        require_finite("atmosphere.temperature", self.atmosphere.temperature)?;
2106        require_finite("atmosphere.pressure", self.atmosphere.pressure)?;
2107        require_finite("atmosphere.altitude", self.atmosphere.altitude)?;
2108        // One validator and one impossible-air rule. The station RH
2109        // goes through `RelativeHumidity` (a percent in [0, 100], a sensor reading within 5
2110        // points of it flown as the end it reads as, anything farther out refused and never
2111        // clamped),
2112        // the resolved station must be air that exists (`StationAir::new`, the predicate
2113        // `atmosphere.density_altitude` applies), and so must every downrange zone.
2114        self.station_air()?;
2115        if let Some(sock) = &self.atmo_sock {
2116            sock.validate()
2117                .map_err(|error| BallisticsError::from(error.to_string()))?;
2118        }
2119
2120        require_positive("max_range", self.max_range)?;
2121        // Adaptive RK45 owns its step size; the caller-provided fixed step is used only by Euler
2122        // and fixed RK4.
2123        if !self.inputs.use_rk4 || !self.inputs.use_adaptive_rk45 {
2124            require_positive("time_step", self.time_step)?;
2125        }
2126
2127        if self.inputs.enable_trajectory_sampling {
2128            require_finite("sight_height", self.inputs.sight_height)?;
2129            require_positive("sample_interval", self.inputs.sample_interval)?;
2130            projected_sample_count(self.max_range, self.inputs.sample_interval)?;
2131        }
2132
2133        // MBA-1403: the target-plane drops reference divides sampled drop by
2134        // cos(shooting_angle); at or beyond 90 degrees the transform is undefined.
2135        // Gated on the non-default mode only, so LOS-mode validation is unchanged.
2136        if self.inputs.drops_reference == DropsReference::Target {
2137            require_finite("target_height", self.inputs.target_height)?;
2138            if self.inputs.shooting_angle.cos() <= 1e-9 {
2139                return Err(BallisticsError::from(
2140                    "drops reference 'target' is undefined for shooting angles at or beyond 90 degrees",
2141                ));
2142            }
2143        }
2144
2145        if self.inputs.enable_coriolis {
2146            require_finite("shot_azimuth", self.inputs.shot_azimuth)?;
2147            if let Some(latitude) = self.inputs.latitude {
2148                require_finite("latitude", latitude)?;
2149            }
2150        }
2151
2152        Ok(())
2153    }
2154
2155    /// Public solve results must never report success with NaN or infinity, nor with values a
2156    /// physical trajectory cannot produce: a negative terminal downrange distance, time of
2157    /// flight, speed, or energy (MBA-1293 — a stiff-input integration explosion reported
2158    /// `Ok(max_range: -50.59)`). The input gate catches malformed scalar state; this
2159    /// postcondition also covers overflow and malformed optional tables/segments without
2160    /// imposing arbitrary upper bounds on otherwise finite inputs.
2161    fn validate_result_sanity(&self, result: &TrajectoryResult) -> Result<(), BallisticsError> {
2162        let require_finite = |name: &str, value: f64| {
2163            if value.is_finite() {
2164                Ok(())
2165            } else {
2166                Err(BallisticsError::from(format!(
2167                    "trajectory result contains non-finite {name}"
2168                )))
2169            }
2170        };
2171        let require_non_negative = |name: &str, value: f64| {
2172            if value >= 0.0 {
2173                Ok(())
2174            } else {
2175                Err(BallisticsError::from(format!(
2176                    "trajectory result contains non-physical negative {name} ({value})"
2177                )))
2178            }
2179        };
2180        let require_indexed_finite = |collection: &str, index: usize, field: &str, value: f64| {
2181            if value.is_finite() {
2182                Ok(())
2183            } else {
2184                Err(BallisticsError::from(format!(
2185                    "trajectory result contains non-finite {collection}[{index}].{field}"
2186                )))
2187            }
2188        };
2189        let require_indexed_non_negative = |collection: &str,
2190                                            index: usize,
2191                                            field: &str,
2192                                            value: f64| {
2193            if value >= 0.0 {
2194                Ok(())
2195            } else {
2196                Err(BallisticsError::from(format!(
2197                        "trajectory result contains non-physical negative {collection}[{index}].{field} ({value})"
2198                    )))
2199            }
2200        };
2201
2202        require_finite("max_range", result.max_range)?;
2203        require_finite("max_height", result.max_height)?;
2204        require_finite("time_of_flight", result.time_of_flight)?;
2205        require_finite("impact_velocity", result.impact_velocity)?;
2206        require_finite("impact_energy", result.impact_energy)?;
2207        require_finite("projectile_mass_kg", result.projectile_mass_kg)?;
2208        require_finite("line_of_sight_height_m", result.line_of_sight_height_m)?;
2209        require_finite(
2210            "station_speed_of_sound_mps",
2211            result.station_speed_of_sound_mps,
2212        )?;
2213
2214        // The solve starts at x = 0 and only ever fires downrange, so these scalars are
2215        // non-negative for every physically meaningful trajectory. (max_height is exempt:
2216        // points can legitimately sit below y = 0 with an elevated muzzle.)
2217        require_non_negative("max_range", result.max_range)?;
2218        require_non_negative("time_of_flight", result.time_of_flight)?;
2219        require_non_negative("impact_velocity", result.impact_velocity)?;
2220        require_non_negative("impact_energy", result.impact_energy)?;
2221        require_non_negative("projectile_mass_kg", result.projectile_mass_kg)?;
2222        require_non_negative(
2223            "station_speed_of_sound_mps",
2224            result.station_speed_of_sound_mps,
2225        )?;
2226
2227        for (index, point) in result.points.iter().enumerate() {
2228            require_indexed_finite("points", index, "time", point.time)?;
2229            require_indexed_finite("points", index, "position.x", point.position.x)?;
2230            require_indexed_finite("points", index, "position.y", point.position.y)?;
2231            require_indexed_finite("points", index, "position.z", point.position.z)?;
2232            require_indexed_finite(
2233                "points",
2234                index,
2235                "velocity_magnitude",
2236                point.velocity_magnitude,
2237            )?;
2238            require_indexed_finite("points", index, "kinetic_energy", point.kinetic_energy)?;
2239            require_indexed_non_negative("points", index, "time", point.time)?;
2240            require_indexed_non_negative(
2241                "points",
2242                index,
2243                "velocity_magnitude",
2244                point.velocity_magnitude,
2245            )?;
2246            require_indexed_non_negative("points", index, "kinetic_energy", point.kinetic_energy)?;
2247        }
2248
2249        if let Some(samples) = &result.sampled_points {
2250            for (index, sample) in samples.iter().enumerate() {
2251                require_indexed_finite("sampled_points", index, "distance_m", sample.distance_m)?;
2252                require_indexed_finite("sampled_points", index, "drop_m", sample.drop_m)?;
2253                require_indexed_finite(
2254                    "sampled_points",
2255                    index,
2256                    "wind_drift_m",
2257                    sample.wind_drift_m,
2258                )?;
2259                require_indexed_finite(
2260                    "sampled_points",
2261                    index,
2262                    "velocity_mps",
2263                    sample.velocity_mps,
2264                )?;
2265                require_indexed_finite("sampled_points", index, "energy_j", sample.energy_j)?;
2266                require_indexed_finite("sampled_points", index, "time_s", sample.time_s)?;
2267            }
2268        }
2269
2270        for (name, value) in [
2271            ("min_pitch_damping", result.min_pitch_damping),
2272            ("transonic_mach", result.transonic_mach),
2273            ("max_yaw_angle", result.max_yaw_angle),
2274            ("max_precession_angle", result.max_precession_angle),
2275        ] {
2276            if let Some(value) = value {
2277                require_finite(name, value)?;
2278            }
2279        }
2280
2281        if let Some(state) = result.angular_state {
2282            for (name, value) in [
2283                ("angular_state.pitch_angle", state.pitch_angle),
2284                ("angular_state.yaw_angle", state.yaw_angle),
2285                ("angular_state.pitch_rate", state.pitch_rate),
2286                ("angular_state.yaw_rate", state.yaw_rate),
2287                ("angular_state.precession_angle", state.precession_angle),
2288                ("angular_state.nutation_phase", state.nutation_phase),
2289            ] {
2290                require_finite(name, value)?;
2291            }
2292        }
2293
2294        if let Some(jump) = result.aerodynamic_jump {
2295            for (name, value) in [
2296                ("aerodynamic_jump.vertical_jump_moa", jump.vertical_jump_moa),
2297                (
2298                    "aerodynamic_jump.horizontal_jump_moa",
2299                    jump.horizontal_jump_moa,
2300                ),
2301                ("aerodynamic_jump.jump_angle_rad", jump.jump_angle_rad),
2302                (
2303                    "aerodynamic_jump.magnus_component_moa",
2304                    jump.magnus_component_moa,
2305                ),
2306                ("aerodynamic_jump.yaw_component_moa", jump.yaw_component_moa),
2307                (
2308                    "aerodynamic_jump.stabilization_factor",
2309                    jump.stabilization_factor,
2310                ),
2311            ] {
2312                require_finite(name, value)?;
2313            }
2314        }
2315
2316        Ok(())
2317    }
2318
2319    /// Integration methods store the pre-step state in `points`. Validate each newly accepted
2320    /// state as well, otherwise a poisoned final step could terminate the loop and leave only the
2321    /// previous finite point in an apparently successful result.
2322    ///
2323    /// Beyond finiteness, an accepted state must respect the physical speed budget: drag is
2324    /// dissipative (it drives the projectile toward the wind frame, never past it), Magnus and
2325    /// Coriolis act perpendicular to the velocity and do no work, and gravity adds at most g*t.
2326    /// Ground-frame speed therefore cannot legitimately exceed muzzle speed + strongest wind +
2327    /// g*t. Exceeding that budget means the integrator itself diverged — for stiff inputs the
2328    /// minimum-step RK45 acceptance can multiply speed by orders of magnitude in one step
2329    /// (MBA-1293: 13x and a sign reversal in a single 1 microsecond step) — so the solve must
2330    /// fail rather than report the garbage as `Ok`.
2331    fn validate_integration_state(
2332        &self,
2333        position: &Vector3<f64>,
2334        velocity: &Vector3<f64>,
2335        time: f64,
2336    ) -> Result<(), BallisticsError> {
2337        if !(position.iter().all(|value| value.is_finite())
2338            && velocity.iter().all(|value| value.is_finite())
2339            && time.is_finite())
2340        {
2341            return Err(BallisticsError::from(
2342                "trajectory integration produced a non-finite state (often from physically \
2343                 extreme inputs — e.g. an absurd bore/muzzle height placing the launch far \
2344                 from sea level, or a degenerate atmosphere; check those inputs, or set \
2345                 --altitude explicitly)",
2346            ));
2347        }
2348
2349        let speed = velocity.magnitude();
2350        let budget = self.speed_budget(time);
2351        if speed > budget {
2352            return Err(BallisticsError::from(format!(
2353                "trajectory integration diverged: speed {speed:.3e} m/s at t={time:.6}s exceeds \
2354                 the physical budget of {budget:.3e} m/s"
2355            )));
2356        }
2357        Ok(())
2358    }
2359
2360    /// The refusal of a step that failed to a non-finite state because it flew into air that
2361    /// cannot exist: from the station's (or the covering zone's) temperature the lapse reaches
2362    /// absolute zero within the step's reach of `step_start`, where there is no air at all
2363    /// ([`crate::atmosphere::air_aloft_refusal`]). Any other failure is `error`, unchanged.
2364    ///
2365    /// The step's reach is `step_s` at the speed budget ([`Self::speed_budget`] at `end_time`),
2366    /// at least twice any speed the flight can have, so it covers every stage the step
2367    /// evaluated. Called only once a step has failed: a flight that stays below that height flies
2368    /// exactly as it did.
2369    #[allow(clippy::too_many_arguments)]
2370    fn refusal_of_failed_step(
2371        &self,
2372        error: BallisticsError,
2373        station: &StationAir,
2374        step_start: &Vector3<f64>,
2375        position: &Vector3<f64>,
2376        velocity: &Vector3<f64>,
2377        step_s: f64,
2378        end_time: f64,
2379    ) -> BallisticsError {
2380        if position
2381            .iter()
2382            .chain(velocity.iter())
2383            .all(|value| value.is_finite())
2384        {
2385            return error;
2386        }
2387        let altitude_m = crate::atmosphere::shot_frame_altitude(
2388            self.atmosphere.altitude,
2389            step_start.x,
2390            step_start.y,
2391            self.inputs.shooting_angle,
2392        );
2393        crate::atmosphere::air_aloft_refusal(
2394            &KernelAtmosphere::Station(*station),
2395            self.atmo_sock.as_ref(),
2396            step_start.x,
2397            altitude_m,
2398            step_s * self.speed_budget(end_time),
2399        )
2400        .map_or(error, BallisticsError::from)
2401    }
2402
2403    /// Ceiling on ground-frame speed a physical trajectory can reach by time `t` (see
2404    /// [`Self::validate_integration_state`]). The factor-2 slack absorbs boundary-layer
2405    /// wind-shear amplification and integrator transients; genuine divergence clears the
2406    /// budget by orders of magnitude.
2407    fn speed_budget(&self, time: f64) -> f64 {
2408        let scalar_wind = self.wind.speed.abs() + self.wind.vertical_speed.abs();
2409        let wind_bound = match &self.wind_sock {
2410            Some(sock) => scalar_wind.max(sock.max_speed_mps()),
2411            None => scalar_wind,
2412        };
2413        2.0 * (self.inputs.muzzle_velocity + wind_bound + 10.0) + self.gravity.magnitude() * time
2414    }
2415
2416    /// Store one public trajectory point, collapsing a downrange stall, without exceeding the
2417    /// per-solve resource budget. `collapsed_steps` is the solve's own count of earlier calls that
2418    /// replaced the previous point instead of storing a new one.
2419    fn push_trajectory_point(
2420        &self,
2421        points: &mut Vec<TrajectoryPoint>,
2422        point: TrajectoryPoint,
2423        collapsed_steps: &mut usize,
2424    ) -> Result<(), BallisticsError> {
2425        // The budget counts calls, not stored points. Every earlier call either stored a point or
2426        // collapsed one, so points.len() + collapsed_steps is the number of earlier calls, which
2427        // is what points.len() was when every call stored a point. The limit therefore fires at
2428        // the same step, with the same message, whether or not the flight stalled (MBA-1599).
2429        if points.len() + *collapsed_steps >= self.max_trajectory_points {
2430            return Err(BallisticsError::from(format!(
2431                "trajectory point limit of {} exceeded",
2432                self.max_trajectory_points
2433            )));
2434        }
2435        // MBA-1599: the public trajectory is indexed by downrange distance, so stored x must
2436        // strictly increase. A drag-dominated flight (the bottom of the BC range, a slow
2437        // bc_segments band, or a long fall to a deep ground_threshold) can shed so much downrange
2438        // speed that a whole step moves x by less than half a ULP: x + vx*dt == x while y keeps
2439        // falling. Two states cannot both be kept at one representable range, so the newer state
2440        // wins, the same rule append_terminal_endpoint applies to the terminal point. The
2441        // collapsed step is still counted against max_trajectory_points above, so a stall that
2442        // outlasts the budget fails at the step where it always did; only the stored points
2443        // shrink. A strict DECREASE is deliberately still pushed: that is a reversal, which the
2444        // checked observation API reports.
2445        if let Some(last) = points.last_mut() {
2446            if point.position.x == last.position.x {
2447                *last = point;
2448                *collapsed_steps += 1;
2449                return Ok(());
2450            }
2451        }
2452        points.push(point);
2453        Ok(())
2454    }
2455
2456    /// Supply downrange-segmented wind. Each segment is `(speed_kmh, angle_deg,
2457    /// until_distance_m)`; the wind for a given downrange distance is the first
2458    /// segment whose `until_distance_m` exceeds it (a step function), and wind is
2459    /// zero beyond the last segment. An empty list clears segmented wind (reverts
2460    /// to the scalar `wind`). The angle convention matches `WindConditions`
2461    /// (0 = headwind, 90 = from the right).
2462    pub fn set_wind_segments(&mut self, segments: Vec<crate::wind::WindSegment>) {
2463        self.wind_sock = if segments.is_empty() {
2464            None
2465        } else {
2466            Some(crate::wind::WindSock::new(segments))
2467        };
2468    }
2469
2470    /// Supply downrange-segmented atmosphere (MBA-1137). Each segment is
2471    /// `(temp_c, pressure_hpa, humidity_percent, until_distance_m)`, defined at the shooter base
2472    /// altitude; the per-substep local-atmosphere recompute selects the active zone by downrange
2473    /// distance (first zone whose `until_distance_m` exceeds it; the last zone is held beyond the
2474    /// final threshold). The zone's base conditions, its humidity included, are composed with the
2475    /// vertical altitude lapse by [`crate::atmosphere::air_at`], so a steeply-arcing shot still
2476    /// sees the y-lapse on top of the zone base. An empty list clears segmented atmosphere
2477    /// (reverts to the resolved single-station conditions).
2478    pub fn set_atmo_segments(&mut self, segments: Vec<crate::atmosphere::AtmoSegment>) {
2479        self.atmo_sock = if segments.is_empty() {
2480            None
2481        } else {
2482            Some(crate::atmosphere::AtmoSock::new(segments))
2483        };
2484    }
2485
2486    /// Effective initial launch direction `(elevation, azimuth)` in radians, including
2487    /// the aerodynamic-jump muzzle perturbation when `enable_aerodynamic_jump` is set.
2488    ///
2489    /// Aerodynamic jump is the fixed angular departure imparted as the projectile
2490    /// transitions from the constrained bore to free flight; applying it as an initial
2491    /// launch-angle offset is the physically correct integration point. Returns the bare
2492    /// `(muzzle_angle, azimuth_angle)` when the flag is off, so a default solve is
2493    /// numerically identical to pre-feature behavior. (MBA-959)
2494    fn launch_angles_from(
2495        &self,
2496        aj: Option<&crate::aerodynamic_jump::AerodynamicJumpComponents>,
2497    ) -> (f64, f64) {
2498        let (mut elev, mut azim) = (self.inputs.muzzle_angle, self.inputs.azimuth_angle);
2499        // MBA-1286: cant rotates the sight-frame aim offsets about the line of sight.
2500        // Positive = clockwise from the shooter: the upward zero correction leaks right
2501        // (+z) and shrinks by cos(cant) -> POI right and low. Exactly-0.0 skips all float
2502        // ops so un-canted solves stay bit-identical. Aerodynamic jump is added AFTER the
2503        // rotation: it arises at bore exit from crosswind/spin in the ground frame, not
2504        // from the rifle's sight geometry.
2505        if self.inputs.cant_angle != 0.0 {
2506            let (sin_c, cos_c) = self.inputs.cant_angle.sin_cos();
2507            let (e0, a0) = (elev, azim);
2508            elev = e0 * cos_c - a0 * sin_c;
2509            azim = a0 * cos_c + e0 * sin_c;
2510        }
2511        match aj {
2512            Some(c) => {
2513                // vertical_/horizontal_jump_moa ARE the jump angles expressed in MOA.
2514                const MOA_PER_RAD: f64 = 3437.7467707849;
2515                (
2516                    elev + c.vertical_jump_moa / MOA_PER_RAD,
2517                    azim + c.horizontal_jump_moa / MOA_PER_RAD,
2518                )
2519            }
2520            None => (elev, azim),
2521        }
2522    }
2523
2524    /// Compute the aerodynamic-jump components for the current inputs, or `None` when the
2525    /// feature is disabled / inputs are degenerate.
2526    ///
2527    /// Uses Bryan Litz's crosswind aerodynamic-jump estimator
2528    /// (`Y = 0.01*Sg - 0.0024*L + 0.032` MOA/mph) fed by the engine's own Miller Sg.
2529    /// Aerodynamic jump is a vertical effect, so only the elevation is perturbed.
2530    /// The estimator is a regression best near Sg ~ 1.75 — see MBA-959.
2531    fn aerodynamic_jump_components(
2532        &self,
2533    ) -> Option<crate::aerodynamic_jump::AerodynamicJumpComponents> {
2534        if !self.inputs.enable_aerodynamic_jump {
2535            return None;
2536        }
2537        // Reject degenerate/non-finite inputs before they can reach the launch angle.
2538        // A bare `<= 0.0` test lets NaN through (NaN comparisons are always false), and a
2539        // NaN/Inf here would poison the muzzle angle and collapse the whole trajectory.
2540        let diameter_m = self.inputs.bullet_diameter;
2541        if !(self.inputs.twist_rate.is_finite()
2542            && self.inputs.twist_rate != 0.0
2543            && diameter_m.is_finite()
2544            && diameter_m > 0.0
2545            && self.inputs.bullet_length.is_finite()
2546            && self.inputs.bullet_length > 0.0
2547            && self.inputs.muzzle_velocity.is_finite())
2548        {
2549            return None;
2550        }
2551
2552        // Engine's own gyroscopic (Miller) stability factor — same Sg shown elsewhere.
2553        let (temp_c, pressure_hpa) = self.resolved_station_conditions();
2554        let sg = crate::stability::compute_stability_coefficient(
2555            &self.inputs,
2556            (self.atmosphere.altitude, temp_c, pressure_hpa, 0.0),
2557        );
2558        if !(sg.is_finite() && sg > 0.0) {
2559            return None;
2560        }
2561        let length_calibers = self.inputs.bullet_length / diameter_m;
2562
2563        // Crosswind-from-the-right (mph) for Litz's estimator. Wind direction uses the
2564        // wind-FROM convention (0 = headwind, +90deg = from the right), matching the
2565        // fast-integrate path (fast_trajectory::aerodynamic_jump_launch_offset_rad) and
2566        // the lateral windage sign, so a from-the-right wind on a right-twist barrel
2567        // jumps the impact UP and drifts it left.
2568        const MS_TO_MPH: f64 = 2.236_936_292_054_4;
2569        let crosswind_from_right_mps = if let Some(sock) = &self.wind_sock {
2570            -sock.vector_for_range_stateless(0.0)[2]
2571        } else {
2572            self.wind.speed * self.wind.direction.sin()
2573        };
2574        let crosswind_from_right_mph = crosswind_from_right_mps * MS_TO_MPH;
2575
2576        let vertical_jump_moa = crate::aerodynamic_jump::litz_crosswind_jump_moa(
2577            sg,
2578            length_calibers,
2579            crosswind_from_right_mph,
2580            self.inputs.is_twist_right,
2581        );
2582        if !vertical_jump_moa.is_finite() {
2583            return None;
2584        }
2585
2586        const MOA_PER_RAD: f64 = 3437.7467707849;
2587        Some(crate::aerodynamic_jump::AerodynamicJumpComponents {
2588            vertical_jump_moa,
2589            // Aerodynamic jump is a vertical effect; the Litz estimator has no horizontal term.
2590            horizontal_jump_moa: 0.0,
2591            jump_angle_rad: vertical_jump_moa.abs() / MOA_PER_RAD,
2592            magnus_component_moa: 0.0,
2593            yaw_component_moa: 0.0,
2594            stabilization_factor: (sg / 1.5).clamp(0.0, 1.0),
2595        })
2596    }
2597
2598    /// Station temperature (°C) and absolute pressure (hPa) after presence resolution.
2599    fn resolved_station_conditions(&self) -> (f64, f64) {
2600        // NEITHER is the old legacy-sentinel arm exactly, BOTH the old authoritative arm.
2601        self.atmosphere.resolved_station(self.station_presence)
2602    }
2603
2604    /// The station air this solve flies: built once per solve, it seeds every per-step
2605    /// [`crate::atmosphere::air_at_with_gravity`] lookup and is the reference for station Mach.
2606    ///
2607    /// Its density and sound speed are `calculate_atmosphere` at the resolved station, as they
2608    /// always were, through [`StationAir::new`]: so an RH within
2609    /// [`crate::HUMIDITY_SENSOR_TOLERANCE_PERCENT`] (5 points) of [0, 100] is a sensor reading
2610    /// that flies exactly as 100 or 0, an RH beyond that band (or not finite) is refused, never
2611    /// clamped, and so is air that cannot exist or a resolved station pressure at or below 0.
2612    /// `validate_for_solve` runs this before any integration. It is
2613    /// [`AtmosphericConditions::station_air`] at this solver's presence, and its refusal is
2614    /// stated in the `atmosphere.*` fields' words: air that cannot exist names the humidity
2615    /// with the RESOLVED station temperature (°C) and pressure (hPa) it is impossible in.
2616    fn station_air(&self) -> Result<StationAir, BallisticsError> {
2617        self.atmosphere
2618            .station_air(self.station_presence)
2619            .map_err(|_| {
2620                let refusal = self
2621                    .atmosphere
2622                    .air_refusal(
2623                        self.station_presence,
2624                        [
2625                            crate::atmosphere::AirField::named("atmosphere.humidity"),
2626                            crate::atmosphere::AirField::named("atmosphere.temperature"),
2627                            crate::atmosphere::AirField::named("atmosphere.pressure"),
2628                            crate::atmosphere::AirField::named("atmosphere.altitude"),
2629                        ],
2630                        self.atmosphere.humidity,
2631                        crate::atmosphere::AirUnits::METRIC,
2632                    )
2633                    .expect("the station refused this air");
2634                BallisticsError::from(refusal.message().to_string())
2635            })
2636    }
2637
2638    /// `(density, speed_of_sound, temp_c, pressure_hpa)` of [`Self::station_air`], the shape the
2639    /// tests were written against.
2640    #[cfg(test)]
2641    fn resolved_atmosphere(&self) -> (f64, f64, f64, f64) {
2642        let station = self.station_air().expect("test atmospheres are valid");
2643        (
2644            station.density_kg_m3(),
2645            station.speed_of_sound_mps(),
2646            station.temperature_c(),
2647            station.pressure_hpa(),
2648        )
2649    }
2650
2651    fn precession_nutation_params(
2652        &self,
2653        velocity_mps: f64,
2654        air_density_kg_m3: f64,
2655        speed_of_sound_mps: f64,
2656    ) -> PrecessionNutationParams {
2657        let (spin_inertia, transverse_inertia) = self.precession_nutation_inertias;
2658        let spin_rate_rad_s = if self.inputs.twist_rate > 0.0 {
2659            let velocity_fps = velocity_mps * 3.28084;
2660            let twist_rate_ft = self.inputs.twist_rate / 12.0;
2661            (velocity_fps / twist_rate_ft) * 2.0 * std::f64::consts::PI
2662        } else {
2663            0.0
2664        };
2665
2666        PrecessionNutationParams {
2667            mass_kg: self.inputs.bullet_mass,
2668            caliber_m: self.inputs.bullet_diameter,
2669            length_m: self.inputs.bullet_length,
2670            spin_rate_rad_s,
2671            spin_inertia,
2672            transverse_inertia,
2673            velocity_mps,
2674            air_density_kg_m3,
2675            mach: velocity_mps / speed_of_sound_mps,
2676            pitch_damping_coeff: PitchDampingCoefficients::default().subsonic,
2677            nutation_damping_factor: 0.05,
2678        }
2679    }
2680
2681    /// Append the exact state at the earliest boundary crossed by the final integration step.
2682    ///
2683    /// Each solver stores its pre-step state. Keeping only that point makes early ground and time
2684    /// exits indistinguishable from ordinary integration knots, and historically left the
2685    /// reported endpoint one step short. Interpolating all supported boundaries here gives every
2686    /// solver one explicit terminal point and one authoritative termination reason.
2687    /// `collapsed_steps` is the solve's running count from push_trajectory_point, so a stored
2688    /// terminal point is checked against the same budget as every integration step.
2689    fn append_terminal_endpoint(
2690        &self,
2691        points: &mut Vec<TrajectoryPoint>,
2692        post_position: Vector3<f64>,
2693        post_velocity: Vector3<f64>,
2694        post_time: f64,
2695        max_height: &mut f64,
2696        collapsed_steps: &mut usize,
2697    ) -> Result<TrajectoryTermination, BallisticsError> {
2698        let previous = points
2699            .last()
2700            .cloned()
2701            .ok_or_else(|| BallisticsError::from("No trajectory points generated"))?;
2702
2703        let mut crossings = Vec::with_capacity(3);
2704        if previous.position.x < self.max_range && post_position.x >= self.max_range {
2705            let span = post_position.x - previous.position.x;
2706            if span.is_finite() && span > 0.0 {
2707                crossings.push((
2708                    (self.max_range - previous.position.x) / span,
2709                    TrajectoryTermination::MaxRange,
2710                ));
2711            }
2712        }
2713        if self.inputs.ground_threshold.is_finite()
2714            && previous.position.y > self.inputs.ground_threshold
2715            && post_position.y <= self.inputs.ground_threshold
2716        {
2717            let span = post_position.y - previous.position.y;
2718            if span.is_finite() && span < 0.0 {
2719                crossings.push((
2720                    (self.inputs.ground_threshold - previous.position.y) / span,
2721                    TrajectoryTermination::GroundThreshold,
2722                ));
2723            }
2724        }
2725        if previous.time < TRAJECTORY_TIME_LIMIT_S && post_time >= TRAJECTORY_TIME_LIMIT_S {
2726            let span = post_time - previous.time;
2727            if span.is_finite() && span > 0.0 {
2728                crossings.push((
2729                    (TRAJECTORY_TIME_LIMIT_S - previous.time) / span,
2730                    TrajectoryTermination::TimeLimit,
2731                ));
2732            }
2733        }
2734
2735        let (fraction, termination) = crossings
2736            .into_iter()
2737            .filter(|(fraction, _)| fraction.is_finite() && (0.0..=1.0).contains(fraction))
2738            .min_by(|left, right| {
2739                let priority = |termination: TrajectoryTermination| match termination {
2740                    TrajectoryTermination::GroundThreshold => 0,
2741                    TrajectoryTermination::MaxRange => 1,
2742                    TrajectoryTermination::TimeLimit => 2,
2743                    TrajectoryTermination::VelocityFloor => 3,
2744                };
2745                left.0
2746                    .total_cmp(&right.0)
2747                    .then_with(|| priority(left.1).cmp(&priority(right.1)))
2748            })
2749            .ok_or_else(|| {
2750                BallisticsError::from(
2751                    "trajectory integration stopped without crossing a supported boundary",
2752                )
2753            })?;
2754
2755        let mut position = previous.position + (post_position - previous.position) * fraction;
2756        match termination {
2757            TrajectoryTermination::MaxRange => position.x = self.max_range,
2758            TrajectoryTermination::GroundThreshold => {
2759                position.y = self.inputs.ground_threshold;
2760            }
2761            TrajectoryTermination::TimeLimit | TrajectoryTermination::VelocityFloor => {}
2762        }
2763        let velocity_magnitude = previous.velocity_magnitude
2764            + (post_velocity.magnitude() - previous.velocity_magnitude) * fraction;
2765        let mut time = previous.time + (post_time - previous.time) * fraction;
2766        if termination == TrajectoryTermination::TimeLimit {
2767            time = TRAJECTORY_TIME_LIMIT_S;
2768        }
2769        let kinetic_energy =
2770            0.5 * self.inputs.bullet_mass * velocity_magnitude * velocity_magnitude;
2771
2772        if position.y > *max_height {
2773            *max_height = position.y;
2774        }
2775        let terminal_point = TrajectoryPoint {
2776            time,
2777            position,
2778            velocity_magnitude,
2779            kinetic_energy,
2780            drag_coefficient: None,
2781        };
2782        if terminal_point.position.x < previous.position.x {
2783            return Err(BallisticsError::from(
2784                "trajectory terminal state reversed downrange before the crossed boundary",
2785            ));
2786        }
2787        if terminal_point.position.x == previous.position.x {
2788            // A very early ground/time crossing can be distinct in time but less than one ULP
2789            // downrange. There is no representable range at which to retain both states, so make
2790            // the terminal state authoritative instead of creating a duplicate-X trajectory that
2791            // the checked observation API must reject (see push_trajectory_point).
2792            let last = points.last_mut().ok_or_else(|| {
2793                BallisticsError::from("trajectory points disappeared during terminal finalization")
2794            })?;
2795            *last = terminal_point;
2796        } else {
2797            self.push_trajectory_point(points, terminal_point, collapsed_steps)?;
2798        }
2799        Ok(termination)
2800    }
2801
2802    fn gravity_acceleration(&self) -> Vector3<f64> {
2803        self.gravity.in_frame(self.inputs.shooting_angle)
2804    }
2805
2806    /// The boundary-layer model this solver applies, or `None` when shear is off: the flag is
2807    /// clear, or the model name is `"none"`, which every kernel and front-end reads as no shear.
2808    ///
2809    /// Names match wind_shear::get_wind_at_position (MBA-965). An unrecognized name falls back
2810    /// to the power law, the historical "exponential" behaviour that the Python and Ruby
2811    /// bindings document for their dict and hash inputs; the CLI, WASM and solve-json front-ends
2812    /// parse an enum, so none of them can send one. `"none"` used to fall into that fallback
2813    /// too, so asking for no model applied the power law, while `fast_integrate` and the RK45
2814    /// kernel applied nothing.
2815    fn boundary_layer_shear_model(&self) -> Option<WindShearModel> {
2816        if !self.inputs.enable_wind_shear {
2817            return None;
2818        }
2819        match self.inputs.wind_shear_model.as_str() {
2820            "none" => None,
2821            "logarithmic" => Some(WindShearModel::Logarithmic),
2822            "power_law" | "powerlaw" | "exponential" => Some(WindShearModel::PowerLaw),
2823            "ekman_spiral" | "ekman" => Some(WindShearModel::EkmanSpiral),
2824            "custom_layers" | "custom" => Some(WindShearModel::CustomLayers),
2825            _ => Some(WindShearModel::PowerLaw),
2826        }
2827    }
2828
2829    fn get_wind_at_altitude(&self, height_agl_m: f64, model: WindShearModel) -> Vector3<f64> {
2830        // Scale the operative surface wind by the boundary-layer multiplier. `height_agl_m` is
2831        // the bullet's height above the GROUND, from wind_shear::shear_height_agl_m: its
2832        // shot-frame y (measured perpendicular to the line of sight from the level
2833        // `muzzle_height` is measured from), plus 0 when `muzzle_height` is set or the assumed
2834        // 1.5 m bore height when it is left at 0. The ground is the one the ground_threshold
2835        // check uses, parallel to the line of sight, so an inclined shot's ground follows its
2836        // slope. The multiplier is floored at 1.0, so flat-fire trajectories keep ~full wind and
2837        // only high-arcing shots see increased wind.
2838        //
2839        // We build the vector with THIS solver's non-shear sign convention (X=-cos, Z=-sin; see
2840        // the `wind_vector` used in solve_rk4/solve_euler, matching WindSock) and scale it, so that
2841        // "shear on" equals "shear off" * ratio (ratio == 1.0 for flat fire). An earlier revision
2842        // attenuated the wind near the line of sight and flipped its sign relative to the non-shear
2843        // path; this keeps them sign-consistent.
2844        let speed_ratio = crate::wind_shear::boundary_layer_speed_ratio_agl(height_agl_m, model);
2845
2846        // 0deg = headwind, 90deg = from the right (McCoy wind-FROM convention, matching
2847        // WindConditions / WindSock); wind enters drag via velocity - wind.
2848        //
2849        // MBA-728: the horizontal vector is built with vertical=0.0 and scaled by speed_ratio,
2850        // then wind.vertical_speed is added back UNSCALED — boundary-layer shear scales
2851        // horizontal wind only, vertical passes through as-is.
2852        crate::wind::wind_vector(self.wind.speed, self.wind.direction, 0.0) * speed_ratio
2853            + Vector3::new(0.0, self.wind.vertical_speed, 0.0)
2854    }
2855
2856    pub fn solve(&self) -> Result<TrajectoryResult, BallisticsError> {
2857        self.validate_for_solve()?;
2858        let mut result = if self.inputs.use_rk4 {
2859            if self.inputs.use_adaptive_rk45 {
2860                self.solve_rk45()?
2861            } else {
2862                self.solve_rk4()?
2863            }
2864        } else {
2865            self.solve_euler()?
2866        };
2867        self.apply_spin_drift(&mut result);
2868        self.validate_result_sanity(&result)?;
2869        Ok(result)
2870    }
2871
2872    /// Gyroscopic spin drift via the empirical Litz model, applied in the engine
2873    /// (not the WASM formatter) so it covers Euler/RK4/RK45 and all consumers.
2874    /// Uses the canonical SI fields and converts to grains/inches correctly,
2875    /// avoiding the kg/m-vs-grains/in unit bug in `calculate_enhanced_spin_drift`.
2876    /// Frame (McCoy): Z = lateral (windage), so drift adds to `position.z`.
2877    fn apply_spin_drift(&self, result: &mut TrajectoryResult) {
2878        if !self.inputs.use_enhanced_spin_drift {
2879            return;
2880        }
2881        let d_in = self.inputs.bullet_diameter / 0.0254; // m -> in
2882        let m_gr = self.inputs.bullet_mass / crate::constants::GRAINS_TO_KG; // kg -> grains
2883        let twist_in = self.inputs.twist_rate; // inches/turn
2884        if d_in <= 0.0 || m_gr <= 0.0 || twist_in <= 0.0 {
2885            return;
2886        }
2887
2888        // MBA-1134 (rank 31): single source of truth for the muzzle Sg —
2889        // stability::compute_stability_coefficient via spin_drift::effective_sg_from_inputs. This
2890        // ADDS the (v/2800)^(1/3) muzzle-velocity term the bare miller_stability() lacked, so the
2891        // spin-drift Sg now matches the reported SG and the aerodynamic-jump Sg. The linear Miller
2892        // density correction ((T/T0)*(P0/P), a no-op at sea-level standard) and the 4.5-caliber
2893        // length fallback are handled inside effective_sg_from_inputs.
2894        let sg = self.effective_spin_drift_sg();
2895
2896        for p in result.points.iter_mut() {
2897            if p.time <= 0.0 {
2898                continue;
2899            }
2900            // Canonical Litz drift, shared with the fast / Monte-Carlo path (spin_drift::litz_*).
2901            p.position.z +=
2902                crate::spin_drift::litz_drift_meters(sg, p.time, self.inputs.is_twist_right);
2903        }
2904
2905        // sampled_points are snapshotted from the PRE-drift trajectory inside each solver, so the
2906        // sampled wind_drift_m column would omit the spin drift that result.points carry. Apply
2907        // the same canonical Litz drift to keep the two user-facing outputs consistent.
2908        if let Some(samples) = result.sampled_points.as_mut() {
2909            for s in samples.iter_mut() {
2910                if s.time_s <= 0.0 {
2911                    continue;
2912                }
2913                s.wind_drift_m +=
2914                    crate::spin_drift::litz_drift_meters(sg, s.time_s, self.inputs.is_twist_right);
2915            }
2916        }
2917    }
2918
2919    /// Muzzle gyroscopic stability Sg used by the empirical Litz spin-drift post-process
2920    /// (MBA-1134). Extracted so the exact value is unit-testable and provably identical to the Sg
2921    /// the fast / Monte-Carlo path uses — both go through
2922    /// [`crate::spin_drift::effective_sg_from_inputs`] with the resolved muzzle atmosphere.
2923    fn effective_spin_drift_sg(&self) -> f64 {
2924        let (temp_c, press_hpa) = self.resolved_station_conditions();
2925        crate::spin_drift::effective_sg_from_inputs(&self.inputs, temp_c, press_hpa)
2926    }
2927
2928    /// Bore muzzle position at t=0 (bore-origin frame, `muzzle_height` above ground).
2929    /// With cant the rifle rotates about the LINE OF SIGHT, so the bore — sight_height
2930    /// below the sight — swings laterally by `-sight_height*sin(cant)` (left of the aim
2931    /// plane for clockwise cant) and rises by `sight_height*(1-cos(cant))` toward the
2932    /// pivot. (MBA-1286)
2933    ///
2934    /// A lateral sight-mount offset (MBA-1396) additionally displaces the bore
2935    /// `sight_offset_lateral_m` from the LOS (a sight mounted right of the bore puts the
2936    /// bore left of the sight line). Cant rotates the WHOLE bore-to-sight displacement
2937    /// vector rigidly about the LOS, so the vertical drop `-sight_height` and the lateral
2938    /// offset `-sight_offset_lateral_m` couple: rotating `(u, w) = (-sh, -off)` by the
2939    /// cant angle gives `y += sh*(1-cos) + off*sin` and `z = -sh*sin - off*cos`. Both the
2940    /// cant-only case (off = 0) and the offset-only case (cos = 1, sin = 0) collapse to
2941    /// the historical terms, so only a simultaneously canted AND offset rifle sees the
2942    /// coupling. The windage-zero convergence that makes the trajectory cross the LOS at
2943    /// the zero range lives in `windage_zero_bias_rad`, not here. Exactly-0.0 cant AND
2944    /// offset return the historical position (bit-identical).
2945    fn initial_position(&self) -> Vector3<f64> {
2946        if self.inputs.cant_angle == 0.0 && self.inputs.sight_offset_lateral_m == 0.0 {
2947            return Vector3::new(0.0, self.inputs.muzzle_height, 0.0);
2948        }
2949        let (sin_c, cos_c) = self.inputs.cant_angle.sin_cos();
2950        let sh = self.inputs.sight_height;
2951        let off = self.inputs.sight_offset_lateral_m;
2952        Vector3::new(
2953            0.0,
2954            self.inputs.muzzle_height + sh * (1.0 - cos_c) + off * sin_c,
2955            -sh * sin_c - off * cos_c,
2956        )
2957    }
2958
2959    /// Shared post-integration sampling used by all three integrators (MBA-1403).
2960    ///
2961    /// Builds the `TrajectoryData`/`TrajectoryOutputs` pair and runs
2962    /// [`sample_trajectory`] when `enable_trajectory_sampling` is set. This is the
2963    /// single place the sampler's LOS datum (`target_vertical_height_m`) is chosen,
2964    /// replacing three per-integrator copies that had to be edited in parallel.
2965    fn build_sampled_points(
2966        &self,
2967        points: &[TrajectoryPoint],
2968        max_height: f64,
2969        transonic_distances: Vec<f64>,
2970        mach_transitions: &MachTransitionTracker,
2971    ) -> Result<Option<Vec<TrajectorySample>>, BallisticsError> {
2972        if !self.inputs.enable_trajectory_sampling {
2973            return Ok(None);
2974        }
2975
2976        let last_point = points.last().ok_or("No trajectory points generated")?;
2977        let trajectory_data = TrajectoryData {
2978            times: points.iter().map(|p| p.time).collect(),
2979            positions: points.iter().map(|p| p.position).collect(),
2980            velocities: points
2981                .iter()
2982                .map(|p| {
2983                    // Reconstruct velocity vectors from magnitude (approximate)
2984                    Vector3::new(0.0, 0.0, p.velocity_magnitude)
2985                })
2986                .collect(),
2987            transonic_distances, // populated by the integrator at each Mach-threshold crossing
2988            mach_1_2_distance_m: mach_transitions.mach_1_2_distance_m,
2989            mach_1_0_distance_m: mach_transitions.mach_1_0_distance_m,
2990            mach_0_9_distance_m: mach_transitions.mach_0_9_distance_m,
2991        };
2992
2993        // For LOS calculation in ground-referenced coordinates:
2994        // sight_position_m is the sight's actual y-position above ground
2995        // (muzzle_height + sight_height, not just sight_height)
2996        // For flat shots, target is at same height as the sight (horizontal LOS)
2997        let sight_position_m = self.inputs.muzzle_height + self.inputs.sight_height;
2998        let target_reference = self.inputs.drops_reference == DropsReference::Target;
2999        // MBA-1403: only the (new, non-default) target mode reads `target_height` here,
3000        // and only when a real (non-zero) height was supplied — the sampler's LOS then
3001        // slopes toward the actual target instead of staying at the sight height. LOS
3002        // mode keeps the historical datum byte-identically, and zero-solve
3003        // `target_height` semantics (an explicit function argument, never this field)
3004        // are untouched.
3005        let target_vertical_height_m = if target_reference && self.inputs.target_height != 0.0 {
3006            self.inputs.target_height
3007        } else {
3008            sight_position_m
3009        };
3010        let outputs = TrajectoryOutputs {
3011            target_distance_horiz_m: last_point.position.x, // X is downrange
3012            target_vertical_height_m,
3013            time_of_flight_s: last_point.time,
3014            max_ord_dist_horiz_m: max_height,
3015            sight_height_m: sight_position_m,
3016        };
3017
3018        // Sample at specified intervals
3019        let mut samples = sample_trajectory(
3020            &trajectory_data,
3021            &outputs,
3022            self.inputs.sample_interval,
3023            self.inputs.bullet_mass,
3024        )?;
3025
3026        // MBA-1403 target-plane reference: scale the LOS-perpendicular drop to vertical
3027        // in the target plane. Scaling by the positive constant 1/cos preserves signs
3028        // and ordering, so the sampler's zero-crossing/apex flags are unaffected.
3029        // validate_for_solve rejects target mode at |shooting_angle| >= 90 degrees, so
3030        // cos_theta is strictly positive here. Downstream mil/moa conversions derive
3031        // from drop_m, so they inherit the transform without further edits.
3032        if target_reference {
3033            let cos_theta = self.inputs.shooting_angle.cos();
3034            for sample in &mut samples {
3035                sample.drop_m /= cos_theta;
3036            }
3037        }
3038        Ok(Some(samples))
3039    }
3040
3041    fn solve_euler(&self) -> Result<TrajectoryResult, BallisticsError> {
3042        // Simple trajectory integration using Euler method
3043        let mut time = 0.0;
3044        // Bullet starts at the BORE position, which is muzzle_height above ground
3045        // The sight is sight_height ABOVE the bore, so we don't add sight_height here
3046        // cant-adjusted via initial_position (MBA-1286)
3047        let mut position = self.initial_position();
3048        // Calculate initial velocity components with both elevation and azimuth
3049        // McCoy coordinate system: X=downrange, Y=vertical, Z=lateral (right)
3050        // Launch direction includes the aerodynamic-jump muzzle perturbation when enabled
3051        // (a no-op returning the bare muzzle/azimuth angles otherwise). MBA-959. Computed
3052        // once here and reused for the result so it isn't evaluated twice per solve.
3053        let aj_components = self.aerodynamic_jump_components();
3054        let (launch_elev, launch_azim) = self.launch_angles_from(aj_components.as_ref());
3055        let horizontal_velocity = self.inputs.muzzle_velocity * launch_elev.cos();
3056        let mut velocity = Vector3::new(
3057            horizontal_velocity * launch_azim.cos(), // X: downrange (forward)
3058            self.inputs.muzzle_velocity * launch_elev.sin(), // Y: vertical component
3059            horizontal_velocity * launch_azim.sin(), // Z: lateral (side deviation)
3060        );
3061
3062        let mut points = Vec::new();
3063        // Steps push_trajectory_point collapsed onto the previous point; they still count
3064        // against the point budget (MBA-1599).
3065        let mut collapsed_steps = 0;
3066        let mut max_height = position.y;
3067        let mut min_pitch_damping = f64::INFINITY; // Track minimum pitch damping coefficient
3068        let mut transonic_mach = None; // Track when we enter transonic
3069                                       // Downrange distances where the projectile crosses Mach 1.2 (transonic) then Mach 1.0
3070                                       // (subsonic), so the sampled trajectory output can flag those transitions
3071                                       // (trajectory_sampling::add_trajectory_flags consumes this).
3072        let mut transonic_distances: Vec<f64> = Vec::new();
3073        let mut mach_transitions = MachTransitionTracker::default();
3074
3075        // Initialize angular state for precession/nutation tracking
3076        let mut angular_state = if self.inputs.enable_precession_nutation {
3077            Some(AngularState {
3078                pitch_angle: 0.001, // Small initial disturbance
3079                yaw_angle: 0.001,
3080                pitch_rate: 0.0,
3081                yaw_rate: 0.0,
3082                precession_angle: 0.0,
3083                nutation_phase: 0.0,
3084            })
3085        } else {
3086            None
3087        };
3088        let mut max_yaw_angle = 0.0;
3089        let mut max_precession_angle = 0.0;
3090
3091        // Calculate air density
3092        // The station air, resolved once per solve. It seeds the per-substep local-altitude
3093        // air lookup inside calculate_acceleration (MBA-1136), and its frozen density and sound
3094        // speed below are the station values the Mach-transition, pitch-damping and
3095        // precession/nutation diagnostics are intentionally referenced to (station Mach).
3096        let station = self.station_air()?;
3097        let air_density = station.density_kg_m3();
3098        let speed_of_sound = station.speed_of_sound_mps();
3099
3100        // Wind vector (McCoy): X=downrange (head/tail wind), Y=0, Z=lateral (crosswind)
3101        // 0deg = headwind, 90deg = from the right (McCoy wind-FROM convention, matching
3102        // WindSock); wind enters drag via velocity - wind. Used when no segmented wind.
3103        // MBA-728: no shear/no segments here, so vertical_speed passes straight through
3104        // (there is no horizontal-only scaling step on this path).
3105        let wind_vector = crate::wind::wind_vector(
3106            self.wind.speed,
3107            self.wind.direction,
3108            self.wind.vertical_speed,
3109        );
3110
3111        // Pitch-damping coefficients depend only on the (constant) bullet_model; compute once
3112        // instead of re-deriving them (with a to_lowercase alloc) every integration step.
3113        let pitch_coeffs = PitchDampingCoefficients::from_bullet_type(
3114            self.inputs.bullet_model.as_deref().unwrap_or("default"),
3115        );
3116
3117        // Main integration loop (X is downrange)
3118        while position.x < self.max_range
3119            && position.y > self.inputs.ground_threshold
3120            && time < TRAJECTORY_TIME_LIMIT_S
3121        {
3122            // Store trajectory point
3123            let velocity_magnitude = velocity.magnitude();
3124            let kinetic_energy =
3125                0.5 * self.inputs.bullet_mass * velocity_magnitude * velocity_magnitude;
3126
3127            self.push_trajectory_point(
3128                &mut points,
3129                TrajectoryPoint {
3130                    time,
3131                    position,
3132                    velocity_magnitude,
3133                    kinetic_energy,
3134                    drag_coefficient: None,
3135                },
3136                &mut collapsed_steps,
3137            )?;
3138
3139            // Record Mach-transition distances (constant sea-level speed of sound, matching the
3140            // transonic_mach tracking). Each threshold is recorded once, in descending order.
3141            {
3142                let mach_here = if speed_of_sound > 0.0 {
3143                    velocity_magnitude / speed_of_sound
3144                } else {
3145                    0.0
3146                };
3147                mach_transitions.record_downward_crossings(
3148                    mach_here,
3149                    position.x,
3150                    &mut transonic_distances,
3151                );
3152            }
3153
3154            // Track max height
3155            if position.y > max_height {
3156                max_height = position.y;
3157            }
3158
3159            // Calculate pitch damping if enabled
3160            if self.inputs.enable_pitch_damping {
3161                let mach = velocity_magnitude / speed_of_sound;
3162
3163                // Track when we enter transonic
3164                if transonic_mach.is_none() && mach < 1.2 && mach > 0.8 {
3165                    transonic_mach = Some(mach);
3166                }
3167
3168                // Calculate pitch damping coefficient
3169                let pitch_damping = calculate_pitch_damping_coefficient(mach, &pitch_coeffs);
3170
3171                // Track minimum (most critical for stability)
3172                if pitch_damping < min_pitch_damping {
3173                    min_pitch_damping = pitch_damping;
3174                }
3175            }
3176
3177            // Calculate precession/nutation if enabled
3178            if self.inputs.enable_precession_nutation {
3179                if let Some(ref mut state) = angular_state {
3180                    let velocity_magnitude = velocity.magnitude();
3181                    let params = self.precession_nutation_params(
3182                        velocity_magnitude,
3183                        air_density,
3184                        speed_of_sound,
3185                    );
3186
3187                    // Update angular state
3188                    *state = calculate_combined_angular_motion(
3189                        &params,
3190                        state,
3191                        time,
3192                        self.time_step,
3193                        0.001, // Initial disturbance
3194                    );
3195
3196                    // Track maximums
3197                    if state.yaw_angle.abs() > max_yaw_angle {
3198                        max_yaw_angle = state.yaw_angle.abs();
3199                    }
3200                    if state.precession_angle.abs() > max_precession_angle {
3201                        max_precession_angle = state.precession_angle.abs();
3202                    }
3203                }
3204            }
3205
3206            // Use the same acceleration kernel as RK4/RK45 so all three solvers share ONE drag
3207            // model. solve_euler previously used a bespoke frontal-area drag (0.5*rho*Cd*A*v^2/m)
3208            // that IGNORED the ballistic coefficient entirely (diverging up to ~2.3x from the
3209            // BC-retardation RK4/RK45 path), and also omitted the Magnus/Coriolis terms.
3210            // calculate_acceleration applies BC-retardation drag, gravity, Coriolis, Magnus, wind
3211            // shear, and the zero-relative-velocity gravity-only guard.
3212            let acceleration =
3213                self.calculate_acceleration(&position, &velocity, &wind_vector, &station);
3214
3215            // Update state
3216            let step_start = position;
3217            velocity += acceleration * self.time_step;
3218            position += velocity * self.time_step;
3219            time += self.time_step;
3220            self.validate_integration_state(&position, &velocity, time)
3221                .map_err(|error| {
3222                    self.refusal_of_failed_step(
3223                        error,
3224                        &station,
3225                        &step_start,
3226                        &position,
3227                        &velocity,
3228                        self.time_step,
3229                        time,
3230                    )
3231                })?;
3232        }
3233
3234        let termination = self.append_terminal_endpoint(
3235            &mut points,
3236            position,
3237            velocity,
3238            time,
3239            &mut max_height,
3240            &mut collapsed_steps,
3241        )?;
3242
3243        // Get final values
3244        // MBA-1423: fill the per-point Cd here, once, rather than inside each integrator loop.
3245        // Every solver family reaches this line, so none can leave the field empty while the
3246        // others populate it. Must precede the `last_point` borrow below.
3247        self.annotate_drag_coefficients(&mut points, speed_of_sound);
3248
3249        let last_point = points.last().ok_or("No trajectory points generated")?;
3250
3251        // Create trajectory sampling data if enabled (shared helper, MBA-1403)
3252        let sampled_points =
3253            self.build_sampled_points(&points, max_height, transonic_distances, &mach_transitions)?;
3254
3255        Ok(TrajectoryResult {
3256            max_range: last_point.position.x, // X is downrange
3257            max_height,
3258            time_of_flight: last_point.time,
3259            impact_velocity: last_point.velocity_magnitude,
3260            impact_energy: last_point.kinetic_energy,
3261            projectile_mass_kg: self.inputs.bullet_mass,
3262            line_of_sight_height_m: self.inputs.muzzle_height + self.inputs.sight_height,
3263            station_speed_of_sound_mps: speed_of_sound,
3264            termination,
3265            points,
3266            sampled_points,
3267            min_pitch_damping: if self.inputs.enable_pitch_damping {
3268                Some(min_pitch_damping)
3269            } else {
3270                None
3271            },
3272            transonic_mach,
3273            angular_state,
3274            max_yaw_angle: if self.inputs.enable_precession_nutation {
3275                Some(max_yaw_angle)
3276            } else {
3277                None
3278            },
3279            max_precession_angle: if self.inputs.enable_precession_nutation {
3280                Some(max_precession_angle)
3281            } else {
3282                None
3283            },
3284            aerodynamic_jump: aj_components,
3285            mach_1_2_distance_m: mach_transitions.mach_1_2_distance_m,
3286            mach_1_0_distance_m: mach_transitions.mach_1_0_distance_m,
3287            mach_0_9_distance_m: mach_transitions.mach_0_9_distance_m,
3288        })
3289    }
3290
3291    fn solve_rk4(&self) -> Result<TrajectoryResult, BallisticsError> {
3292        // RK4 trajectory integration for better accuracy
3293        let mut time = 0.0;
3294        // Bullet starts at the BORE position, which is muzzle_height above ground
3295        // The sight is sight_height ABOVE the bore, so we don't add sight_height here
3296        // The sight_height affects the LOS calculation and zero angle, not the starting position
3297        // cant-adjusted via initial_position (MBA-1286)
3298        let mut position = self.initial_position();
3299
3300        // Calculate initial velocity components with both elevation and azimuth
3301        // McCoy coordinate system: X=downrange, Y=vertical, Z=lateral (right)
3302        // Launch direction includes the aerodynamic-jump muzzle perturbation when enabled
3303        // (a no-op returning the bare muzzle/azimuth angles otherwise). MBA-959. Computed
3304        // once here and reused for the result so it isn't evaluated twice per solve.
3305        let aj_components = self.aerodynamic_jump_components();
3306        let (launch_elev, launch_azim) = self.launch_angles_from(aj_components.as_ref());
3307        let horizontal_velocity = self.inputs.muzzle_velocity * launch_elev.cos();
3308        let mut velocity = Vector3::new(
3309            horizontal_velocity * launch_azim.cos(), // X: downrange (forward)
3310            self.inputs.muzzle_velocity * launch_elev.sin(), // Y: vertical component
3311            horizontal_velocity * launch_azim.sin(), // Z: lateral (side deviation)
3312        );
3313
3314        let mut points = Vec::new();
3315        // Steps push_trajectory_point collapsed onto the previous point; they still count
3316        // against the point budget (MBA-1599).
3317        let mut collapsed_steps = 0;
3318        let mut max_height = position.y;
3319        let mut min_pitch_damping = f64::INFINITY; // Track minimum pitch damping coefficient
3320        let mut transonic_mach = None; // Track when we enter transonic
3321                                       // Downrange distances where the projectile crosses Mach 1.2 (transonic) then Mach 1.0
3322                                       // (subsonic), so the sampled trajectory output can flag those transitions
3323                                       // (trajectory_sampling::add_trajectory_flags consumes this).
3324        let mut transonic_distances: Vec<f64> = Vec::new();
3325        let mut mach_transitions = MachTransitionTracker::default();
3326
3327        // Initialize angular state for precession/nutation tracking
3328        let mut angular_state = if self.inputs.enable_precession_nutation {
3329            Some(AngularState {
3330                pitch_angle: 0.001, // Small initial disturbance
3331                yaw_angle: 0.001,
3332                pitch_rate: 0.0,
3333                yaw_rate: 0.0,
3334                precession_angle: 0.0,
3335                nutation_phase: 0.0,
3336            })
3337        } else {
3338            None
3339        };
3340        let mut max_yaw_angle = 0.0;
3341        let mut max_precession_angle = 0.0;
3342
3343        // Calculate air density
3344        // The station air, resolved once per solve. It seeds the per-substep local-altitude
3345        // air lookup inside calculate_acceleration (MBA-1136), and its frozen density and sound
3346        // speed below are the station values the Mach-transition, pitch-damping and
3347        // precession/nutation diagnostics are intentionally referenced to (station Mach).
3348        let station = self.station_air()?;
3349        let air_density = station.density_kg_m3();
3350        let speed_of_sound = station.speed_of_sound_mps();
3351
3352        // Wind vector (McCoy): X=downrange (head/tail wind), Y=0, Z=lateral (crosswind)
3353        // 0deg = headwind, 90deg = from the right (McCoy wind-FROM convention, matching
3354        // WindSock); wind enters drag via velocity - wind. Used when no segmented wind.
3355        // MBA-728: no shear/no segments here, so vertical_speed passes straight through
3356        // (there is no horizontal-only scaling step on this path).
3357        let wind_vector = crate::wind::wind_vector(
3358            self.wind.speed,
3359            self.wind.direction,
3360            self.wind.vertical_speed,
3361        );
3362
3363        // Pitch-damping coefficients depend only on the (constant) bullet_model; compute once
3364        // instead of re-deriving them (with a to_lowercase alloc) every integration step.
3365        let pitch_coeffs = PitchDampingCoefficients::from_bullet_type(
3366            self.inputs.bullet_model.as_deref().unwrap_or("default"),
3367        );
3368
3369        // Main RK4 integration loop (X is downrange)
3370        while position.x < self.max_range
3371            && position.y > self.inputs.ground_threshold
3372            && time < TRAJECTORY_TIME_LIMIT_S
3373        {
3374            // Store trajectory point
3375            let velocity_magnitude = velocity.magnitude();
3376            let kinetic_energy =
3377                0.5 * self.inputs.bullet_mass * velocity_magnitude * velocity_magnitude;
3378
3379            self.push_trajectory_point(
3380                &mut points,
3381                TrajectoryPoint {
3382                    time,
3383                    position,
3384                    velocity_magnitude,
3385                    kinetic_energy,
3386                    drag_coefficient: None,
3387                },
3388                &mut collapsed_steps,
3389            )?;
3390
3391            // Record Mach-transition distances (constant sea-level speed of sound, matching the
3392            // transonic_mach tracking). Each threshold is recorded once, in descending order.
3393            {
3394                let mach_here = if speed_of_sound > 0.0 {
3395                    velocity_magnitude / speed_of_sound
3396                } else {
3397                    0.0
3398                };
3399                mach_transitions.record_downward_crossings(
3400                    mach_here,
3401                    position.x,
3402                    &mut transonic_distances,
3403                );
3404            }
3405
3406            if position.y > max_height {
3407                max_height = position.y;
3408            }
3409
3410            // Calculate pitch damping if enabled (RK4 solver)
3411            if self.inputs.enable_pitch_damping {
3412                let mach = velocity_magnitude / speed_of_sound;
3413
3414                // Track when we enter transonic
3415                if transonic_mach.is_none() && mach < 1.2 && mach > 0.8 {
3416                    transonic_mach = Some(mach);
3417                }
3418
3419                // Calculate pitch damping coefficient
3420                let pitch_damping = calculate_pitch_damping_coefficient(mach, &pitch_coeffs);
3421
3422                // Track minimum (most critical for stability)
3423                if pitch_damping < min_pitch_damping {
3424                    min_pitch_damping = pitch_damping;
3425                }
3426            }
3427
3428            // Calculate precession/nutation if enabled (RK4 solver)
3429            if self.inputs.enable_precession_nutation {
3430                if let Some(ref mut state) = angular_state {
3431                    let velocity_magnitude = velocity.magnitude();
3432                    let params = self.precession_nutation_params(
3433                        velocity_magnitude,
3434                        air_density,
3435                        speed_of_sound,
3436                    );
3437
3438                    // Update angular state
3439                    *state = calculate_combined_angular_motion(
3440                        &params,
3441                        state,
3442                        time,
3443                        self.time_step,
3444                        0.001, // Initial disturbance
3445                    );
3446
3447                    // Track maximums
3448                    if state.yaw_angle.abs() > max_yaw_angle {
3449                        max_yaw_angle = state.yaw_angle.abs();
3450                    }
3451                    if state.precession_angle.abs() > max_precession_angle {
3452                        max_precession_angle = state.precession_angle.abs();
3453                    }
3454                }
3455            }
3456
3457            // RK4 method
3458            let dt = self.time_step;
3459
3460            // k1
3461            let acc1 = self.calculate_acceleration(&position, &velocity, &wind_vector, &station);
3462
3463            // k2
3464            let pos2 = position + velocity * (dt * 0.5);
3465            let vel2 = velocity + acc1 * (dt * 0.5);
3466            let acc2 = self.calculate_acceleration(&pos2, &vel2, &wind_vector, &station);
3467
3468            // k3
3469            let pos3 = position + vel2 * (dt * 0.5);
3470            let vel3 = velocity + acc2 * (dt * 0.5);
3471            let acc3 = self.calculate_acceleration(&pos3, &vel3, &wind_vector, &station);
3472
3473            // k4
3474            let pos4 = position + vel3 * dt;
3475            let vel4 = velocity + acc3 * dt;
3476            let acc4 = self.calculate_acceleration(&pos4, &vel4, &wind_vector, &station);
3477
3478            // Update position and velocity
3479            let step_start = position;
3480            position += (velocity + vel2 * 2.0 + vel3 * 2.0 + vel4) * (dt / 6.0);
3481            velocity += (acc1 + acc2 * 2.0 + acc3 * 2.0 + acc4) * (dt / 6.0);
3482            time += dt;
3483            self.validate_integration_state(&position, &velocity, time)
3484                .map_err(|error| {
3485                    self.refusal_of_failed_step(
3486                        error,
3487                        &station,
3488                        &step_start,
3489                        &position,
3490                        &velocity,
3491                        dt,
3492                        time,
3493                    )
3494                })?;
3495        }
3496
3497        let termination = self.append_terminal_endpoint(
3498            &mut points,
3499            position,
3500            velocity,
3501            time,
3502            &mut max_height,
3503            &mut collapsed_steps,
3504        )?;
3505
3506        // Get final values
3507        // MBA-1423: fill the per-point Cd here, once, rather than inside each integrator loop.
3508        // Every solver family reaches this line, so none can leave the field empty while the
3509        // others populate it. Must precede the `last_point` borrow below.
3510        self.annotate_drag_coefficients(&mut points, speed_of_sound);
3511
3512        let last_point = points.last().ok_or("No trajectory points generated")?;
3513
3514        // Create trajectory sampling data if enabled (shared helper, MBA-1403)
3515        let sampled_points =
3516            self.build_sampled_points(&points, max_height, transonic_distances, &mach_transitions)?;
3517
3518        Ok(TrajectoryResult {
3519            max_range: last_point.position.x, // X is downrange
3520            max_height,
3521            time_of_flight: last_point.time,
3522            impact_velocity: last_point.velocity_magnitude,
3523            impact_energy: last_point.kinetic_energy,
3524            projectile_mass_kg: self.inputs.bullet_mass,
3525            line_of_sight_height_m: self.inputs.muzzle_height + self.inputs.sight_height,
3526            station_speed_of_sound_mps: speed_of_sound,
3527            termination,
3528            points,
3529            sampled_points,
3530            min_pitch_damping: if self.inputs.enable_pitch_damping {
3531                Some(min_pitch_damping)
3532            } else {
3533                None
3534            },
3535            transonic_mach,
3536            angular_state,
3537            max_yaw_angle: if self.inputs.enable_precession_nutation {
3538                Some(max_yaw_angle)
3539            } else {
3540                None
3541            },
3542            max_precession_angle: if self.inputs.enable_precession_nutation {
3543                Some(max_precession_angle)
3544            } else {
3545                None
3546            },
3547            aerodynamic_jump: aj_components,
3548            mach_1_2_distance_m: mach_transitions.mach_1_2_distance_m,
3549            mach_1_0_distance_m: mach_transitions.mach_1_0_distance_m,
3550            mach_0_9_distance_m: mach_transitions.mach_0_9_distance_m,
3551        })
3552    }
3553
3554    fn solve_rk45(&self) -> Result<TrajectoryResult, BallisticsError> {
3555        // RK45 adaptive step size integration (Dormand-Prince method)
3556        let mut time = 0.0;
3557        // Bullet starts at the BORE position, which is muzzle_height above ground
3558        // The sight is sight_height ABOVE the bore, so we don't add sight_height here
3559        // cant-adjusted via initial_position (MBA-1286)
3560        let mut position = self.initial_position();
3561
3562        // Calculate initial velocity components
3563        // McCoy coordinate system: X=downrange, Y=vertical, Z=lateral (right)
3564        // Launch direction includes the aerodynamic-jump muzzle perturbation when enabled
3565        // (a no-op returning the bare muzzle/azimuth angles otherwise). MBA-959. Computed
3566        // once here and reused for the result so it isn't evaluated twice per solve.
3567        let aj_components = self.aerodynamic_jump_components();
3568        let (launch_elev, launch_azim) = self.launch_angles_from(aj_components.as_ref());
3569        let horizontal_velocity = self.inputs.muzzle_velocity * launch_elev.cos();
3570        let mut velocity = Vector3::new(
3571            horizontal_velocity * launch_azim.cos(), // X: downrange (forward)
3572            self.inputs.muzzle_velocity * launch_elev.sin(), // Y: vertical component
3573            horizontal_velocity * launch_azim.sin(), // Z: lateral (side deviation)
3574        );
3575
3576        let mut points = Vec::new();
3577        // Steps push_trajectory_point collapsed onto the previous point; they still count
3578        // against the point budget (MBA-1599).
3579        let mut collapsed_steps = 0;
3580        let mut max_height = position.y;
3581        let mut dt = 0.001; // Initial step size
3582
3583        // Air density and wind are constant for the whole solve (self.atmosphere / self.wind
3584        // are immutable); compute once instead of every iteration (mirrors solve_rk4).
3585        // The station air, resolved once per solve. It seeds the per-substep local-altitude
3586        // air lookup inside calculate_acceleration (MBA-1136), and its frozen density and sound
3587        // speed below are the station values the Mach-transition, pitch-damping and
3588        // precession/nutation diagnostics are intentionally referenced to (station Mach).
3589        let station = self.station_air()?;
3590        let air_density = station.density_kg_m3();
3591        let speed_of_sound = station.speed_of_sound_mps();
3592        // 0deg = headwind, 90deg = from the right (McCoy wind-FROM convention, matching
3593        // WindSock); wind enters drag via velocity - wind. Used when no segmented wind.
3594        // MBA-728: no shear/no segments here, so vertical_speed passes straight through
3595        // (there is no horizontal-only scaling step on this path).
3596        let wind_vector = crate::wind::wind_vector(
3597            self.wind.speed,
3598            self.wind.direction,
3599            self.wind.vertical_speed,
3600        );
3601
3602        // Mach-transition distances for the sampled-output flags (see solve_euler/solve_rk4).
3603        let mut transonic_distances: Vec<f64> = Vec::new();
3604        let mut mach_transitions = MachTransitionTracker::default();
3605
3606        // Pitch-damping / precession diagnostics (MBA-966). Previously only the
3607        // Euler and fixed-RK4 solvers tracked these, so the default adaptive
3608        // RK45 path always reported null even with --enable-pitch-damping /
3609        // --enable-precession set. Mirror the RK4 tracking here.
3610        let mut min_pitch_damping = f64::INFINITY;
3611        let mut transonic_mach: Option<f64> = None;
3612        let pitch_coeffs = PitchDampingCoefficients::from_bullet_type(
3613            self.inputs.bullet_model.as_deref().unwrap_or("default"),
3614        );
3615        let mut angular_state = if self.inputs.enable_precession_nutation {
3616            Some(AngularState {
3617                pitch_angle: 0.001,
3618                yaw_angle: 0.001,
3619                pitch_rate: 0.0,
3620                yaw_rate: 0.0,
3621                precession_angle: 0.0,
3622                nutation_phase: 0.0,
3623            })
3624        } else {
3625            None
3626        };
3627        let mut max_yaw_angle = 0.0;
3628        let mut max_precession_angle = 0.0;
3629
3630        while position.x < self.max_range
3631            && position.y > self.inputs.ground_threshold
3632            && time < TRAJECTORY_TIME_LIMIT_S
3633        {
3634            // Store current point
3635            let velocity_magnitude = velocity.magnitude();
3636            let kinetic_energy = 0.5 * self.inputs.bullet_mass * velocity_magnitude.powi(2);
3637
3638            self.push_trajectory_point(
3639                &mut points,
3640                TrajectoryPoint {
3641                    time,
3642                    position,
3643                    velocity_magnitude,
3644                    kinetic_energy,
3645                    drag_coefficient: None,
3646                },
3647                &mut collapsed_steps,
3648            )?;
3649
3650            // Record Mach-transition distances (constant sea-level speed of sound, matching the
3651            // transonic_mach tracking). Each threshold is recorded once, in descending order.
3652            {
3653                let mach_here = if speed_of_sound > 0.0 {
3654                    velocity_magnitude / speed_of_sound
3655                } else {
3656                    0.0
3657                };
3658                mach_transitions.record_downward_crossings(
3659                    mach_here,
3660                    position.x,
3661                    &mut transonic_distances,
3662                );
3663            }
3664
3665            if position.y > max_height {
3666                max_height = position.y;
3667            }
3668
3669            // Pitch damping (RK45 solver) — track the minimum coefficient and the
3670            // Mach at which the projectile enters the transonic band (MBA-966).
3671            if self.inputs.enable_pitch_damping {
3672                let mach = velocity_magnitude / speed_of_sound;
3673                if transonic_mach.is_none() && mach < 1.2 && mach > 0.8 {
3674                    transonic_mach = Some(mach);
3675                }
3676                let pitch_damping = calculate_pitch_damping_coefficient(mach, &pitch_coeffs);
3677                if pitch_damping < min_pitch_damping {
3678                    min_pitch_damping = pitch_damping;
3679                }
3680            }
3681
3682            // Retry the same state until the embedded error estimate accepts the
3683            // candidate. No trajectory or angular state advances on rejection.
3684            let accepted_step =
3685                self.adaptive_rk45_step(&position, &velocity, dt, &wind_vector, &station);
3686            debug_assert!(
3687                accepted_step.error <= RK45_TOLERANCE || accepted_step.used_dt <= RK45_MIN_DT
3688            );
3689
3690            // Precession / nutation advances only after the translational step
3691            // is accepted, using that accepted interval rather than a rejected
3692            // trial's dt.
3693            if self.inputs.enable_precession_nutation {
3694                if let Some(ref mut state) = angular_state {
3695                    let params = self.precession_nutation_params(
3696                        velocity_magnitude,
3697                        air_density,
3698                        speed_of_sound,
3699                    );
3700
3701                    *state = calculate_combined_angular_motion(
3702                        &params,
3703                        state,
3704                        time,
3705                        accepted_step.used_dt,
3706                        0.001,
3707                    );
3708
3709                    if state.yaw_angle.abs() > max_yaw_angle {
3710                        max_yaw_angle = state.yaw_angle.abs();
3711                    }
3712                    if state.precession_angle.abs() > max_precession_angle {
3713                        max_precession_angle = state.precession_angle.abs();
3714                    }
3715                }
3716            }
3717
3718            let step_start = position;
3719            position = accepted_step.position;
3720            velocity = accepted_step.velocity;
3721            time += accepted_step.used_dt;
3722            self.validate_integration_state(&position, &velocity, time)
3723                .map_err(|error| {
3724                    self.refusal_of_failed_step(
3725                        error,
3726                        &station,
3727                        &step_start,
3728                        &position,
3729                        &velocity,
3730                        accepted_step.used_dt,
3731                        time,
3732                    )
3733                })?;
3734
3735            // Adapt the step size for the NEXT iteration.
3736            dt = accepted_step.next_dt;
3737        }
3738
3739        // Ensure we have at least one point
3740        if points.is_empty() {
3741            return Err(BallisticsError::from("No trajectory points calculated"));
3742        }
3743
3744        // Shared MBA-968/MBA-1218 range-crossing interpolation for all solver modes.
3745        let termination = self.append_terminal_endpoint(
3746            &mut points,
3747            position,
3748            velocity,
3749            time,
3750            &mut max_height,
3751            &mut collapsed_steps,
3752        )?;
3753
3754        // MBA-1423: see the sibling solvers — fill the per-point Cd before the borrow below.
3755        self.annotate_drag_coefficients(&mut points, speed_of_sound);
3756
3757        let last_point = points.last().unwrap();
3758
3759        // Generate sampled trajectory points if enabled (shared helper, MBA-1403)
3760        let sampled_points =
3761            self.build_sampled_points(&points, max_height, transonic_distances, &mach_transitions)?;
3762
3763        Ok(TrajectoryResult {
3764            max_range: last_point.position.x, // X is downrange
3765            max_height,
3766            time_of_flight: last_point.time,
3767            impact_velocity: last_point.velocity_magnitude,
3768            impact_energy: last_point.kinetic_energy,
3769            projectile_mass_kg: self.inputs.bullet_mass,
3770            line_of_sight_height_m: self.inputs.muzzle_height + self.inputs.sight_height,
3771            station_speed_of_sound_mps: speed_of_sound,
3772            termination,
3773            points,
3774            sampled_points,
3775            min_pitch_damping: if self.inputs.enable_pitch_damping {
3776                Some(min_pitch_damping)
3777            } else {
3778                None
3779            },
3780            transonic_mach,
3781            angular_state,
3782            max_yaw_angle: if self.inputs.enable_precession_nutation {
3783                Some(max_yaw_angle)
3784            } else {
3785                None
3786            },
3787            max_precession_angle: if self.inputs.enable_precession_nutation {
3788                Some(max_precession_angle)
3789            } else {
3790                None
3791            },
3792            aerodynamic_jump: aj_components,
3793            mach_1_2_distance_m: mach_transitions.mach_1_2_distance_m,
3794            mach_1_0_distance_m: mach_transitions.mach_1_0_distance_m,
3795            mach_0_9_distance_m: mach_transitions.mach_0_9_distance_m,
3796        })
3797    }
3798
3799    fn adaptive_rk45_step(
3800        &self,
3801        position: &Vector3<f64>,
3802        velocity: &Vector3<f64>,
3803        initial_dt: f64,
3804        wind_vector: &Vector3<f64>,
3805        station: &StationAir,
3806    ) -> Rk45AcceptedStep {
3807        let mut trial_dt = initial_dt;
3808
3809        loop {
3810            let trial = self.rk45_step(
3811                position,
3812                velocity,
3813                trial_dt,
3814                wind_vector,
3815                RK45_TOLERANCE,
3816                station,
3817            );
3818            // A finite-but-extreme input or malformed optional curve can overflow an embedded
3819            // trial. Do not let a NaN suggested step poison `trial_dt` and retry forever: shrink
3820            // to the minimum step, return the non-finite trial there, and let the immediate
3821            // integration-state check turn it into a clean Err.
3822            let next_dt = if trial.suggested_dt.is_finite() {
3823                (RK45_SAFETY_FACTOR * trial.suggested_dt).clamp(RK45_MIN_DT, RK45_MAX_DT)
3824            } else {
3825                RK45_MIN_DT
3826            };
3827
3828            if trial.error <= RK45_TOLERANCE || trial_dt <= RK45_MIN_DT {
3829                return Rk45AcceptedStep {
3830                    position: trial.position,
3831                    velocity: trial.velocity,
3832                    used_dt: trial_dt,
3833                    next_dt,
3834                    error: trial.error,
3835                };
3836            }
3837
3838            trial_dt = next_dt;
3839        }
3840    }
3841
3842    fn rk45_step(
3843        &self,
3844        position: &Vector3<f64>,
3845        velocity: &Vector3<f64>,
3846        dt: f64,
3847        wind_vector: &Vector3<f64>,
3848        tolerance: f64,
3849        station: &StationAir,
3850    ) -> Rk45Trial {
3851        // Dormand-Prince coefficients
3852        const A21: f64 = 1.0 / 5.0;
3853        const A31: f64 = 3.0 / 40.0;
3854        const A32: f64 = 9.0 / 40.0;
3855        const A41: f64 = 44.0 / 45.0;
3856        const A42: f64 = -56.0 / 15.0;
3857        const A43: f64 = 32.0 / 9.0;
3858        const A51: f64 = 19372.0 / 6561.0;
3859        const A52: f64 = -25360.0 / 2187.0;
3860        const A53: f64 = 64448.0 / 6561.0;
3861        const A54: f64 = -212.0 / 729.0;
3862        const A61: f64 = 9017.0 / 3168.0;
3863        const A62: f64 = -355.0 / 33.0;
3864        const A63: f64 = 46732.0 / 5247.0;
3865        const A64: f64 = 49.0 / 176.0;
3866        const A65: f64 = -5103.0 / 18656.0;
3867        const A71: f64 = 35.0 / 384.0;
3868        const A73: f64 = 500.0 / 1113.0;
3869        const A74: f64 = 125.0 / 192.0;
3870        const A75: f64 = -2187.0 / 6784.0;
3871        const A76: f64 = 11.0 / 84.0;
3872
3873        // 5th order coefficients
3874        const B1: f64 = 35.0 / 384.0;
3875        const B3: f64 = 500.0 / 1113.0;
3876        const B4: f64 = 125.0 / 192.0;
3877        const B5: f64 = -2187.0 / 6784.0;
3878        const B6: f64 = 11.0 / 84.0;
3879
3880        // 4th order coefficients for error estimation
3881        const B1_ERR: f64 = 5179.0 / 57600.0;
3882        const B3_ERR: f64 = 7571.0 / 16695.0;
3883        const B4_ERR: f64 = 393.0 / 640.0;
3884        const B5_ERR: f64 = -92097.0 / 339200.0;
3885        const B6_ERR: f64 = 187.0 / 2100.0;
3886        const B7_ERR: f64 = 1.0 / 40.0;
3887
3888        // Compute RK45 stages
3889        let k1_v = self.calculate_acceleration(position, velocity, wind_vector, station);
3890        let k1_p = *velocity;
3891
3892        let p2 = position + dt * A21 * k1_p;
3893        let v2 = velocity + dt * A21 * k1_v;
3894        let k2_v = self.calculate_acceleration(&p2, &v2, wind_vector, station);
3895        let k2_p = v2;
3896
3897        let p3 = position + dt * (A31 * k1_p + A32 * k2_p);
3898        let v3 = velocity + dt * (A31 * k1_v + A32 * k2_v);
3899        let k3_v = self.calculate_acceleration(&p3, &v3, wind_vector, station);
3900        let k3_p = v3;
3901
3902        let p4 = position + dt * (A41 * k1_p + A42 * k2_p + A43 * k3_p);
3903        let v4 = velocity + dt * (A41 * k1_v + A42 * k2_v + A43 * k3_v);
3904        let k4_v = self.calculate_acceleration(&p4, &v4, wind_vector, station);
3905        let k4_p = v4;
3906
3907        let p5 = position + dt * (A51 * k1_p + A52 * k2_p + A53 * k3_p + A54 * k4_p);
3908        let v5 = velocity + dt * (A51 * k1_v + A52 * k2_v + A53 * k3_v + A54 * k4_v);
3909        let k5_v = self.calculate_acceleration(&p5, &v5, wind_vector, station);
3910        let k5_p = v5;
3911
3912        let p6 = position + dt * (A61 * k1_p + A62 * k2_p + A63 * k3_p + A64 * k4_p + A65 * k5_p);
3913        let v6 = velocity + dt * (A61 * k1_v + A62 * k2_v + A63 * k3_v + A64 * k4_v + A65 * k5_v);
3914        let k6_v = self.calculate_acceleration(&p6, &v6, wind_vector, station);
3915        let k6_p = v6;
3916
3917        let p7 = position + dt * (A71 * k1_p + A73 * k3_p + A74 * k4_p + A75 * k5_p + A76 * k6_p);
3918        let v7 = velocity + dt * (A71 * k1_v + A73 * k3_v + A74 * k4_v + A75 * k5_v + A76 * k6_v);
3919        let k7_v = self.calculate_acceleration(&p7, &v7, wind_vector, station);
3920        let k7_p = v7;
3921
3922        // 5th order solution
3923        let new_pos = position + dt * (B1 * k1_p + B3 * k3_p + B4 * k4_p + B5 * k5_p + B6 * k6_p);
3924        let new_vel = velocity + dt * (B1 * k1_v + B3 * k3_v + B4 * k4_v + B5 * k5_v + B6 * k6_v);
3925
3926        // 4th order solution for error estimate
3927        let pos_err = position
3928            + dt * (B1_ERR * k1_p
3929                + B3_ERR * k3_p
3930                + B4_ERR * k4_p
3931                + B5_ERR * k5_p
3932                + B6_ERR * k6_p
3933                + B7_ERR * k7_p);
3934        let vel_err = velocity
3935            + dt * (B1_ERR * k1_v
3936                + B3_ERR * k3_v
3937                + B4_ERR * k4_v
3938                + B5_ERR * k5_v
3939                + B6_ERR * k6_v
3940                + B7_ERR * k7_v);
3941
3942        // Estimate error
3943        let error = cli_rk45_error_norm(position, velocity, &new_pos, &new_vel, &pos_err, &vel_err);
3944
3945        // Calculate new step size
3946        let dt_new = if error < tolerance {
3947            dt * (tolerance / error).powf(0.2).min(2.0)
3948        } else {
3949            dt * (tolerance / error).powf(0.25).max(0.1)
3950        };
3951
3952        Rk45Trial {
3953            position: new_pos,
3954            velocity: new_vel,
3955            suggested_dt: dt_new,
3956            error,
3957        }
3958    }
3959
3960    fn apply_cluster_bc_correction(&self, base_bc: f64, velocity_fps: f64) -> f64 {
3961        if let Some(ref cluster_bc) = self.cluster_bc {
3962            cluster_bc.apply_correction_for_drag_model(
3963                base_bc,
3964                self.inputs.caliber_inches,
3965                self.inputs.weight_grains,
3966                velocity_fps,
3967                self.inputs.bc_type,
3968            )
3969        } else {
3970            base_bc
3971        }
3972    }
3973
3974    fn calculate_acceleration(
3975        &self,
3976        position: &Vector3<f64>,
3977        velocity: &Vector3<f64>,
3978        wind_vector: &Vector3<f64>,
3979        station: &StationAir,
3980    ) -> Vector3<f64> {
3981        // Resolve the wind at this point. Downrange-segmented wind (when supplied)
3982        // takes precedence and is sampled by downrange distance (position.x) per
3983        // step; otherwise altitude-dependent shear (if enabled); otherwise the
3984        // constant `wind_vector`. Segmented wind is not combined with shear (the
3985        // CLI/WASM front-ends reject that combination), so the order is safe.
3986        let actual_wind = if let Some(ref sock) = self.wind_sock {
3987            sock.vector_for_range_stateless(position.x)
3988        } else if let Some(model) = self.boundary_layer_shear_model() {
3989            self.get_wind_at_altitude(
3990                crate::wind_shear::shear_height_agl_m(position.y, self.inputs.muzzle_height),
3991                model,
3992            )
3993        } else {
3994            *wind_vector
3995        };
3996        let actual_wind =
3997            crate::derivatives::level_vector_to_shot_frame(actual_wind, self.inputs.shooting_angle);
3998
3999        let relative_velocity = velocity - actual_wind;
4000        let velocity_magnitude = relative_velocity.magnitude();
4001
4002        if velocity_magnitude < 0.001 {
4003            return self.gravity_acceleration();
4004        }
4005
4006        // MBA-1136 (rank 30): the air at the LOCAL substep altitude, not the frozen station
4007        // scalars, so density AND speed of sound vary with altitude (matters on elevated /
4008        // long-range shots; a no-op at the shooter altitude, where the ratio-based density
4009        // recovers the station value exactly). `station` was resolved once per solve by
4010        // station_air().
4011        //
4012        // MBA-1137: with downrange-segmented atmosphere, the zone selected by downrange distance
4013        // (position.x) replaces the station as the BASE (its T/P/RH, and a CIPM density ratio at
4014        // its RH), and the world-vertical altitude lapse multiplies on top of it, so the two
4015        // compose without double-counting. Magnus dynamic stability consumes the resulting local
4016        // density rather than freezing a launch-density correction.
4017        //
4018        // air_at_with_gravity is the engine's ONE per-step air lookup; every kernel family
4019        // (compute_derivatives, fast_integrate, the lean Monte Carlo) calls it too.
4020        let local_alt = crate::atmosphere::shot_frame_altitude(
4021            self.atmosphere.altitude,
4022            position.x,
4023            position.y,
4024            self.inputs.shooting_angle,
4025        );
4026        let local_air = crate::atmosphere::air_at_with_gravity(
4027            &KernelAtmosphere::Station(*station),
4028            self.atmo_sock.as_ref(),
4029            position.x,
4030            local_alt,
4031            self.gravity,
4032        );
4033        let (air_density, speed_of_sound) = (local_air.density_kg_m3, local_air.speed_of_sound_mps);
4034        // The Mach `drag_terms` looks the Cd up at (`calculate_drag_coefficient`'s
4035        // `velocity / speed_of_sound`), from the values passed to it below.
4036        #[cfg(test)]
4037        crate::atmosphere::air_trace::record_consumed(
4038            air_density,
4039            velocity_magnitude,
4040            velocity_magnitude / speed_of_sound,
4041        );
4042
4043        // Resolve the Cd and the retardation denominator through the shared resolver. MBA-1423's
4044        // per-point Cd goes through this same resolver (annotate_drag_coefficients), so the two
4045        // cannot drift apart; it is evaluated at the station speed of sound the result reports
4046        // Mach against, not at this step's local sound speed.
4047        let (cd, retard_denom) = self.drag_terms(velocity_magnitude, speed_of_sound);
4048
4049        // Convert velocity to fps (still used below outside the BC lookup).
4050        let velocity_fps = velocity_magnitude * 3.28084;
4051
4052        // Use proper ballistics retardation formula
4053        // This matches the proven formula from fast_trajectory.rs
4054        // The standard retardation factor converts Cd to drag deceleration
4055        // Note: velocity_fps already calculated above for BC segment lookup
4056        let cd_to_retard = crate::constants::CD_TO_RETARD;
4057        let standard_factor = cd * cd_to_retard;
4058        let density_scale = air_density / 1.225; // Scale relative to standard air (1.225 kg/m³)
4059
4060        // Drag acceleration in ft/s² then convert to m/s²
4061        let a_drag_ft_s2 =
4062            (velocity_fps * velocity_fps) * standard_factor * density_scale / retard_denom;
4063        let a_drag_m_s2 = a_drag_ft_s2 * 0.3048; // ft/s² to m/s²
4064
4065        // Apply drag opposite to velocity direction
4066        let drag_acceleration = -a_drag_m_s2 * (relative_velocity / velocity_magnitude);
4067
4068        // Total acceleration = drag + gravity. `shooting_angle` rotates gravity into the shot
4069        // frame for inclined fire; at 0 deg this is the normal vertical-only gravity vector.
4070        let mut accel = drag_acceleration + self.gravity_acceleration();
4071
4072        // Coriolis (Earth rotation). McCoy frame: X=downrange, Y=vertical, Z=lateral,
4073        // azimuth 0 = North. McCoy frame: X=downrange, Y=vertical, Z=lateral.
4074        if self.inputs.enable_coriolis {
4075            if let Some(lat_deg) = self.inputs.latitude {
4076                let omega_earth = 7.2921159e-5_f64; // rad/s
4077                let lat = lat_deg.to_radians();
4078                let az = self.inputs.shot_azimuth; // compass bearing (0=N), NOT the aiming offset
4079                                                   // Earth's angular velocity in level downrange/up/lateral axes.
4080                                                   // Projecting Omega=(0, Ω cosφ, Ω sinφ) [local E,N,U] by azimuth gives
4081                                                   // a NEGATIVE lateral component:
4082                                                   // lateral = downrange × up points East for a North shot, and
4083                                                   // Omega·East = -Ω cosφ sin(az). The previous code dropped that sign.
4084                let omega = Vector3::new(
4085                    omega_earth * lat.cos() * az.cos(),  // X: downrange
4086                    omega_earth * lat.sin(),             // Y: vertical
4087                    -omega_earth * lat.cos() * az.sin(), // Z: lateral (MBA-938: corrected sign)
4088                );
4089                let omega = crate::derivatives::level_vector_to_shot_frame(
4090                    omega,
4091                    self.inputs.shooting_angle,
4092                );
4093                // Coriolis acceleration is the physical -2 Ω×v (MBA-938). The old +2 with
4094                // an "output-preserving relabel" justification produced left-ward drift for
4095                // a North shot in the Northern hemisphere; first principles (and the +Eötvös
4096                // lift for East shots) require -2 with the corrected omega above.
4097                accel += -2.0 * omega.cross(velocity);
4098            }
4099        }
4100
4101        // Magnus force (spinning projectile). SI units in this solver.
4102        // MBA-1134 (rank 35): the canonical empirical Litz spin-drift post-process
4103        // (apply_spin_drift) already captures the gyroscopic yaw-of-repose lateral, so the
4104        // explicit Magnus side force must NOT be added on top of it — otherwise the two lateral
4105        // models stack and double-count the drift. Suppress Magnus whenever Litz spin drift is
4106        // active. (The inverse is intentionally NOT done: Litz is not suppressed when Magnus is on.)
4107        if self.inputs.enable_magnus
4108            && !self.inputs.use_enhanced_spin_drift
4109            && self.inputs.bullet_diameter > 0.0
4110            && self.inputs.twist_rate > 0.0
4111        {
4112            let diameter_m = self.inputs.bullet_diameter;
4113            let (spin_rad_s, spin_param) = crate::spin_drift::calculate_magnus_spin_state(
4114                self.inputs.muzzle_velocity,
4115                velocity_magnitude,
4116                self.inputs.twist_rate,
4117                diameter_m,
4118            );
4119            // Mach and dynamic stability both use the LOCAL atmosphere recomputed above.
4120            let mach = velocity_magnitude / speed_of_sound;
4121
4122            // Imperial conversions for the stability / yaw-of-repose helpers.
4123            let d_in = self.inputs.bullet_diameter / 0.0254;
4124            let m_gr = self.inputs.bullet_mass / crate::constants::GRAINS_TO_KG;
4125            let l_in = if self.inputs.bullet_length > 0.0 {
4126                self.inputs.bullet_length / 0.0254
4127            } else {
4128                // MBA-1135: mass-based length estimate (was a mass-blind 4.5-caliber default).
4129                let est_m = crate::stability::estimate_bullet_length_m(
4130                    self.inputs.bullet_diameter,
4131                    self.inputs.bullet_mass,
4132                );
4133                if est_m > 0.0 {
4134                    est_m / 0.0254
4135                } else {
4136                    4.5 * d_in
4137                }
4138            };
4139            // Use current-flight Sg with the muzzle-set spin. The helper back-calculates the
4140            // effective twist from fixed spin and current airspeed, so Sg and yaw of repose grow
4141            // downrange instead of remaining tied to launch conditions.
4142            let sg = crate::spin_drift::calculate_dynamic_stability(
4143                m_gr,
4144                velocity_magnitude,
4145                spin_rad_s,
4146                d_in,
4147                l_in,
4148                air_density,
4149            );
4150
4151            // Yaw of repose (radians); zero for unstable bullets (Sg <= 1).
4152            let (yaw_rad, _) = crate::spin_drift::calculate_yaw_of_repose_with_gravity(
4153                sg,
4154                velocity_magnitude,
4155                spin_rad_s,
4156                0.0, // crosswind handled elsewhere
4157                0.0, // pitch rate not tracked
4158                air_density,
4159                d_in,
4160                l_in,
4161                m_gr,
4162                mach,
4163                "match",
4164                false,
4165                self.gravity,
4166            );
4167
4168            // Proper McCoy Magnus FORCE: F = q S C_Npa (pd/2V) sin(alpha_R).
4169            let c_np = crate::derivatives::calculate_magnus_moment_coefficient(mach);
4170            let area = std::f64::consts::PI * (diameter_m / 2.0).powi(2);
4171            let magnus_force = 0.5
4172                * air_density
4173                * velocity_magnitude.powi(2)
4174                * area
4175                * c_np
4176                * spin_param
4177                * yaw_rad.sin();
4178
4179            // The yaw of repose is lateral, so its Magnus force follows gravity projected normal
4180            // to flight (down for right-hand twist). Lateral yaw lift belongs to the separate Litz
4181            // spin-drift model and must not be synthesized from this Magnus magnitude.
4182            if magnus_force.abs() > 1e-12 {
4183                if let Some(dir) = crate::derivatives::yaw_of_repose_magnus_direction(
4184                    relative_velocity,
4185                    self.gravity_acceleration(),
4186                    self.inputs.is_twist_right,
4187                ) {
4188                    accel += (magnus_force / self.inputs.bullet_mass) * dir;
4189                }
4190            }
4191        }
4192
4193        accel
4194    }
4195
4196    /// The reference drag coefficient and the retardation denominator this solver divides by,
4197    /// at one speed.
4198    ///
4199    /// This is the single place the two are resolved. `calculate_acceleration` divides one by
4200    /// the other to produce drag; [`Self::effective_drag_coefficient`] recombines them into the
4201    /// projectile's own Cd for reporting (MBA-1423). Keeping both callers on one resolver is
4202    /// deliberate: a second copy of the BC-precedence ladder below is exactly the kind of
4203    /// duplicate that drifts silently once someone edits one of them.
4204    ///
4205    /// The denominator is a BC (lb/in²) for a G-model and for a custom table flown as a
4206    /// reference curve (`custom_drag_reference`), and the sectional density for a custom table
4207    /// flown as the projectile's own curve, because that table already supplies the
4208    /// projectile's actual Cd (see [`BallisticInputs::custom_drag_denominator`]).
4209    fn drag_terms(&self, velocity_magnitude: f64, speed_of_sound: f64) -> (f64, f64) {
4210        let cd = self.calculate_drag_coefficient(velocity_magnitude, speed_of_sound);
4211
4212        let velocity_fps = velocity_magnitude * 3.28084;
4213
4214        // Match the other solver families' BC precedence: enabled velocity-keyed segments first,
4215        // then legacy Mach-keyed segments, then the scalar BC. `use_bc_segments` gates velocity
4216        // tables, while explicit Mach segments remain active when it is false; derivatives.rs and
4217        // the fast solver preserve that legacy contract for callers that provide a Mach table.
4218        let (base_bc, bc_from_segments) = if let Some(segments) = self
4219            .inputs
4220            .bc_segments_data
4221            .as_ref()
4222            .filter(|segments| self.inputs.use_bc_segments && !segments.is_empty())
4223        {
4224            // Find matching segment for current velocity.
4225            (
4226                crate::bc_estimation::velocity_segment_bc(
4227                    velocity_fps,
4228                    segments,
4229                    self.inputs.bc_value,
4230                ),
4231                true,
4232            )
4233        } else if let Some(segments) = self
4234            .inputs
4235            .bc_segments
4236            .as_ref()
4237            .filter(|segments| !segments.is_empty())
4238        {
4239            (
4240                crate::derivatives::interpolated_bc(
4241                    velocity_magnitude / speed_of_sound,
4242                    segments,
4243                    Some(&self.inputs),
4244                ),
4245                true,
4246            )
4247        } else {
4248            (self.inputs.bc_value, false)
4249        };
4250
4251        // Segment tables already own the velocity-dependent BC shape. Stacking the empirical
4252        // cluster ladder on top would apply that shape twice (MBA-1175). Cluster correction is
4253        // therefore only a fallback for a scalar BC, regardless of which explicit segment
4254        // representation supplied the active value.
4255        let effective_bc = if bc_from_segments {
4256            base_bc
4257        } else {
4258            self.apply_cluster_bc_correction(base_bc, velocity_fps)
4259        };
4260        // The scalar BC is validated at the solve boundary. Retain a small denominator floor for
4261        // explicit segment tables, whose interpolated values are independent caller data.
4262        let effective_bc = effective_bc.max(1e-6);
4263
4264        // When a custom drag table is active, calculate_drag_coefficient returned the table's
4265        // Cd. For the projectile's own curve the retardation denominator must be the sectional
4266        // density (lb/in²), not a BC: Cd_own / SD == Cd_ref / BC. A reference curve divides by
4267        // the BC resolved above instead, band and all, exactly as a G-model does
4268        // (see BallisticInputs::custom_drag_denominator).
4269        let retard_denom = if self.inputs.custom_drag_table.is_some() {
4270            self.inputs.custom_drag_denominator(effective_bc)
4271        } else {
4272            effective_bc
4273        };
4274
4275        (cd, retard_denom)
4276    }
4277
4278    /// The projectile's own drag coefficient at one speed — the curve a shooter would compare
4279    /// against a measured CDM trace, not the reference-table Cd (MBA-1423).
4280    ///
4281    /// A G-model Cd describes the *standard* projectile, so reporting it directly would hand a
4282    /// consumer the same G7 curve no matter which bullet was flown. Scaling by the form factor
4283    /// `SD / BC` converts it to this projectile's actual Cd, from the identity that both
4284    /// descriptions must produce the same retardation:
4285    ///
4286    /// ```text
4287    /// Cd_own / SD == Cd_ref / BC   =>   Cd_own == Cd_ref * SD / BC
4288    /// ```
4289    ///
4290    /// Because the denominator comes from the same internal resolver the integrator divides by,
4291    /// a velocity- or Mach-segmented BC
4292    /// carries into the result and its band steps appear in the reported curve. The same
4293    /// expression is correct for both readings of a custom drag table: for the projectile's own
4294    /// curve the denominator *is* the sectional density and the scale factor collapses to 1,
4295    /// and for a reference curve (`custom_drag_reference`) the denominator is the resolved BC,
4296    /// exactly as for a G-model.
4297    ///
4298    /// Returns `None` when the projectile's mass or diameter is unavailable, since sectional
4299    /// density — and therefore the projectile's own Cd — is undefined without both.
4300    pub fn effective_drag_coefficient(
4301        &self,
4302        velocity_magnitude: f64,
4303        speed_of_sound: f64,
4304    ) -> Option<f64> {
4305        if !velocity_magnitude.is_finite() || speed_of_sound <= 1e-9 {
4306            return None;
4307        }
4308        let sectional_density = self.inputs.sectional_density_lb_in2()?;
4309        let (cd, retard_denom) = self.drag_terms(velocity_magnitude, speed_of_sound);
4310        if retard_denom <= 0.0 {
4311            return None;
4312        }
4313        let effective = cd * sectional_density / retard_denom;
4314        effective.is_finite().then_some(effective)
4315    }
4316
4317    /// Fill every point's [`TrajectoryPoint::drag_coefficient`] in one pass (MBA-1423).
4318    ///
4319    /// Deliberately a pass over the finished vector rather than a value set where points are
4320    /// built: this solver constructs them in several places — terminal interpolation plus one
4321    /// loop per integrator family — and a pass covers a site added later for free.
4322    ///
4323    /// `speed_of_sound` must be the station value the result reports Mach against, so that a
4324    /// consumer plotting Cd against Mach gets a self-consistent pair. Feeding each step's local
4325    /// speed of sound instead would attribute a Cd to a Mach the document never shows.
4326    fn annotate_drag_coefficients(&self, points: &mut [TrajectoryPoint], speed_of_sound: f64) {
4327        for point in points.iter_mut() {
4328            point.drag_coefficient =
4329                self.effective_drag_coefficient(point.velocity_magnitude, speed_of_sound);
4330        }
4331    }
4332
4333    fn calculate_drag_coefficient(&self, velocity: f64, speed_of_sound: f64) -> f64 {
4334        let mach = velocity / speed_of_sound;
4335
4336        // MBA-940: a user-supplied custom drag table is the final Cd, used as-is — no G-model
4337        // lookup, no transonic shape correction, no form factor. The supplied curve already
4338        // encodes the projectile's true drag, so applying those would distort/double-count it.
4339        if let Some(ref table) = self.inputs.custom_drag_table {
4340            // MBA-1357: cd_scale is a single whole-curve drag multiplier applied here, at the
4341            // Cd lookup site. The Mach-keyed DSF table (truing_dsf.rs) is a SEPARATE, drop-only
4342            // post-processing correction applied to a solved TrajectoryResult's points after
4343            // integration finishes — it never touches this Cd/drag-force computation.
4344            return table.interpolate(mach) * self.inputs.cd_scale;
4345        }
4346
4347        // A published/measured BC already contains the projectile form factor (BC = SD / i).
4348        // Multiplying reference Cd by a second name-derived factor double-counts shape.
4349        crate::drag::get_drag_coefficient(mach, &self.inputs.bc_type)
4350    }
4351}
4352
4353// Monte Carlo parameters
4354#[derive(Debug, Clone)]
4355pub struct MonteCarloParams {
4356    pub num_simulations: usize,
4357    pub velocity_std_dev: f64,
4358    pub angle_std_dev: f64,
4359    pub bc_std_dev: f64,
4360    pub wind_speed_std_dev: f64,
4361    pub target_distance: Option<f64>,
4362    pub base_wind_speed: f64,
4363    pub base_wind_direction: f64,
4364    pub azimuth_std_dev: f64, // Horizontal aiming variation in radians
4365}
4366
4367impl Default for MonteCarloParams {
4368    fn default() -> Self {
4369        Self {
4370            num_simulations: 1000,
4371            velocity_std_dev: 1.0,
4372            angle_std_dev: 0.001,
4373            bc_std_dev: 0.01,
4374            wind_speed_std_dev: 1.0,
4375            target_distance: None,
4376            base_wind_speed: 0.0,
4377            base_wind_direction: 0.0,
4378            azimuth_std_dev: 0.001, // Default horizontal spread ~0.057 degrees
4379        }
4380    }
4381}
4382
4383// Monte Carlo results
4384#[derive(Debug, Clone)]
4385pub struct MonteCarloResults {
4386    pub ranges: Vec<f64>,
4387    pub impact_velocities: Vec<f64>,
4388    /// Deviations from the baseline point of aim at the target plane.
4389    ///
4390    /// A sample that falls short of the plane is encoded as
4391    /// `(0, TARGET_NOT_REACHED_SENTINEL_M, 0)` so it remains aligned with
4392    /// `ranges` and `impact_velocities` and still counts as a miss.
4393    pub impact_positions: Vec<Vector3<f64>>,
4394}
4395
4396/// Default hit-zone radius (meters) around the point of aim at the target plane — a 30 cm
4397/// circle. Shared by the CLI, FFI, and WASM so "hit probability" means the same thing everywhere.
4398pub const DEFAULT_HIT_RADIUS_M: f64 = 0.3;
4399
4400/// Vertical-position marker for a Monte Carlo sample that never reached the target plane.
4401///
4402/// The marker preserves the equal-length result-vector and C-ABI contract. Exclude marked
4403/// positions from target-plane dispersion statistics, but keep them in the denominator for hit
4404/// probability because they are definite misses.
4405pub const TARGET_NOT_REACHED_SENTINEL_M: f64 = -1.0e9;
4406
4407impl MonteCarloResults {
4408    /// Whether an encoded impact position represents a finite arrival at the target plane.
4409    pub fn position_reached_target(position: &Vector3<f64>) -> bool {
4410        position.iter().all(|component| component.is_finite())
4411            && position.y != TARGET_NOT_REACHED_SENTINEL_M
4412    }
4413
4414    /// Number of recorded simulations that reached the target plane.
4415    pub fn target_arrival_count(&self) -> usize {
4416        self.impact_positions
4417            .iter()
4418            .filter(|position| Self::position_reached_target(position))
4419            .count()
4420    }
4421
4422    /// Fraction of recorded simulations that fell short of (or otherwise failed to produce a
4423    /// finite position at) the target plane.
4424    pub fn target_shortfall_fraction(&self) -> f64 {
4425        if self.impact_positions.is_empty() {
4426            return 0.0;
4427        }
4428        (self.impact_positions.len() - self.target_arrival_count()) as f64
4429            / self.impact_positions.len() as f64
4430    }
4431
4432    /// Upper-median radial miss among samples that reached the target plane.
4433    ///
4434    /// This preserves the CLI's historical radial-to-baseline "CEP (approx)" convention while
4435    /// preventing the finite target-shortfall marker from becoming the median (MBA-1159).
4436    /// Returns `None` when no recorded simulation reached the target plane.
4437    pub fn target_plane_cep(&self) -> Option<f64> {
4438        let mut radial_misses: Vec<f64> = self
4439            .impact_positions
4440            .iter()
4441            .filter(|position| Self::position_reached_target(position))
4442            .map(Vector3::norm)
4443            .filter(|miss| miss.is_finite())
4444            .collect();
4445        radial_misses.sort_by(f64::total_cmp);
4446        if radial_misses.is_empty() {
4447            None
4448        } else {
4449            Some(radial_misses[radial_misses.len() / 2])
4450        }
4451    }
4452
4453    /// Fraction of simulations whose impact at the target plane lands within `hit_radius_m`
4454    /// of the point of aim. `impact_positions` are deviations from the baseline at the target
4455    /// plane (the downrange component is 0), so the vector norm is the radial miss distance.
4456    /// Samples that fall short of the target remain in the denominator and count as misses.
4457    /// Returns 0.0 when there are no samples.
4458    ///
4459    /// Single source of truth for hit probability — previously the CLI used a range-precision
4460    /// notion and the FFI a position notion with a redundant clause, so they disagreed.
4461    pub fn hit_probability(&self, hit_radius_m: f64) -> f64 {
4462        if self.impact_positions.is_empty() {
4463            return 0.0;
4464        }
4465        let hits = self
4466            .impact_positions
4467            .iter()
4468            .filter(|position| Self::position_is_hit(position, hit_radius_m))
4469            .count();
4470        hits as f64 / self.impact_positions.len() as f64
4471    }
4472
4473    /// Whether one encoded impact position is a hit inside `hit_radius_m` of the point of aim.
4474    ///
4475    /// The single source of truth for the hit predicate itself, as
4476    /// [`hit_probability`](Self::hit_probability) is for the ratio. Both that method and the
4477    /// adaptive driver ([`run_monte_carlo_adaptive_seeded`]) call this, so "hit" means the
4478    /// same thing whether it was counted over a retained result vector or streamed one trial
4479    /// at a time and then discarded.
4480    ///
4481    /// A sample that never reached the target plane is a definite miss, never a hit: the
4482    /// shortfall marker's norm is enormous, but the marker is excluded explicitly rather than
4483    /// left to depend on that.
4484    pub fn position_is_hit(position: &Vector3<f64>, hit_radius_m: f64) -> bool {
4485        Self::position_reached_target(position) && position.norm() < hit_radius_m
4486    }
4487
4488    /// Fixed-`n` Wilson companion to [`hit_probability`](Self::hit_probability): the same point
4489    /// estimate, plus a confidence interval for it and the `n` behind it.
4490    ///
4491    /// Returns `(p_hat, (ci_low, ci_high), n)`. This is a *composition* of two existing
4492    /// functions, not a second derivation of either: `p_hat` is
4493    /// [`hit_probability`](Self::hit_probability) called directly, and the bounds are
4494    /// [`wilson_interval`] over the hit count and `impact_positions.len()`. The denominator is
4495    /// therefore identical -- samples that fell short of the target plane are counted as
4496    /// misses in `n`, exactly as `hit_probability` counts them -- and the two can never drift
4497    /// apart under maintenance.
4498    ///
4499    /// # When this is the wrong interval
4500    ///
4501    /// A fixed-`n` interval is only valid if `n` was fixed *before* the data was seen. Use
4502    /// this for a run of a pre-declared `num_simulations`. If the sample count was instead
4503    /// chosen by watching the results -- stopping once the interval looked tight enough --
4504    /// this interval has no coverage guarantee at all; use [`run_monte_carlo_adaptive_seeded`],
4505    /// whose interval is anytime-valid, for that.
4506    ///
4507    /// With no samples the result is `(0.0, (0.0, 1.0), 0)`: the `0.0` that `hit_probability`
4508    /// reports, alongside the total-ignorance interval `wilson_interval` reports at `n == 0`.
4509    pub fn hit_probability_wilson(
4510        &self,
4511        hit_radius_m: f64,
4512        level: ConfidenceLevel,
4513    ) -> (f64, (f64, f64), u64) {
4514        let trials = self.impact_positions.len() as u64;
4515        let hits = self
4516            .impact_positions
4517            .iter()
4518            .filter(|position| Self::position_is_hit(position, hit_radius_m))
4519            .count() as u64;
4520        (
4521            self.hit_probability(hit_radius_m),
4522            wilson_interval(hits, trials, level),
4523            trials,
4524        )
4525    }
4526
4527    /// Fraction of simulations whose impact at the target plane lands within the axis-aligned
4528    /// rectangle `width_m` (lateral, Z) x `height_m` (vertical, Y) centered on the point of aim
4529    /// — i.e. within `width_m / 2` of center laterally AND `height_m / 2` of center vertically.
4530    ///
4531    /// This is the WEZ (Weapon Employment Zone, MBA-1317) counterpart of [`hit_probability`]'s
4532    /// circular radius for rectangular target sizes (e.g. an 18"x30" steel plate). Samples that
4533    /// fall short of the target plane remain in the denominator and count as misses, matching
4534    /// `hit_probability`'s convention. Returns 0.0 when there are no samples or when either
4535    /// dimension is non-positive.
4536    ///
4537    /// [`hit_probability`]: Self::hit_probability
4538    pub fn rect_hit_probability(&self, width_m: f64, height_m: f64) -> f64 {
4539        let dimensions_invalid =
4540            width_m.is_nan() || width_m <= 0.0 || height_m.is_nan() || height_m <= 0.0;
4541        if self.impact_positions.is_empty() || dimensions_invalid {
4542            return 0.0;
4543        }
4544        let half_width = width_m / 2.0;
4545        let half_height = height_m / 2.0;
4546        let hits = self
4547            .impact_positions
4548            .iter()
4549            .filter(|position| {
4550                Self::position_reached_target(position)
4551                    && position.z.abs() <= half_width
4552                    && position.y.abs() <= half_height
4553            })
4554            .count();
4555        hits as f64 / self.impact_positions.len() as f64
4556    }
4557}
4558
4559fn wind_from_signed_speed_sample(
4560    signed_speed: f64,
4561    sampled_direction: f64,
4562    vertical_speed: f64,
4563) -> WindConditions {
4564    // The base wind's vertical component rides along un-dispersed: vertical wind is a
4565    // systematic input (MBA-728), not a sampled dispersion source. Dropping it here
4566    // would make every per-sample solve disagree with the baseline solve by the whole
4567    // vertical deflection — a phantom bias in the MC statistics.
4568    if signed_speed < 0.0 {
4569        WindConditions {
4570            speed: -signed_speed,
4571            direction: sampled_direction + std::f64::consts::PI,
4572            vertical_speed,
4573        }
4574    } else {
4575        WindConditions {
4576            speed: signed_speed,
4577            direction: sampled_direction,
4578            vertical_speed,
4579        }
4580    }
4581}
4582
4583struct MonteCarloWindSampler {
4584    speed: rand_distr::Normal<f64>,
4585    direction: rand_distr::Normal<f64>,
4586    /// Base wind's vertical component, carried into every sample un-dispersed.
4587    vertical_speed: f64,
4588}
4589
4590impl MonteCarloWindSampler {
4591    fn new(
4592        base_wind: &WindConditions,
4593        wind_speed_std_dev: f64,
4594        wind_direction_std_dev: f64,
4595    ) -> Result<Self, BallisticsError> {
4596        use rand_distr::Normal;
4597
4598        if !wind_direction_std_dev.is_finite() || wind_direction_std_dev < 0.0 {
4599            return Err("Wind direction standard deviation must be finite and non-negative".into());
4600        }
4601
4602        let speed = Normal::new(base_wind.speed, wind_speed_std_dev)
4603            .map_err(|e| format!("Invalid wind speed distribution: {e}"))?;
4604        let direction = Normal::new(base_wind.direction, wind_direction_std_dev)
4605            .map_err(|e| format!("Invalid wind direction distribution: {e}"))?;
4606        Ok(Self {
4607            speed,
4608            direction,
4609            vertical_speed: base_wind.vertical_speed,
4610        })
4611    }
4612
4613    fn sample<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> WindConditions {
4614        use rand_distr::Distribution;
4615
4616        wind_from_signed_speed_sample(
4617            self.speed.sample(rng),
4618            self.direction.sample(rng),
4619            self.vertical_speed,
4620        )
4621    }
4622}
4623
4624/// One Monte Carlo trial's recorded outcome: the three quantities the legacy result vectors
4625/// hold, for one sample.
4626#[derive(Debug, Clone, Copy)]
4627struct TrialOutcome {
4628    /// Ground-impact range (m), recorded for every sample regardless of the target plane
4629    /// (MBA-967).
4630    range: f64,
4631    /// Ground-impact velocity (m/s), likewise recorded for every sample.
4632    impact_velocity: f64,
4633    /// Deviation from the baseline point of aim at the target plane, or
4634    /// `(0, TARGET_NOT_REACHED_SENTINEL_M, 0)` when this sample fell short of it.
4635    impact_position: Vector3<f64>,
4636}
4637
4638/// The per-trial context of a Monte Carlo run: the baseline solve, the resolved target plane
4639/// and the five input distributions, all built once and reused by every trial.
4640///
4641/// Extracted verbatim from the body of
4642/// [`run_monte_carlo_with_wind_and_direction_std_dev_using_rng`] so the adaptive driver
4643/// ([`run_monte_carlo_adaptive_seeded`]) runs the *identical* trial rather than a second copy
4644/// of it that could drift out of agreement.
4645///
4646/// # The draw order is a compatibility contract
4647///
4648/// [`Self::sample_one_trial`] consumes exactly six draws from the caller's RNG, in this order:
4649/// muzzle-velocity delta, muzzle angle, ballistic coefficient, azimuth, wind speed, wind
4650/// direction. Changing the count or the order shifts every subsequent sample of an
4651/// already-seeded run, so `monte_carlo_seeded_tests::legacy_seeded_estimates_are_pinned_bit_for_bit`
4652/// pins a committed seed's output bit-for-bit as the check on it.
4653///
4654/// The distributions are also *constructed* in the order the original inline code constructed
4655/// them. That is not cosmetic: construction is where an invalid standard deviation is
4656/// rejected, so the order decides which malformed parameter a caller is told about first.
4657struct MonteCarloTrialSampler {
4658    base_inputs: BallisticInputs,
4659    atmosphere: AtmosphericConditions,
4660    /// Which of `atmosphere`'s temperature and pressure were supplied; every solve uses it.
4661    station_presence: StationAtmospherePresence,
4662    solver_max_range: f64,
4663    /// Resolved target plane: `params.target_distance` when the caller gave one, else the
4664    /// baseline solve's own max range.
4665    target_distance: f64,
4666    /// Baseline (undispersed) position at `target_distance`. Every trial's impact position is
4667    /// a deviation from this point.
4668    baseline_at_target: Vector3<f64>,
4669    velocity_delta_dist: rand_distr::Normal<f64>,
4670    angle_dist: rand_distr::Normal<f64>,
4671    bc_dist: rand_distr::Normal<f64>,
4672    wind_sampler: MonteCarloWindSampler,
4673    azimuth_dist: rand_distr::Normal<f64>,
4674}
4675
4676impl MonteCarloTrialSampler {
4677    /// Solves the baseline trajectory and builds the input distributions.
4678    ///
4679    /// Consumes no randomness -- every RNG draw happens in [`Self::sample_one_trial`].
4680    fn new(
4681        base_inputs: BallisticInputs,
4682        base_wind: &WindConditions,
4683        params: &MonteCarloParams,
4684        wind_direction_std_dev: f64,
4685        station_presence: StationAtmospherePresence,
4686    ) -> Result<Self, BallisticsError> {
4687        use rand_distr::Normal;
4688
4689        let atmosphere = AtmosphericConditions {
4690            temperature: base_inputs.temperature,
4691            pressure: base_inputs.pressure,
4692            humidity: base_inputs.humidity_percent,
4693            altitude: base_inputs.altitude,
4694        };
4695        let target_hint = params
4696            .target_distance
4697            .unwrap_or(base_inputs.target_distance);
4698        let solver_max_range = target_hint.max(1000.0) * 2.0;
4699
4700        // First, calculate baseline trajectory with no variations
4701        let mut baseline_solver = TrajectorySolver::new_with_station_presence(
4702            base_inputs.clone(),
4703            base_wind.clone(),
4704            atmosphere.clone(),
4705            station_presence,
4706        );
4707        baseline_solver.set_max_range(solver_max_range);
4708        let baseline_result = baseline_solver.solve()?;
4709
4710        // Determine target distance: use explicit target or baseline max range
4711        let target_distance = params.target_distance.unwrap_or(baseline_result.max_range);
4712
4713        // Get baseline position at target distance (interpolated)
4714        let baseline_at_target = baseline_result
4715            .position_at_range(target_distance)
4716            .ok_or("Could not interpolate baseline at target distance")?;
4717
4718        // Create normal distributions for variations
4719        // Sample muzzle velocity as a DELTA and apply it after TrajectorySolver::new resolves the
4720        // powder-temperature model. Sampling an absolute value here let a powder curve overwrite
4721        // every draw in the constructor, collapsing the requested dispersion to zero (MBA-1176).
4722        let velocity_delta_dist = Normal::new(0.0, params.velocity_std_dev)
4723            .map_err(|e| format!("Invalid velocity distribution: {}", e))?;
4724        let angle_dist = Normal::new(base_inputs.muzzle_angle, params.angle_std_dev)
4725            .map_err(|e| format!("Invalid angle distribution: {}", e))?;
4726        let bc_dist = Normal::new(base_inputs.bc_value, params.bc_std_dev)
4727            .map_err(|e| format!("Invalid BC distribution: {}", e))?;
4728        // Direction uncertainty is an independent angular quantity in radians. Do not derive it from
4729        // wind-speed uncertainty: meters/second cannot supply an angular standard deviation.
4730        let wind_sampler = MonteCarloWindSampler::new(
4731            base_wind,
4732            params.wind_speed_std_dev,
4733            wind_direction_std_dev,
4734        )?;
4735        let azimuth_dist = Normal::new(base_inputs.azimuth_angle, params.azimuth_std_dev)
4736            .map_err(|e| format!("Invalid azimuth distribution: {}", e))?;
4737
4738        Ok(Self {
4739            base_inputs,
4740            atmosphere,
4741            station_presence,
4742            solver_max_range,
4743            target_distance,
4744            baseline_at_target,
4745            velocity_delta_dist,
4746            angle_dist,
4747            bc_dist,
4748            wind_sampler,
4749            azimuth_dist,
4750        })
4751    }
4752
4753    /// Draws one trial: six RNG draws, one trajectory solve, one recorded outcome.
4754    ///
4755    /// `None` means the trial produced nothing to record -- either the solve failed, or it
4756    /// succeeded but the target plane could not be interpolated despite being within range (a
4757    /// defensive branch). Both were a bare `continue` in the original loop, i.e. the trial was
4758    /// dropped rather than counted as a miss, and callers must preserve that.
4759    ///
4760    /// All six draws happen *before* the solve, so a dropped trial still consumes exactly six
4761    /// draws and the RNG stream stays aligned with a run in which it succeeded.
4762    fn sample_one_trial<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> Option<TrialOutcome> {
4763        use rand_distr::Distribution;
4764
4765        // Create varied inputs
4766        let mut inputs = self.base_inputs.clone();
4767        let muzzle_velocity_delta = self.velocity_delta_dist.sample(&mut *rng);
4768        inputs.muzzle_angle = self.angle_dist.sample(&mut *rng);
4769        inputs.bc_value = self.bc_dist.sample(&mut *rng).max(0.01);
4770        inputs.azimuth_angle = self.azimuth_dist.sample(&mut *rng); // Add horizontal variation
4771
4772        // Create varied wind (now based on base wind conditions)
4773        let wind = self.wind_sampler.sample(&mut *rng);
4774
4775        // Run trajectory. The sampled velocity delta is applied to the SOLVER's inputs, after
4776        // TrajectorySolver::new has resolved any powder-temperature model -- see the MBA-1176
4777        // note on `velocity_delta_dist` above.
4778        let mut solver = TrajectorySolver::new_with_station_presence(
4779            inputs,
4780            wind,
4781            self.atmosphere.clone(),
4782            self.station_presence,
4783        );
4784        solver.inputs.muzzle_velocity =
4785            (solver.inputs.muzzle_velocity + muzzle_velocity_delta).max(0.0);
4786        solver.set_max_range(self.solver_max_range);
4787        // Skip failed simulations
4788        let result = solver.solve().ok()?;
4789
4790        // MBA-967: do NOT skip samples that fall short of the target. range/velocity are
4791        // recorded at GROUND IMPACT for EVERY sample, so "Mean Range" is the ground-impact
4792        // distribution — independent of target_distance and consistent with `trajectory`.
4793        // All three result vectors still grow together per sample, so the equal-length FFI
4794        // ABI (exposed under one count) is preserved.
4795        let impact_position = if result.max_range < self.target_distance {
4796            // This sample never reached the target plane -> definite miss. Keep the
4797            // encoded miss finite but far outside any practical target radius.
4798            Vector3::new(0.0, TARGET_NOT_REACHED_SENTINEL_M, 0.0)
4799        } else {
4800            // defensive: drop the whole sample (keeps the result vectors aligned)
4801            let pos_at_target = result.position_at_range(self.target_distance)?;
4802            // Deviation from baseline at the SAME target distance (McCoy): X = downrange
4803            // (0 here), Y = vertical (elevation), Z = lateral (windage). Muzzle-angle
4804            // sampling already models vertical pointing dispersion, so do not add a
4805            // second independent vertical pointing draw here.
4806            Vector3::new(
4807                0.0,
4808                pos_at_target.y - self.baseline_at_target.y,
4809                pos_at_target.z - self.baseline_at_target.z,
4810            )
4811        };
4812
4813        Some(TrialOutcome {
4814            range: result.max_range,
4815            impact_velocity: result.impact_velocity,
4816            impact_position,
4817        })
4818    }
4819}
4820
4821/// Run a Monte Carlo simulation (backwards compatibility).
4822///
4823/// Presence-blind: `base_inputs`' temperature and pressure go through the legacy
4824/// default-sentinel rule (see [`TrajectorySolver::new`]). See
4825/// [`run_monte_carlo_with_station_presence`].
4826pub fn run_monte_carlo(
4827    base_inputs: BallisticInputs,
4828    params: MonteCarloParams,
4829) -> Result<MonteCarloResults, BallisticsError> {
4830    run_monte_carlo_with_direction_std_dev(base_inputs, params, 0.0)
4831}
4832
4833/// Run Monte Carlo with an independent wind-direction standard deviation in radians.
4834///
4835/// The older [`run_monte_carlo`] entry point remains source compatible and delegates here with
4836/// zero direction uncertainty.
4837///
4838/// Presence-blind; see [`run_monte_carlo_with_station_presence`].
4839pub fn run_monte_carlo_with_direction_std_dev(
4840    base_inputs: BallisticInputs,
4841    params: MonteCarloParams,
4842    wind_direction_std_dev: f64,
4843) -> Result<MonteCarloResults, BallisticsError> {
4844    let base_wind = WindConditions {
4845        speed: params.base_wind_speed,
4846        direction: params.base_wind_direction,
4847        vertical_speed: 0.0,
4848    };
4849    run_monte_carlo_with_wind_and_direction_std_dev(
4850        base_inputs,
4851        base_wind,
4852        params,
4853        wind_direction_std_dev,
4854    )
4855}
4856
4857/// Run a Monte Carlo simulation with an explicit base wind.
4858///
4859/// Presence-blind; see [`run_monte_carlo_with_station_presence`].
4860pub fn run_monte_carlo_with_wind(
4861    base_inputs: BallisticInputs,
4862    base_wind: WindConditions,
4863    params: MonteCarloParams,
4864) -> Result<MonteCarloResults, BallisticsError> {
4865    run_monte_carlo_with_wind_and_direction_std_dev(base_inputs, base_wind, params, 0.0)
4866}
4867
4868/// Run Monte Carlo with explicit base wind and independent direction uncertainty in radians.
4869///
4870/// The older [`run_monte_carlo_with_wind`] entry point delegates here with zero direction
4871/// uncertainty, preserving its API while removing the former speed-to-angle unit conflation.
4872///
4873/// Presence-blind; see [`run_monte_carlo_with_station_presence`].
4874pub fn run_monte_carlo_with_wind_and_direction_std_dev(
4875    base_inputs: BallisticInputs,
4876    base_wind: WindConditions,
4877    params: MonteCarloParams,
4878    wind_direction_std_dev: f64,
4879) -> Result<MonteCarloResults, BallisticsError> {
4880    run_monte_carlo_with_station_presence(
4881        base_inputs,
4882        base_wind,
4883        params,
4884        wind_direction_std_dev,
4885        None,
4886        StationAtmospherePresence::NEITHER,
4887    )
4888}
4889
4890/// Run Monte Carlo knowing which of `base_inputs`' temperature and pressure the caller
4891/// supplied (0.49.0).
4892///
4893/// `seed: None` draws from the process-global RNG, as
4894/// [`run_monte_carlo_with_wind_and_direction_std_dev`] does; `Some(seed)` seeds a `StdRng`,
4895/// as [`run_monte_carlo_with_wind_and_direction_std_dev_seeded`] does. Every trial and the
4896/// baseline solve resolve the station air with `station_presence` (see
4897/// [`TrajectorySolver::new_with_station_presence`]): a supplied temperature or pressure flies
4898/// as given, an omitted one keeps the legacy default-sentinel rule. With
4899/// [`StationAtmospherePresence::NEITHER`] this is bit-identical to those two functions.
4900pub fn run_monte_carlo_with_station_presence(
4901    base_inputs: BallisticInputs,
4902    base_wind: WindConditions,
4903    params: MonteCarloParams,
4904    wind_direction_std_dev: f64,
4905    seed: Option<u64>,
4906    station_presence: StationAtmospherePresence,
4907) -> Result<MonteCarloResults, BallisticsError> {
4908    match seed {
4909        None => {
4910            let mut rng = rand::rng();
4911            run_monte_carlo_with_wind_and_direction_std_dev_using_rng(
4912                base_inputs,
4913                base_wind,
4914                params,
4915                wind_direction_std_dev,
4916                station_presence,
4917                &mut rng,
4918            )
4919        }
4920        Some(seed) => {
4921            use rand::{rngs::StdRng, SeedableRng};
4922            let mut rng = StdRng::seed_from_u64(seed);
4923            run_monte_carlo_with_wind_and_direction_std_dev_using_rng(
4924                base_inputs,
4925                base_wind,
4926                params,
4927                wind_direction_std_dev,
4928                station_presence,
4929                &mut rng,
4930            )
4931        }
4932    }
4933}
4934
4935/// Run Monte Carlo with an explicit PRNG seed, for deterministic/reproducible output.
4936///
4937/// Otherwise identical to [`run_monte_carlo_with_wind_and_direction_std_dev`], which draws
4938/// from the process-global RNG instead. Intended for callers that need repeatable results
4939/// across runs — e.g. tests, or a WEZ (Weapon Employment Zone, MBA-1317) sweep that a caller
4940/// wants to reproduce exactly while tuning target size or wind-call error.
4941///
4942/// Presence-blind; see [`run_monte_carlo_with_station_presence`].
4943pub fn run_monte_carlo_with_wind_and_direction_std_dev_seeded(
4944    base_inputs: BallisticInputs,
4945    base_wind: WindConditions,
4946    params: MonteCarloParams,
4947    wind_direction_std_dev: f64,
4948    seed: u64,
4949) -> Result<MonteCarloResults, BallisticsError> {
4950    run_monte_carlo_with_station_presence(
4951        base_inputs,
4952        base_wind,
4953        params,
4954        wind_direction_std_dev,
4955        Some(seed),
4956        StationAtmospherePresence::NEITHER,
4957    )
4958}
4959
4960fn run_monte_carlo_with_wind_and_direction_std_dev_using_rng<R: rand::Rng + ?Sized>(
4961    base_inputs: BallisticInputs,
4962    base_wind: WindConditions,
4963    params: MonteCarloParams,
4964    wind_direction_std_dev: f64,
4965    station_presence: StationAtmospherePresence,
4966    rng: &mut R,
4967) -> Result<MonteCarloResults, BallisticsError> {
4968    let mut ranges = Vec::new();
4969    let mut impact_velocities = Vec::new();
4970    let mut impact_positions = Vec::new();
4971
4972    let sampler = MonteCarloTrialSampler::new(
4973        base_inputs,
4974        &base_wind,
4975        &params,
4976        wind_direction_std_dev,
4977        station_presence,
4978    )?;
4979
4980    for _ in 0..params.num_simulations {
4981        // A dropped trial pushes nothing at all, exactly as the original `continue` arms did,
4982        // so all three vectors stay equal-length (the FFI exposes them under one count) --
4983        // they are simply shorter than `num_simulations`.
4984        if let Some(outcome) = sampler.sample_one_trial(rng) {
4985            ranges.push(outcome.range);
4986            impact_velocities.push(outcome.impact_velocity);
4987            impact_positions.push(outcome.impact_position);
4988        }
4989    }
4990
4991    if ranges.is_empty() {
4992        return Err("No successful simulations".into());
4993    }
4994
4995    Ok(MonteCarloResults {
4996        ranges,
4997        impact_velocities,
4998        impact_positions,
4999    })
5000}
5001
5002/// Schema version of [`AdaptiveMcReportV1`]'s JSON wire form.
5003pub const MC_ADAPTIVE_SCHEMA_VERSION_V1: u32 = 1;
5004
5005/// The value [`AdaptiveMcReportV1::method`] always carries: Robbins' beta-binomial mixture
5006/// confidence sequence, revision 1.
5007///
5008/// Named so a consumer can branch on the estimator rather than on the schema version -- the
5009/// schema can gain fields without the statistics changing, and the statistics could be
5010/// replaced without the field set changing.
5011pub const MC_ADAPTIVE_METHOD_V1: &str = "anytime_beta_binomial_mixture_cs_v1";
5012
5013/// The four disclosures every [`AdaptiveMcReportV1`] carries, in order.
5014///
5015/// These are stated in the payload itself rather than only in this crate's documentation,
5016/// because the payload is what travels: a consumer that renders a hit probability and an
5017/// interval has everything it needs to over-claim, and these four sentences are what stop it.
5018/// In order they disclose (0) that the interval covers sampling error only, not model error;
5019/// (1) that stopping early is legitimate here specifically because the sequence is
5020/// anytime-valid; (2) that the input dispersions are independent normals with no modeled
5021/// correlation; and (3) how the continuous statistics were accumulated and which denominator
5022/// the hit probability uses.
5023///
5024/// Pinned per-index, full-string, by
5025/// `monte_carlo_seeded_tests::adaptive_report_carries_schema_method_and_all_four_assumptions`.
5026pub const MC_ADAPTIVE_ASSUMPTIONS_V1: [&str; 4] = [
5027    "Sampling uncertainty only: intervals cover Monte Carlo sampling error, not model error in the trajectory solver or its inputs.",
5028    "Anytime-valid stopping: the beta-binomial mixture confidence sequence keeps its coverage guarantee despite stopping the moment the target half-width is met.",
5029    "Input dispersions are the independent normal distributions declared in MonteCarloParams; correlations between inputs are not modeled.",
5030    "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.",
5031];
5032
5033/// How precise the hit probability has to get, and how much sampling may be spent getting
5034/// there.
5035///
5036/// [`Default`] reproduces the legacy fixed-count run's sample size as the *floor*
5037/// (`min_samples: 1_000`, which is [`MonteCarloParams::default`]'s `num_simulations`) and then
5038/// keeps going, in batches, until the interval is tight enough or the ceiling is hit.
5039#[derive(Debug, Clone)]
5040pub struct McConvergence {
5041    /// Confidence level of the reported interval.
5042    pub level: ConfidenceLevel,
5043    /// Stop once the confidence sequence's half-width is at or below this, in probability
5044    /// units. `0.02` means "the hit probability is known to about +-2 percentage points".
5045    pub target_half_width: f64,
5046    /// Never stop before this many trials, even if the interval is already tight. Guards
5047    /// against an early run of all-hits or all-misses producing a narrow interval off a
5048    /// handful of trials.
5049    pub min_samples: u64,
5050    /// Never run more than this many trials, even if the interval is still wide. This is what
5051    /// bounds the wall time of an unreachable `target_half_width`.
5052    pub max_samples: u64,
5053    /// How many trials to run between convergence checks. Larger batches check less often (a
5054    /// `bounds()` call is two 200-step bisections); smaller batches can stop sooner.
5055    pub batch_size: u64,
5056}
5057
5058impl Default for McConvergence {
5059    fn default() -> Self {
5060        Self {
5061            level: ConfidenceLevel::P95,
5062            target_half_width: 0.02,
5063            min_samples: 1_000,
5064            max_samples: 100_000,
5065            batch_size: 500,
5066        }
5067    }
5068}
5069
5070impl McConvergence {
5071    /// Rejects a configuration that cannot produce a meaningful run, naming the offending
5072    /// field.
5073    ///
5074    /// Checked once up front rather than defended against inside the loop: a zero
5075    /// `batch_size` would spin forever making no progress, and a non-positive or `NaN`
5076    /// `target_half_width` can never be met, so both would surface as a hang or a silent
5077    /// max-samples cap instead of an error the caller can read. `NaN` is caught by the
5078    /// `is_finite` test -- `NaN <= 0.0` is `false`, so a bare comparison would let it through.
5079    pub fn validate(&self) -> Result<(), String> {
5080        if !self.target_half_width.is_finite() || self.target_half_width <= 0.0 {
5081            return Err(format!(
5082                "McConvergence.target_half_width must be a finite value greater than zero (got {})",
5083                self.target_half_width
5084            ));
5085        }
5086        if self.batch_size == 0 {
5087            return Err("McConvergence.batch_size must be greater than zero".to_string());
5088        }
5089        if self.max_samples == 0 {
5090            return Err("McConvergence.max_samples must be greater than zero".to_string());
5091        }
5092        if self.max_samples < self.min_samples {
5093            return Err(format!(
5094                "McConvergence.max_samples ({}) must be at least McConvergence.min_samples ({})",
5095                self.max_samples, self.min_samples
5096            ));
5097        }
5098        Ok(())
5099    }
5100}
5101
5102/// Why an adaptive run stopped.
5103#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
5104#[serde(rename_all = "snake_case")]
5105pub enum McStopReason {
5106    /// The confidence sequence reached [`McConvergence::target_half_width`]. The reported
5107    /// precision is the requested precision.
5108    TargetHalfWidthMet,
5109    /// [`McConvergence::max_samples`] was exhausted first. The interval is whatever that many
5110    /// trials bought -- read `ci_low`/`ci_high`, not just `hit_probability`.
5111    MaxSamplesReached,
5112}
5113
5114/// The result of a confidence-controlled Monte Carlo run.
5115///
5116/// Produced by [`run_monte_carlo_adaptive_seeded`]. Unlike [`MonteCarloResults`] this retains
5117/// no per-trial data at all: the continuous quantities arrive as streaming [`Welford`] moments
5118/// and the hit/miss counts as a running confidence sequence, so a 100,000-trial run costs the
5119/// same memory as a 1,000-trial one.
5120#[derive(Debug, Clone, serde::Serialize)]
5121pub struct AdaptiveMcReportV1 {
5122    /// Always [`MC_ADAPTIVE_SCHEMA_VERSION_V1`].
5123    pub schema_version: u32,
5124    /// Always [`MC_ADAPTIVE_METHOD_V1`].
5125    pub method: String,
5126    /// Always the four sentences of [`MC_ADAPTIVE_ASSUMPTIONS_V1`], in order.
5127    pub assumptions: Vec<String>,
5128    /// Confidence level of `ci_low`/`ci_high`, as a whole-number percentage.
5129    pub confidence_percent: u32,
5130    /// Point estimate `S / n`: hits over all trials, including trials that never reached the
5131    /// target plane.
5132    pub hit_probability: f64,
5133    /// Lower bound of the anytime-valid interval.
5134    pub ci_low: f64,
5135    /// Upper bound of the anytime-valid interval.
5136    pub ci_high: f64,
5137    /// Trials actually folded into the statistics (`n`).
5138    pub samples: u64,
5139    /// Trials *drawn*, including any the solver could not complete.
5140    ///
5141    /// `attempts - samples` is the drop count. It is normally zero, and equals `samples`
5142    /// whenever it is -- but without this field a run with a 40% solver-failure rate is
5143    /// indistinguishable in the payload from a clean one at the same `samples`, which is the
5144    /// one thing `samples` alone cannot tell you. `attempts` is also what
5145    /// [`McConvergence::max_samples`] caps, so [`McStopReason::MaxSamplesReached`] always has
5146    /// `attempts == max_samples` -- but the reverse does not hold: a
5147    /// [`McStopReason::TargetHalfWidthMet`] stop on the very last batch can reach the same
5148    /// equality, so `attempts == max_samples` alone does not identify the stop reason.
5149    pub attempts: u64,
5150    /// Trials that reached the target plane -- the population behind the three at-target
5151    /// statistics below, and the `n` in their `n-1` standard deviations.
5152    ///
5153    /// This is the magnitude behind the asymmetry `assumptions[3]` discloses qualitatively:
5154    /// `mean_drop_at_target_m`, `mean_wind_drift_at_target_m` and `mean_impact_velocity_mps`
5155    /// describe these `arrivals` trials, while `hit_probability` is over all `samples` (a
5156    /// trial that fell short is a definite miss, so it is in that denominator but has no
5157    /// measured position to contribute). With `arrivals` well below `samples`, the at-target
5158    /// statistics describe only part of the run and this field is what says so.
5159    ///
5160    /// The fixed-count path exposes the same information as
5161    /// [`MonteCarloResults::target_arrival_count`] and
5162    /// [`MonteCarloResults::target_shortfall_fraction`]; `samples - arrivals` is the shortfall
5163    /// count and `1 - arrivals / samples` the shortfall fraction.
5164    pub arrivals: u64,
5165    /// Why the run stopped. Serializes as `"target_half_width_met"` / `"max_samples_reached"`.
5166    pub stop_reason: McStopReason,
5167    /// Hit-zone radius the probability was computed against.
5168    pub hit_radius_m: f64,
5169    /// Resolved target plane: `params.target_distance` if given, else the baseline's max range.
5170    pub target_distance_m: f64,
5171    /// Mean ground-impact velocity over trials that reached the target plane.
5172    ///
5173    /// The velocity is the one the legacy path records: speed at *ground impact*, not at the
5174    /// target plane (MBA-967). Only the conditioning is on reaching the plane.
5175    pub mean_impact_velocity_mps: f64,
5176    /// Sample (`n-1`) standard deviation of the above. `0.0` for fewer than two such trials.
5177    pub std_impact_velocity_mps: f64,
5178    /// Mean *vertical deviation from the baseline point of aim* at the target plane, in
5179    /// meters, positive high.
5180    ///
5181    /// Named "drop" for continuity with the rest of the API, but it is a deviation from the
5182    /// undispersed baseline, not a drop from the bore line: with symmetric input dispersions
5183    /// its expectation is near zero and the informative number is
5184    /// [`std_drop_at_target_m`](Self::std_drop_at_target_m).
5185    pub mean_drop_at_target_m: f64,
5186    /// Sample (`n-1`) standard deviation of the vertical deviation -- the run's vertical
5187    /// dispersion at the target.
5188    pub std_drop_at_target_m: f64,
5189    /// Mean lateral deviation from the baseline point of aim at the target plane, in meters.
5190    /// The same "deviation, not absolute" caveat as `mean_drop_at_target_m` applies.
5191    pub mean_wind_drift_at_target_m: f64,
5192    /// Sample (`n-1`) standard deviation of the lateral deviation -- the run's horizontal
5193    /// dispersion at the target.
5194    pub std_wind_drift_at_target_m: f64,
5195}
5196
5197/// Runs a Monte Carlo hit-probability estimate that decides its own sample size, from an
5198/// explicit seed.
5199///
5200/// # What this buys over the fixed-count path
5201///
5202/// [`run_monte_carlo_with_wind_and_direction_std_dev_seeded`] runs exactly
5203/// `params.num_simulations` trials and reports a point estimate; whether that count was enough
5204/// is left to the caller to guess. This instead runs until the answer is as precise as the
5205/// caller asked for, and reports the achieved precision either way. **`params.num_simulations`
5206/// is ignored here** -- the sample count comes from `convergence`, and
5207/// [`McConvergence::min_samples`] defaults to the same `1_000` so the floor matches the legacy
5208/// default.
5209///
5210/// # Why the interval is anytime-valid
5211///
5212/// Stopping when the interval looks tight enough is optional stopping, and a fixed-`n`
5213/// interval (Wilson, Wald, anything) checked repeatedly that way has no coverage guarantee:
5214/// the error rate grows with the number of peeks. [`BernoulliConfidenceSequence`] is instead
5215/// valid at every `n` simultaneously, so a data-dependent stopping rule is legitimate. The
5216/// price is a strictly wider interval at any given `n` than the fixed-`n`
5217/// [`MonteCarloResults::hit_probability_wilson`] would report on the same counts. Paying it is
5218/// the point.
5219///
5220/// # The trial is the same trial
5221///
5222/// Each trial is `MonteCarloTrialSampler::sample_one_trial` (crate-internal), the same body
5223/// and the same six-draw sequence the legacy loop runs, and the hit test is
5224/// [`MonteCarloResults::position_is_hit`], the same predicate
5225/// [`MonteCarloResults::hit_probability`] counts with. A trial that never reached the target
5226/// plane is a definite miss and stays in the denominator, exactly as it does there. Wind
5227/// direction is not dispersed: [`MonteCarloParams`] has no direction-sigma field, so this
5228/// passes `0.0`, matching [`run_monte_carlo_with_wind`].
5229///
5230/// # Sample accounting
5231///
5232/// Trials are run in batches of [`McConvergence::batch_size`] (the last batch truncated so the
5233/// ceiling is never overshot), and the stopping rule is evaluated after each batch: stop with
5234/// [`McStopReason::TargetHalfWidthMet`] once at least `min_samples` trials are in *and* the
5235/// half-width is at or below `target_half_width`; stop with
5236/// [`McStopReason::MaxSamplesReached`] once `max_samples` trials have been attempted.
5237///
5238/// The report carries three cardinalities, and they are three different numbers:
5239///
5240/// * `attempts` -- trials drawn. This is what `max_samples` caps.
5241/// * `samples` -- trials that produced an outcome, i.e. the `n` behind `hit_probability` and
5242///   the confidence interval.
5243/// * `arrivals` -- trials that reached the target plane, i.e. the `n` behind the three
5244///   at-target statistics.
5245///
5246/// `attempts >= samples >= arrivals` always. A trial whose solve fails is dropped rather than
5247/// counted as a miss -- the legacy loop's behaviour, preserved so the two paths cannot
5248/// disagree about what a solver failure means -- but it still consumes an attempt, so it
5249/// shows up as `attempts > samples`. With no dropped trials the two are equal, which is the
5250/// normal case; when they differ, `samples` can finish below `min_samples`, and the honest
5251/// report of that is `MaxSamplesReached` with the smaller `n` and the correspondingly wider
5252/// interval. A trial that solved but fell short of the target plane is a definite miss: it is
5253/// a sample (in `hit_probability`'s denominator) but not an arrival, so it shows up as
5254/// `samples > arrivals`. A run in which *every* trial was dropped is an error, not a report.
5255///
5256/// # `hit_radius_m` is not validated
5257///
5258/// Every [`McConvergence`] field is `Err`-checked up front, but `hit_radius_m` itself is not:
5259/// a `NaN` or negative radius makes [`MonteCarloResults::position_is_hit`] false for every
5260/// trial, yielding `p = 0.0` with a tight interval and (usually) a
5261/// [`McStopReason::TargetHalfWidthMet`] stop rather than an error. This is deliberate, not an
5262/// oversight -- it matches [`MonteCarloResults::hit_probability`]'s equally lenient legacy
5263/// posture on the same input, so this path cannot diverge from the fixed-count one over how a
5264/// bad radius is treated.
5265///
5266/// # Errors
5267///
5268/// Returns `Err` if `convergence` is not usable ([`McConvergence::validate`], which names the
5269/// offending field), if the baseline solve or an input distribution is invalid, or if no trial
5270/// at all produced an outcome.
5271///
5272/// Presence-blind: `base_inputs`' temperature and pressure go through the legacy
5273/// default-sentinel rule. See [`run_monte_carlo_adaptive_seeded_with_station_presence`].
5274pub fn run_monte_carlo_adaptive_seeded(
5275    base_inputs: &BallisticInputs,
5276    base_wind: &WindConditions,
5277    params: &MonteCarloParams,
5278    convergence: &McConvergence,
5279    hit_radius_m: f64,
5280    seed: u64,
5281) -> Result<AdaptiveMcReportV1, String> {
5282    run_monte_carlo_adaptive_seeded_with_station_presence(
5283        base_inputs,
5284        base_wind,
5285        params,
5286        convergence,
5287        hit_radius_m,
5288        seed,
5289        StationAtmospherePresence::NEITHER,
5290    )
5291}
5292
5293/// [`run_monte_carlo_adaptive_seeded`] knowing which of `base_inputs`' temperature and
5294/// pressure the caller supplied (0.49.0). A supplied value flies as given, an omitted one keeps
5295/// the legacy default-sentinel rule; [`StationAtmospherePresence::NEITHER`] is bit-identical to
5296/// [`run_monte_carlo_adaptive_seeded`].
5297pub fn run_monte_carlo_adaptive_seeded_with_station_presence(
5298    base_inputs: &BallisticInputs,
5299    base_wind: &WindConditions,
5300    params: &MonteCarloParams,
5301    convergence: &McConvergence,
5302    hit_radius_m: f64,
5303    seed: u64,
5304    station_presence: StationAtmospherePresence,
5305) -> Result<AdaptiveMcReportV1, String> {
5306    use rand::{rngs::StdRng, SeedableRng};
5307
5308    convergence.validate()?;
5309
5310    // `wind_direction_std_dev = 0.0`: MonteCarloParams carries no direction sigma, so this
5311    // matches `run_monte_carlo_with_wind`'s treatment rather than inventing one.
5312    let sampler = MonteCarloTrialSampler::new(
5313        base_inputs.clone(),
5314        base_wind,
5315        params,
5316        0.0,
5317        station_presence,
5318    )
5319    .map_err(|e| e.to_string())?;
5320
5321    let mut rng = StdRng::seed_from_u64(seed);
5322    let mut hits_cs = BernoulliConfidenceSequence::new(convergence.level);
5323    let mut impact_velocity = Welford::new();
5324    let mut drop_at_target = Welford::new();
5325    let mut drift_at_target = Welford::new();
5326
5327    let mut attempts: u64 = 0;
5328    let mut stop_reason = McStopReason::MaxSamplesReached;
5329
5330    while attempts < convergence.max_samples {
5331        // Truncate the final batch so `max_samples` is a ceiling on attempts, not a threshold
5332        // the last batch may overshoot.
5333        let batch = convergence
5334            .batch_size
5335            .min(convergence.max_samples - attempts);
5336        let mut batch_hits: u64 = 0;
5337        let mut batch_trials: u64 = 0;
5338
5339        for _ in 0..batch {
5340            attempts += 1;
5341            let Some(outcome) = sampler.sample_one_trial(&mut rng) else {
5342                continue; // dropped trial: not a miss, not a sample (see the legacy loop)
5343            };
5344            batch_trials += 1;
5345            if MonteCarloResults::position_is_hit(&outcome.impact_position, hit_radius_m) {
5346                batch_hits += 1;
5347            }
5348            // Continuous statistics are conditioned on arrival: a shortfall marker is a
5349            // placeholder, not a measured position, and folding it in would drag the moments
5350            // toward TARGET_NOT_REACHED_SENTINEL_M. It still counts as a miss above.
5351            if MonteCarloResults::position_reached_target(&outcome.impact_position) {
5352                impact_velocity.push(outcome.impact_velocity);
5353                drop_at_target.push(outcome.impact_position.y);
5354                drift_at_target.push(outcome.impact_position.z);
5355            }
5356        }
5357
5358        hits_cs.update_batch(batch_hits, batch_trials);
5359
5360        if hits_cs.trials() >= convergence.min_samples
5361            && hits_cs.half_width() <= convergence.target_half_width
5362        {
5363            stop_reason = McStopReason::TargetHalfWidthMet;
5364            break;
5365        }
5366    }
5367
5368    let samples = hits_cs.trials();
5369    if samples == 0 {
5370        return Err("No successful simulations".to_string());
5371    }
5372    let (ci_low, ci_high) = hits_cs.bounds();
5373
5374    Ok(AdaptiveMcReportV1 {
5375        schema_version: MC_ADAPTIVE_SCHEMA_VERSION_V1,
5376        method: MC_ADAPTIVE_METHOD_V1.to_string(),
5377        assumptions: MC_ADAPTIVE_ASSUMPTIONS_V1
5378            .iter()
5379            .map(|s| s.to_string())
5380            .collect(),
5381        confidence_percent: convergence.level.as_percent(),
5382        hit_probability: hits_cs.successes() as f64 / samples as f64,
5383        ci_low,
5384        ci_high,
5385        samples,
5386        attempts,
5387        // All three at-target accumulators are fed under one guard, in one block, so their
5388        // counts are equal by construction; reading the population off one of them binds this
5389        // field to the actual Welford `n` rather than to a parallel counter that could drift.
5390        arrivals: drop_at_target.count(),
5391        stop_reason,
5392        hit_radius_m,
5393        target_distance_m: sampler.target_distance,
5394        mean_impact_velocity_mps: impact_velocity.mean(),
5395        std_impact_velocity_mps: impact_velocity.sample_std(),
5396        mean_drop_at_target_m: drop_at_target.mean(),
5397        std_drop_at_target_m: drop_at_target.sample_std(),
5398        mean_wind_drift_at_target_m: drift_at_target.mean(),
5399        std_wind_drift_at_target_m: drift_at_target.sample_std(),
5400    })
5401}
5402
5403// Calculate zero angle for a target
5404pub fn calculate_zero_angle(
5405    inputs: BallisticInputs,
5406    target_distance: f64,
5407    target_height: f64,
5408) -> Result<f64, BallisticsError> {
5409    calculate_zero_angle_with_conditions(
5410        inputs,
5411        target_distance,
5412        target_height,
5413        WindConditions::default(),
5414        AtmosphericConditions::default(),
5415    )
5416}
5417
5418/// Solve the bore angle that crosses the line of sight at `target_distance`.
5419///
5420/// Presence-blind: `atmosphere` goes through the legacy default-sentinel rule (see
5421/// [`TrajectorySolver::new`]). See [`calculate_zero_angle_with_station_presence`].
5422pub fn calculate_zero_angle_with_conditions(
5423    inputs: BallisticInputs,
5424    target_distance: f64,
5425    target_height: f64,
5426    wind: WindConditions,
5427    atmosphere: AtmosphericConditions,
5428) -> Result<f64, BallisticsError> {
5429    calculate_zero_angle_with_station_presence(
5430        inputs,
5431        target_distance,
5432        target_height,
5433        wind,
5434        atmosphere,
5435        StationAtmospherePresence::NEITHER,
5436    )
5437}
5438
5439/// [`calculate_zero_angle_with_conditions`] knowing which of `atmosphere`'s temperature and
5440/// pressure the caller supplied (0.49.0); see [`TrajectorySolver::new_with_station_presence`].
5441/// [`StationAtmospherePresence::NEITHER`] is bit-identical to the presence-blind function, and
5442/// [`StationAtmospherePresence::BOTH`] to [`calculate_zero_angle_with_resolved_conditions`].
5443pub fn calculate_zero_angle_with_station_presence(
5444    inputs: BallisticInputs,
5445    target_distance: f64,
5446    target_height: f64,
5447    wind: WindConditions,
5448    atmosphere: AtmosphericConditions,
5449    station_presence: StationAtmospherePresence,
5450) -> Result<f64, BallisticsError> {
5451    let mut solver =
5452        TrajectorySolver::new_with_station_presence(inputs, wind, atmosphere, station_presence);
5453    solver.calculate_and_set_zero_angle(target_distance, target_height, ZeroTargetFrame::SightLine)
5454}
5455
5456/// [`calculate_zero_angle_with_conditions`] for a presence-aware caller that has already
5457/// resolved station temperature/pressure (MBA-1397; e.g. reduced a declared QNH via
5458/// [`crate::atmosphere::resolve_station_conditions_with_presence`]). Unlike the base
5459/// function, `atmosphere`'s temperature/pressure are trusted as-is and never re-interpreted
5460/// through the legacy default-sentinel heuristic.
5461pub fn calculate_zero_angle_with_resolved_conditions(
5462    inputs: BallisticInputs,
5463    target_distance: f64,
5464    target_height: f64,
5465    wind: WindConditions,
5466    atmosphere: AtmosphericConditions,
5467) -> Result<f64, BallisticsError> {
5468    let mut solver =
5469        TrajectorySolver::new_with_resolved_station_atmosphere(inputs, wind, atmosphere);
5470    solver.calculate_and_set_zero_angle(target_distance, target_height, ZeroTargetFrame::SightLine)
5471}
5472
5473/// Generous solve envelope for [`calculate_zero_range_from_angle_with_conditions`] /
5474/// [`calculate_zero_range_from_angle_with_resolved_conditions`] (MBA-1402): a "zero" bore angle
5475/// is a near-horizontal shot, so its far line-of-sight crossing sits well inside this even at
5476/// extended small-arms ranges. Double the engine's own default 1000 m solve envelope
5477/// ([`TrajectorySolver::new`]) rather than something scaled to an (unknown, being solved for)
5478/// target distance; `solve()` still stops at ground impact well before this in the typical
5479/// case, so the larger envelope costs effectively nothing.
5480pub const ZERO_RANGE_FROM_ANGLE_MAX_RANGE_M: f64 = 2000.0;
5481
5482/// Solve the zero RANGE(S) that a fixed bore angle produces. Runs the trajectory at
5483/// `zero_angle_rad` and returns BOTH line-of-sight crossings it finds, as
5484/// [`ZeroCrossings`] — a rifle sighted above the bore generally crosses a level line of
5485/// sight twice on a rising shot (near, ascending, close to the muzzle; far, descending past
5486/// the apex).
5487///
5488/// **This is NOT the exact inverse of [`calculate_zero_angle_with_conditions`].** A single
5489/// bore angle generally implies two valid zero distances (the classic 25/300-yard
5490/// battle-zero relationship is exactly this: one angle, two zeros), and
5491/// [`calculate_zero_angle_with_conditions`]'s own choice of root depends on which target
5492/// distance it was asked to solve for. Round-tripping a solved angle back through this
5493/// function recovers the ORIGINAL distance as one of the two returned crossings, not
5494/// necessarily as `far_m` specifically — for short/flat zeros the forward solver's answer is
5495/// often the NEAR crossing.
5496///
5497/// Presence-blind: `atmosphere` goes through the legacy default-sentinel rule. See
5498/// [`calculate_zero_range_from_angle_with_station_presence`].
5499pub fn calculate_zero_range_from_angle_with_conditions(
5500    inputs: BallisticInputs,
5501    zero_angle_rad: f64,
5502    target_height: f64,
5503    wind: WindConditions,
5504    atmosphere: AtmosphericConditions,
5505) -> Result<ZeroCrossings, BallisticsError> {
5506    calculate_zero_range_from_angle_with_station_presence(
5507        inputs,
5508        zero_angle_rad,
5509        target_height,
5510        wind,
5511        atmosphere,
5512        StationAtmospherePresence::NEITHER,
5513    )
5514}
5515
5516/// [`calculate_zero_range_from_angle_with_conditions`] knowing which of `atmosphere`'s
5517/// temperature and pressure the caller supplied (0.49.0); see
5518/// [`TrajectorySolver::new_with_station_presence`]. [`StationAtmospherePresence::NEITHER`] is
5519/// bit-identical to the presence-blind function.
5520pub fn calculate_zero_range_from_angle_with_station_presence(
5521    inputs: BallisticInputs,
5522    zero_angle_rad: f64,
5523    target_height: f64,
5524    wind: WindConditions,
5525    atmosphere: AtmosphericConditions,
5526    station_presence: StationAtmospherePresence,
5527) -> Result<ZeroCrossings, BallisticsError> {
5528    let mut solver =
5529        TrajectorySolver::new_with_station_presence(inputs, wind, atmosphere, station_presence);
5530    solver.set_max_range(ZERO_RANGE_FROM_ANGLE_MAX_RANGE_M);
5531    solver.find_zero_range(zero_angle_rad, target_height, ZeroTargetFrame::SightLine)
5532}
5533
5534/// [`calculate_zero_range_from_angle_with_conditions`] for a presence-aware caller that has
5535/// already resolved station temperature/pressure — same relationship as
5536/// [`calculate_zero_angle_with_resolved_conditions`] has to
5537/// [`calculate_zero_angle_with_conditions`] (MBA-1397 pattern). See that function's doc
5538/// comment for why this returns both crossings rather than a single "the" zero range.
5539pub fn calculate_zero_range_from_angle_with_resolved_conditions(
5540    inputs: BallisticInputs,
5541    zero_angle_rad: f64,
5542    target_height: f64,
5543    wind: WindConditions,
5544    atmosphere: AtmosphericConditions,
5545) -> Result<ZeroCrossings, BallisticsError> {
5546    let mut solver =
5547        TrajectorySolver::new_with_resolved_station_atmosphere(inputs, wind, atmosphere);
5548    solver.set_max_range(ZERO_RANGE_FROM_ANGLE_MAX_RANGE_M);
5549    solver.find_zero_range(zero_angle_rad, target_height, ZeroTargetFrame::SightLine)
5550}
5551
5552/// What a BC estimate is fit against.
5553#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5554pub enum BcFitMode {
5555    /// Data points are `(distance_m, drop_m)` — the classic drop-curve fit.
5556    Drop,
5557    /// Data points are `(distance_m, velocity_mps)` — a velocity-retention fit,
5558    /// which is immune to zero / sight-height / launch-angle error.
5559    Velocity,
5560}
5561
5562/// The result of a single BC fit (one drag model, one fit basis).
5563#[derive(Debug, Clone, Copy)]
5564pub struct BcEstimate {
5565    /// The estimated ballistic coefficient.
5566    pub bc: f64,
5567    /// RMS residual across the data points, in fit units (meters of drop, or m/s of speed).
5568    pub rms_error: f64,
5569    /// Which standard drag model this BC is referenced to.
5570    pub drag_model: DragModel,
5571    /// Whether the fit was against drop or velocity data.
5572    pub mode: BcFitMode,
5573    /// True if the best fit landed at the edge of the physical BC search range — i.e. the
5574    /// data did not pin down an interior optimum (too sparse/short-range, or wrong units /
5575    /// atmosphere / zero). The reported `bc` is then a floor/ceiling, not a real estimate.
5576    pub at_bound: bool,
5577}
5578
5579/// Interpolate the fitted quantity (drop in meters, or speed in m/s) at a downrange
5580/// distance from a solved trajectory. `None` if the trajectory never reaches `target_dist`.
5581///
5582/// `drop_offset` is subtracted-from convention: for `Drop` the returned value is
5583/// `drop_offset - y`. With `drop_offset = 0` this is bore-referenced drop (flat fire);
5584/// with `drop_offset = sight_height` and a zeroed trajectory it is drop below the
5585/// (horizontal) line of sight — i.e. dope-card drop.
5586fn fit_value_at(
5587    points: &[TrajectoryPoint],
5588    target_dist: f64,
5589    mode: BcFitMode,
5590    drop_offset: f64,
5591) -> Option<f64> {
5592    let val = |p: &TrajectoryPoint| match mode {
5593        BcFitMode::Drop => drop_offset - p.position.y,
5594        BcFitMode::Velocity => p.velocity_magnitude,
5595    };
5596    for i in 0..points.len() {
5597        if points[i].position.x >= target_dist {
5598            if i == 0 {
5599                return Some(val(&points[0]));
5600            }
5601            let p1 = &points[i - 1];
5602            let p2 = &points[i];
5603            let dx = p2.position.x - p1.position.x;
5604            if dx.abs() < 1e-9 {
5605                return Some(val(p2));
5606            }
5607            let t = (target_dist - p1.position.x) / dx;
5608            return Some(val(p1) + t * (val(p2) - val(p1)));
5609        }
5610    }
5611    None
5612}
5613
5614fn fit_residual_sse(
5615    trajectory: &[TrajectoryPoint],
5616    observations: &[(f64, f64)],
5617    mode: BcFitMode,
5618    drop_offset: f64,
5619) -> Option<f64> {
5620    if observations.is_empty() {
5621        return None;
5622    }
5623    let mut total = 0.0;
5624    for (target_dist, target_val) in observations {
5625        // Scores are comparable only when every candidate contains every residual term.
5626        // Reject a trajectory that terminates before even one observation (MBA-1178).
5627        let value = fit_value_at(trajectory, *target_dist, mode, drop_offset)?;
5628        let error = value - target_val;
5629        total += error * error;
5630    }
5631    Some(total)
5632}
5633
5634/// Estimate a BC by fitting a simulated trajectory to measured data, for a chosen drag
5635/// model (G1, G7, …) and fit basis (drop or velocity). Uses a coarse 0.01 sweep over
5636/// plausible BCs followed by a 0.001 local refine around the coarse best.
5637///
5638/// `points` are `(distance_m, value_m_or_mps)` where the second element is drop in meters
5639/// (`BcFitMode::Drop`) or remaining speed in m/s (`BcFitMode::Velocity`).
5640///
5641/// The fit runs under `atmosphere` — BC is only meaningful relative to the air density the
5642/// data was measured at, so this must match the conditions the drop/velocity came from
5643/// (pass ICAO standard for a standard-atmosphere dope card).
5644///
5645/// `zero_range` selects the drop reference frame (ignored for velocity fits):
5646/// - `None` → **bore-referenced**: flat 0° fire, drop below the extended bore axis.
5647/// - `Some(range_m)` → **sight/dope-card-referenced**: the trajectory is zeroed at
5648///   `range_m` (using `sight_height`), and drop is measured below the horizontal line of
5649///   sight — i.e. exactly what a dope card zeroed at that range prints.
5650///
5651/// Presence-blind: `atmosphere` goes through the legacy default-sentinel rule. See
5652/// [`estimate_bc_fit_with_station_presence`].
5653#[allow(clippy::too_many_arguments)] // Public compatibility API; grouping would be breaking.
5654pub fn estimate_bc_fit(
5655    velocity: f64,
5656    mass: f64,
5657    diameter: f64,
5658    points: &[(f64, f64)],
5659    drag_model: DragModel,
5660    mode: BcFitMode,
5661    atmosphere: AtmosphericConditions,
5662    zero_range: Option<f64>,
5663    sight_height: f64,
5664) -> Result<BcEstimate, BallisticsError> {
5665    estimate_bc_fit_with_station_presence(
5666        velocity,
5667        mass,
5668        diameter,
5669        points,
5670        drag_model,
5671        mode,
5672        atmosphere,
5673        zero_range,
5674        sight_height,
5675        StationAtmospherePresence::NEITHER,
5676    )
5677}
5678
5679/// [`estimate_bc_fit`] knowing which of `atmosphere`'s temperature and pressure the caller
5680/// supplied (0.49.0): a supplied value is the air the data was shot in, whatever its value.
5681/// [`StationAtmospherePresence::NEITHER`] is bit-identical to [`estimate_bc_fit`].
5682///
5683/// An out-of-range humidity, or air that cannot exist, is refused before the search with the
5684/// solver's own field-named error (0.50.0), not reported as data no BC fits.
5685#[allow(clippy::too_many_arguments)] // Mirrors estimate_bc_fit plus the presence.
5686pub fn estimate_bc_fit_with_station_presence(
5687    velocity: f64,
5688    mass: f64,
5689    diameter: f64,
5690    points: &[(f64, f64)],
5691    drag_model: DragModel,
5692    mode: BcFitMode,
5693    atmosphere: AtmosphericConditions,
5694    zero_range: Option<f64>,
5695    sight_height: f64,
5696    station_presence: StationAtmospherePresence,
5697) -> Result<BcEstimate, BallisticsError> {
5698    if points.is_empty() {
5699        return Err(BallisticsError::from(
5700            "No data points provided for BC estimation.".to_string(),
5701        ));
5702    }
5703    // The fit's air goes through the solver's own station check once, up front. The sweep below
5704    // drops every trial that fails, so without this an out-of-range
5705    // humidity or air that cannot exist would come back as "Unable to estimate BC from provided
5706    // data", which blames the data for the air.
5707    TrajectorySolver::new_with_station_presence(
5708        BallisticInputs::default(),
5709        WindConditions::default(),
5710        atmosphere.clone(),
5711        station_presence,
5712    )
5713    .station_air()?;
5714    let max_dist = points.iter().map(|(d, _)| *d).fold(0.0_f64, f64::max);
5715    // For a zeroed drop fit, drop is below the horizontal LOS which sits `sight_height`
5716    // above the bore at the muzzle: drop = sight_height - y. Bore-referenced fits use 0.
5717    let drop_offset = if zero_range.is_some() {
5718        sight_height
5719    } else {
5720        0.0
5721    };
5722
5723    // Sum of squared residuals for a trial BC; None unless the solve reaches ALL data points.
5724    let sse = |bc_value: f64| -> Result<Option<f64>, BallisticsError> {
5725        let mut inputs = BallisticInputs {
5726            muzzle_velocity: velocity,
5727            bc_value,
5728            bc_type: drag_model,
5729            bullet_mass: mass,
5730            bullet_diameter: diameter,
5731            sight_height,
5732            ..Default::default()
5733        };
5734        // Zeroed fit: tilt the bore so the bullet crosses LOS at the zero range, so the
5735        // downrange drops match a dope card zeroed there. Bore fit leaves muzzle_angle = 0.
5736        if let Some(zr) = zero_range {
5737            // MBA-1130: zero to the LINE OF SIGHT (y = sight_height) at the zero range,
5738            // not the bore line (y = 0). Drop is measured as `drop_offset - y` with
5739            // drop_offset = sight_height, so a bore-referenced zero left drop != 0 at the
5740            // zero range and the drop-fit no longer round-tripped to the true BC. This
5741            // matches how range-table / come-up / dope-card generation zero.
5742            let za = calculate_zero_angle_with_station_presence(
5743                inputs.clone(),
5744                zr,
5745                sight_height,
5746                WindConditions::default(),
5747                atmosphere.clone(),
5748                station_presence,
5749            )?;
5750            inputs.muzzle_angle = za;
5751        }
5752        let mut solver = TrajectorySolver::new_with_station_presence(
5753            inputs,
5754            WindConditions::default(),
5755            atmosphere.clone(),
5756            station_presence,
5757        );
5758        solver.set_max_range(max_dist * 1.5);
5759        let result = solver.solve()?;
5760        Ok(fit_residual_sse(&result.points, points, mode, drop_offset))
5761    };
5762
5763    // Physical BC search range, per drag model. Real G7 BCs top out well under 0.5 (0.7 is
5764    // a generous ceiling); G1 BCs run higher. Keeping G7 out of G1 territory means a fit
5765    // that runs to the ceiling reports a sane bound, not a nonsensical 1.2.
5766    let (bc_min, bc_max) = match drag_model {
5767        DragModel::G7 => (0.05, 0.70),
5768        _ => (0.10, 1.20),
5769    };
5770
5771    // Coarse sweep across the physical range.
5772    let mut best_bc = f64::NAN;
5773    let mut best_sse = f64::MAX;
5774    let mut air_refusal = None;
5775    let mut bc = bc_min;
5776    while bc <= bc_max + 1e-9 {
5777        match sse(bc) {
5778            Ok(Some(s)) if s < best_sse => {
5779                best_sse = s;
5780                best_bc = bc;
5781            }
5782            Err(error) if error.atmosphere_error().is_some() => {
5783                air_refusal.get_or_insert(error);
5784            }
5785            _ => {}
5786        }
5787        bc += 0.01;
5788    }
5789    if !best_bc.is_finite() {
5790        // A failed trial does not disqualify a successful fit. If none succeeded, keep the
5791        // actual air refusal so the caller can name the station reading it supplied.
5792        if let Some(error) = air_refusal {
5793            return Err(error);
5794        }
5795        return Err(BallisticsError::from(
5796            "Unable to estimate BC from provided data. Check that the values and units are correct."
5797                .to_string(),
5798        ));
5799    }
5800
5801    // Local refine at 0.001 resolution around the coarse best (kept within the range).
5802    let lo = (best_bc - 0.01).max(bc_min);
5803    let hi = (best_bc + 0.01).min(bc_max);
5804    let mut bc = lo;
5805    while bc <= hi + 1e-9 {
5806        if let Ok(Some(s)) = sse(bc) {
5807            if s < best_sse {
5808                best_sse = s;
5809                best_bc = bc;
5810            }
5811        }
5812        bc += 0.001;
5813    }
5814
5815    // A solution sitting on the search boundary means the data didn't determine an interior
5816    // optimum — the fit ran to the floor/ceiling. Flag it so callers don't trust the number.
5817    let at_bound = best_bc <= bc_min + 0.011 || best_bc >= bc_max - 0.011;
5818    // fit_residual_sse rejects partial trajectories, so best_sse contains exactly one residual
5819    // per input point and this denominator is also the honest matched-point count.
5820    let rms_error = (best_sse / points.len() as f64).sqrt();
5821    Ok(BcEstimate {
5822        bc: best_bc,
5823        rms_error,
5824        drag_model,
5825        mode,
5826        at_bound,
5827    })
5828}
5829
5830/// Estimate a G1 BC from a drop curve. Back-compatible wrapper over [`estimate_bc_fit`];
5831/// `points` are `(distance_m, drop_m)`.
5832pub fn estimate_bc_from_trajectory(
5833    velocity: f64,
5834    mass: f64,
5835    diameter: f64,
5836    points: &[(f64, f64)], // (distance, drop) pairs
5837) -> Result<f64, BallisticsError> {
5838    estimate_bc_fit(
5839        velocity,
5840        mass,
5841        diameter,
5842        points,
5843        DragModel::G1,
5844        BcFitMode::Drop,
5845        AtmosphericConditions::default(),
5846        None,
5847        0.05,
5848    )
5849    .map(|e| e.bc)
5850}
5851
5852// Add rand dependencies for Monte Carlo
5853use rand;
5854use rand_distr;
5855
5856#[cfg(test)]
5857mod mba737_powder_resolution_tests {
5858    use super::*;
5859
5860    #[test]
5861    fn linear_model_cold_powder_subtracts() {
5862        // 0.5486 m/s per degC (1 fps/degF), shot day 10 C below the 21.1 C reference.
5863        let v = resolve_powder_adjusted_velocity(823.0, 11.1, true, 0.5486, 21.1, None, None);
5864        assert!((v - (823.0 + 0.5486 * (11.1 - 21.1))).abs() < 1e-12);
5865        assert!(v < 823.0);
5866    }
5867
5868    #[test]
5869    fn linear_model_hot_powder_adds() {
5870        let v = resolve_powder_adjusted_velocity(823.0, 31.1, true, 0.5486, 21.1, None, None);
5871        assert!((v - (823.0 + 0.5486 * 10.0)).abs() < 1e-12);
5872    }
5873
5874    #[test]
5875    fn disabled_flag_is_passthrough() {
5876        let v = resolve_powder_adjusted_velocity(823.0, 40.0, false, 0.5486, 21.1, None, None);
5877        assert_eq!(v, 823.0);
5878    }
5879
5880    #[test]
5881    fn curve_overrides_linear_and_interpolates_at_powder_temp() {
5882        let curve = [(4.4, 798.6), (21.1, 823.0), (37.8, 841.2)];
5883        // Explicit powder temp decouples from ambient: interpolate at 4.4 C, not 30 C.
5884        let v = resolve_powder_adjusted_velocity(
5885            823.0,
5886            30.0,
5887            true,
5888            99.0,
5889            21.1,
5890            Some(&curve),
5891            Some(4.4),
5892        );
5893        assert!((v - 798.6).abs() < 1e-9);
5894    }
5895
5896    #[test]
5897    fn curve_falls_back_to_ambient_and_clamps() {
5898        let curve = [(4.4, 798.6), (37.8, 841.2)];
5899        // Ambient far below the coldest measured point: clamp, no extrapolation.
5900        let v = resolve_powder_adjusted_velocity(823.0, -40.0, true, 1.0, 21.1, Some(&curve), None);
5901        assert!((v - 798.6).abs() < 1e-9);
5902        let v_hot =
5903            resolve_powder_adjusted_velocity(823.0, 60.0, true, 1.0, 21.1, Some(&curve), None);
5904        assert!((v_hot - 841.2).abs() < 1e-9);
5905    }
5906
5907    #[test]
5908    fn empty_curve_suppresses_linear_fallback() {
5909        // Historical `else if` semantics: Some-but-empty curve means NO adjustment.
5910        let v = resolve_powder_adjusted_velocity(823.0, 40.0, true, 0.5486, 21.1, Some(&[]), None);
5911        assert_eq!(v, 823.0);
5912    }
5913
5914    #[test]
5915    fn sweep_huge_range_errors_instead_of_overflowing() {
5916        // Review finding: the old count math saturated the usize cast and the +1
5917        // panicked (debug) or wrapped to zero rows (release), bypassing the cap.
5918        assert!(parse_powder_sweep("0:1e20:1").is_err());
5919        assert!(parse_powder_sweep("0:1e308:1e-3").is_err());
5920    }
5921
5922    #[test]
5923    fn sweep_fractional_step_keeps_end_row() {
5924        // 0.3/0.1 floats to 2.9999999999999996; the END row must survive the floor.
5925        let rows = parse_powder_sweep("0:0.3:0.1").unwrap();
5926        assert_eq!(rows.len(), 4);
5927        assert!((rows[3] - 0.3).abs() < 1e-9);
5928    }
5929
5930    #[test]
5931    fn solver_and_helper_agree_on_linear_model() {
5932        // The solve() seam must fly exactly what the helper reports (MBA-737 contract).
5933        let inputs = BallisticInputs {
5934            use_powder_sensitivity: true,
5935            powder_temp_sensitivity: 0.5486,
5936            powder_temp: 21.1,
5937            temperature: 4.4,
5938            ..Default::default()
5939        };
5940        let expected = resolve_powder_adjusted_velocity(
5941            inputs.muzzle_velocity,
5942            inputs.temperature,
5943            true,
5944            0.5486,
5945            21.1,
5946            None,
5947            None,
5948        );
5949        let solver = TrajectorySolver::new(
5950            inputs,
5951            WindConditions::default(),
5952            AtmosphericConditions::default(),
5953        );
5954        assert!((solver.inputs.muzzle_velocity - expected).abs() < 1e-12);
5955    }
5956}
5957
5958#[cfg(test)]
5959mod mba1302_solver_seam_tests {
5960    use super::*;
5961    use crate::wind::WindSegment;
5962
5963    #[test]
5964    fn authoritative_station_atmosphere_preserves_explicit_standard_values_at_altitude() {
5965        let atmosphere = AtmosphericConditions {
5966            temperature: 15.0,
5967            pressure: 1013.25,
5968            humidity: 50.0,
5969            altitude: 2_000.0,
5970        };
5971        let legacy = TrajectorySolver::new(
5972            BallisticInputs::default(),
5973            WindConditions::default(),
5974            atmosphere.clone(),
5975        );
5976        let authoritative = TrajectorySolver::new_with_resolved_station_atmosphere(
5977            BallisticInputs::default(),
5978            WindConditions::default(),
5979            atmosphere,
5980        );
5981
5982        let (legacy_density, _, legacy_temp_c, legacy_pressure_hpa) = legacy.resolved_atmosphere();
5983        let (authoritative_density, _, authoritative_temp_c, authoritative_pressure_hpa) =
5984            authoritative.resolved_atmosphere();
5985        let (icao_temp_k, icao_pressure_pa) =
5986            crate::atmosphere::calculate_icao_standard_atmosphere(2_000.0);
5987        let (expected_authoritative_density, _) =
5988            crate::atmosphere::calculate_atmosphere(2_000.0, Some(15.0), Some(1013.25), 50.0);
5989
5990        assert!((legacy_temp_c - (icao_temp_k - 273.15)).abs() < 1e-12);
5991        assert!((legacy_pressure_hpa - icao_pressure_pa / 100.0).abs() < 1e-12);
5992        assert_eq!(authoritative_temp_c.to_bits(), 15.0_f64.to_bits());
5993        assert_eq!(authoritative_pressure_hpa.to_bits(), 1013.25_f64.to_bits());
5994        assert_eq!(
5995            authoritative_density.to_bits(),
5996            expected_authoritative_density.to_bits()
5997        );
5998        assert!(
5999            (authoritative_density - legacy_density).abs() > 0.1,
6000            "explicit standard values at altitude must differ from ICAO-at-altitude: explicit={authoritative_density}, ICAO={legacy_density}"
6001        );
6002    }
6003
6004    /// MBA-1397: the CLI/WASM `--pressure-type` mechanism precomputes station conditions via
6005    /// `atmosphere::resolve_station_conditions_with_pressure_mode` and constructs the solver
6006    /// with `new_with_resolved_station_atmosphere` UNCONDITIONALLY (not only for `Qnh`), to
6007    /// avoid re-deriving through the legacy sentinel a second time. This must be bit-for-bit
6008    /// equivalent to the historical `TrajectorySolver::new` (LegacyDefaultSentinels) path for
6009    /// every NON-ambiguous input -- i.e. for `PressureReferenceMode::Absolute`, precomputing
6010    /// and using the Authoritative constructor must reproduce `TrajectorySolver::new` exactly,
6011    /// which is the bit-level guarantee the CLI/WASM byte-identical-output tests rely on.
6012    #[test]
6013    fn precomputed_absolute_resolution_via_authoritative_matches_legacy_new() {
6014        for (temperature, pressure, altitude) in [
6015            (15.0, 1013.25, 0.0),    // sea-level default
6016            (15.0, 1013.25, 2000.0), // sentinel: omitted-pressure-at-altitude
6017            (-5.0, 850.0, 2000.0),   // explicit non-default station values
6018            (22.0, 950.0, 500.0),
6019        ] {
6020            let atmosphere = AtmosphericConditions {
6021                temperature,
6022                pressure,
6023                humidity: 50.0,
6024                altitude,
6025            };
6026            let legacy = TrajectorySolver::new(
6027                BallisticInputs::default(),
6028                WindConditions::default(),
6029                atmosphere.clone(),
6030            );
6031
6032            let (resolved_temp_c, resolved_pressure_hpa) =
6033                crate::atmosphere::resolve_station_conditions_with_pressure_mode(
6034                    temperature,
6035                    pressure,
6036                    altitude,
6037                    crate::atmosphere::PressureReferenceMode::Absolute,
6038                );
6039            let precomputed_atmosphere = AtmosphericConditions {
6040                temperature: resolved_temp_c,
6041                pressure: resolved_pressure_hpa,
6042                humidity: 50.0,
6043                altitude,
6044            };
6045            let precomputed = TrajectorySolver::new_with_resolved_station_atmosphere(
6046                BallisticInputs::default(),
6047                WindConditions::default(),
6048                precomputed_atmosphere,
6049            );
6050
6051            let (legacy_density, legacy_sos, legacy_temp_c, legacy_pressure_hpa) =
6052                legacy.resolved_atmosphere();
6053            let (pre_density, pre_sos, pre_temp_c, pre_pressure_hpa) =
6054                precomputed.resolved_atmosphere();
6055
6056            assert_eq!(
6057                legacy_temp_c.to_bits(),
6058                pre_temp_c.to_bits(),
6059                "temperature=({temperature}, {pressure}, {altitude})"
6060            );
6061            assert_eq!(
6062                legacy_pressure_hpa.to_bits(),
6063                pre_pressure_hpa.to_bits(),
6064                "pressure=({temperature}, {pressure}, {altitude})"
6065            );
6066            assert_eq!(legacy_density.to_bits(), pre_density.to_bits());
6067            assert_eq!(legacy_sos.to_bits(), pre_sos.to_bits());
6068        }
6069
6070        // In-band rows (0.49.0): 15.05 C / 1013.0 hPa sit inside both sentinel bands at a real
6071        // altitude. The presence-blind constructor and NEITHER must reproduce what ab4eb0c
6072        // resolved (ICAO air at the altitude), and BOTH must fly the pair as given, exactly
6073        // like the authoritative constructor.
6074        for (altitude, pinned) in [
6075            (
6076                150.0,
6077                // captured at ab4eb0c: (density, speed of sound, temperature, pressure)
6078                [
6079                    f64::from_bits(0x3ff344d9d9fd1ea1),
6080                    f64::from_bits(0x40754269eee53ba5),
6081                    f64::from_bits(0x402c0ccfd0c49b20),
6082                    f64::from_bits(0x408f1ae13f434f1f),
6083                ],
6084            ),
6085            (
6086                1500.0,
6087                // captured at ab4eb0c
6088                [
6089                    f64::from_bits(0x3ff0e75c08c70bc0),
6090                    f64::from_bits(0x4074ec457a661d16),
6091                    f64::from_bits(0x4015025af8d136c0),
6092                    f64::from_bits(0x408a6cc6358cefbd),
6093                ],
6094            ),
6095        ] {
6096            let atmosphere = AtmosphericConditions {
6097                temperature: 15.05,
6098                pressure: 1013.0,
6099                humidity: 50.0,
6100                altitude,
6101            };
6102            let bits = |r: (f64, f64, f64, f64)| [r.0, r.1, r.2, r.3].map(f64::to_bits);
6103            let pinned = pinned.map(f64::to_bits);
6104            let legacy = TrajectorySolver::new(
6105                BallisticInputs::default(),
6106                WindConditions::default(),
6107                atmosphere.clone(),
6108            );
6109            assert_eq!(
6110                bits(legacy.resolved_atmosphere()),
6111                pinned,
6112                "new at {altitude} m"
6113            );
6114            let neither = TrajectorySolver::new_with_station_presence(
6115                BallisticInputs::default(),
6116                WindConditions::default(),
6117                atmosphere.clone(),
6118                StationAtmospherePresence::NEITHER,
6119            );
6120            assert_eq!(
6121                bits(neither.resolved_atmosphere()),
6122                pinned,
6123                "NEITHER at {altitude} m"
6124            );
6125
6126            let both = TrajectorySolver::new_with_station_presence(
6127                BallisticInputs::default(),
6128                WindConditions::default(),
6129                atmosphere.clone(),
6130                StationAtmospherePresence::BOTH,
6131            );
6132            let authoritative = TrajectorySolver::new_with_resolved_station_atmosphere(
6133                BallisticInputs::default(),
6134                WindConditions::default(),
6135                atmosphere,
6136            );
6137            let both_resolved = both.resolved_atmosphere();
6138            assert_eq!(
6139                bits(both_resolved),
6140                bits(authoritative.resolved_atmosphere())
6141            );
6142            assert_eq!(both_resolved.2.to_bits(), 15.05_f64.to_bits());
6143            assert_eq!(both_resolved.3.to_bits(), 1013.0_f64.to_bits());
6144            assert_ne!(
6145                bits(both_resolved),
6146                pinned,
6147                "BOTH must not swap at {altitude} m"
6148            );
6149        }
6150    }
6151
6152    fn configured_euler_zero(vertical_wind_mps: f64, time_step_s: f64) -> TrajectorySolver {
6153        let inputs = BallisticInputs {
6154            muzzle_velocity: 800.0,
6155            bc_value: 0.5,
6156            bc_type: DragModel::G7,
6157            bullet_mass: 0.0109,
6158            bullet_diameter: 0.00782,
6159            bullet_length: 0.0309,
6160            sight_height: 0.05,
6161            ground_threshold: -100.0,
6162            use_rk4: false,
6163            use_adaptive_rk45: false,
6164            ..BallisticInputs::default()
6165        };
6166        let mut solver = TrajectorySolver::new_with_resolved_station_atmosphere(
6167            inputs,
6168            WindConditions::default(),
6169            AtmosphericConditions::default(),
6170        );
6171        solver.set_max_range(300.0);
6172        solver.set_time_step(time_step_s);
6173        if vertical_wind_mps != 0.0 {
6174            solver.set_wind_segments(vec![WindSegment {
6175                speed_kmh: 0.0,
6176                angle_deg: 0.0,
6177                until_m: 400.0,
6178                vertical_mps: vertical_wind_mps,
6179            }]);
6180        }
6181        solver
6182    }
6183
6184    #[test]
6185    fn inclined_shot_zeroes_like_a_level_rifle() {
6186        // MBA-1412: since MBA-1302, zero_trial_height_at converted trial heights into the
6187        // gravity frame (shot_frame_altitude adds d*sin(shooting_angle) ~ 9 m at 5.71deg /
6188        // 100 yd) while find_zero_angle compared against a sight-frame target height, so ANY
6189        // inclined shot failed to bracket. A zero is a property of a level rifle's sight
6190        // geometry (same doctrine as MBA-1286's cant handling): the trial must solve level.
6191        const ZERO_DISTANCE_M: f64 = 91.44; // 100 yd
6192        const SIGHT_HEIGHT_M: f64 = 0.0381; // 1.5 in
6193
6194        let inputs = BallisticInputs {
6195            bc_value: 0.5,
6196            bullet_mass: 150.0 * 0.06479891 / 1000.0,
6197            muzzle_velocity: 2700.0 * 0.3048,
6198            sight_height: SIGHT_HEIGHT_M,
6199            ..Default::default()
6200        };
6201
6202        let mut level = inputs.clone();
6203        level.shooting_angle = 0.0;
6204        let level_angle = TrajectorySolver::new(level, Default::default(), Default::default())
6205            .find_zero_angle(ZERO_DISTANCE_M, SIGHT_HEIGHT_M, ZeroTargetFrame::SightLine)
6206            .expect("level zero must solve");
6207
6208        let mut inclined = inputs;
6209        inclined.shooting_angle = 5.71_f64.to_radians();
6210        let inclined_angle =
6211            TrajectorySolver::new(inclined, Default::default(), Default::default())
6212                .find_zero_angle(ZERO_DISTANCE_M, SIGHT_HEIGHT_M, ZeroTargetFrame::SightLine)
6213                .expect("MBA-1412: a 5.71 deg incline at a 100 yd zero must be solvable");
6214
6215        assert!(
6216            (inclined_angle - level_angle).abs() < 1e-9,
6217            "zeroing is level-rifle sight geometry; incline must not move the solved zero: \
6218             level={level_angle}, inclined={inclined_angle}"
6219        );
6220    }
6221
6222    #[test]
6223    fn target_below_the_level_bore_impact_zeroes_with_a_downward_bore() {
6224        // A target lower than where a level bore lands needs the bore pointed below
6225        // horizontal. The search used to start at 0 rad, so every such target collapsed onto
6226        // 0 rad and failed with "residual height error too large".
6227        const TARGET_DISTANCE_M: f64 = 457.2; // 500 yd
6228        let inputs = BallisticInputs {
6229            bc_value: 0.462,
6230            bullet_mass: 168.0 * 0.06479891 / 1000.0,
6231            bullet_diameter: 0.308 * 0.0254,
6232            muzzle_velocity: 2700.0 * 0.3048,
6233            sight_height: 0.05,
6234            ..Default::default()
6235        };
6236        let solver = TrajectorySolver::new(inputs, Default::default(), Default::default());
6237        let level_impact_m = solver
6238            .zero_trial_height_at(0.0, TARGET_DISTANCE_M, ZeroTargetFrame::SightLine)
6239            .expect("level trial")
6240            .expect("level trial reaches the target distance");
6241
6242        // From just below the level impact down to a 30-degree depression (still above the
6243        // default -100 m ground threshold).
6244        for depth_m in [0.005, 1.0, 4.572, 91.44] {
6245            let target_m = level_impact_m - depth_m;
6246            let angle = solver
6247                .find_zero_angle(TARGET_DISTANCE_M, target_m, ZeroTargetFrame::SightLine)
6248                .unwrap_or_else(|e| panic!("target {depth_m} m below the level impact: {e}"));
6249            assert!(
6250                angle < 0.0,
6251                "a target below the level impact needs a downward bore: depth={depth_m} m angle={angle}"
6252            );
6253            let hit_m = solver
6254                .zero_trial_height_at(angle, TARGET_DISTANCE_M, ZeroTargetFrame::SightLine)
6255                .expect("verify trial")
6256                .expect("zeroed trial reaches the target distance");
6257            assert!(
6258                (hit_m - target_m).abs() < 0.0001,
6259                "zero missed a target {depth_m} m below the level impact: hit={hit_m} target={target_m}"
6260            );
6261        }
6262    }
6263
6264    #[test]
6265    fn configured_zero_keeps_segments_method_and_time_step_then_sets_base_angle() {
6266        const TARGET_DISTANCE_M: f64 = 150.0;
6267        const TARGET_HEIGHT_M: f64 = 0.05;
6268
6269        // A deliberately coarse Euler step makes an accidental reset to the historical 1 ms
6270        // zeroing step observable, while remaining stable and physically meaningful.
6271        let mut segmented = configured_euler_zero(-10.0, 0.02);
6272        let coarse_height = segmented
6273            .zero_trial_height_at(0.0, TARGET_DISTANCE_M, ZeroTargetFrame::SightLine)
6274            .expect("coarse configured trial")
6275            .expect("coarse trial reaches target");
6276        let mut fine = segmented.clone();
6277        fine.set_time_step(0.001);
6278        let fine_height = fine
6279            .zero_trial_height_at(0.0, TARGET_DISTANCE_M, ZeroTargetFrame::SightLine)
6280            .expect("fine configured trial")
6281            .expect("fine trial reaches target");
6282        assert!(
6283            (coarse_height - fine_height).abs() > 1e-5,
6284            "configured Euler step must affect zero trials: coarse={coarse_height}, fine={fine_height}"
6285        );
6286
6287        let segmented_angle = segmented
6288            .calculate_and_set_zero_angle(
6289                TARGET_DISTANCE_M,
6290                TARGET_HEIGHT_M,
6291                ZeroTargetFrame::SightLine,
6292            )
6293            .expect("segmented zero");
6294        assert_eq!(
6295            segmented.inputs.muzzle_angle.to_bits(),
6296            segmented_angle.to_bits(),
6297            "successful zero must install its angle on the configured solver"
6298        );
6299        assert_eq!(segmented.time_step.to_bits(), 0.02_f64.to_bits());
6300        assert_eq!(segmented.max_range.to_bits(), 300.0_f64.to_bits());
6301        assert!(segmented.wind_sock.is_some());
6302        assert_eq!(segmented.station_presence, StationAtmospherePresence::BOTH);
6303        let zero_height = segmented
6304            .zero_trial_height_at(
6305                segmented_angle,
6306                TARGET_DISTANCE_M,
6307                ZeroTargetFrame::SightLine,
6308            )
6309            .expect("verify segmented zero")
6310            .expect("zeroed trial reaches target");
6311        assert!(
6312            (zero_height - TARGET_HEIGHT_M).abs() < 0.0001,
6313            "configured zero missed target: height={zero_height}"
6314        );
6315
6316        let mut calm = configured_euler_zero(0.0, 0.02);
6317        let calm_angle = calm
6318            .calculate_and_set_zero_angle(
6319                TARGET_DISTANCE_M,
6320                TARGET_HEIGHT_M,
6321                ZeroTargetFrame::SightLine,
6322            )
6323            .expect("calm zero");
6324        assert!(
6325            (segmented_angle - calm_angle).abs() > 1e-5,
6326            "segmented vertical wind must participate in zero trials: segmented={segmented_angle}, calm={calm_angle}"
6327        );
6328    }
6329}
6330
6331#[cfg(test)]
6332mod uniform_gravity_tests {
6333    use super::*;
6334
6335    #[test]
6336    fn uniform_gravity_is_per_solver_and_survives_cloning() {
6337        for (use_rk4, use_adaptive_rk45) in [(false, false), (true, false), (true, true)] {
6338            // A ball with negligible drag provides an independent constant-acceleration oracle.
6339            let inputs = BallisticInputs {
6340                bullet_mass: 0.0459,
6341                bullet_diameter: 0.0427,
6342                bullet_length: 0.0427,
6343                muzzle_velocity: 10.0,
6344                muzzle_height: 10.0,
6345                muzzle_angle: 0.0,
6346                bc_type: DragModel::GS,
6347                custom_drag_table: Some(crate::drag::DragTable::new(
6348                    vec![0.0, 5.0],
6349                    vec![1e-20, 1e-20],
6350                )),
6351                use_rk4,
6352                use_adaptive_rk45,
6353                ..BallisticInputs::default()
6354            };
6355            let public = TrajectorySolver::new(
6356                inputs.clone(),
6357                WindConditions::default(),
6358                AtmosphericConditions::default(),
6359            );
6360            for magnitude in [0.0, 1.62, 9.80665, 20.0] {
6361                let mut solver = TrajectorySolver::new_with_station_presence_and_gravity(
6362                    inputs.clone(),
6363                    WindConditions::default(),
6364                    AtmosphericConditions::default(),
6365                    StationAtmospherePresence::NEITHER,
6366                    Gravity::new(magnitude).unwrap(),
6367                )
6368                .clone();
6369                solver.set_max_range(10.0);
6370                let result = solver.solve().unwrap();
6371                let end = result.points.last().unwrap();
6372                assert!((end.time - 1.0).abs() < 1e-8);
6373                // The endpoint is linearly interpolated across the final step: a parabola's
6374                // interpolation error is bounded by g*dt²/8. Euler also has O(dt) error.
6375                let step = if use_adaptive_rk45 {
6376                    RK45_MAX_DT
6377                } else {
6378                    solver.time_step
6379                };
6380                let tolerance = magnitude * step * step / 8.0
6381                    + if use_rk4 { 0.0 } else { magnitude * step / 2.0 }
6382                    + 1e-8;
6383                assert!(
6384                    (end.position.y - (10.0 - 0.5 * magnitude)).abs() < tolerance,
6385                    "g={magnitude}, rk4={use_rk4}, adaptive={use_adaptive_rk45}, y={}, time={}",
6386                    end.position.y,
6387                    end.time
6388                );
6389                assert!(
6390                    (solver.speed_budget(1.0) - solver.speed_budget(0.0) - magnitude).abs() < 1e-12
6391                );
6392                assert_eq!(public.gravity, Gravity::EARTH);
6393                if magnitude == 9.80665 {
6394                    let mut earth = public.clone();
6395                    earth.set_max_range(10.0);
6396                    let reference = earth.solve().unwrap();
6397                    assert_eq!(result.points.len(), reference.points.len());
6398                    for (actual, expected) in result.points.iter().zip(&reference.points) {
6399                        assert_eq!(actual.time.to_bits(), expected.time.to_bits());
6400                        assert_eq!(actual.position, expected.position);
6401                        assert_eq!(
6402                            actual.velocity_magnitude.to_bits(),
6403                            expected.velocity_magnitude.to_bits()
6404                        );
6405                    }
6406                }
6407            }
6408        }
6409    }
6410
6411    fn match_308_inputs() -> BallisticInputs {
6412        BallisticInputs {
6413            muzzle_velocity: 800.0,
6414            bullet_mass: 168.0 * crate::constants::GRAINS_TO_KG,
6415            bullet_diameter: 0.308 * 0.0254,
6416            bullet_length: 1.215 * 0.0254,
6417            twist_rate: 10.0,
6418            ..BallisticInputs::default()
6419        }
6420    }
6421
6422    fn station_1000_m() -> AtmosphericConditions {
6423        AtmosphericConditions {
6424            temperature: 15.0,
6425            pressure: 1013.25,
6426            humidity: 0.0,
6427            altitude: 1000.0,
6428        }
6429    }
6430
6431    /// The solver's acceleration under `gravity`, minus the shot-frame gravity it adds: what is
6432    /// left is drag and Magnus, the parts that read gravity through the atmosphere and the yaw
6433    /// of repose.
6434    fn aerodynamic_acceleration_with_gravity(
6435        inputs: &BallisticInputs,
6436        gravity: Gravity,
6437        position: Vector3<f64>,
6438        velocity: Vector3<f64>,
6439    ) -> Vector3<f64> {
6440        let solver = TrajectorySolver::new_with_station_presence_and_gravity(
6441            inputs.clone(),
6442            WindConditions::default(),
6443            station_1000_m(),
6444            StationAtmospherePresence::BOTH,
6445            gravity,
6446        );
6447        let station = solver.station_air().unwrap();
6448        solver.calculate_acceleration(&position, &velocity, &Vector3::zeros(), &station)
6449            - solver.gravity_acceleration()
6450    }
6451
6452    #[test]
6453    fn local_atmosphere_uses_the_simulation_gravity() {
6454        let inputs = match_308_inputs(); // Magnus off
6455        let velocity = Vector3::new(600.0, 0.0, 0.0);
6456        let low_gravity = Gravity::new(3.71).unwrap();
6457        let aerodynamic = |position, gravity| {
6458            aerodynamic_acceleration_with_gravity(&inputs, gravity, position, velocity)
6459        };
6460
6461        // Control: at the station there is no air column to integrate, so gravity cannot reach
6462        // the density.
6463        let earth = aerodynamic(Vector3::zeros(), Gravity::EARTH);
6464        let low = aerodynamic(Vector3::zeros(), low_gravity);
6465        assert!(
6466            (earth - low).norm() < 1e-12,
6467            "station-altitude drag must not depend on gravity: earth={earth:?}, low={low:?}"
6468        );
6469
6470        // 2000 m above the station, pressure falls more slowly under weaker gravity, so the air is
6471        // denser and drag is stronger.
6472        let aloft = Vector3::new(0.0, 2_000.0, 0.0);
6473        let earth = aerodynamic(aloft, Gravity::EARTH);
6474        let low = aerodynamic(aloft, low_gravity);
6475        let ratio = low.x / earth.x;
6476        assert!(earth.x < 0.0, "drag must oppose flight: {earth:?}");
6477        assert!(
6478            (ratio - 1.162_702).abs() < 1e-4,
6479            "drag aloft must follow the simulation's hydrostatic density: low/earth={ratio}, \
6480             expected 1.162702 (standard lapse rate, 1000 m station, 2000 m above it)"
6481        );
6482    }
6483
6484    #[test]
6485    fn magnus_yaw_of_repose_uses_the_simulation_gravity() {
6486        let velocity = Vector3::new(800.0, 0.0, 0.0);
6487        let low_gravity = Gravity::new(3.71).unwrap();
6488        // At the station, so the density cannot depend on gravity.
6489        let aerodynamic = |enable_magnus, gravity| {
6490            let inputs = BallisticInputs {
6491                enable_magnus,
6492                ..match_308_inputs()
6493            };
6494            aerodynamic_acceleration_with_gravity(&inputs, gravity, Vector3::zeros(), velocity)
6495        };
6496
6497        // Control: without Magnus the aerodynamic acceleration is the same under both gravities.
6498        let earth = aerodynamic(false, Gravity::EARTH);
6499        let low = aerodynamic(false, low_gravity);
6500        assert!(
6501            (earth - low).norm() < 1e-12,
6502            "Magnus-off drag must not depend on gravity: earth={earth:?}, low={low:?}"
6503        );
6504
6505        // Yaw of repose is proportional to g, and the Magnus force to the sine of that small yaw.
6506        let earth = aerodynamic(true, Gravity::EARTH) - earth;
6507        let low = aerodynamic(true, low_gravity) - low;
6508        let ratio = low.y / earth.y;
6509        let expected = low_gravity.magnitude() / Gravity::EARTH.magnitude();
6510        assert!(
6511            earth.y < 0.0,
6512            "right-hand Magnus must point down: {earth:?}"
6513        );
6514        assert!(
6515            (ratio - expected).abs() < 1e-6,
6516            "Magnus must scale with the simulation's gravity: low/earth={ratio}, expected={expected}"
6517        );
6518    }
6519}
6520
6521#[cfg(test)]
6522mod result_sanity_tests {
6523    use super::*;
6524
6525    fn default_solver() -> TrajectorySolver {
6526        TrajectorySolver::new(
6527            BallisticInputs::default(),
6528            WindConditions::default(),
6529            AtmosphericConditions::default(),
6530        )
6531    }
6532
6533    fn minimal_result() -> TrajectoryResult {
6534        TrajectoryResult {
6535            max_range: 100.0,
6536            max_height: 1.0,
6537            time_of_flight: 0.5,
6538            impact_velocity: 700.0,
6539            impact_energy: 2450.0,
6540            projectile_mass_kg: 0.01,
6541            line_of_sight_height_m: 1.5,
6542            station_speed_of_sound_mps: 340.0,
6543            termination: TrajectoryTermination::MaxRange,
6544            points: vec![],
6545            sampled_points: None,
6546            min_pitch_damping: None,
6547            transonic_mach: None,
6548            angular_state: None,
6549            max_yaw_angle: None,
6550            max_precession_angle: None,
6551            aerodynamic_jump: None,
6552            mach_1_2_distance_m: None,
6553            mach_1_0_distance_m: None,
6554            mach_0_9_distance_m: None,
6555        }
6556    }
6557
6558    #[test]
6559    fn mba1293_negative_scalars_fail_the_result_postcondition() {
6560        let solver = default_solver();
6561        solver
6562            .validate_result_sanity(&minimal_result())
6563            .expect("a sane result must pass");
6564
6565        for (name, mutate) in [
6566            (
6567                "max_range",
6568                (|r| r.max_range = -50.588) as fn(&mut TrajectoryResult),
6569            ),
6570            ("time_of_flight", |r| r.time_of_flight = -1.0),
6571            ("impact_velocity", |r| r.impact_velocity = -700.0),
6572            ("impact_energy", |r| r.impact_energy = -1.0),
6573        ] {
6574            let mut result = minimal_result();
6575            mutate(&mut result);
6576            let error = solver
6577                .validate_result_sanity(&result)
6578                .expect_err("negative scalar must fail");
6579            assert!(
6580                error.to_string().contains(name),
6581                "error for {name} did not name the field: {error}"
6582            );
6583        }
6584    }
6585
6586    #[test]
6587    fn mba1293_speed_budget_bounds_legitimate_states_and_rejects_divergence() {
6588        let solver = default_solver();
6589        let mv = solver.inputs.muzzle_velocity;
6590
6591        // A state at muzzle speed is always inside the budget.
6592        let position = Vector3::new(10.0, 0.0, 0.0);
6593        solver
6594            .validate_integration_state(&position, &Vector3::new(mv, 0.0, 0.0), 0.01)
6595            .expect("muzzle-speed state must pass");
6596
6597        // The MBA-1293 explosion (13x the muzzle speed) must be rejected as divergence.
6598        let error = solver
6599            .validate_integration_state(&position, &Vector3::new(-13.0 * mv, 0.0, 0.0), 0.01)
6600            .expect_err("13x muzzle speed must fail the budget");
6601        assert!(error.to_string().contains("diverged"), "{error}");
6602
6603        // The budget grows with gravity's g*t so long lobbed arcs never trip it.
6604        let after_fall = mv + crate::constants::G_ACCEL_MPS2 * 60.0;
6605        solver
6606            .validate_integration_state(&position, &Vector3::new(0.0, -after_fall, 0.0), 60.0)
6607            .expect("gravity-accelerated speed within g*t must pass");
6608    }
6609}
6610
6611#[cfg(test)]
6612mod trajectory_point_budget_tests {
6613    use super::*;
6614    use crate::MAX_TRAJECTORY_SAMPLES;
6615
6616    fn solver_with_budget(
6617        use_rk4: bool,
6618        use_adaptive_rk45: bool,
6619        point_budget: usize,
6620        max_range: f64,
6621    ) -> TrajectorySolver {
6622        let inputs = BallisticInputs {
6623            use_rk4,
6624            use_adaptive_rk45,
6625            ground_threshold: f64::NEG_INFINITY,
6626            ..BallisticInputs::default()
6627        };
6628        let mut solver = TrajectorySolver::new(
6629            inputs,
6630            WindConditions::default(),
6631            AtmosphericConditions::default(),
6632        );
6633        solver.max_trajectory_points = point_budget;
6634        solver.set_max_range(max_range);
6635        solver.set_time_step(0.001);
6636        solver
6637    }
6638
6639    #[test]
6640    fn mba1283_every_solver_errors_instead_of_exceeding_point_budget() {
6641        for (mode, use_rk4, use_adaptive_rk45) in [
6642            ("Euler", false, false),
6643            ("RK4", true, false),
6644            ("RK45", true, true),
6645        ] {
6646            let error = solver_with_budget(use_rk4, use_adaptive_rk45, 3, 10.0)
6647                .solve()
6648                .expect_err("a solve requiring more than three points must fail");
6649            assert!(
6650                error.to_string().contains("point limit of 3"),
6651                "unexpected {mode} point-budget error: {error}"
6652            );
6653        }
6654    }
6655
6656    #[test]
6657    fn mba1283_interpolated_endpoint_counts_toward_point_budget() {
6658        for (mode, use_rk4, use_adaptive_rk45) in [
6659            ("Euler", false, false),
6660            ("RK4", true, false),
6661            ("RK45", true, true),
6662        ] {
6663            let result = solver_with_budget(use_rk4, use_adaptive_rk45, 2, 0.1)
6664                .solve()
6665                .expect("the initial point plus exact endpoint fit a two-point budget");
6666            assert_eq!(result.points.len(), 2, "unexpected {mode} point count");
6667
6668            let error = solver_with_budget(use_rk4, use_adaptive_rk45, 1, 0.1)
6669                .solve()
6670                .expect_err("the exact endpoint must not exceed a one-point budget");
6671            assert!(
6672                error.to_string().contains("point limit of 1"),
6673                "unexpected {mode} endpoint-budget error: {error}"
6674            );
6675        }
6676    }
6677
6678    /// MBA-1599: a stalled flight stores one point per downrange distance, but every step it
6679    /// collapses still counts against the point budget. The budget here is one more than the
6680    /// points the flight stores, so the stored points alone can never reach it and only the
6681    /// collapsed steps can. It is still far smaller than the steps the flight took, so the solve
6682    /// fails at the budget as it did when every step was stored, instead of running on to the
6683    /// ground threshold. (A budget of exactly the stored points would fail on the first collapse
6684    /// after the last stored point whether or not collapsed steps were counted.)
6685    #[test]
6686    fn mba1599_collapsed_stall_steps_count_toward_point_budget() {
6687        for (mode, use_rk4, use_adaptive_rk45, bc_value) in [
6688            ("Euler", false, false, 2.0e-4),
6689            ("RK4", true, false, 1.0e-4),
6690            ("RK45", true, true, 1.0e-4),
6691        ] {
6692            let stalled = |point_budget: usize| {
6693                let inputs = BallisticInputs {
6694                    bc_value,
6695                    bc_type: DragModel::G7,
6696                    bullet_mass: 0.01134,
6697                    bullet_diameter: 0.00782,
6698                    muzzle_velocity: 823.0,
6699                    use_rk4,
6700                    use_adaptive_rk45,
6701                    ground_threshold: -100.0,
6702                    ..BallisticInputs::default()
6703                };
6704                let mut solver = TrajectorySolver::new(
6705                    inputs,
6706                    WindConditions::default(),
6707                    AtmosphericConditions::default(),
6708                );
6709                solver.max_trajectory_points = point_budget;
6710                solver.set_max_range(300.0);
6711                solver.set_time_step(0.001);
6712                solver.solve()
6713            };
6714
6715            let flown = stalled(MAX_TRAJECTORY_POINTS)
6716                .unwrap_or_else(|error| panic!("{mode}: the stall ends inside the cap: {error}"));
6717            assert_eq!(
6718                flown.termination,
6719                TrajectoryTermination::GroundThreshold,
6720                "{mode}"
6721            );
6722            let stored = flown.points.len();
6723            let budget = stored + 1;
6724            let Err(error) = stalled(budget) else {
6725                panic!("{mode}: the flight fit a {budget}-point budget with {stored} stored points, so the collapsed steps were not counted");
6726            };
6727            assert!(
6728                error
6729                    .to_string()
6730                    .contains(&format!("trajectory point limit of {budget} exceeded")),
6731                "unexpected {mode} stall-budget error: {error}"
6732            );
6733        }
6734    }
6735
6736    /// MBA-1599: the budget counts calls, stored or collapsed, so the call that fails is call
6737    /// budget + 1 however many earlier calls collapsed. That is the call that failed when every
6738    /// call stored a point. The stored terminal point is held to the same count.
6739    #[test]
6740    fn mba1599_point_budget_fails_on_the_same_call_with_or_without_collapsing() {
6741        let solver = solver_with_budget(true, false, 4, 10.0);
6742        let point = |x: f64| TrajectoryPoint {
6743            time: x,
6744            position: Vector3::new(x, 0.0, 0.0),
6745            velocity_magnitude: 1.0,
6746            kinetic_energy: 0.0,
6747            drag_coefficient: None,
6748        };
6749        let assert_over_budget = |error: BallisticsError| {
6750            assert!(
6751                error
6752                    .to_string()
6753                    .contains("trajectory point limit of 4 exceeded"),
6754                "unexpected point-budget error: {error}"
6755            );
6756        };
6757        for distances in [
6758            [0.0, 1.0, 2.0, 3.0],
6759            [0.0, 1.0, 1.0, 2.0],
6760            [0.0, 0.0, 0.0, 0.0],
6761        ] {
6762            let mut points = Vec::new();
6763            let mut collapsed_steps = 0;
6764            for x in distances {
6765                solver
6766                    .push_trajectory_point(&mut points, point(x), &mut collapsed_steps)
6767                    .expect("four calls fit a four-point budget");
6768            }
6769            assert_eq!(points.len() + collapsed_steps, 4, "{distances:?}");
6770
6771            // A fifth call fails whether it would collapse or store a point.
6772            for x in [distances[3], 5.0] {
6773                let error = solver
6774                    .push_trajectory_point(
6775                        &mut points.clone(),
6776                        point(x),
6777                        &mut collapsed_steps.clone(),
6778                    )
6779                    .expect_err("a fifth call exceeds a four-point budget");
6780                assert_over_budget(error);
6781            }
6782            // So does a terminal point stored after four integration steps.
6783            let error = solver
6784                .append_terminal_endpoint(
6785                    &mut points.clone(),
6786                    Vector3::new(20.0, 0.0, 0.0),
6787                    Vector3::new(1.0, 0.0, 0.0),
6788                    10.0,
6789                    &mut 0.0,
6790                    &mut collapsed_steps.clone(),
6791                )
6792                .expect_err("the terminal point is a fifth call");
6793            assert_over_budget(error);
6794        }
6795    }
6796
6797    #[test]
6798    fn mba1299_every_solver_preflights_the_sample_budget() {
6799        for (mode, use_rk4, use_adaptive_rk45) in [
6800            ("Euler", false, false),
6801            ("RK4", true, false),
6802            ("RK45", true, true),
6803        ] {
6804            let inputs = BallisticInputs {
6805                use_rk4,
6806                use_adaptive_rk45,
6807                enable_trajectory_sampling: true,
6808                sample_interval: 1.0,
6809                ground_threshold: f64::NEG_INFINITY,
6810                ..BallisticInputs::default()
6811            };
6812            let mut solver = TrajectorySolver::new(
6813                inputs,
6814                WindConditions::default(),
6815                AtmosphericConditions::default(),
6816            );
6817            solver.set_max_range(MAX_TRAJECTORY_SAMPLES as f64);
6818            // If validation does not reject the sample grid before dispatch, the first attempted
6819            // integration point produces a distinct point-budget error.
6820            solver.max_trajectory_points = 0;
6821
6822            let error = solver
6823                .solve()
6824                .expect_err("an over-limit sample grid must fail before integration");
6825            assert!(
6826                error
6827                    .to_string()
6828                    .contains("trajectory sample limit of 250000 exceeded"),
6829                "unexpected {mode} sample-budget error: {error}"
6830            );
6831        }
6832    }
6833
6834    #[test]
6835    fn mba1299_normal_sampling_does_not_change_solver_results() {
6836        for (mode, use_rk4, use_adaptive_rk45) in [
6837            ("Euler", false, false),
6838            ("RK4", true, false),
6839            ("RK45", true, true),
6840        ] {
6841            let solve = |enable_trajectory_sampling| {
6842                let inputs = BallisticInputs {
6843                    use_rk4,
6844                    use_adaptive_rk45,
6845                    enable_trajectory_sampling,
6846                    sample_interval: 0.5,
6847                    ground_threshold: f64::NEG_INFINITY,
6848                    ..BallisticInputs::default()
6849                };
6850                let mut solver = TrajectorySolver::new(
6851                    inputs,
6852                    WindConditions::default(),
6853                    AtmosphericConditions::default(),
6854                );
6855                solver.set_max_range(2.0);
6856                solver.solve().expect("normal short-range solve")
6857            };
6858
6859            let baseline = solve(false);
6860            let sampled = solve(true);
6861            for (field, left, right) in [
6862                ("max_range", baseline.max_range, sampled.max_range),
6863                ("max_height", baseline.max_height, sampled.max_height),
6864                (
6865                    "time_of_flight",
6866                    baseline.time_of_flight,
6867                    sampled.time_of_flight,
6868                ),
6869                (
6870                    "impact_velocity",
6871                    baseline.impact_velocity,
6872                    sampled.impact_velocity,
6873                ),
6874                (
6875                    "impact_energy",
6876                    baseline.impact_energy,
6877                    sampled.impact_energy,
6878                ),
6879            ] {
6880                assert_eq!(
6881                    left.to_bits(),
6882                    right.to_bits(),
6883                    "{mode} sampling changed {field}"
6884                );
6885            }
6886            assert_eq!(baseline.points.len(), sampled.points.len());
6887            for (index, (left, right)) in baseline.points.iter().zip(&sampled.points).enumerate() {
6888                assert_eq!(
6889                    left.time.to_bits(),
6890                    right.time.to_bits(),
6891                    "{mode} point {index}"
6892                );
6893                assert_eq!(
6894                    left.position.map(f64::to_bits),
6895                    right.position.map(f64::to_bits),
6896                    "{mode} point {index} position"
6897                );
6898                assert_eq!(
6899                    left.velocity_magnitude.to_bits(),
6900                    right.velocity_magnitude.to_bits(),
6901                    "{mode} point {index} velocity"
6902                );
6903                assert_eq!(
6904                    left.kinetic_energy.to_bits(),
6905                    right.kinetic_energy.to_bits(),
6906                    "{mode} point {index} energy"
6907                );
6908            }
6909            assert!(baseline.sampled_points.is_none());
6910            let samples = sampled
6911                .sampled_points
6912                .expect("sampling-enabled solve should return observations");
6913            assert_eq!(
6914                samples
6915                    .iter()
6916                    .map(|sample| sample.distance_m)
6917                    .collect::<Vec<_>>(),
6918                vec![0.0, 0.5, 1.0, 1.5, 2.0],
6919                "{mode} normal sampling grid changed"
6920            );
6921        }
6922    }
6923}
6924
6925#[cfg(test)]
6926mod monte_carlo_result_tests {
6927    use super::*;
6928
6929    fn make_results(impact_positions: Vec<Vector3<f64>>) -> MonteCarloResults {
6930        let count = impact_positions.len();
6931        MonteCarloResults {
6932            ranges: vec![500.0; count],
6933            impact_velocities: vec![300.0; count],
6934            impact_positions,
6935        }
6936    }
6937
6938    #[test]
6939    fn target_plane_cep_excludes_shortfall_markers() {
6940        let mut positions: Vec<Vector3<f64>> = (1..=5)
6941            .map(|radius| Vector3::new(0.0, radius as f64, 0.0))
6942            .collect();
6943        positions.extend((0..5).map(|_| Vector3::new(0.0, TARGET_NOT_REACHED_SENTINEL_M, 0.0)));
6944        let results = make_results(positions);
6945
6946        assert_eq!(results.target_arrival_count(), 5);
6947        assert_eq!(results.target_shortfall_fraction(), 0.5);
6948        assert_eq!(results.target_plane_cep(), Some(3.0));
6949
6950        let one_shortfall = make_results(vec![
6951            Vector3::new(0.0, 1.0, 0.0),
6952            Vector3::new(0.0, 2.0, 0.0),
6953            Vector3::new(0.0, 3.0, 0.0),
6954            Vector3::new(0.0, 4.0, 0.0),
6955            Vector3::new(0.0, 5.0, 0.0),
6956            Vector3::new(0.0, TARGET_NOT_REACHED_SENTINEL_M, 0.0),
6957        ]);
6958        assert_eq!(one_shortfall.target_plane_cep(), Some(3.0));
6959    }
6960
6961    #[test]
6962    fn all_shortfalls_have_no_cep_but_still_count_as_misses() {
6963        let all_shortfalls = make_results(vec![
6964            Vector3::new(0.0, TARGET_NOT_REACHED_SENTINEL_M, 0.0),
6965            Vector3::new(0.0, TARGET_NOT_REACHED_SENTINEL_M, 0.0),
6966        ]);
6967        assert_eq!(all_shortfalls.target_arrival_count(), 0);
6968        assert_eq!(all_shortfalls.target_shortfall_fraction(), 1.0);
6969        assert_eq!(all_shortfalls.target_plane_cep(), None);
6970        assert_eq!(all_shortfalls.hit_probability(0.3), 0.0);
6971
6972        let one_hit_one_shortfall = make_results(vec![
6973            Vector3::new(0.0, 0.1, 0.0),
6974            Vector3::new(0.0, TARGET_NOT_REACHED_SENTINEL_M, 0.0),
6975        ]);
6976        assert_eq!(one_hit_one_shortfall.hit_probability(0.3), 0.5);
6977    }
6978
6979    // MBA-1317: WEZ rectangular hit probability.
6980    #[test]
6981    fn rect_hit_probability_checks_independent_axis_halves() {
6982        let results = make_results(vec![
6983            // Inside a 0.4 (lateral) x 0.6 (vertical) box: half-width 0.2, half-height 0.3.
6984            Vector3::new(0.0, 0.1, 0.1),
6985            // On the lateral edge (exactly half-width) -> counts as a hit ("<=").
6986            Vector3::new(0.0, 0.0, 0.2),
6987            // Outside laterally (just past half-width).
6988            Vector3::new(0.0, 0.0, 0.201),
6989            // Outside vertically (just past half-height).
6990            Vector3::new(0.0, 0.301, 0.0),
6991            // Shortfall marker: stays in the denominator, never a hit.
6992            Vector3::new(0.0, TARGET_NOT_REACHED_SENTINEL_M, 0.0),
6993        ]);
6994        // 2 hits out of 5 samples.
6995        assert!((results.rect_hit_probability(0.4, 0.6) - 0.4).abs() < 1e-12);
6996    }
6997
6998    #[test]
6999    fn rect_hit_probability_matches_circular_hit_probability_for_a_centered_hit() {
7000        let results = make_results(vec![Vector3::new(0.0, 0.0, 0.0)]);
7001        assert_eq!(results.rect_hit_probability(0.5, 0.5), 1.0);
7002        assert_eq!(results.hit_probability(0.3), 1.0);
7003    }
7004
7005    #[test]
7006    fn rect_hit_probability_is_zero_for_empty_or_nonpositive_dimensions() {
7007        let empty = make_results(vec![]);
7008        assert_eq!(empty.rect_hit_probability(1.0, 1.0), 0.0);
7009
7010        let results = make_results(vec![Vector3::new(0.0, 0.0, 0.0)]);
7011        assert_eq!(results.rect_hit_probability(0.0, 1.0), 0.0);
7012        assert_eq!(results.rect_hit_probability(1.0, 0.0), 0.0);
7013        assert_eq!(results.rect_hit_probability(-1.0, 1.0), 0.0);
7014    }
7015}
7016
7017/// 0.49.0: the `*_with_station_presence` twins. Every NEITHER assertion is against a value
7018/// pinned at ab4eb0c, never against the legacy name alone: the legacy names now delegate to
7019/// the twins, so a twin-against-legacy comparison would move with a broken twin.
7020#[cfg(test)]
7021mod station_presence_twin_tests {
7022    use super::*;
7023
7024    fn rifle() -> BallisticInputs {
7025        BallisticInputs {
7026            muzzle_velocity: 823.0,
7027            bc_value: 0.475,
7028            bc_type: DragModel::G1,
7029            bullet_mass: 0.0109,
7030            bullet_diameter: 0.00782,
7031            sight_height: 0.0381,
7032            ..Default::default()
7033        }
7034    }
7035
7036    fn air(temperature: f64, pressure: f64, altitude: f64) -> AtmosphericConditions {
7037        AtmosphericConditions {
7038            temperature,
7039            pressure,
7040            humidity: 50.0,
7041            altitude,
7042        }
7043    }
7044
7045    #[test]
7046    fn zero_twins_reproduce_ab4eb0c_with_neither_and_fly_a_supplied_reading() {
7047        // (temperature, pressure, altitude, zero angle, near crossing, far crossing for a
7048        // 0.002 rad bore angle), all captured at ab4eb0c.
7049        // Re-captured in 0.50.0 (the default 50 % RH aloft now holds the
7050        // station's water-vapour mole fraction, with a virtual-temperature lapse), old -> new: the
7051        // zero angles did not move (the bisection's 1e-7 rad step hides it); the crossings near
7052        // 20.667807586483896 -> 20.66780758664646 m (+7.9e-12) and far 224.33240698998765 ->
7053        // 224.33240545071135 m (-6.9e-9) at 150 m, and near 20.665489730827762 -> 20.66548973089652
7054        // m (+3.3e-12) and far 227.33514089305447 -> 227.33514021685897 m (-3.0e-9) at 1500 m.
7055        let cases = [
7056            (
7057                20.0,
7058                1013.0,
7059                150.0,
7060                f64::from_bits(0x3f65f73333333333),
7061                f64::from_bits(0x4034aaf57020aad0),
7062                f64::from_bits(0x406c0aa310c17a28),
7063            ),
7064            (
7065                15.0,
7066                850.0,
7067                1500.0,
7068                f64::from_bits(0x3f6594ccccccccce),
7069                f64::from_bits(0x4034aa5d88f6063f),
7070                f64::from_bits(0x406c6ab977f9df7a),
7071            ),
7072        ];
7073        for (t, p, alt, zero, near, far) in cases {
7074            let calm = WindConditions::default;
7075            let legacy = calculate_zero_angle_with_conditions(
7076                rifle(),
7077                300.0,
7078                0.0381,
7079                calm(),
7080                air(t, p, alt),
7081            )
7082            .unwrap();
7083            let neither = calculate_zero_angle_with_station_presence(
7084                rifle(),
7085                300.0,
7086                0.0381,
7087                calm(),
7088                air(t, p, alt),
7089                StationAtmospherePresence::NEITHER,
7090            )
7091            .unwrap();
7092            assert_eq!(
7093                legacy.to_bits(),
7094                zero.to_bits(),
7095                "legacy zero ({t}, {p}, {alt})"
7096            );
7097            assert_eq!(
7098                neither.to_bits(),
7099                zero.to_bits(),
7100                "NEITHER zero ({t}, {p}, {alt})"
7101            );
7102
7103            let legacy_range = calculate_zero_range_from_angle_with_conditions(
7104                rifle(),
7105                0.002,
7106                0.0381,
7107                calm(),
7108                air(t, p, alt),
7109            )
7110            .unwrap();
7111            let neither_range = calculate_zero_range_from_angle_with_station_presence(
7112                rifle(),
7113                0.002,
7114                0.0381,
7115                calm(),
7116                air(t, p, alt),
7117                StationAtmospherePresence::NEITHER,
7118            )
7119            .unwrap();
7120            for crossings in [legacy_range, neither_range] {
7121                assert_eq!(crossings.near_m.unwrap().to_bits(), near.to_bits());
7122                assert_eq!(crossings.far_m.unwrap().to_bits(), far.to_bits());
7123            }
7124
7125            // BOTH flies the pair as given: it equals the authoritative path that existed at
7126            // ab4eb0c, and differs from the swapped NEITHER result.
7127            let both = calculate_zero_angle_with_station_presence(
7128                rifle(),
7129                300.0,
7130                0.0381,
7131                calm(),
7132                air(t, p, alt),
7133                StationAtmospherePresence::BOTH,
7134            )
7135            .unwrap();
7136            let authoritative = calculate_zero_angle_with_resolved_conditions(
7137                rifle(),
7138                300.0,
7139                0.0381,
7140                calm(),
7141                air(t, p, alt),
7142            )
7143            .unwrap();
7144            assert_eq!(both.to_bits(), authoritative.to_bits());
7145            assert_ne!(
7146                both.to_bits(),
7147                zero.to_bits(),
7148                "BOTH must not swap ({t}, {p}, {alt})"
7149            );
7150
7151            let both_range = calculate_zero_range_from_angle_with_station_presence(
7152                rifle(),
7153                0.002,
7154                0.0381,
7155                calm(),
7156                air(t, p, alt),
7157                StationAtmospherePresence::BOTH,
7158            )
7159            .unwrap();
7160            let authoritative_range = calculate_zero_range_from_angle_with_resolved_conditions(
7161                rifle(),
7162                0.002,
7163                0.0381,
7164                calm(),
7165                air(t, p, alt),
7166            )
7167            .unwrap();
7168            assert_eq!(both_range, authoritative_range);
7169            assert_ne!(both_range.far_m.unwrap().to_bits(), far.to_bits());
7170        }
7171    }
7172
7173    #[test]
7174    fn solver_twin_with_both_lies_between_out_of_band_neighbours() {
7175        let impact = |p: f64, presence| {
7176            let mut solver = TrajectorySolver::new_with_station_presence(
7177                rifle(),
7178                WindConditions::default(),
7179                air(20.0, p, 150.0),
7180                presence,
7181            );
7182            solver.set_max_range(600.0);
7183            solver.solve().unwrap().impact_velocity
7184        };
7185        let low = impact(1012.0, StationAtmospherePresence::NEITHER);
7186        let high = impact(1014.0, StationAtmospherePresence::NEITHER);
7187        let both = impact(1013.0, StationAtmospherePresence::BOTH);
7188        let neither = impact(1013.0, StationAtmospherePresence::NEITHER);
7189        // Denser air slows the bullet more: velocity falls as pressure rises.
7190        assert!(high < both && both < low, "{high} < {both} < {low}");
7191        assert_ne!(both.to_bits(), neither.to_bits());
7192
7193        let temperature = |t: f64, presence| {
7194            let mut solver = TrajectorySolver::new_with_station_presence(
7195                rifle(),
7196                WindConditions::default(),
7197                air(t, 850.0, 1500.0),
7198                presence,
7199            );
7200            solver.set_max_range(600.0);
7201            solver.solve().unwrap().impact_velocity
7202        };
7203        let cold = temperature(14.8, StationAtmospherePresence::NEITHER);
7204        let warm = temperature(15.2, StationAtmospherePresence::NEITHER);
7205        let both = temperature(15.0, StationAtmospherePresence::BOTH);
7206        // Warmer air is thinner: velocity rises with temperature.
7207        assert!(cold < both && both < warm, "{cold} < {both} < {warm}");
7208        assert_ne!(
7209            both.to_bits(),
7210            temperature(15.0, StationAtmospherePresence::NEITHER).to_bits()
7211        );
7212    }
7213
7214    /// The `legacy_seeded_estimates_are_pinned_bit_for_bit` fixture through the twin.
7215    #[test]
7216    fn monte_carlo_twin_with_neither_reproduces_the_legacy_seeded_pins() {
7217        let inputs = BallisticInputs {
7218            muzzle_velocity: 800.0,
7219            ..BallisticInputs::default()
7220        };
7221        let params = MonteCarloParams {
7222            num_simulations: 200,
7223            target_distance: Some(500.0),
7224            ..MonteCarloParams::default()
7225        };
7226        let results = run_monte_carlo_with_station_presence(
7227            inputs,
7228            WindConditions::default(),
7229            params,
7230            0.01,
7231            Some(0x1352_5EED),
7232            StationAtmospherePresence::NEITHER,
7233        )
7234        .unwrap();
7235        assert_eq!(results.ranges.len(), 200);
7236        assert_eq!(
7237            results.hit_probability(DEFAULT_HIT_RADIUS_M).to_bits(),
7238            0.14_f64.to_bits()
7239        );
7240        // The legacy seeded pins of `monte_carlo_seeded_tests`, re-captured with them for the
7241        // aloft change.
7242        let expected_ranges: [f64; 3] = [1907.9716332174821, 1936.4071333440454, 1912.81384414182];
7243        let expected_velocities: [f64; 3] =
7244            [238.6179931921287, 239.9185187950357, 243.14025219104838];
7245        let expected_positions: [(f64, f64); 3] = [
7246            (-0.06435559190712015, 0.7344970251956466),
7247            (0.5769422272471794, 0.2722720177468328),
7248            (-0.7440424901848259, 0.15418044529361857),
7249        ];
7250        for i in 0..3 {
7251            assert_eq!(results.ranges[i].to_bits(), expected_ranges[i].to_bits());
7252            assert_eq!(
7253                results.impact_velocities[i].to_bits(),
7254                expected_velocities[i].to_bits()
7255            );
7256            assert_eq!(
7257                results.impact_positions[i].y.to_bits(),
7258                expected_positions[i].0.to_bits()
7259            );
7260            assert_eq!(
7261                results.impact_positions[i].z.to_bits(),
7262                expected_positions[i].1.to_bits()
7263            );
7264        }
7265    }
7266
7267    fn in_band_mc_inputs() -> BallisticInputs {
7268        BallisticInputs {
7269            muzzle_velocity: 800.0,
7270            temperature: 20.0,
7271            pressure: 1013.0,
7272            altitude: 150.0,
7273            ..BallisticInputs::default()
7274        }
7275    }
7276
7277    #[test]
7278    fn monte_carlo_in_band_seeded_case_is_pinned_and_both_differs() {
7279        let params = MonteCarloParams {
7280            num_simulations: 50,
7281            target_distance: Some(500.0),
7282            ..MonteCarloParams::default()
7283        };
7284        // captured at ab4eb0c: (range, impact velocity) of the first three trials
7285        // Re-captured in 0.50.0 (the default 50 % RH aloft now holds the
7286        // station's water-vapour mole fraction, with a virtual-temperature lapse), old -> new:
7287        // ranges 1933.7023025926699 -> 1933.7006673718802, 1962.5974312446554 -> 1962.5957266568341
7288        // and 1938.055244658578 -> 1938.0537040308395 m (-8.0e-7 to -8.7e-7); velocities
7289        // 243.03343313165846 -> 243.0324000563029, 244.31973944033203 -> 244.3187166797008 and
7290        // 247.59724147726604 -> 247.596028157198 m/s (-4.2e-6 to -4.9e-6).
7291        let pinned = [
7292            (
7293                f64::from_bits(0x409e36cd7bbf5e66),
7294                f64::from_bits(0x406e61096bd7c6b4),
7295            ),
7296            (
7297                f64::from_bits(0x409eaa62062b31d5),
7298                f64::from_bits(0x406e8a32ed528026),
7299            ),
7300            (
7301                f64::from_bits(0x409e4836fe30807a),
7302                f64::from_bits(0x406ef312a9a45523),
7303            ),
7304        ];
7305        let seeded = run_monte_carlo_with_wind_and_direction_std_dev_seeded(
7306            in_band_mc_inputs(),
7307            WindConditions::default(),
7308            params.clone(),
7309            0.01,
7310            0x1352_5EED,
7311        )
7312        .unwrap();
7313        let neither = run_monte_carlo_with_station_presence(
7314            in_band_mc_inputs(),
7315            WindConditions::default(),
7316            params.clone(),
7317            0.01,
7318            Some(0x1352_5EED),
7319            StationAtmospherePresence::NEITHER,
7320        )
7321        .unwrap();
7322        for results in [&seeded, &neither] {
7323            assert_eq!(results.ranges.len(), 50);
7324            for (i, (range, velocity)) in pinned.iter().enumerate() {
7325                assert_eq!(results.ranges[i].to_bits(), range.to_bits(), "range[{i}]");
7326                assert_eq!(
7327                    results.impact_velocities[i].to_bits(),
7328                    velocity.to_bits(),
7329                    "velocity[{i}]"
7330                );
7331            }
7332        }
7333        let both = run_monte_carlo_with_station_presence(
7334            in_band_mc_inputs(),
7335            WindConditions::default(),
7336            params,
7337            0.01,
7338            Some(0x1352_5EED),
7339            StationAtmospherePresence::BOTH,
7340        )
7341        .unwrap();
7342        assert_ne!(both.ranges[0].to_bits(), pinned[0].0.to_bits());
7343        // 1013 hPa is denser than the ICAO 995 hPa it used to be swapped for: shorter flights.
7344        assert!(both.ranges[0] < pinned[0].0);
7345    }
7346
7347    #[test]
7348    fn adaptive_monte_carlo_twin_is_pinned_and_both_differs() {
7349        let params = MonteCarloParams {
7350            num_simulations: 1,
7351            velocity_std_dev: 3.0,
7352            angle_std_dev: 3.5e-4,
7353            bc_std_dev: 0.01,
7354            wind_speed_std_dev: 1.0,
7355            target_distance: Some(300.0),
7356            base_wind_speed: 0.0,
7357            base_wind_direction: 0.0,
7358            azimuth_std_dev: 3.5e-4,
7359        };
7360        let convergence = McConvergence {
7361            min_samples: 40,
7362            max_samples: 80,
7363            batch_size: 40,
7364            ..McConvergence::default()
7365        };
7366        let legacy = run_monte_carlo_adaptive_seeded(
7367            &in_band_mc_inputs(),
7368            &WindConditions::default(),
7369            &params,
7370            &convergence,
7371            DEFAULT_HIT_RADIUS_M,
7372            7,
7373        )
7374        .unwrap();
7375        let neither = run_monte_carlo_adaptive_seeded_with_station_presence(
7376            &in_band_mc_inputs(),
7377            &WindConditions::default(),
7378            &params,
7379            &convergence,
7380            DEFAULT_HIT_RADIUS_M,
7381            7,
7382            StationAtmospherePresence::NEITHER,
7383        )
7384        .unwrap();
7385        for report in [&legacy, &neither] {
7386            assert_eq!(report.samples, 80);
7387            assert_eq!(report.attempts, 80);
7388            // captured at ab4eb0c
7389            // Re-captured in 0.50.0 (the default 50 % RH aloft now holds the
7390            // station's water-vapour mole fraction, with a virtual-temperature lapse), old -> new:
7391            // the hit probability did not move; the mean impact velocity 244.8044668331616 ->
7392            // 244.80335002519013 m/s (-4.6e-6) and the mean drop at the target 0.00242533056417438
7393            // -> 0.002425330711117544 m (+6.1e-8).
7394            assert_eq!(
7395                report.hit_probability.to_bits(),
7396                f64::from_bits(0x3fef99999999999a).to_bits()
7397            );
7398            assert_eq!(
7399                report.mean_impact_velocity_mps.to_bits(),
7400                0x406e99b50b1cadd6
7401            );
7402            assert_eq!(report.mean_drop_at_target_m.to_bits(), 0x3f63de4982c26e62);
7403        }
7404        let both = run_monte_carlo_adaptive_seeded_with_station_presence(
7405            &in_band_mc_inputs(),
7406            &WindConditions::default(),
7407            &params,
7408            &convergence,
7409            DEFAULT_HIT_RADIUS_M,
7410            7,
7411            StationAtmospherePresence::BOTH,
7412        )
7413        .unwrap();
7414        assert_ne!(both.mean_impact_velocity_mps.to_bits(), 0x406e99b50b1cadd6);
7415    }
7416
7417    /// Every trial's impact position is its deviation from the baseline solve, so the baseline
7418    /// must fly the trials' air. With no dispersion each trial is the baseline itself, so the
7419    /// deviation is exactly zero under every presence, in-band readings included.
7420    #[test]
7421    fn monte_carlo_baseline_flies_the_trials_air() {
7422        let params = MonteCarloParams {
7423            num_simulations: 3,
7424            velocity_std_dev: 0.0,
7425            angle_std_dev: 0.0,
7426            bc_std_dev: 0.0,
7427            wind_speed_std_dev: 0.0,
7428            target_distance: Some(500.0),
7429            base_wind_speed: 0.0,
7430            base_wind_direction: 0.0,
7431            azimuth_std_dev: 0.0,
7432        };
7433        let inputs = BallisticInputs {
7434            temperature: 15.0,
7435            ..in_band_mc_inputs()
7436        };
7437        for presence in [
7438            StationAtmospherePresence::NEITHER,
7439            StationAtmospherePresence::new(true, false),
7440            StationAtmospherePresence::new(false, true),
7441            StationAtmospherePresence::BOTH,
7442        ] {
7443            let results = run_monte_carlo_with_station_presence(
7444                inputs.clone(),
7445                WindConditions::default(),
7446                params.clone(),
7447                0.0,
7448                Some(7),
7449                presence,
7450            )
7451            .unwrap();
7452            assert_eq!(results.impact_positions.len(), 3);
7453            for position in &results.impact_positions {
7454                assert_eq!(position.y.to_bits(), 0.0_f64.to_bits(), "{presence:?}");
7455                assert_eq!(position.z.to_bits(), 0.0_f64.to_bits(), "{presence:?}");
7456            }
7457        }
7458    }
7459
7460    /// A zeroed drop fit zeroes in the air it flies: drops generated from a solve zeroed at
7461    /// 100 m in a typed in-band air fit back with no residual. A zero left on the old rule
7462    /// (ICAO air) under a flight in the typed air leaves one at every candidate BC.
7463    #[test]
7464    fn estimate_bc_fit_twin_zeroes_in_the_supplied_air() {
7465        let atmosphere = air(15.0, 1013.0, 150.0);
7466        let presence = StationAtmospherePresence::BOTH;
7467        let mut inputs = BallisticInputs {
7468            muzzle_velocity: 823.0,
7469            bc_value: 0.475,
7470            bc_type: DragModel::G1,
7471            bullet_mass: 0.0109,
7472            bullet_diameter: 0.00782,
7473            sight_height: 0.0381,
7474            ..Default::default()
7475        };
7476        inputs.muzzle_angle = calculate_zero_angle_with_station_presence(
7477            inputs.clone(),
7478            100.0,
7479            0.0381,
7480            WindConditions::default(),
7481            atmosphere.clone(),
7482            presence,
7483        )
7484        .unwrap();
7485        let mut solver = TrajectorySolver::new_with_station_presence(
7486            inputs,
7487            WindConditions::default(),
7488            atmosphere.clone(),
7489            presence,
7490        );
7491        solver.set_max_range(750.0);
7492        let flight = solver.solve().unwrap();
7493        let points: Vec<(f64, f64)> = [300.0, 500.0]
7494            .iter()
7495            .map(|&d| {
7496                (
7497                    d,
7498                    fit_value_at(&flight.points, d, BcFitMode::Drop, 0.0381).unwrap(),
7499                )
7500            })
7501            .collect();
7502        let fit = estimate_bc_fit_with_station_presence(
7503            823.0,
7504            0.0109,
7505            0.00782,
7506            &points,
7507            DragModel::G1,
7508            BcFitMode::Drop,
7509            atmosphere,
7510            Some(100.0),
7511            0.0381,
7512            presence,
7513        )
7514        .unwrap();
7515        assert!((fit.bc - 0.475).abs() < 1e-9, "{fit:?}");
7516        assert!(fit.rms_error < 1e-9, "{fit:?}");
7517    }
7518
7519    #[test]
7520    fn estimate_bc_fit_twin_is_pinned_and_both_fits_the_supplied_air() {
7521        let points = [(300.0, 650.0), (500.0, 560.0)];
7522        let fit = |p: f64, presence| {
7523            estimate_bc_fit_with_station_presence(
7524                823.0,
7525                0.0109,
7526                0.00782,
7527                &points,
7528                DragModel::G1,
7529                BcFitMode::Velocity,
7530                air(20.0, p, 150.0),
7531                None,
7532                0.0381,
7533                presence,
7534            )
7535            .unwrap()
7536            .bc
7537        };
7538        let legacy = estimate_bc_fit(
7539            823.0,
7540            0.0109,
7541            0.00782,
7542            &points,
7543            DragModel::G1,
7544            BcFitMode::Velocity,
7545            air(20.0, 1013.0, 150.0),
7546            None,
7547            0.0381,
7548        )
7549        .unwrap()
7550        .bc;
7551        // captured at ab4eb0c: 1013.0 hPa at 150 m was fitted in ICAO 995 hPa air.
7552        let pinned = f64::from_bits(0x3fe0000000000003);
7553        assert_eq!(legacy.to_bits(), pinned.to_bits());
7554        assert_eq!(
7555            fit(1013.0, StationAtmospherePresence::NEITHER).to_bits(),
7556            pinned.to_bits()
7557        );
7558        // The fit searches a 0.001 BC grid and 1 hPa moves the answer by about 0.0005, so the
7559        // out-of-band neighbours are 3 hPa away on each side to make "strictly between"
7560        // resolvable. They are flown as typed by every rule.
7561        let low = fit(1010.0, StationAtmospherePresence::NEITHER);
7562        let high = fit(1016.0, StationAtmospherePresence::NEITHER);
7563        let both = fit(1013.0, StationAtmospherePresence::BOTH);
7564        assert!(low < both && both < high, "{low} < {both} < {high}");
7565    }
7566
7567    #[test]
7568    fn monte_carlo_kernel_twin_is_pinned_and_both_lies_between_neighbours() {
7569        let kernel_inputs = |p: f64| BallisticInputs {
7570            muzzle_velocity: 823.0,
7571            bc_value: 0.475,
7572            bullet_mass: 0.0109,
7573            bullet_diameter: 0.00782,
7574            target_distance: 500.0,
7575            temperature: 20.0,
7576            pressure: p,
7577            altitude: 150.0,
7578            ..Default::default()
7579        };
7580        let solve = |p: f64, presence| {
7581            crate::monte_carlo::solve_trajectory_for_monte_carlo_with_station_presence(
7582                &kernel_inputs(p),
7583                presence,
7584            )
7585            .unwrap()
7586        };
7587        let legacy =
7588            crate::monte_carlo::solve_trajectory_for_monte_carlo(&kernel_inputs(1013.0)).unwrap();
7589        let neither = solve(1013.0, StationAtmospherePresence::NEITHER);
7590        for output in [&legacy, &neither] {
7591            // Captured at ab4eb0c (drop 0x40039eddd41bdb44, velocity 0x4080fe7009642434) when
7592            // this kernel flew the default 50 % RH in its density but 0 % in its sound speed.
7593            // Re-captured in 0.50.0, where it flies 50 % in both, exactly
7594            // as TrajectorySolver does: the drop is 0.61 mm longer and the speed
7595            // 0.19 m/s lower at 500 m.
7596            // Re-captured again with the aloft change (the aloft air now holds the station's
7597            // water-vapour mole fraction, with a virtual-temperature lapse): drop 2.453183461133607
7598            // -> 2.4531833213074137 m (-0.14 um), velocity 543.6188052770763 -> 543.6189355048916
7599            // m/s (+0.13 mm/s).
7600            assert_eq!(output.drop.to_bits(), 0x4003a01e93c0dd30);
7601            assert_eq!(output.velocity.to_bits(), 0x4080fcf394753ebe);
7602        }
7603        let low = solve(1012.0, StationAtmospherePresence::NEITHER).velocity;
7604        let high = solve(1014.0, StationAtmospherePresence::NEITHER).velocity;
7605        let both = solve(1013.0, StationAtmospherePresence::BOTH).velocity;
7606        assert!(high < both && both < low, "{high} < {both} < {low}");
7607    }
7608}
7609
7610#[cfg(test)]
7611mod monte_carlo_seeded_tests {
7612    use super::*;
7613
7614    /// Shared fixture for the seeded Monte Carlo tests: the crate defaults at an explicit
7615    /// 800 m/s muzzle velocity in still air.
7616    ///
7617    /// The brief for this task assumed the module already had such a helper; it did not (every
7618    /// test above restated the same two literals inline), so it is introduced here and the
7619    /// adaptive-driver tests below share it. The existing tests keep their own inline fixtures
7620    /// deliberately: rewriting them to call this helper would change nothing about what they
7621    /// assert but would put unrelated churn in the same commit as a bit-for-bit pin.
7622    fn seeded_test_fixture() -> (BallisticInputs, WindConditions) {
7623        (
7624            BallisticInputs {
7625                muzzle_velocity: 800.0,
7626                ..BallisticInputs::default()
7627            },
7628            WindConditions::default(),
7629        )
7630    }
7631
7632    /// Dispersions for the adaptive-driver tests: a 300 m shot with small pointing and wind
7633    /// error, so almost every trial lands inside `DEFAULT_HIT_RADIUS_M` of the baseline.
7634    ///
7635    /// Tuned for *test wall time*, deliberately. A confidence sequence's half-width scales
7636    /// with `sqrt(p(1-p) * log(n) / n)`, so a hit probability near `1` reaches the default
7637    /// `0.02` target inside `min_samples` (1000 trials) while a `p` near `0.5` would need
7638    /// roughly 4-5x as many -- and every trial is a full trajectory solve, run unoptimised
7639    /// under `cargo test`. It stays a little short of a degenerate `p == 1`: a handful of
7640    /// misses in 1000 keeps the hit *counting* under test rather than trivially saturated.
7641    fn loose_params() -> MonteCarloParams {
7642        MonteCarloParams {
7643            num_simulations: 1, // deliberately absurd: the adaptive driver must ignore it
7644            velocity_std_dev: 3.0,
7645            angle_std_dev: 3.5e-4,
7646            bc_std_dev: 0.01,
7647            wind_speed_std_dev: 1.0,
7648            target_distance: Some(300.0),
7649            base_wind_speed: 0.0,
7650            base_wind_direction: 0.0,
7651            azimuth_std_dev: 3.5e-4,
7652        }
7653    }
7654
7655    /// Params whose target plane sits *inside* the ground-impact scatter, so some trials
7656    /// arrive at it and some fall short.
7657    ///
7658    /// The pin fixture records ground impact between 1907 m and 1936 m for this projectile, so
7659    /// a 1920 m plane splits the run. That split is the point: with `loose_params()` every
7660    /// trial arrives, which makes `arrivals`, `samples` and `attempts` numerically identical
7661    /// and therefore useless for catching a report that populates one of them from another.
7662    fn mixed_arrival_params() -> MonteCarloParams {
7663        MonteCarloParams {
7664            num_simulations: 1,
7665            target_distance: Some(1920.0),
7666            ..MonteCarloParams::default()
7667        }
7668    }
7669
7670    /// THE bit-for-bit compatibility contract for the legacy seeded Monte Carlo path
7671    /// (Plan C spec 9.5).
7672    ///
7673    /// Every literal below was captured by running this exact fixture against the tree at
7674    /// commit 5a421bf ("fix(decision-support): close the last three Plan B branch-review
7675    /// gaps"), i.e. the last commit before any Plan C change touched `src/cli_api.rs`, and
7676    /// printed with `{:?}` (shortest round-tripping form, so the pasted literal reproduces the
7677    /// captured `f64` to the bit).
7678    ///
7679    /// It exists to be run BEFORE and AFTER the per-trial body is extracted into
7680    /// [`MonteCarloTrialSampler::sample_one_trial`]. The extraction is only legitimate if the
7681    /// sequence and count of RNG draws per trial is unchanged, and that is not something the
7682    /// type system can check: a reordered or added draw shifts every subsequent sample and
7683    /// shows up here as a mismatch. If this test fails after a refactor of the trial loop, the
7684    /// refactor is wrong -- do not re-capture the literals.
7685    #[test]
7686    fn legacy_seeded_estimates_are_pinned_bit_for_bit() {
7687        let (inputs, wind) = seeded_test_fixture();
7688        let params = MonteCarloParams {
7689            num_simulations: 200,
7690            target_distance: Some(500.0),
7691            ..MonteCarloParams::default()
7692        };
7693
7694        let results = run_monte_carlo_with_wind_and_direction_std_dev_seeded(
7695            inputs,
7696            wind,
7697            params,
7698            0.01,
7699            0x1352_5EED,
7700        )
7701        .expect("seeded legacy run");
7702
7703        // Every trial is recorded: no solve failed and no target-plane interpolation was
7704        // skipped, so the three vectors are all 200 long. This is asserted, not assumed --
7705        // an extraction that started dropping trials would otherwise shorten the vectors
7706        // while the first three entries below still matched.
7707        assert_eq!(results.ranges.len(), 200, "ranges length");
7708        assert_eq!(
7709            results.impact_velocities.len(),
7710            200,
7711            "impact_velocities length"
7712        );
7713        assert_eq!(
7714            results.impact_positions.len(),
7715            200,
7716            "impact_positions length"
7717        );
7718
7719        // 28 hits in 200 trials.
7720        assert_eq!(
7721            results.hit_probability(DEFAULT_HIT_RADIUS_M).to_bits(),
7722            0.14_f64.to_bits(),
7723            "hit_probability = {:?}",
7724            results.hit_probability(DEFAULT_HIT_RADIUS_M)
7725        );
7726
7727        // Re-captured in 0.50.0 (the default 50 % RH aloft now holds the
7728        // station's water-vapour mole fraction, with a virtual-temperature lapse), old -> new:
7729        // ranges 1907.972891143359 -> 1907.9716332174821, 1936.408435469319 -> 1936.4071333440454
7730        // and 1912.8150447617645 -> 1912.81384414182 m (-6.3e-7 to -6.7e-7); velocities
7731        // 238.6187151542299 -> 238.6179931921287, 239.91923651600106 -> 239.9185187950357 and
7732        // 243.14112455427164 -> 243.14025219104838 m/s (-3.0e-6 to -3.6e-6); the impact positions
7733        // by at most 0.12 um (-0.0643556039548101 -> -0.06435559190712015, 0.7344970252014579 ->
7734        // 0.7344970251956466, 0.5769422971539162 -> 0.5769422272471794, 0.27227201756386726 ->
7735        // 0.2722720177468328, -0.7440425792472842 -> -0.7440424901848259, 0.1541804446282822 ->
7736        // 0.15418044529361857). The hit count did not move.
7737
7738        let expected_ranges: [f64; 3] = [1907.9716332174821, 1936.4071333440454, 1912.81384414182];
7739        let expected_velocities: [f64; 3] =
7740            [238.6179931921287, 239.9185187950357, 243.14025219104838];
7741        let expected_positions: [(f64, f64, f64); 3] = [
7742            (0.0, -0.06435559190712015, 0.7344970251956466),
7743            (0.0, 0.5769422272471794, 0.2722720177468328),
7744            (0.0, -0.7440424901848259, 0.15418044529361857),
7745        ];
7746
7747        for (i, expected) in expected_ranges.iter().enumerate() {
7748            assert_eq!(
7749                results.ranges[i].to_bits(),
7750                expected.to_bits(),
7751                "ranges[{i}] = {:?}, pinned {expected:?}",
7752                results.ranges[i]
7753            );
7754        }
7755        for (i, expected) in expected_velocities.iter().enumerate() {
7756            assert_eq!(
7757                results.impact_velocities[i].to_bits(),
7758                expected.to_bits(),
7759                "impact_velocities[{i}] = {:?}, pinned {expected:?}",
7760                results.impact_velocities[i]
7761            );
7762        }
7763        for (i, (x, y, z)) in expected_positions.iter().enumerate() {
7764            let actual = results.impact_positions[i];
7765            assert_eq!(
7766                actual.x.to_bits(),
7767                x.to_bits(),
7768                "impact_positions[{i}].x = {:?}",
7769                actual.x
7770            );
7771            assert_eq!(
7772                actual.y.to_bits(),
7773                y.to_bits(),
7774                "impact_positions[{i}].y = {:?}",
7775                actual.y
7776            );
7777            assert_eq!(
7778                actual.z.to_bits(),
7779                z.to_bits(),
7780                "impact_positions[{i}].z = {:?}",
7781                actual.z
7782            );
7783        }
7784    }
7785
7786    #[test]
7787    fn seeded_runs_are_deterministic_and_match_the_using_rng_path() {
7788        let inputs = BallisticInputs {
7789            muzzle_velocity: 800.0,
7790            ..BallisticInputs::default()
7791        };
7792        let params = MonteCarloParams {
7793            num_simulations: 64,
7794            target_distance: Some(200.0),
7795            ..MonteCarloParams::default()
7796        };
7797
7798        let a = run_monte_carlo_with_wind_and_direction_std_dev_seeded(
7799            inputs.clone(),
7800            WindConditions::default(),
7801            params.clone(),
7802            0.01,
7803            42,
7804        )
7805        .expect("seeded run a");
7806        let b = run_monte_carlo_with_wind_and_direction_std_dev_seeded(
7807            inputs,
7808            WindConditions::default(),
7809            params,
7810            0.01,
7811            42,
7812        )
7813        .expect("seeded run b");
7814
7815        assert_eq!(a.ranges.len(), b.ranges.len());
7816        for (ra, rb) in a.ranges.iter().zip(b.ranges.iter()) {
7817            assert_eq!(ra.to_bits(), rb.to_bits());
7818        }
7819        for (pa, pb) in a.impact_positions.iter().zip(b.impact_positions.iter()) {
7820            assert_eq!(pa.x.to_bits(), pb.x.to_bits());
7821            assert_eq!(pa.y.to_bits(), pb.y.to_bits());
7822            assert_eq!(pa.z.to_bits(), pb.z.to_bits());
7823        }
7824    }
7825
7826    #[test]
7827    fn different_seeds_generally_produce_different_draws() {
7828        let inputs = BallisticInputs {
7829            muzzle_velocity: 800.0,
7830            ..BallisticInputs::default()
7831        };
7832        let params = MonteCarloParams {
7833            num_simulations: 32,
7834            velocity_std_dev: 5.0,
7835            target_distance: Some(200.0),
7836            ..MonteCarloParams::default()
7837        };
7838
7839        let a = run_monte_carlo_with_wind_and_direction_std_dev_seeded(
7840            inputs.clone(),
7841            WindConditions::default(),
7842            params.clone(),
7843            0.0,
7844            1,
7845        )
7846        .expect("seeded run a");
7847        let b = run_monte_carlo_with_wind_and_direction_std_dev_seeded(
7848            inputs,
7849            WindConditions::default(),
7850            params,
7851            0.0,
7852            2,
7853        )
7854        .expect("seeded run b");
7855
7856        assert_ne!(a.impact_velocities, b.impact_velocities);
7857    }
7858
7859    #[test]
7860    fn adaptive_stops_at_target_half_width_on_an_easy_case() {
7861        let (inputs, wind) = seeded_test_fixture();
7862        let conv = McConvergence {
7863            target_half_width: 0.05,
7864            ..Default::default()
7865        };
7866        let r = run_monte_carlo_adaptive_seeded(
7867            &inputs,
7868            &wind,
7869            &loose_params(),
7870            &conv,
7871            DEFAULT_HIT_RADIUS_M,
7872            0x1352_ADA9,
7873        )
7874        .unwrap();
7875
7876        assert_eq!(r.stop_reason, McStopReason::TargetHalfWidthMet);
7877        assert!(
7878            (r.ci_high - r.ci_low) / 2.0 <= 0.05 + 1e-12,
7879            "half-width {} exceeds the requested 0.05",
7880            (r.ci_high - r.ci_low) / 2.0
7881        );
7882        assert!(r.samples >= conv.min_samples, "stopped below min_samples");
7883        assert!(r.samples < conv.max_samples, "did not actually stop early");
7884        assert!(r.samples.is_multiple_of(conv.batch_size) || r.samples == conv.min_samples);
7885        assert!(r.ci_low <= r.hit_probability && r.hit_probability <= r.ci_high);
7886
7887        // The report must describe the run it actually did, not the params it ignored.
7888        assert_eq!(r.hit_radius_m, DEFAULT_HIT_RADIUS_M);
7889        assert_eq!(r.target_distance_m, 300.0);
7890        assert_eq!(r.confidence_percent, 95);
7891        // `num_simulations` is 1 in `loose_params`; if it were honoured we would see 1 sample.
7892        assert!(
7893            r.samples > 1,
7894            "params.num_simulations must be ignored by the adaptive driver"
7895        );
7896        // The streaming moments ran over trials that reached the plane: a 300 m shot at
7897        // 800 m/s is still supersonic, and the dispersions are nonzero, so both must be too.
7898        assert!(
7899            r.mean_impact_velocity_mps > 0.0,
7900            "no impact velocity accumulated"
7901        );
7902        assert!(
7903            r.std_drop_at_target_m > 0.0 && r.std_wind_drift_at_target_m > 0.0,
7904            "dispersion collapsed: drop sd {} drift sd {}",
7905            r.std_drop_at_target_m,
7906            r.std_wind_drift_at_target_m
7907        );
7908    }
7909
7910    #[test]
7911    fn adaptive_caps_at_max_samples_on_an_impossible_target() {
7912        let (inputs, wind) = seeded_test_fixture();
7913        let conv = McConvergence {
7914            target_half_width: 1e-6,
7915            max_samples: 3_000,
7916            batch_size: 500,
7917            min_samples: 1_000,
7918            level: ConfidenceLevel::P95,
7919        };
7920        let r = run_monte_carlo_adaptive_seeded(
7921            &inputs,
7922            &wind,
7923            &loose_params(),
7924            &conv,
7925            DEFAULT_HIT_RADIUS_M,
7926            7,
7927        )
7928        .unwrap();
7929
7930        assert_eq!(r.stop_reason, McStopReason::MaxSamplesReached);
7931        assert_eq!(r.samples, 3_000);
7932    }
7933
7934    /// The adaptive middle: a stop that is decided by the DATA, not by either bound.
7935    ///
7936    /// Every other stopping test lands on a boundary -- the easy case and the determinism case
7937    /// both stop at exactly `min_samples`, and the impossible case runs to `max_samples`. None
7938    /// of them would notice if the half-width check were, say, only consulted on the first
7939    /// batch. Here `min_samples` is 0 and `max_samples` is far away, so the sample count is
7940    /// whatever the confidence sequence decides it is, and the assertions pin that it landed
7941    /// strictly inside both bounds after more than one batch.
7942    #[test]
7943    fn adaptive_stops_between_the_floor_and_the_ceiling() {
7944        let (inputs, wind) = seeded_test_fixture();
7945        let conv = McConvergence {
7946            level: ConfidenceLevel::P95,
7947            target_half_width: 0.03,
7948            min_samples: 0,
7949            max_samples: 10_000,
7950            batch_size: 100,
7951        };
7952        let r = run_monte_carlo_adaptive_seeded(
7953            &inputs,
7954            &wind,
7955            &loose_params(),
7956            &conv,
7957            DEFAULT_HIT_RADIUS_M,
7958            0x1352_5A1D,
7959        )
7960        .unwrap();
7961
7962        assert_eq!(r.stop_reason, McStopReason::TargetHalfWidthMet);
7963        assert!(r.samples > 0);
7964        assert!(
7965            r.samples.is_multiple_of(conv.batch_size),
7966            "samples {} is not a whole number of batches",
7967            r.samples
7968        );
7969        assert!(
7970            r.samples > conv.min_samples,
7971            "stopped on the floor, not on the data"
7972        );
7973        assert!(
7974            r.samples < conv.max_samples,
7975            "ran to the ceiling, so nothing adaptive was exercised"
7976        );
7977        assert!(
7978            r.samples > conv.batch_size,
7979            "stopped on the very first look ({} samples); the multi-batch path is untested",
7980            r.samples
7981        );
7982        assert!((r.ci_high - r.ci_low) / 2.0 <= 0.03 + 1e-12);
7983        assert!(r.ci_low <= r.hit_probability && r.hit_probability <= r.ci_high);
7984        assert_eq!(r.attempts, r.samples, "no trial should have been dropped");
7985    }
7986
7987    /// The final batch is truncated so `max_samples` is a hard ceiling, not a threshold the
7988    /// last batch overshoots.
7989    ///
7990    /// `750 = 500 + 250`, so the second batch must run short. With a `max_samples` that is a
7991    /// whole multiple of `batch_size` -- as in every other test here -- the
7992    /// `batch_size.min(max_samples - attempts)` clamp never actually clamps, and a driver that
7993    /// ignored it entirely would pass. This one would report 1000.
7994    #[test]
7995    fn adaptive_runs_a_truncated_final_batch_up_to_max_samples() {
7996        let (inputs, wind) = seeded_test_fixture();
7997        let conv = McConvergence {
7998            level: ConfidenceLevel::P95,
7999            target_half_width: 1e-6,
8000            min_samples: 0,
8001            max_samples: 750,
8002            batch_size: 500,
8003        };
8004        let r = run_monte_carlo_adaptive_seeded(
8005            &inputs,
8006            &wind,
8007            &loose_params(),
8008            &conv,
8009            DEFAULT_HIT_RADIUS_M,
8010            0x1352_7B10,
8011        )
8012        .unwrap();
8013
8014        assert_eq!(r.stop_reason, McStopReason::MaxSamplesReached);
8015        assert_eq!(
8016            r.samples, 750,
8017            "the 250-trial final batch did not run, or was not truncated"
8018        );
8019        assert_eq!(r.attempts, 750);
8020        assert!(!r.samples.is_multiple_of(conv.batch_size));
8021    }
8022
8023    #[test]
8024    fn adaptive_is_deterministic_for_a_seed() {
8025        let (inputs, wind) = seeded_test_fixture();
8026        let conv = McConvergence::default();
8027        let a = run_monte_carlo_adaptive_seeded(
8028            &inputs,
8029            &wind,
8030            &loose_params(),
8031            &conv,
8032            DEFAULT_HIT_RADIUS_M,
8033            99,
8034        )
8035        .unwrap();
8036        let b = run_monte_carlo_adaptive_seeded(
8037            &inputs,
8038            &wind,
8039            &loose_params(),
8040            &conv,
8041            DEFAULT_HIT_RADIUS_M,
8042            99,
8043        )
8044        .unwrap();
8045
8046        assert_eq!(a.hit_probability.to_bits(), b.hit_probability.to_bits());
8047        assert_eq!(a.samples, b.samples);
8048        assert_eq!(a.ci_low.to_bits(), b.ci_low.to_bits());
8049        assert_eq!(a.ci_high.to_bits(), b.ci_high.to_bits());
8050        // The streaming moments have to be reproducible too, not just the hit counts: they
8051        // are the part that would drift if the trial body consumed draws inconsistently.
8052        assert_eq!(
8053            a.mean_impact_velocity_mps.to_bits(),
8054            b.mean_impact_velocity_mps.to_bits()
8055        );
8056        assert_eq!(
8057            a.std_drop_at_target_m.to_bits(),
8058            b.std_drop_at_target_m.to_bits()
8059        );
8060    }
8061
8062    #[test]
8063    fn adaptive_report_carries_schema_method_and_all_four_assumptions() {
8064        let (inputs, wind) = seeded_test_fixture();
8065        // Nothing here depends on the statistics converging, so keep it to one batch. The
8066        // fixture is the mixed-arrival one so the three cardinalities come out DISTINCT --
8067        // see the assertions below.
8068        let conv = McConvergence {
8069            min_samples: 0,
8070            max_samples: 50,
8071            batch_size: 50,
8072            target_half_width: 1.0,
8073            level: ConfidenceLevel::P90,
8074        };
8075        let r = run_monte_carlo_adaptive_seeded(
8076            &inputs,
8077            &wind,
8078            &mixed_arrival_params(),
8079            &conv,
8080            DEFAULT_HIT_RADIUS_M,
8081            0x1352_D0C5,
8082        )
8083        .unwrap();
8084
8085        assert_eq!(r.schema_version, MC_ADAPTIVE_SCHEMA_VERSION_V1);
8086        assert_eq!(r.schema_version, 1);
8087        assert_eq!(r.method, "anytime_beta_binomial_mixture_cs_v1");
8088        assert_eq!(r.confidence_percent, 90);
8089
8090        // The three cardinalities, pinned against each other rather than each against 50.
8091        // `attempts` and `samples` are both 50 here (nothing was dropped), but `arrivals` is
8092        // strictly smaller because the 1920 m plane sits inside the ground-impact scatter --
8093        // so a report that populated `arrivals` from `samples` (or vice versa) fails here,
8094        // which it could not if all three were the same number.
8095        assert_eq!(r.attempts, 50, "one full batch was drawn");
8096        assert_eq!(r.samples, 50, "no trial was dropped by the solver");
8097        assert!(
8098            r.arrivals > 0 && r.arrivals < r.samples,
8099            "fixture must split the run: arrivals {} of samples {}",
8100            r.arrivals,
8101            r.samples
8102        );
8103        // ...and the at-target statistics really are the `arrivals` population: two or more
8104        // arrivals is what makes a Bessel-corrected standard deviation defined at all.
8105        assert!(
8106            r.arrivals >= 2,
8107            "arrivals {} too few for a sample sd",
8108            r.arrivals
8109        );
8110        assert!(r.std_drop_at_target_m > 0.0 && r.std_impact_velocity_mps > 0.0);
8111        // The ordering invariant the doc comments promise.
8112        assert!(r.attempts >= r.samples && r.samples >= r.arrivals);
8113
8114        // Length AND per-index full-string equality against literals restated here character
8115        // for character. Deliberately NOT compared against MC_ADAPTIVE_ASSUMPTIONS_V1: that
8116        // would be circular, passing for any edit to the constant. `contains()` is likewise
8117        // not a pin -- a substring probe survives a sentence being reworded, truncated, or
8118        // having its meaning inverted around the matched word.
8119        assert_eq!(r.assumptions.len(), 4, "exactly four assumptions expected");
8120        assert_eq!(
8121            r.assumptions[0],
8122            "Sampling uncertainty only: intervals cover Monte Carlo sampling error, not model error in the trajectory solver or its inputs."
8123        );
8124        assert_eq!(
8125            r.assumptions[1],
8126            "Anytime-valid stopping: the beta-binomial mixture confidence sequence keeps its coverage guarantee despite stopping the moment the target half-width is met."
8127        );
8128        assert_eq!(
8129            r.assumptions[2],
8130            "Input dispersions are the independent normal distributions declared in MonteCarloParams; correlations between inputs are not modeled."
8131        );
8132        assert_eq!(
8133            r.assumptions[3],
8134            "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."
8135        );
8136
8137        // The stop reason is a snake_case string on the wire, not a variant name or an index.
8138        assert_eq!(
8139            serde_json::to_string(&McStopReason::TargetHalfWidthMet).unwrap(),
8140            "\"target_half_width_met\""
8141        );
8142        assert_eq!(
8143            serde_json::to_string(&McStopReason::MaxSamplesReached).unwrap(),
8144            "\"max_samples_reached\""
8145        );
8146    }
8147
8148    #[test]
8149    fn adaptive_rejects_nonsense_convergence() {
8150        let (inputs, wind) = seeded_test_fixture();
8151        let run = |conv: McConvergence| {
8152            run_monte_carlo_adaptive_seeded(
8153                &inputs,
8154                &wind,
8155                &loose_params(),
8156                &conv,
8157                DEFAULT_HIT_RADIUS_M,
8158                1,
8159            )
8160            .unwrap_err()
8161        };
8162
8163        for bad_width in [0.0, -0.01, f64::NAN] {
8164            let err = run(McConvergence {
8165                target_half_width: bad_width,
8166                ..Default::default()
8167            });
8168            assert!(
8169                err.contains("target_half_width"),
8170                "error must name the field, got: {err}"
8171            );
8172        }
8173
8174        let err = run(McConvergence {
8175            batch_size: 0,
8176            ..Default::default()
8177        });
8178        assert!(err.contains("batch_size"), "got: {err}");
8179
8180        let err = run(McConvergence {
8181            min_samples: 5_000,
8182            max_samples: 1_000,
8183            ..Default::default()
8184        });
8185        assert!(err.contains("max_samples"), "got: {err}");
8186        assert!(err.contains("min_samples"), "got: {err}");
8187
8188        let err = run(McConvergence {
8189            max_samples: 0,
8190            min_samples: 0,
8191            ..Default::default()
8192        });
8193        assert!(err.contains("max_samples"), "got: {err}");
8194
8195        // Validation happens before any trajectory work: a rejected config costs no solves.
8196        let err = McConvergence {
8197            batch_size: 0,
8198            ..Default::default()
8199        }
8200        .validate()
8201        .unwrap_err();
8202        assert!(err.contains("batch_size"));
8203    }
8204
8205    #[test]
8206    fn wilson_companion_matches_hit_probability_and_wilson_interval() {
8207        let (inputs, wind) = seeded_test_fixture();
8208        let params = MonteCarloParams {
8209            num_simulations: 128,
8210            target_distance: Some(500.0),
8211            ..MonteCarloParams::default()
8212        };
8213        let results = run_monte_carlo_with_wind_and_direction_std_dev_seeded(
8214            inputs,
8215            wind,
8216            params,
8217            0.01,
8218            0x1352_C0DE,
8219        )
8220        .expect("seeded legacy run");
8221
8222        for level in [
8223            ConfidenceLevel::P90,
8224            ConfidenceLevel::P95,
8225            ConfidenceLevel::P99,
8226        ] {
8227            let (p_hat, (lo, hi), n) = results.hit_probability_wilson(DEFAULT_HIT_RADIUS_M, level);
8228
8229            // The companion is a composition, not a re-derivation: p_hat must be the very
8230            // number `hit_probability` returns, bit for bit.
8231            assert_eq!(
8232                p_hat.to_bits(),
8233                results.hit_probability(DEFAULT_HIT_RADIUS_M).to_bits()
8234            );
8235            assert_eq!(n, results.impact_positions.len() as u64);
8236
8237            // ...and the bounds must be `wilson_interval` over the same counts. The hit count
8238            // is recomputed here from the shared predicate rather than taken from the
8239            // companion, so a wrong denominator (e.g. excluding target shortfalls) fails.
8240            let hits = results
8241                .impact_positions
8242                .iter()
8243                .filter(|p| MonteCarloResults::position_is_hit(p, DEFAULT_HIT_RADIUS_M))
8244                .count() as u64;
8245            let (want_lo, want_hi) = wilson_interval(hits, n, level);
8246            assert_eq!(lo.to_bits(), want_lo.to_bits());
8247            assert_eq!(hi.to_bits(), want_hi.to_bits());
8248            assert!(lo <= p_hat && p_hat <= hi, "interval excludes p_hat");
8249        }
8250
8251        // Empty results: hit_probability's 0.0 alongside wilson_interval's n == 0 ignorance.
8252        let empty = MonteCarloResults {
8253            ranges: Vec::new(),
8254            impact_velocities: Vec::new(),
8255            impact_positions: Vec::new(),
8256        };
8257        assert_eq!(
8258            empty.hit_probability_wilson(DEFAULT_HIT_RADIUS_M, ConfidenceLevel::P95),
8259            (0.0, (0.0, 1.0), 0)
8260        );
8261    }
8262}
8263
8264#[cfg(test)]
8265mod monte_carlo_powder_curve_tests {
8266    use super::*;
8267    use rand::{rngs::StdRng, SeedableRng};
8268
8269    #[test]
8270    fn powder_curve_preserves_sampled_muzzle_velocity_dispersion() {
8271        let inputs = BallisticInputs {
8272            muzzle_velocity: 700.0,
8273            powder_temp_curve: Some(vec![(15.0, 800.0)]),
8274            powder_curve_temp_c: Some(15.0),
8275            ..BallisticInputs::default()
8276        };
8277        let params = MonteCarloParams {
8278            num_simulations: 16,
8279            velocity_std_dev: 20.0,
8280            angle_std_dev: 1e-12,
8281            bc_std_dev: 1e-12,
8282            wind_speed_std_dev: 1e-12,
8283            target_distance: Some(100.0),
8284            azimuth_std_dev: 1e-12,
8285            ..MonteCarloParams::default()
8286        };
8287
8288        let mut rng = StdRng::seed_from_u64(0x5EED_1176);
8289        let results = run_monte_carlo_with_wind_and_direction_std_dev_using_rng(
8290            inputs,
8291            WindConditions::default(),
8292            params,
8293            0.0,
8294            StationAtmospherePresence::NEITHER,
8295            &mut rng,
8296        )
8297        .expect("Monte Carlo solve");
8298        let min_velocity = results
8299            .impact_velocities
8300            .iter()
8301            .copied()
8302            .fold(f64::INFINITY, f64::min);
8303        let max_velocity = results
8304            .impact_velocities
8305            .iter()
8306            .copied()
8307            .fold(f64::NEG_INFINITY, f64::max);
8308
8309        assert!(
8310            max_velocity - min_velocity > 1.0,
8311            "20 m/s muzzle spread collapsed after curve resolution: impact-velocity span={} m/s",
8312            max_velocity - min_velocity
8313        );
8314    }
8315}
8316
8317#[cfg(test)]
8318mod monte_carlo_wind_sampling_tests {
8319    use super::*;
8320    use rand::{rngs::StdRng, SeedableRng};
8321
8322    #[test]
8323    fn wind_speed_sigma_does_not_change_seeded_direction_draws() {
8324        let base_wind = WindConditions {
8325            speed: 100.0,
8326            direction: 0.37,
8327            vertical_speed: 0.0,
8328        };
8329        let narrow_speed = MonteCarloWindSampler::new(&base_wind, 0.5, 0.2).unwrap();
8330        let wide_speed = MonteCarloWindSampler::new(&base_wind, 4.0, 0.2).unwrap();
8331        let mut narrow_rng = StdRng::seed_from_u64(0x5EED_1223);
8332        let mut wide_rng = StdRng::seed_from_u64(0x5EED_1223);
8333        let mut speed_changed = false;
8334
8335        for _ in 0..32 {
8336            let narrow = narrow_speed.sample(&mut narrow_rng);
8337            let wide = wide_speed.sample(&mut wide_rng);
8338            assert!(narrow.speed > 0.0 && wide.speed > 0.0);
8339            assert_eq!(narrow.direction.to_bits(), wide.direction.to_bits());
8340            speed_changed |= narrow.speed.to_bits() != wide.speed.to_bits();
8341        }
8342        assert!(
8343            speed_changed,
8344            "different speed sigmas must still vary speed draws"
8345        );
8346    }
8347
8348    #[test]
8349    fn zero_direction_sigma_has_no_angular_jitter() {
8350        let base_wind = WindConditions {
8351            speed: 100.0,
8352            direction: 0.37,
8353            vertical_speed: 0.0,
8354        };
8355        let sampler = MonteCarloWindSampler::new(&base_wind, 4.0, 0.0).unwrap();
8356        let mut rng = StdRng::seed_from_u64(0x5EED_1223);
8357        let mut speed_changed = false;
8358
8359        for _ in 0..32 {
8360            let wind = sampler.sample(&mut rng);
8361            speed_changed |= wind.speed.to_bits() != base_wind.speed.to_bits();
8362            assert_eq!(wind.direction.to_bits(), base_wind.direction.to_bits());
8363        }
8364        assert!(speed_changed, "speed uncertainty should remain active");
8365    }
8366
8367    #[test]
8368    fn direction_sigma_controls_seeded_angular_spread_in_radians() {
8369        let base_wind = WindConditions {
8370            speed: 100.0,
8371            direction: 0.37,
8372            vertical_speed: 0.0,
8373        };
8374        let narrow = MonteCarloWindSampler::new(&base_wind, 4.0, 0.1).unwrap();
8375        let wide = MonteCarloWindSampler::new(&base_wind, 4.0, 0.2).unwrap();
8376        let mut narrow_rng = StdRng::seed_from_u64(0x5EED_1223);
8377        let mut wide_rng = StdRng::seed_from_u64(0x5EED_1223);
8378        let mut nonzero_direction_draw = false;
8379
8380        for _ in 0..32 {
8381            let narrow_wind = narrow.sample(&mut narrow_rng);
8382            let wide_wind = wide.sample(&mut wide_rng);
8383            assert_eq!(narrow_wind.speed.to_bits(), wide_wind.speed.to_bits());
8384
8385            let narrow_delta = narrow_wind.direction - base_wind.direction;
8386            let wide_delta = wide_wind.direction - base_wind.direction;
8387            assert!((wide_delta - 2.0 * narrow_delta).abs() < 1e-12);
8388            nonzero_direction_draw |= narrow_delta.abs() > 1e-6;
8389        }
8390        assert!(
8391            nonzero_direction_draw,
8392            "positive radians sigma must vary direction"
8393        );
8394    }
8395
8396    #[test]
8397    fn direction_sigma_rejects_negative_or_nonfinite_values() {
8398        let base_wind = WindConditions::default();
8399        for sigma in [-0.1, f64::NAN, f64::INFINITY] {
8400            assert!(MonteCarloWindSampler::new(&base_wind, 1.0, sigma).is_err());
8401        }
8402    }
8403
8404    #[test]
8405    fn base_vertical_wind_rides_into_every_mc_sample() {
8406        // MBA-728: vertical wind is a systematic input, not a dispersion source —
8407        // every sampled wind must carry the base vertical un-dispersed. (Before
8408        // this fix, samples dropped it, biasing the whole MC cloud vs the baseline.)
8409        use rand::SeedableRng;
8410        let base_wind = WindConditions {
8411            vertical_speed: 4.2,
8412            ..Default::default()
8413        };
8414        let sampler = MonteCarloWindSampler::new(&base_wind, 1.0, 0.2).unwrap();
8415        let mut rng = rand::rngs::StdRng::seed_from_u64(7);
8416        for _ in 0..32 {
8417            let w = sampler.sample(&mut rng);
8418            assert_eq!(w.vertical_speed, 4.2);
8419        }
8420    }
8421
8422    #[test]
8423    fn negative_speed_sample_reverses_wind_direction() {
8424        let direction = 0.25;
8425        let signed_speed = -2.5;
8426        let wind = wind_from_signed_speed_sample(signed_speed, direction, 0.0);
8427        let positive_wind = wind_from_signed_speed_sample(2.5, direction, 0.0);
8428
8429        assert_eq!(wind.speed, 2.5);
8430        assert!(
8431            (wind.direction - (direction + std::f64::consts::PI)).abs() < f64::EPSILON,
8432            "negative speed must reverse direction by pi: got {}",
8433            wind.direction
8434        );
8435        assert_eq!(positive_wind.speed, 2.5);
8436        assert_eq!(positive_wind.direction, direction);
8437
8438        let normalized_x = -wind.speed * wind.direction.cos();
8439        let normalized_z = -wind.speed * wind.direction.sin();
8440        let signed_x = -signed_speed * direction.cos();
8441        let signed_z = -signed_speed * direction.sin();
8442        assert!((normalized_x - signed_x).abs() < 1e-12);
8443        assert!((normalized_z - signed_z).abs() < 1e-12);
8444    }
8445}
8446
8447#[cfg(test)]
8448mod bc_fit_objective_tests {
8449    use super::*;
8450
8451    #[test]
8452    fn all_trials_refused_in_flight_preserve_the_atmosphere_cause() {
8453        let temperature = -273.1435;
8454        let error = estimate_bc_fit_with_station_presence(
8455            823.0,
8456            0.0109,
8457            0.00782,
8458            &[(800.0, 0.1), (900.0, 0.3)],
8459            DragModel::G7,
8460            BcFitMode::Drop,
8461            AtmosphericConditions {
8462                temperature,
8463                pressure: 0.0187,
8464                humidity: 0.0,
8465                ..Default::default()
8466            },
8467            Some(600.0),
8468            0.05,
8469            StationAtmospherePresence::BOTH,
8470        )
8471        .unwrap_err();
8472        let cause = error
8473            .atmosphere_error()
8474            .expect("the refused flight's cause");
8475        assert_eq!(cause.field(), "temperature_c");
8476        assert_eq!(cause.value().to_bits(), temperature.to_bits());
8477        assert_eq!(
8478            cause.reason(),
8479            crate::AtmosphereErrorReason::AirAloftBelowAbsoluteZero
8480        );
8481    }
8482
8483    fn velocity_point(range_m: f64, velocity_mps: f64) -> TrajectoryPoint {
8484        TrajectoryPoint {
8485            time: 0.0,
8486            position: Vector3::new(range_m, 0.0, 0.0),
8487            velocity_magnitude: velocity_mps,
8488            kinetic_energy: 0.0,
8489            drag_coefficient: None,
8490        }
8491    }
8492
8493    #[test]
8494    fn candidate_that_misses_an_observation_has_no_score() {
8495        let trajectory = vec![velocity_point(0.0, 800.0), velocity_point(100.0, 700.0)];
8496        let observations = vec![(50.0, 750.0), (150.0, 600.0)];
8497
8498        assert!(
8499            fit_residual_sse(&trajectory, &observations, BcFitMode::Velocity, 0.0).is_none(),
8500            "a candidate that reaches only one of two observations must not compete on partial SSE"
8501        );
8502
8503        let complete_observations = vec![(50.0, 740.0), (100.0, 680.0)];
8504        assert_eq!(
8505            fit_residual_sse(
8506                &trajectory,
8507                &complete_observations,
8508                BcFitMode::Velocity,
8509                0.0,
8510            ),
8511            Some(500.0)
8512        );
8513    }
8514}
8515
8516#[cfg(test)]
8517mod cluster_bc_reference_space_tests {
8518    use super::*;
8519
8520    fn acceleration_at_1100_fps(inputs: BallisticInputs) -> Vector3<f64> {
8521        let solver = TrajectorySolver::new(
8522            inputs,
8523            WindConditions::default(),
8524            AtmosphericConditions::default(),
8525        );
8526        let position = Vector3::zeros();
8527        let velocity = Vector3::new(1100.0 / 3.28084, 0.0, 0.0);
8528        let station = solver.station_air().unwrap();
8529        solver.calculate_acceleration(&position, &velocity, &Vector3::zeros(), &station)
8530    }
8531
8532    #[test]
8533    fn solver_passes_g7_reference_model_to_cluster_classifier() {
8534        let inputs = BallisticInputs {
8535            bc_value: 0.190,
8536            bc_type: DragModel::G7,
8537            bullet_mass: 77.0 * crate::constants::GRAINS_TO_KG,
8538            bullet_diameter: 0.224 * 0.0254,
8539            use_cluster_bc: true,
8540            ..BallisticInputs::default()
8541        };
8542
8543        let solver = TrajectorySolver::new(
8544            inputs,
8545            WindConditions::default(),
8546            AtmosphericConditions::default(),
8547        );
8548        let corrected = solver.apply_cluster_bc_correction(0.190, 2800.0);
8549
8550        assert!(
8551            (corrected / 0.190 - 1.004).abs() < 1e-12,
8552            "solver selected the wrong G7 cluster multiplier: {}",
8553            corrected / 0.190
8554        );
8555    }
8556
8557    #[test]
8558    fn velocity_bc_segments_are_not_cluster_corrected_twice() {
8559        let segmented_clustered = BallisticInputs {
8560            bc_value: 0.5,
8561            bc_type: DragModel::G7,
8562            use_bc_segments: true,
8563            bc_segments_data: Some(vec![
8564                crate::BCSegmentData {
8565                    velocity_min: 0.0,
8566                    velocity_max: 1_600.0,
8567                    bc_value: 0.4,
8568                },
8569                crate::BCSegmentData {
8570                    velocity_min: 1_600.0,
8571                    velocity_max: 5_000.0,
8572                    bc_value: 0.45,
8573                },
8574            ]),
8575            use_cluster_bc: true,
8576            ..BallisticInputs::default()
8577        };
8578        let mut segmented_only = segmented_clustered.clone();
8579        segmented_only.use_cluster_bc = false;
8580        let mut constant_clustered = segmented_clustered.clone();
8581        constant_clustered.bc_value = 0.4;
8582        constant_clustered.bc_segments_data = None;
8583
8584        let stacked = acceleration_at_1100_fps(segmented_clustered);
8585        let segment_only = acceleration_at_1100_fps(segmented_only);
8586        let cluster_only = acceleration_at_1100_fps(constant_clustered);
8587
8588        assert!(
8589            (stacked.x - segment_only.x).abs() < 1e-12,
8590            "segment BC already owns the velocity shape: stacked ax={} segment-only ax={}",
8591            stacked.x,
8592            segment_only.x
8593        );
8594        assert!(
8595            (cluster_only.x - segment_only.x).abs() > 1e-6,
8596            "cluster correction must remain active for a constant BC"
8597        );
8598    }
8599
8600    #[test]
8601    fn mach_bc_segments_are_not_cluster_corrected_twice() {
8602        let mach_segmented_clustered = BallisticInputs {
8603            bc_value: 0.5,
8604            bc_type: DragModel::G7,
8605            use_bc_segments: false,
8606            bc_segments: Some(vec![(0.5, 0.3), (1.5, 0.5)]),
8607            use_cluster_bc: true,
8608            ..BallisticInputs::default()
8609        };
8610        let mut mach_segmented_only = mach_segmented_clustered.clone();
8611        mach_segmented_only.use_cluster_bc = false;
8612
8613        let stacked = acceleration_at_1100_fps(mach_segmented_clustered);
8614        let segment_only = acceleration_at_1100_fps(mach_segmented_only);
8615
8616        assert!(
8617            (stacked.x - segment_only.x).abs() < 1e-12,
8618            "Mach segment BC already owns the velocity shape: stacked ax={} segment-only ax={}",
8619            stacked.x,
8620            segment_only.x
8621        );
8622    }
8623}
8624
8625#[cfg(test)]
8626mod velocity_bc_flag_tests {
8627    use super::*;
8628
8629    fn acceleration_at_600_mps(inputs: BallisticInputs) -> Vector3<f64> {
8630        let solver = TrajectorySolver::new(
8631            inputs,
8632            WindConditions::default(),
8633            AtmosphericConditions::default(),
8634        );
8635        let station = solver.station_air().unwrap();
8636        solver.calculate_acceleration(
8637            &Vector3::zeros(),
8638            &Vector3::new(600.0, 0.0, 0.0),
8639            &Vector3::zeros(),
8640            &station,
8641        )
8642    }
8643
8644    #[test]
8645    fn velocity_bc_data_requires_opt_in_in_trajectory_solver() {
8646        let scalar_inputs = BallisticInputs {
8647            bc_value: 0.5,
8648            bc_type: DragModel::G7,
8649            ..BallisticInputs::default()
8650        };
8651        let mut disabled_inputs = scalar_inputs.clone();
8652        disabled_inputs.bc_segments_data = Some(vec![crate::BCSegmentData {
8653            velocity_min: 0.0,
8654            velocity_max: 4_000.0,
8655            bc_value: 0.46,
8656        }]);
8657        disabled_inputs.use_bc_segments = false;
8658        let mut enabled_inputs = disabled_inputs.clone();
8659        enabled_inputs.use_bc_segments = true;
8660        let mut mach_only_inputs = scalar_inputs.clone();
8661        mach_only_inputs.bc_segments = Some(vec![(0.0, 0.4), (3.0, 0.4)]);
8662        let mut disabled_with_both = mach_only_inputs.clone();
8663        disabled_with_both.bc_segments_data = disabled_inputs.bc_segments_data.clone();
8664
8665        let scalar = acceleration_at_600_mps(scalar_inputs);
8666        let disabled = acceleration_at_600_mps(disabled_inputs);
8667        let enabled = acceleration_at_600_mps(enabled_inputs);
8668        let mach_only = acceleration_at_600_mps(mach_only_inputs);
8669        let disabled_with_both = acceleration_at_600_mps(disabled_with_both);
8670
8671        assert_eq!(
8672            disabled.x.to_bits(),
8673            scalar.x.to_bits(),
8674            "a populated velocity table must not change drag while use_bc_segments is false"
8675        );
8676        assert!(
8677            enabled.x < disabled.x - 1.0,
8678            "enabling the lower BC table must increase drag: disabled ax={} enabled ax={}",
8679            disabled.x,
8680            enabled.x
8681        );
8682        assert_eq!(
8683            disabled_with_both.x.to_bits(),
8684            mach_only.x.to_bits(),
8685            "disabling velocity data must fall through to an explicit Mach table"
8686        );
8687    }
8688}
8689
8690#[cfg(test)]
8691mod mach_bc_segment_tests {
8692    use super::*;
8693
8694    #[test]
8695    fn trajectory_solver_interpolates_explicit_mach_bc_segments() {
8696        let segmented_inputs = BallisticInputs {
8697            bc_value: 0.8,
8698            use_bc_segments: false,
8699            bc_segments: Some(vec![(1.0, 0.2), (2.0, 0.4)]),
8700            bc_segments_data: None,
8701            ..BallisticInputs::default()
8702        };
8703
8704        let mut expected_inputs = segmented_inputs.clone();
8705        expected_inputs.bc_value = 0.3;
8706        expected_inputs.bc_segments = None;
8707
8708        let atmosphere = AtmosphericConditions::default();
8709        let segmented_solver = TrajectorySolver::new(
8710            segmented_inputs,
8711            WindConditions::default(),
8712            atmosphere.clone(),
8713        );
8714        let expected_solver =
8715            TrajectorySolver::new(expected_inputs, WindConditions::default(), atmosphere);
8716        let position = Vector3::zeros();
8717        let (density, _, temp_c, pressure_hpa) = segmented_solver.resolved_atmosphere();
8718        let (_, local_speed_of_sound) = crate::atmosphere::get_local_atmosphere_humid(
8719            segmented_solver.atmosphere.altitude,
8720            segmented_solver.atmosphere.altitude,
8721            temp_c,
8722            pressure_hpa,
8723            density / 1.225,
8724            segmented_solver.atmosphere.humidity,
8725        );
8726        let velocity = Vector3::new(1.5 * local_speed_of_sound, 0.0, 0.0);
8727        // Both solvers fly the same default atmosphere, so they share one station.
8728        let station = segmented_solver.station_air().unwrap();
8729
8730        let segmented_acceleration = segmented_solver.calculate_acceleration(
8731            &position,
8732            &velocity,
8733            &Vector3::zeros(),
8734            &station,
8735        );
8736        let expected_acceleration = expected_solver.calculate_acceleration(
8737            &position,
8738            &velocity,
8739            &Vector3::zeros(),
8740            &station,
8741        );
8742
8743        assert!(
8744            (segmented_acceleration.x - expected_acceleration.x).abs() < 1e-12,
8745            "Mach 1.5 must interpolate BC 0.3: segmented ax={} expected ax={}",
8746            segmented_acceleration.x,
8747            expected_acceleration.x
8748        );
8749    }
8750}
8751
8752#[cfg(test)]
8753mod custom_drag_table_validation_tests {
8754    use super::*;
8755
8756    #[test]
8757    fn solve_accepts_zero_bc_when_custom_table_present() {
8758        let inputs = BallisticInputs {
8759            bc_value: 0.0, // ignored when a table is set
8760            bullet_mass: 0.0106,
8761            bullet_diameter: 0.00782,
8762            muzzle_velocity: 850.0,
8763            custom_drag_table: Some(crate::drag::DragTable::new(
8764                vec![0.5, 1.0, 2.0, 3.0],
8765                vec![0.23, 0.40, 0.30, 0.26],
8766            )),
8767            ..BallisticInputs::default()
8768        };
8769        let solver = TrajectorySolver::new(
8770            inputs,
8771            WindConditions::default(),
8772            AtmosphericConditions::default(),
8773        );
8774        // Must not error on the bc_value gate.
8775        assert!(solver.solve().is_ok());
8776    }
8777
8778    #[test]
8779    fn solve_still_requires_bc_without_table() {
8780        let inputs = BallisticInputs {
8781            bc_value: 0.0,
8782            bullet_mass: 0.0106,
8783            bullet_diameter: 0.00782,
8784            muzzle_velocity: 850.0,
8785            ..BallisticInputs::default()
8786        };
8787        let solver = TrajectorySolver::new(
8788            inputs,
8789            WindConditions::default(),
8790            AtmosphericConditions::default(),
8791        );
8792        assert!(solver.solve().is_err());
8793    }
8794}
8795
8796/// MBA-1356: cd_scale — a whole-curve multiplier on the custom-deck Cd.
8797#[cfg(test)]
8798mod cd_scale_tests {
8799    use super::*;
8800
8801    fn deck() -> crate::drag::DragTable {
8802        crate::drag::DragTable::new(vec![0.5, 1.0, 2.0, 3.0], vec![0.23, 0.40, 0.30, 0.26])
8803    }
8804
8805    fn deck_inputs(cd_scale: f64) -> BallisticInputs {
8806        BallisticInputs {
8807            bullet_mass: 0.0106,
8808            bullet_diameter: 0.00782,
8809            muzzle_velocity: 850.0,
8810            custom_drag_table: Some(deck()),
8811            cd_scale,
8812            ..BallisticInputs::default()
8813        }
8814    }
8815
8816    #[test]
8817    fn default_cd_scale_is_one() {
8818        assert_eq!(BallisticInputs::default().cd_scale, 1.0);
8819    }
8820
8821    /// (a) Default invariance: omitting `cd_scale` (picked up from `..Default::default()`)
8822    /// must be byte-identical to explicitly setting `1.0`, on the custom-deck Cd itself.
8823    #[test]
8824    fn cd_scale_absent_is_byte_identical_to_explicit_one() {
8825        let omitted = BallisticInputs {
8826            bullet_mass: 0.0106,
8827            bullet_diameter: 0.00782,
8828            muzzle_velocity: 850.0,
8829            custom_drag_table: Some(deck()),
8830            ..BallisticInputs::default()
8831        };
8832        let explicit = BallisticInputs {
8833            cd_scale: 1.0,
8834            ..omitted.clone()
8835        };
8836
8837        let solver_omitted = TrajectorySolver::new(
8838            omitted,
8839            WindConditions::default(),
8840            AtmosphericConditions::default(),
8841        );
8842        let solver_explicit = TrajectorySolver::new(
8843            explicit,
8844            WindConditions::default(),
8845            AtmosphericConditions::default(),
8846        );
8847
8848        let cd_omitted = solver_omitted.calculate_drag_coefficient(700.0, 340.0);
8849        let cd_explicit = solver_explicit.calculate_drag_coefficient(700.0, 340.0);
8850        assert_eq!(
8851            cd_omitted.to_bits(),
8852            cd_explicit.to_bits(),
8853            "default cd_scale must be bit-identical to an explicit 1.0"
8854        );
8855
8856        // And a full custom-deck solve (the existing pre-MBA-1356 test surface) must still
8857        // succeed unchanged with the field simply absent from the literal.
8858        let result = solver_omitted.solve();
8859        assert!(
8860            result.is_ok(),
8861            "existing custom-deck solves must pass unchanged"
8862        );
8863    }
8864
8865    /// The custom-deck interpolation site multiplies the deck's Cd by `cd_scale` exactly.
8866    #[test]
8867    fn cd_scale_multiplies_the_interpolated_cd_exactly() {
8868        let velocity = 700.0;
8869        let speed_of_sound = 340.0;
8870        let mach = velocity / speed_of_sound;
8871        let expected_unscaled = deck().interpolate(mach);
8872
8873        for &scale in &[0.90, 1.0, 1.10, 1.5] {
8874            let solver = TrajectorySolver::new(
8875                deck_inputs(scale),
8876                WindConditions::default(),
8877                AtmosphericConditions::default(),
8878            );
8879            let cd = solver.calculate_drag_coefficient(velocity, speed_of_sound);
8880            assert!(
8881                (cd - expected_unscaled * scale).abs() < 1e-12,
8882                "scale={scale}: cd={cd} expected={}",
8883                expected_unscaled * scale
8884            );
8885        }
8886    }
8887
8888    /// (b) Scale-direction test, cli_api (RK4/RK45) solver path: a higher cd_scale means more
8889    /// drag, so the solve loses more velocity (and correspondingly drops more) over the same
8890    /// downrange distance; a lower cd_scale loses less.
8891    #[test]
8892    fn cd_scale_direction_on_cli_api_solver() {
8893        let solve = |scale: f64| {
8894            TrajectorySolver::new(
8895                deck_inputs(scale),
8896                WindConditions::default(),
8897                AtmosphericConditions::default(),
8898            )
8899            .solve()
8900            .expect("custom-deck solve should succeed")
8901        };
8902
8903        let baseline = solve(1.0);
8904        let scaled_up = solve(1.10);
8905        let scaled_down = solve(0.90);
8906
8907        assert!(
8908            scaled_up.impact_velocity < baseline.impact_velocity,
8909            "cd_scale=1.10 must increase drag -> lower impact velocity: base={} up={}",
8910            baseline.impact_velocity,
8911            scaled_up.impact_velocity
8912        );
8913        assert!(
8914            scaled_down.impact_velocity > baseline.impact_velocity,
8915            "cd_scale=0.90 must decrease drag -> higher impact velocity: base={} down={}",
8916            baseline.impact_velocity,
8917            scaled_down.impact_velocity
8918        );
8919    }
8920
8921    /// (d) `validate_for_solve` rejects a non-finite or non-positive `cd_scale`.
8922    #[test]
8923    fn validate_for_solve_rejects_invalid_cd_scale() {
8924        for bad in [0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
8925            let solver = TrajectorySolver::new(
8926                deck_inputs(bad),
8927                WindConditions::default(),
8928                AtmosphericConditions::default(),
8929            );
8930            assert!(
8931                solver.solve().is_err(),
8932                "cd_scale={bad} must be rejected by validate_for_solve"
8933            );
8934        }
8935    }
8936
8937    /// `require_positive("cd_scale", ...)` is unconditional in `validate_for_solve` (see the
8938    /// comment there) — it must reject an invalid scale even with NO custom drag table present,
8939    /// not just on the deck path the other tests in this module exercise. Otherwise a caller
8940    /// that sets an invalid `cd_scale` without ever touching `custom_drag_table` would slip
8941    /// through unvalidated (the field would simply go unread on this path, but the validation
8942    /// gate itself must not silently skip it).
8943    #[test]
8944    fn validate_for_solve_rejects_invalid_cd_scale_without_a_custom_drag_table() {
8945        for bad in [0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
8946            let inputs = BallisticInputs {
8947                bc_value: 0.5,
8948                bc_type: crate::DragModel::G1,
8949                bullet_mass: 0.0106,
8950                bullet_diameter: 0.00782,
8951                muzzle_velocity: 850.0,
8952                cd_scale: bad,
8953                ..BallisticInputs::default()
8954            };
8955            assert!(
8956                inputs.custom_drag_table.is_none(),
8957                "precondition: no custom deck"
8958            );
8959            let solver = TrajectorySolver::new(
8960                inputs,
8961                WindConditions::default(),
8962                AtmosphericConditions::default(),
8963            );
8964            assert!(
8965                solver.solve().is_err(),
8966                "cd_scale={bad} must be rejected by validate_for_solve even without a custom \
8967                 drag table"
8968            );
8969        }
8970    }
8971
8972    /// cd_scale must be inert on the standard G-model/BC path (no custom_drag_table): the
8973    /// scale is read only inside the `custom_drag_table` branch, so a scale far from 1.0 must
8974    /// not perturb a plain G1/G7 solve at all.
8975    #[test]
8976    fn cd_scale_is_inert_without_a_custom_drag_table() {
8977        let make = |cd_scale: f64| BallisticInputs {
8978            bc_value: 0.5,
8979            bc_type: crate::DragModel::G1,
8980            bullet_mass: 0.0106,
8981            bullet_diameter: 0.00782,
8982            muzzle_velocity: 850.0,
8983            cd_scale,
8984            ..BallisticInputs::default()
8985        };
8986        let solver_neutral = TrajectorySolver::new(
8987            make(1.0),
8988            WindConditions::default(),
8989            AtmosphericConditions::default(),
8990        );
8991        let solver_far = TrajectorySolver::new(
8992            make(1.5),
8993            WindConditions::default(),
8994            AtmosphericConditions::default(),
8995        );
8996        let cd_neutral = solver_neutral.calculate_drag_coefficient(700.0, 340.0);
8997        let cd_far = solver_far.calculate_drag_coefficient(700.0, 340.0);
8998        assert_eq!(
8999            cd_neutral.to_bits(),
9000            cd_far.to_bits(),
9001            "cd_scale must not affect the G-model/BC drag path"
9002        );
9003    }
9004
9005    /// (c) Cross-solver consistency: cli_api (RK4/RK45), derivatives-driven, and fast_trajectory
9006    /// all shift together (same relative direction) under cd_scale != 1.0 on the same deck.
9007    #[test]
9008    fn cd_scale_shifts_all_three_solver_paths_in_the_same_direction() {
9009        // --- cli_api ---
9010        let cli_solve = |scale: f64| {
9011            TrajectorySolver::new(
9012                deck_inputs(scale),
9013                WindConditions::default(),
9014                AtmosphericConditions::default(),
9015            )
9016            .solve()
9017            .expect("cli_api custom-deck solve should succeed")
9018        };
9019        let cli_baseline = cli_solve(1.0);
9020        let cli_scaled = cli_solve(1.10);
9021        assert!(
9022            cli_scaled.impact_velocity < cli_baseline.impact_velocity,
9023            "cli_api: cd_scale=1.10 must lower impact velocity"
9024        );
9025
9026        // --- derivatives (the RK4/RK45 generic integrator's kernel) ---
9027        let derivatives_accel_x = |scale: f64| {
9028            let inputs = deck_inputs(scale);
9029            crate::derivatives::compute_derivatives(
9030                nalgebra::Vector3::zeros(),
9031                nalgebra::Vector3::new(700.0, 0.0, 0.0),
9032                &inputs,
9033                nalgebra::Vector3::zeros(),
9034                &KernelAtmosphere::uniform(1.225, 340.0).unwrap(),
9035                inputs.bc_value,
9036                None,
9037                0.0,
9038                None,
9039            )[3]
9040        };
9041        let deriv_baseline = derivatives_accel_x(1.0);
9042        let deriv_scaled = derivatives_accel_x(1.10);
9043        assert!(
9044            deriv_scaled < deriv_baseline,
9045            "derivatives: cd_scale=1.10 must make x-acceleration more negative (more drag): \
9046             base={deriv_baseline} scaled={deriv_scaled}"
9047        );
9048
9049        // --- fast_trajectory (fast_integrate) ---
9050        let fast_final_speed = |scale: f64| {
9051            let inputs = deck_inputs(scale);
9052            let wind_sock = crate::wind::WindSock::new(vec![]);
9053            let params = crate::fast_trajectory::FastIntegrationParams {
9054                horiz: 500.0,
9055                vert: 0.0,
9056                initial_state: [0.0, 0.0, 0.0, 850.0, 0.0, 0.0],
9057                t_span: (0.0, 5.0),
9058                atmosphere: KernelAtmosphere::from_legacy_params(
9059                    (0.0, 15.0, 1013.25, 1.0),
9060                    crate::atmosphere::RelativeHumidity::DRY,
9061                )
9062                .unwrap(),
9063                atmo_sock: None,
9064            };
9065            let solution = crate::fast_trajectory::fast_integrate(&inputs, &wind_sock, params);
9066            assert!(
9067                solution.success,
9068                "fast_integrate must succeed for scale={scale}"
9069            );
9070            let last = solution.t.len() - 1;
9071            let (vx, vy, vz) = (
9072                solution.y[3][last],
9073                solution.y[4][last],
9074                solution.y[5][last],
9075            );
9076            (vx * vx + vy * vy + vz * vz).sqrt()
9077        };
9078        let fast_baseline = fast_final_speed(1.0);
9079        let fast_scaled = fast_final_speed(1.10);
9080        assert!(
9081            fast_scaled < fast_baseline,
9082            "fast_trajectory: cd_scale=1.10 must lower final speed: base={fast_baseline} scaled={fast_scaled}"
9083        );
9084    }
9085}
9086
9087/// `custom_drag_reference`: a custom table flown as a reference curve, divided by the resolved
9088/// BC exactly as a built-in model's curve is, instead of the projectile's own Cd over sectional
9089/// density.
9090#[cfg(test)]
9091mod custom_drag_reference_tests {
9092    use super::*;
9093
9094    /// The engine's own G7 table, as a caller would send it.
9095    fn g7_table() -> crate::drag::DragTable {
9096        crate::drag::DragTable::from_csv_str(include_str!("../data/g7.csv"))
9097            .expect("bundled table parses")
9098    }
9099
9100    /// The engine's own G1 table, a curve far from `bc_type: G7`'s.
9101    fn g1_table() -> crate::drag::DragTable {
9102        crate::drag::DragTable::from_csv_str(include_str!("../data/g1.csv"))
9103            .expect("bundled table parses")
9104    }
9105
9106    /// A .308 175 gr G7 0.243 at 823 m/s with a two-band ladder (edge at 2400 fps) whose BCs both
9107    /// differ from the scalar. The imperial mirrors are set too, so the sectional density read
9108    /// off these inputs is the one `TrajectorySolver::new` re-derives from the SI fields.
9109    fn laddered_inputs() -> BallisticInputs {
9110        BallisticInputs {
9111            bc_value: 0.243,
9112            bc_type: DragModel::G7,
9113            bullet_mass: 175.0 * crate::constants::GRAINS_TO_KG,
9114            bullet_diameter: 0.308 * 0.0254,
9115            weight_grains: 175.0,
9116            caliber_inches: 0.308,
9117            muzzle_velocity: 823.0,
9118            use_bc_segments: true,
9119            bc_segments_data: Some(vec![
9120                crate::BCSegmentData {
9121                    velocity_min: 2400.0,
9122                    velocity_max: 4000.0,
9123                    bc_value: 0.260,
9124                },
9125                crate::BCSegmentData {
9126                    velocity_min: 0.0,
9127                    velocity_max: 2400.0,
9128                    bc_value: 0.220,
9129                },
9130            ]),
9131            ..BallisticInputs::default()
9132        }
9133    }
9134
9135    fn reference(inputs: BallisticInputs) -> BallisticInputs {
9136        BallisticInputs {
9137            custom_drag_table: Some(g7_table()),
9138            custom_drag_reference: true,
9139            ..inputs
9140        }
9141    }
9142
9143    fn solve(inputs: BallisticInputs) -> TrajectoryResult {
9144        let mut solver = TrajectorySolver::new(
9145            inputs,
9146            WindConditions::default(),
9147            AtmosphericConditions::default(),
9148        );
9149        solver.set_max_range(800.0);
9150        solver.solve().expect("solve")
9151    }
9152
9153    #[test]
9154    fn default_is_the_projectiles_own_curve() {
9155        assert!(!BallisticInputs::default().custom_drag_reference);
9156    }
9157
9158    #[test]
9159    fn the_denominator_is_the_resolved_bc_for_a_reference_curve() {
9160        let own = BallisticInputs {
9161            custom_drag_table: Some(g7_table()),
9162            ..laddered_inputs()
9163        };
9164        let sd = own.sectional_density_lb_in2().expect("SD");
9165        assert_eq!(own.custom_drag_denominator(0.220), sd);
9166        let reference = reference(laddered_inputs());
9167        assert_eq!(reference.custom_drag_denominator(0.220), 0.220);
9168        assert_eq!(reference.custom_drag_denominator(0.260), 0.260);
9169    }
9170
9171    /// The same ladder on the built-in G7 model and on the engine's G7 table sent as a reference
9172    /// curve is the same arithmetic, so the two fly bit-identically. Without the flag the table
9173    /// is read as the projectile's own Cd over sectional density, a different projectile.
9174    #[test]
9175    fn a_reference_curve_flies_a_ladder_exactly_as_the_builtin_model() {
9176        let builtin = solve(laddered_inputs());
9177        let table = solve(reference(laddered_inputs()));
9178        assert_eq!(table.points.len(), builtin.points.len());
9179        for (t, b) in table.points.iter().zip(&builtin.points) {
9180            assert_eq!(t.position, b.position);
9181            assert_eq!(
9182                t.velocity_magnitude.to_bits(),
9183                b.velocity_magnitude.to_bits()
9184            );
9185        }
9186
9187        let own_curve = solve(BallisticInputs {
9188            custom_drag_reference: false,
9189            ..reference(laddered_inputs())
9190        });
9191        assert!(
9192            (own_curve.impact_velocity - builtin.impact_velocity).abs() > 10.0,
9193            "the fixture must tell the readings apart: {} vs {}",
9194            own_curve.impact_velocity,
9195            builtin.impact_velocity
9196        );
9197    }
9198
9199    /// The table is what flies, not `bc_type`'s curve: the G7 table above is the same numbers as
9200    /// `bc_type: G7`, so it cannot tell them apart. The G1 table flown as a reference curve while
9201    /// `bc_type` stays G7 must equal the built-in G1 model with the same ladder, bit for bit; a
9202    /// drag site that read `bc_type` beside the flag would give the G7 answer instead.
9203    #[test]
9204    fn a_reference_curve_flies_the_table_not_bc_types_curve() {
9205        let table = solve(BallisticInputs {
9206            custom_drag_table: Some(g1_table()),
9207            custom_drag_reference: true,
9208            bc_type: DragModel::G7,
9209            ..laddered_inputs()
9210        });
9211        let builtin_g1 = solve(BallisticInputs {
9212            bc_type: DragModel::G1,
9213            ..laddered_inputs()
9214        });
9215        assert_eq!(table.points.len(), builtin_g1.points.len());
9216        for (t, b) in table.points.iter().zip(&builtin_g1.points) {
9217            assert_eq!(t.position, b.position);
9218            assert_eq!(
9219                t.velocity_magnitude.to_bits(),
9220                b.velocity_magnitude.to_bits()
9221            );
9222        }
9223
9224        let builtin_g7 = solve(laddered_inputs());
9225        assert!(
9226            (builtin_g1.impact_velocity - builtin_g7.impact_velocity).abs() > 50.0,
9227            "the fixture must tell the curves apart: G1 {} vs G7 {}",
9228            builtin_g1.impact_velocity,
9229            builtin_g7.impact_velocity
9230        );
9231    }
9232
9233    /// The BC divides the curve again, so it is held to the built-in model's rule, while the
9234    /// own-curve reading still ignores it.
9235    #[test]
9236    fn validate_for_solve_requires_a_bc_for_a_reference_curve() {
9237        for bad in [0.0, -0.1, f64::NAN, f64::INFINITY] {
9238            let inputs = BallisticInputs {
9239                bc_value: bad,
9240                ..reference(laddered_inputs())
9241            };
9242            let error = TrajectorySolver::new(
9243                inputs.clone(),
9244                WindConditions::default(),
9245                AtmosphericConditions::default(),
9246            )
9247            .solve()
9248            .expect_err("a reference curve needs a finite positive BC");
9249            assert!(error.to_string().contains("bc_value"), "{error}");
9250
9251            let own_curve = BallisticInputs {
9252                custom_drag_reference: false,
9253                use_bc_segments: false,
9254                bc_segments_data: None,
9255                ..inputs
9256            };
9257            assert!(
9258                TrajectorySolver::new(
9259                    own_curve,
9260                    WindConditions::default(),
9261                    AtmosphericConditions::default(),
9262                )
9263                .solve()
9264                .is_ok(),
9265                "bc_value={bad} is still ignored by the own-curve reading"
9266            );
9267        }
9268    }
9269
9270    /// An Army Standard Metro BC divides a reference curve, so its conversion is real: the
9271    /// scalar and every band convert exactly as they would on the built-in model, and no inert
9272    /// warning is raised.
9273    #[test]
9274    fn army_standard_metro_converts_a_reference_curves_bcs() {
9275        let asm = BallisticInputs {
9276            bc_reference_standard: BcReferenceStandard::ArmyStandardMetro,
9277            ..reference(laddered_inputs())
9278        };
9279        assert!(asm.bc_reference_standard_inert_warning().is_none());
9280        assert!(BallisticInputs {
9281            custom_drag_reference: false,
9282            ..asm.clone()
9283        }
9284        .bc_reference_standard_inert_warning()
9285        .is_some());
9286
9287        let converted = solve(asm);
9288        let builtin_asm = solve(BallisticInputs {
9289            bc_reference_standard: BcReferenceStandard::ArmyStandardMetro,
9290            ..laddered_inputs()
9291        });
9292        let icao = solve(reference(laddered_inputs()));
9293        assert_eq!(
9294            converted.impact_velocity.to_bits(),
9295            builtin_asm.impact_velocity.to_bits()
9296        );
9297        assert!(
9298            converted.impact_velocity < icao.impact_velocity,
9299            "the ASM BCs are smaller once converted, so the bullet must slow more: {} vs {}",
9300            converted.impact_velocity,
9301            icao.impact_velocity
9302        );
9303    }
9304
9305    /// The reported Cd is the projectile's own: the reference curve times SD over the band BC
9306    /// that flies, exactly as for a built-in model.
9307    #[test]
9308    fn the_reported_cd_is_the_projectiles_own() {
9309        let inputs = reference(laddered_inputs());
9310        let sd = inputs.sectional_density_lb_in2().expect("SD");
9311        let solver = TrajectorySolver::new(
9312            inputs,
9313            WindConditions::default(),
9314            AtmosphericConditions::default(),
9315        );
9316        let sos = 340.0;
9317        for (fps, band_bc) in [(2600.0, 0.260), (2200.0, 0.220)] {
9318            let velocity = fps / 3.28084;
9319            let expected = g7_table().interpolate(velocity / sos) * sd / band_bc;
9320            let reported = solver
9321                .effective_drag_coefficient(velocity, sos)
9322                .expect("mass and diameter are set");
9323            assert!(
9324                (reported - expected).abs() < 1e-12,
9325                "{fps} fps: reported {reported}, expected {expected}"
9326            );
9327        }
9328    }
9329}
9330
9331#[cfg(test)]
9332mod humid_local_mach_tests {
9333    use super::*;
9334
9335    fn solver_with_station_humidity(humidity_percent: f64) -> TrajectorySolver {
9336        let inputs = BallisticInputs {
9337            custom_drag_table: Some(crate::drag::DragTable::new(vec![0.5, 1.5], vec![0.1, 1.1])),
9338            ..BallisticInputs::default()
9339        };
9340        TrajectorySolver::new(
9341            inputs,
9342            WindConditions::default(),
9343            AtmosphericConditions {
9344                temperature: 30.0,
9345                pressure: 1013.25,
9346                humidity: humidity_percent,
9347                altitude: 0.0,
9348            },
9349        )
9350    }
9351
9352    fn acceleration(solver: &TrajectorySolver, base_ratio: f64) -> Vector3<f64> {
9353        // The solver's own 30 C / 1013.25 hPa station and humidity, with a density ratio the
9354        // test holds fixed so that only the sound speed can respond to the humidity.
9355        let humidity =
9356            crate::atmosphere::RelativeHumidity::try_percent(solver.atmosphere.humidity).unwrap();
9357        let station = StationAir::with_density_ratio(
9358            solver.atmosphere.altitude,
9359            30.0,
9360            1013.25,
9361            base_ratio,
9362            humidity,
9363        )
9364        .unwrap();
9365        solver.calculate_acceleration(
9366            &Vector3::zeros(),
9367            &Vector3::new(350.0, 0.0, 0.0),
9368            &Vector3::zeros(),
9369            &station,
9370        )
9371    }
9372
9373    #[test]
9374    fn local_mach_uses_station_humidity_when_density_is_held_constant() {
9375        let dry = acceleration(&solver_with_station_humidity(0.0), 1.0);
9376        let humid = acceleration(&solver_with_station_humidity(100.0), 1.0);
9377
9378        assert!(
9379            humid.x > dry.x,
9380            "humid sound speed should lower Mach and drag on the rising test curve: dry ax={} humid ax={}",
9381            dry.x,
9382            humid.x
9383        );
9384    }
9385
9386    #[test]
9387    fn active_atmosphere_zone_uses_zone_humidity_instead_of_station_humidity() {
9388        let zone_humidity = 80.0;
9389        let zone_ratio =
9390            crate::atmosphere::calculate_air_density_cimp(30.0, 1013.25, zone_humidity) / 1.225;
9391        let station_solver = solver_with_station_humidity(zone_humidity);
9392        let mut zoned_solver = solver_with_station_humidity(0.0);
9393        zoned_solver.set_atmo_segments(vec![(30.0, 1013.25, zone_humidity, 1_000.0)]);
9394
9395        let station = acceleration(&station_solver, zone_ratio);
9396        let zoned = acceleration(&zoned_solver, zone_ratio);
9397
9398        assert!(
9399            (zoned - station).norm() < 1e-12,
9400            "active zone T/P/RH should override the station atmosphere: station={station:?} zoned={zoned:?}"
9401        );
9402    }
9403}
9404
9405#[cfg(test)]
9406mod inclined_atmosphere_frame_tests {
9407    use super::*;
9408
9409    fn expected_shot_frame_vector(level: Vector3<f64>, angle: f64) -> Vector3<f64> {
9410        let (sin_angle, cos_angle) = angle.sin_cos();
9411        Vector3::new(
9412            level.x * cos_angle + level.y * sin_angle,
9413            -level.x * sin_angle + level.y * cos_angle,
9414            level.z,
9415        )
9416    }
9417
9418    #[test]
9419    fn inclined_positions_at_same_world_altitude_have_same_solver_acceleration() {
9420        let angle = std::f64::consts::FRAC_PI_6;
9421        let inputs = BallisticInputs {
9422            shooting_angle: angle,
9423            ..BallisticInputs::default()
9424        };
9425        let atmosphere = AtmosphericConditions {
9426            altitude: 100.0,
9427            ..AtmosphericConditions::default()
9428        };
9429        let solver = TrajectorySolver::new(inputs, WindConditions::default(), atmosphere);
9430        let station = solver.station_air().unwrap();
9431        let velocity = Vector3::new(600.0, 0.0, 0.0);
9432        let along_slant = Vector3::new(1_000.0, 0.0, 0.0);
9433        let across_slant = Vector3::new(0.0, 500.0 / angle.cos(), 0.0);
9434
9435        let a = solver.calculate_acceleration(&along_slant, &velocity, &Vector3::zeros(), &station);
9436        let b =
9437            solver.calculate_acceleration(&across_slant, &velocity, &Vector3::zeros(), &station);
9438
9439        assert!(
9440            (a - b).norm() < 1e-10,
9441            "solver acceleration differs at equal world altitude: {a:?} vs {b:?}"
9442        );
9443    }
9444
9445    #[test]
9446    fn inclined_headwind_is_rotated_into_solver_frame() {
9447        let angle = std::f64::consts::FRAC_PI_6;
9448        let inputs = BallisticInputs {
9449            shooting_angle: angle,
9450            ..BallisticInputs::default()
9451        };
9452        let solver = TrajectorySolver::new(
9453            inputs,
9454            WindConditions::default(),
9455            AtmosphericConditions::default(),
9456        );
9457        let level_headwind = Vector3::new(-100.0, 0.0, 0.0);
9458        let velocity = expected_shot_frame_vector(level_headwind, angle);
9459        let station = solver.station_air().unwrap();
9460        let actual =
9461            solver.calculate_acceleration(&Vector3::zeros(), &velocity, &level_headwind, &station);
9462
9463        assert!(
9464            (actual - solver.gravity_acceleration()).norm() < 1e-12,
9465            "co-moving horizontal wind must leave only shot-frame gravity: {actual:?}"
9466        );
9467    }
9468
9469    #[test]
9470    fn inclined_coriolis_is_rotated_into_solver_frame() {
9471        let angle = std::f64::consts::FRAC_PI_6;
9472        let latitude_deg = 45.0_f64;
9473        let shot_azimuth = 0.4_f64;
9474        let velocity = Vector3::new(600.0, 20.0, 5.0);
9475        let base_inputs = BallisticInputs {
9476            shooting_angle: angle,
9477            latitude: Some(latitude_deg),
9478            shot_azimuth,
9479            ..BallisticInputs::default()
9480        };
9481        let acceleration = |enable_coriolis| {
9482            let mut inputs = base_inputs.clone();
9483            inputs.enable_coriolis = enable_coriolis;
9484            let solver = TrajectorySolver::new(
9485                inputs,
9486                WindConditions::default(),
9487                AtmosphericConditions::default(),
9488            );
9489            let station = solver.station_air().unwrap();
9490            solver.calculate_acceleration(&Vector3::zeros(), &velocity, &Vector3::zeros(), &station)
9491        };
9492
9493        let omega_earth = 7.2921159e-5_f64;
9494        let latitude = latitude_deg.to_radians();
9495        let level_omega = Vector3::new(
9496            omega_earth * latitude.cos() * shot_azimuth.cos(),
9497            omega_earth * latitude.sin(),
9498            -omega_earth * latitude.cos() * shot_azimuth.sin(),
9499        );
9500        let expected = -2.0 * expected_shot_frame_vector(level_omega, angle).cross(&velocity);
9501        let actual = acceleration(true) - acceleration(false);
9502
9503        assert!(
9504            (actual - expected).norm() < 1e-12,
9505            "inclined Coriolis mismatch: actual={actual:?}, expected={expected:?}"
9506        );
9507    }
9508}
9509
9510#[cfg(test)]
9511mod terminal_range_interpolation_tests {
9512    use super::*;
9513
9514    #[test]
9515    fn terminal_finalizer_selects_the_earliest_crossed_boundary() {
9516        let inputs = BallisticInputs {
9517            ground_threshold: 0.0,
9518            ..BallisticInputs::default()
9519        };
9520        let mut solver = TrajectorySolver::new(
9521            inputs,
9522            WindConditions::default(),
9523            AtmosphericConditions::default(),
9524        );
9525        solver.set_max_range(120.0);
9526
9527        let previous_speed = 700.0;
9528        let mut points = vec![TrajectoryPoint {
9529            time: 99.0,
9530            position: Vector3::new(90.0, 1.0, -1.0),
9531            velocity_magnitude: previous_speed,
9532            kinetic_energy: 0.5 * solver.inputs.bullet_mass * previous_speed.powi(2),
9533            drag_coefficient: None,
9534        }];
9535        let mut max_height = 1.0;
9536        let termination = solver
9537            .append_terminal_endpoint(
9538                &mut points,
9539                Vector3::new(130.0, -3.0, 3.0),
9540                Vector3::new(600.0, 0.0, 0.0),
9541                101.0,
9542                &mut max_height,
9543                &mut 0,
9544            )
9545            .expect("the final step brackets supported boundaries");
9546
9547        assert_eq!(termination, TrajectoryTermination::GroundThreshold);
9548        assert_eq!(points.len(), 2);
9549        let terminal = points.last().expect("terminal point");
9550        assert_eq!(terminal.time, 99.5);
9551        assert_eq!(terminal.position, Vector3::new(100.0, 0.0, 0.0));
9552        assert_eq!(terminal.velocity_magnitude, 675.0);
9553        assert_eq!(
9554            terminal.kinetic_energy,
9555            0.5 * solver.inputs.bullet_mass * 675.0_f64.powi(2)
9556        );
9557
9558        // At x=100 the range and ground crossings tie; physical ground impact wins explicitly.
9559        solver.set_max_range(100.0);
9560        let mut tied_points = vec![points[0].clone()];
9561        assert_eq!(
9562            solver
9563                .append_terminal_endpoint(
9564                    &mut tied_points,
9565                    Vector3::new(130.0, -3.0, 3.0),
9566                    Vector3::new(600.0, 0.0, 0.0),
9567                    101.0,
9568                    &mut max_height,
9569                    &mut 0,
9570                )
9571                .expect("tied boundaries remain a valid terminal"),
9572            TrajectoryTermination::GroundThreshold
9573        );
9574    }
9575
9576    #[test]
9577    fn sub_ulp_terminal_crossing_replaces_instead_of_duplicating_range() {
9578        let ground_threshold = f64::from_bits(1.0_f64.to_bits() - 1);
9579        let inputs = BallisticInputs {
9580            ground_threshold,
9581            ..BallisticInputs::default()
9582        };
9583        let mut solver = TrajectorySolver::new(
9584            inputs,
9585            WindConditions::default(),
9586            AtmosphericConditions::default(),
9587        );
9588        solver.set_max_range(1_000.0);
9589
9590        let speed = 700.0;
9591        let mut points = vec![TrajectoryPoint {
9592            time: 0.0,
9593            position: Vector3::new(100.0, 1.0, 0.0),
9594            velocity_magnitude: speed,
9595            kinetic_energy: 0.5 * solver.inputs.bullet_mass * speed.powi(2),
9596            drag_coefficient: None,
9597        }];
9598        let mut max_height = 1.0;
9599        let termination = solver
9600            .append_terminal_endpoint(
9601                &mut points,
9602                Vector3::new(101.0, 0.0, 0.0),
9603                Vector3::new(699.0, 0.0, 0.0),
9604                1.0,
9605                &mut max_height,
9606                &mut 0,
9607            )
9608            .expect("sub-ULP ground crossing remains representable as one terminal state");
9609
9610        assert_eq!(termination, TrajectoryTermination::GroundThreshold);
9611        assert_eq!(points.len(), 1);
9612        assert_eq!(points[0].position.x, 100.0);
9613        assert_eq!(points[0].position.y.to_bits(), ground_threshold.to_bits());
9614        assert!(points[0].time > 0.0);
9615    }
9616
9617    /// MBA-1599: at the bottom of the BC range the projectile sheds its downrange speed within a
9618    /// few metres and then falls almost straight down. Once a whole step moves x by less than half
9619    /// a ULP, `x + vx*dt == x` while y keeps falling. Every solver must keep one stored point per
9620    /// downrange distance and still end at the real boundary, so the checked observation API
9621    /// accepts the flight. Euler flies 2e-4 because explicit Euler at 1 ms is unstable at 1e-4.
9622    #[test]
9623    fn downrange_stall_replaces_instead_of_duplicating_range() {
9624        for (name, use_rk4, use_adaptive_rk45, bc_value) in [
9625            ("Euler", false, false, 2.0e-4),
9626            ("RK4", true, false, 1.0e-4),
9627            ("RK45", true, true, 1.0e-4),
9628        ] {
9629            let inputs = BallisticInputs {
9630                bc_value,
9631                bc_type: DragModel::G7,
9632                bullet_mass: 0.01134,
9633                bullet_diameter: 0.00782,
9634                muzzle_velocity: 823.0,
9635                use_rk4,
9636                use_adaptive_rk45,
9637                ground_threshold: -100.0,
9638                ..BallisticInputs::default()
9639            };
9640            let mut solver = TrajectorySolver::new(
9641                inputs,
9642                WindConditions::default(),
9643                AtmosphericConditions::default(),
9644            );
9645            solver.set_max_range(300.0);
9646            solver.set_time_step(0.001);
9647
9648            let result = solver
9649                .solve()
9650                .unwrap_or_else(|error| panic!("{name}: a stalled flight still solves: {error}"));
9651            assert!(
9652                result
9653                    .points
9654                    .windows(2)
9655                    .all(|pair| pair[1].position.x > pair[0].position.x),
9656                "{name}: stored downrange distances must strictly increase"
9657            );
9658            assert_eq!(
9659                result.termination,
9660                TrajectoryTermination::GroundThreshold,
9661                "{name}"
9662            );
9663            assert!(
9664                result.max_range > 0.0 && result.max_range < 300.0,
9665                "{name}: the stall ends short of max_range, got {} m",
9666                result.max_range
9667            );
9668            let terminal = result.points.last().expect("terminal point");
9669            assert_eq!(terminal.position.y, -100.0, "{name}");
9670            result
9671                .sample_observations(50.0, 100)
9672                .unwrap_or_else(|error| panic!("{name}: checked sampling refused: {error}"));
9673        }
9674    }
9675
9676    #[test]
9677    fn every_solver_appends_an_exact_max_range_endpoint() {
9678        let target_range = 0.1;
9679        let modes = [
9680            ("Euler", false, false),
9681            ("RK4", true, false),
9682            ("RK45", true, true),
9683        ];
9684
9685        for (name, use_rk4, use_adaptive_rk45) in modes {
9686            let inputs = BallisticInputs {
9687                use_rk4,
9688                use_adaptive_rk45,
9689                ground_threshold: f64::NEG_INFINITY,
9690                enable_trajectory_sampling: true,
9691                sample_interval: target_range,
9692                ..BallisticInputs::default()
9693            };
9694            let mut solver = TrajectorySolver::new(
9695                inputs,
9696                WindConditions::default(),
9697                AtmosphericConditions::default(),
9698            );
9699            solver.set_max_range(target_range);
9700
9701            let result = solver.solve().expect("short-range solve should succeed");
9702            let terminal = result.points.last().expect("terminal point is missing");
9703            let muzzle = result.points.first().expect("muzzle point is missing");
9704
9705            assert_eq!(result.termination, TrajectoryTermination::MaxRange);
9706            assert_eq!(
9707                terminal.position.x.to_bits(),
9708                target_range.to_bits(),
9709                "{name} did not terminate exactly at max_range"
9710            );
9711            assert_eq!(result.max_range.to_bits(), target_range.to_bits());
9712            assert!(
9713                result.time_of_flight > 0.0 && result.time_of_flight < solver.time_step,
9714                "{name} terminal time was not interpolated within the crossing step: {}",
9715                result.time_of_flight
9716            );
9717            assert_eq!(result.time_of_flight.to_bits(), terminal.time.to_bits());
9718            assert_eq!(
9719                result.impact_velocity.to_bits(),
9720                terminal.velocity_magnitude.to_bits()
9721            );
9722            assert_eq!(
9723                result.impact_energy.to_bits(),
9724                terminal.kinetic_energy.to_bits()
9725            );
9726            let expected_energy = 0.5 * solver.inputs.bullet_mass * result.impact_velocity.powi(2);
9727            assert!((result.impact_energy - expected_energy).abs() < 1e-12);
9728            assert!(terminal.velocity_magnitude < muzzle.velocity_magnitude);
9729            assert!(terminal.kinetic_energy < muzzle.kinetic_energy);
9730
9731            let terminal_sample = result
9732                .sampled_points
9733                .as_ref()
9734                .and_then(|samples| samples.last())
9735                .expect("terminal trajectory sample is missing");
9736            assert_eq!(
9737                terminal_sample.distance_m.to_bits(),
9738                target_range.to_bits(),
9739                "{name} sampling did not include max_range"
9740            );
9741            assert_eq!(
9742                terminal_sample.time_s.to_bits(),
9743                result.time_of_flight.to_bits()
9744            );
9745            assert_eq!(
9746                terminal_sample.velocity_mps.to_bits(),
9747                result.impact_velocity.to_bits()
9748            );
9749            assert!((terminal_sample.energy_j - result.impact_energy).abs() < 1e-12);
9750        }
9751    }
9752}
9753
9754#[cfg(test)]
9755mod precession_inertia_wiring_tests {
9756    use super::*;
9757
9758    #[test]
9759    fn solver_uses_projectile_specific_moments_of_inertia() {
9760        let mass_kg = 55.0 * crate::constants::GRAINS_TO_KG;
9761        let caliber_m = 0.224 * 0.0254;
9762        let length_m = 0.75 * 0.0254;
9763        let inputs = BallisticInputs {
9764            bullet_mass: mass_kg,
9765            bullet_diameter: caliber_m,
9766            bullet_length: length_m,
9767            muzzle_velocity: 800.0,
9768            twist_rate: 7.0,
9769            enable_precession_nutation: true,
9770            use_rk4: false,
9771            use_adaptive_rk45: false,
9772            ..BallisticInputs::default()
9773        };
9774        let mut solver = TrajectorySolver::new(
9775            inputs,
9776            WindConditions::default(),
9777            AtmosphericConditions::default(),
9778        );
9779        solver.set_max_range(0.1);
9780
9781        let (air_density, speed_of_sound, _, _) = solver.resolved_atmosphere();
9782        let velocity_mps = solver.inputs.muzzle_velocity;
9783        let velocity_fps = velocity_mps * 3.28084;
9784        let twist_rate_ft = solver.inputs.twist_rate / 12.0;
9785        let spin_rate_rad_s = (velocity_fps / twist_rate_ft) * 2.0 * std::f64::consts::PI;
9786        let initial_state = AngularState {
9787            pitch_angle: 0.001,
9788            yaw_angle: 0.001,
9789            pitch_rate: 0.0,
9790            yaw_rate: 0.0,
9791            precession_angle: 0.0,
9792            nutation_phase: 0.0,
9793        };
9794        let params = PrecessionNutationParams {
9795            mass_kg,
9796            caliber_m,
9797            length_m,
9798            spin_rate_rad_s,
9799            spin_inertia: crate::spin_decay::calculate_moment_of_inertia(
9800                mass_kg, caliber_m, length_m, "ogive",
9801            ),
9802            transverse_inertia: crate::pitch_damping::calculate_transverse_moment_of_inertia(
9803                mass_kg, caliber_m, length_m, "ogive",
9804            ),
9805            velocity_mps,
9806            air_density_kg_m3: air_density,
9807            mach: velocity_mps / speed_of_sound,
9808            pitch_damping_coeff: PitchDampingCoefficients::default().subsonic,
9809            nutation_damping_factor: 0.05,
9810        };
9811        let expected = calculate_combined_angular_motion(
9812            &params,
9813            &initial_state,
9814            0.0,
9815            solver.time_step,
9816            0.001,
9817        );
9818        let actual = solver
9819            .solve()
9820            .expect("one-step solve should succeed")
9821            .angular_state
9822            .expect("precession/nutation was enabled");
9823
9824        assert!(
9825            (actual.precession_angle - expected.precession_angle).abs() < 1e-15,
9826            "precession phase used the wrong inertia: actual={}, expected={}",
9827            actual.precession_angle,
9828            expected.precession_angle
9829        );
9830        assert!(
9831            (actual.nutation_phase - expected.nutation_phase).abs() < 1e-15,
9832            "nutation phase used the wrong inertia: actual={}, expected={}",
9833            actual.nutation_phase,
9834            expected.nutation_phase
9835        );
9836    }
9837}
9838
9839#[cfg(test)]
9840mod form_factor_drag_tests {
9841    use super::*;
9842
9843    fn acceleration_with_form_factor_flag(enabled: bool) -> Vector3<f64> {
9844        let inputs = BallisticInputs {
9845            bc_value: 0.462,
9846            bc_type: DragModel::G1,
9847            bullet_model: Some("168gr SMK Match".to_string()),
9848            use_form_factor: enabled,
9849            ..BallisticInputs::default()
9850        };
9851        let solver = TrajectorySolver::new(
9852            inputs,
9853            WindConditions::default(),
9854            AtmosphericConditions::default(),
9855        );
9856        let station = solver.station_air().unwrap();
9857        solver.calculate_acceleration(
9858            &Vector3::zeros(),
9859            &Vector3::new(600.0, 0.0, 0.0),
9860            &Vector3::zeros(),
9861            &station,
9862        )
9863    }
9864
9865    #[test]
9866    fn measured_bc_drag_does_not_apply_name_based_form_factor_again() {
9867        let baseline = acceleration_with_form_factor_flag(false);
9868        let flagged = acceleration_with_form_factor_flag(true);
9869
9870        assert!(
9871            (flagged - baseline).norm() < 1e-12,
9872            "published BC already encodes form factor: baseline={baseline:?} flagged={flagged:?}"
9873        );
9874    }
9875}
9876
9877#[cfg(test)]
9878mod rk45_adaptivity_tests {
9879    use super::*;
9880
9881    #[test]
9882    fn cli_rk45_error_norm_scales_components_independently() {
9883        let position = Vector3::new(1.0e9, 0.0, 0.0);
9884        let velocity = Vector3::new(800.0, 0.0, 0.0);
9885        let fifth_position = position;
9886        let fifth_velocity = velocity;
9887        let fourth_position = position;
9888        let fourth_velocity = Vector3::new(800.0, 1.0e-3, 0.0);
9889
9890        let error = cli_rk45_error_norm(
9891            &position,
9892            &velocity,
9893            &fifth_position,
9894            &fifth_velocity,
9895            &fourth_position,
9896            &fourth_velocity,
9897        );
9898        let expected = 1.0e-3 / 6.0_f64.sqrt();
9899
9900        assert!(
9901            (error - expected).abs() <= 1e-15,
9902            "large downrange position masked a velocity-component error: {error}"
9903        );
9904    }
9905
9906    fn discontinuous_wind_solver() -> TrajectorySolver {
9907        let inputs = BallisticInputs::default();
9908        let mut solver = TrajectorySolver::new(
9909            inputs,
9910            WindConditions::default(),
9911            AtmosphericConditions::default(),
9912        );
9913        solver.set_wind_segments(vec![
9914            crate::wind::WindSegment::new(0.0, 90.0, 4.0),
9915            crate::wind::WindSegment::new(1_000.0, 90.0, 10_000.0),
9916        ]);
9917        solver
9918    }
9919
9920    #[test]
9921    fn rk45_retries_discontinuous_trial_before_advancing() {
9922        let solver = discontinuous_wind_solver();
9923        let position = Vector3::new(0.0, solver.inputs.muzzle_height, 0.0);
9924        let velocity = Vector3::new(solver.inputs.muzzle_velocity, 0.0, 0.0);
9925        let station = solver.station_air().unwrap();
9926        let dt = 0.01;
9927
9928        let rejected_trial = solver.rk45_step(
9929            &position,
9930            &velocity,
9931            dt,
9932            &Vector3::zeros(),
9933            RK45_TOLERANCE,
9934            &station,
9935        );
9936        assert!(
9937            rejected_trial.error > RK45_TOLERANCE,
9938            "discontinuous full step must exceed tolerance, got {}",
9939            rejected_trial.error
9940        );
9941
9942        let accepted =
9943            solver.adaptive_rk45_step(&position, &velocity, dt, &Vector3::zeros(), &station);
9944        assert!(accepted.used_dt < dt, "oversized trial was not retried");
9945        assert!(
9946            accepted.error <= RK45_TOLERANCE || accepted.used_dt <= RK45_MIN_DT,
9947            "accepted error {} exceeds tolerance at dt {}",
9948            accepted.error,
9949            accepted.used_dt
9950        );
9951
9952        let accepted_trial = solver.rk45_step(
9953            &position,
9954            &velocity,
9955            accepted.used_dt,
9956            &Vector3::zeros(),
9957            RK45_TOLERANCE,
9958            &station,
9959        );
9960        assert_eq!(accepted.position, accepted_trial.position);
9961        assert_eq!(accepted.velocity, accepted_trial.velocity);
9962        assert!((RK45_MIN_DT..=RK45_MAX_DT).contains(&accepted.next_dt));
9963    }
9964}
9965
9966#[cfg(test)]
9967mod ground_termination_tests {
9968    use super::*;
9969    use crate::trajectory_observation::TrajectoryObservationFlag;
9970
9971    #[test]
9972    fn every_solver_reports_one_exact_early_ground_endpoint() {
9973        for (name, use_rk4, use_adaptive_rk45) in [
9974            ("Euler", false, false),
9975            ("RK4", true, false),
9976            ("RK45", true, true),
9977        ] {
9978            let inputs = BallisticInputs {
9979                muzzle_height: 1.0,
9980                muzzle_angle: -0.2,
9981                ground_threshold: 0.0,
9982                use_rk4,
9983                use_adaptive_rk45,
9984                ..BallisticInputs::default()
9985            };
9986            let mut solver = TrajectorySolver::new(
9987                inputs,
9988                WindConditions::default(),
9989                AtmosphericConditions::default(),
9990            );
9991            solver.set_max_range(1_000.0);
9992
9993            let result = solver.solve().expect("early-ground solve should succeed");
9994            let terminal = result.points.last().expect("terminal point is missing");
9995
9996            assert_eq!(result.termination, TrajectoryTermination::GroundThreshold);
9997            assert_eq!(terminal.position.y.to_bits(), 0.0_f64.to_bits());
9998            assert!(
9999                terminal.position.x < 1_000.0,
10000                "{name} incorrectly reached max range"
10001            );
10002            assert_eq!(result.max_range.to_bits(), terminal.position.x.to_bits());
10003            assert_eq!(
10004                result
10005                    .points
10006                    .iter()
10007                    .filter(|point| point.position.y == 0.0)
10008                    .count(),
10009                1,
10010                "{name} did not retain exactly one ground endpoint"
10011            );
10012
10013            let observations = result
10014                .sample_observations(1.0, 100)
10015                .expect("checked early-ground sampling should succeed");
10016            assert!(observations[..observations.len() - 1]
10017                .iter()
10018                .all(|observation| observation.distance_m < terminal.position.x));
10019            let terminal_observation = observations.last().expect("terminal observation");
10020            assert_eq!(
10021                terminal_observation.distance_m.to_bits(),
10022                terminal.position.x.to_bits()
10023            );
10024            assert!(terminal_observation
10025                .flags
10026                .contains(&TrajectoryObservationFlag::Terminal));
10027            assert!(terminal_observation
10028                .flags
10029                .contains(&TrajectoryObservationFlag::GroundThreshold));
10030            assert_eq!(
10031                observations
10032                    .iter()
10033                    .filter(|observation| observation
10034                        .flags
10035                        .contains(&TrajectoryObservationFlag::Terminal))
10036                    .count(),
10037                1,
10038                "{name} repeated the terminal observation"
10039            );
10040        }
10041    }
10042
10043    // Regression lock for the unified ground termination: solve_euler/solve_rk4/solve_rk45 all
10044    // loop while `position.y > ground_threshold` (default -100.0), so they agree with RK45. A
10045    // lofted shot that returns to launch level before reaching max_range must keep descending to
10046    // the -100 m floor instead of stopping at y = 0 — and RK4-fixed and RK45 must behave the same.
10047    #[test]
10048    fn rk4_and_rk45_descend_to_ground_threshold() {
10049        for adaptive in [false, true] {
10050            let inputs = BallisticInputs {
10051                muzzle_angle: 0.1, // ~5.7 deg: arcs up, then descends past launch level
10052                use_rk4: true,
10053                use_adaptive_rk45: adaptive,
10054                ..BallisticInputs::default()
10055            };
10056            assert_eq!(
10057                inputs.ground_threshold, -100.0,
10058                "default ground_threshold is -100 m"
10059            );
10060
10061            let mut solver = TrajectorySolver::new(
10062                inputs,
10063                WindConditions::default(),
10064                AtmosphericConditions::default(),
10065            );
10066            // Huge max range: termination must be driven by ground_threshold, not the range cap.
10067            solver.set_max_range(1.0e7);
10068
10069            let result = solver.solve().expect("solve should succeed");
10070            let final_y = result
10071                .points
10072                .last()
10073                .expect("trajectory has points")
10074                .position
10075                .y;
10076            assert!(
10077                final_y < -1.0,
10078                "adaptive_rk45={adaptive}: final y = {final_y} m; a lofted shot should descend \
10079                 past launch level toward the ground_threshold floor, not stop at y = 0"
10080            );
10081        }
10082    }
10083}
10084
10085#[cfg(test)]
10086mod magnus_stability_tests {
10087    use super::*;
10088
10089    #[test]
10090    fn yaw_of_repose_magnus_force_is_vertical_and_twist_signed() {
10091        let acceleration = |enable_magnus, is_twist_right| {
10092            let inputs = BallisticInputs {
10093                muzzle_velocity: 822.96,
10094                bullet_mass: 168.0 * crate::constants::GRAINS_TO_KG,
10095                bullet_diameter: 0.308 * 0.0254,
10096                bullet_length: 1.215 * 0.0254,
10097                twist_rate: 10.0,
10098                is_twist_right,
10099                enable_magnus,
10100                ..BallisticInputs::default()
10101            };
10102            let solver = TrajectorySolver::new(
10103                inputs,
10104                WindConditions::default(),
10105                AtmosphericConditions::default(),
10106            );
10107            let station = solver.station_air().unwrap();
10108            solver.calculate_acceleration(
10109                &Vector3::zeros(),
10110                &Vector3::new(822.96, 0.0, 0.0),
10111                &Vector3::zeros(),
10112                &station,
10113            )
10114        };
10115
10116        let baseline = acceleration(false, true);
10117        let right_twist = acceleration(true, true) - baseline;
10118        let left_twist = acceleration(true, false) - baseline;
10119
10120        assert!(
10121            right_twist.y < 0.0,
10122            "right-hand Magnus must point down, got {right_twist:?}"
10123        );
10124        assert!(
10125            left_twist.y > 0.0,
10126            "left-hand Magnus must point up, got {left_twist:?}"
10127        );
10128        assert!((right_twist.y + left_twist.y).abs() < 1e-12);
10129        assert!(right_twist.x.abs() < 1e-12 && right_twist.z.abs() < 1e-12);
10130        assert!(left_twist.x.abs() < 1e-12 && left_twist.z.abs() < 1e-12);
10131    }
10132
10133    #[test]
10134    fn magnus_uses_velocity_corrected_muzzle_stability_gate() {
10135        let muzzle_velocity = 1_400.0 / 3.28084;
10136        let inputs = BallisticInputs {
10137            muzzle_velocity,
10138            bullet_mass: 168.0 * crate::constants::GRAINS_TO_KG,
10139            bullet_diameter: 0.308 * 0.0254,
10140            bullet_length: 1.215 * 0.0254,
10141            twist_rate: 15.0,
10142            enable_magnus: true,
10143            ..BallisticInputs::default()
10144        };
10145        let solver = TrajectorySolver::new(
10146            inputs.clone(),
10147            WindConditions::default(),
10148            AtmosphericConditions::default(),
10149        );
10150
10151        let bare_sg = crate::spin_drift::miller_stability(0.308, 168.0, 15.0, 1.215);
10152        let canonical_sg = solver.effective_spin_drift_sg();
10153        assert!(bare_sg > 1.0, "test requires bare Sg above the Magnus gate");
10154        assert!(
10155            canonical_sg < 1.0,
10156            "velocity-corrected Sg must be below the gate, got {canonical_sg}"
10157        );
10158
10159        let station = solver.station_air().unwrap();
10160        let acceleration = solver.calculate_acceleration(
10161            &Vector3::zeros(),
10162            &Vector3::new(muzzle_velocity, 0.0, 0.0),
10163            &Vector3::zeros(),
10164            &station,
10165        );
10166        let mut baseline_inputs = inputs;
10167        baseline_inputs.enable_magnus = false;
10168        let baseline_solver = TrajectorySolver::new(
10169            baseline_inputs,
10170            WindConditions::default(),
10171            AtmosphericConditions::default(),
10172        );
10173        let baseline = baseline_solver.calculate_acceleration(
10174            &Vector3::zeros(),
10175            &Vector3::new(muzzle_velocity, 0.0, 0.0),
10176            &Vector3::zeros(),
10177            &station,
10178        );
10179
10180        assert_eq!(
10181            acceleration, baseline,
10182            "canonical Sg below 1 must suppress every Magnus acceleration component"
10183        );
10184    }
10185
10186    #[test]
10187    fn magnus_force_grows_as_fixed_spin_projectile_slows() {
10188        let inputs = BallisticInputs {
10189            muzzle_velocity: 800.0,
10190            bullet_mass: 168.0 * crate::constants::GRAINS_TO_KG,
10191            bullet_diameter: 0.308 * 0.0254,
10192            bullet_length: 1.215 * 0.0254,
10193            twist_rate: 12.0,
10194            enable_magnus: true,
10195            ..BallisticInputs::default()
10196        };
10197
10198        let magnus_acceleration = |speed_mps| {
10199            let evaluate = |enable_magnus| {
10200                let mut run_inputs = inputs.clone();
10201                run_inputs.enable_magnus = enable_magnus;
10202                let solver = TrajectorySolver::new(
10203                    run_inputs,
10204                    WindConditions::default(),
10205                    AtmosphericConditions::default(),
10206                );
10207                let station = solver.station_air().unwrap();
10208                solver
10209                    .calculate_acceleration(
10210                        &Vector3::zeros(),
10211                        &Vector3::new(speed_mps, 0.0, 0.0),
10212                        &Vector3::zeros(),
10213                        &station,
10214                    )
10215                    .y
10216            };
10217            (evaluate(true) - evaluate(false)).abs()
10218        };
10219
10220        let fast = magnus_acceleration(200.0);
10221        let slow = magnus_acceleration(100.0);
10222        let ratio = slow / fast;
10223        let expected_ratio = 2.0_f64.powf(5.0 / 3.0);
10224
10225        assert!(fast > 0.0 && slow > 0.0, "fast={fast}, slow={slow}");
10226        assert!(
10227            (ratio - expected_ratio).abs() < 1e-3,
10228            "fixed-spin Magnus acceleration must grow downrange; slow/fast={ratio}, \
10229             expected={expected_ratio}"
10230        );
10231    }
10232}
10233
10234#[cfg(test)]
10235mod coriolis_direction_tests {
10236    use super::*;
10237    use std::f64::consts::FRAC_PI_2;
10238
10239    #[test]
10240    fn supersonic_crossing_flags_a_positive_range_sample() {
10241        // A supersonic shot that slows past Mach 1 must flag a sampled point as a Mach
10242        // transition. The underlying transonic_distances were a Vec::new() TODO, so this
10243        // flag was NEVER set regardless of trajectory — this is the regression guard.
10244        use crate::trajectory_sampling::TrajectoryFlag;
10245
10246        for (solver_name, use_rk4, use_adaptive_rk45) in [
10247            ("Euler", false, false),
10248            ("RK4", true, false),
10249            ("RK45", true, true),
10250        ] {
10251            let inputs = BallisticInputs {
10252                muzzle_velocity: 850.0,
10253                bc_value: 0.2,
10254                bc_type: DragModel::G7,
10255                muzzle_angle: 0.03,
10256                enable_trajectory_sampling: true,
10257                sample_interval: 50.0,
10258                use_rk4,
10259                use_adaptive_rk45,
10260                ..BallisticInputs::default()
10261            };
10262            let mut solver = TrajectorySolver::new(
10263                inputs,
10264                WindConditions::default(),
10265                AtmosphericConditions::default(),
10266            );
10267            solver.set_max_range(2000.0);
10268            let samples = solver
10269                .solve()
10270                .expect("supersonic solve should succeed")
10271                .sampled_points
10272                .expect("sampling was enabled");
10273            let flagged_distances: Vec<_> = samples
10274                .iter()
10275                .filter(|sample| sample.flags.contains(&TrajectoryFlag::MachTransition))
10276                .map(|sample| sample.distance_m)
10277                .collect();
10278
10279            assert!(
10280                !flagged_distances.is_empty()
10281                    && flagged_distances.iter().all(|distance| *distance > 0.0),
10282                "{solver_name} must flag genuine crossings only at positive range: {flagged_distances:?}"
10283            );
10284        }
10285    }
10286
10287    #[test]
10288    fn subsonic_launch_does_not_flag_a_muzzle_transition() {
10289        use crate::trajectory_sampling::TrajectoryFlag;
10290
10291        for (solver_name, use_rk4, use_adaptive_rk45) in [
10292            ("Euler", false, false),
10293            ("RK4", true, false),
10294            ("RK45", true, true),
10295        ] {
10296            let inputs = BallisticInputs {
10297                muzzle_velocity: 250.0,
10298                muzzle_angle: 0.02,
10299                enable_trajectory_sampling: true,
10300                sample_interval: 25.0,
10301                use_rk4,
10302                use_adaptive_rk45,
10303                ..BallisticInputs::default()
10304            };
10305            let mut solver = TrajectorySolver::new(
10306                inputs,
10307                WindConditions::default(),
10308                AtmosphericConditions::default(),
10309            );
10310            solver.set_max_range(300.0);
10311            let samples = solver
10312                .solve()
10313                .expect("subsonic solve should succeed")
10314                .sampled_points
10315                .expect("sampling was enabled");
10316
10317            assert!(
10318                samples
10319                    .iter()
10320                    .all(|sample| !sample.flags.contains(&TrajectoryFlag::MachTransition)),
10321                "{solver_name} marked a Mach transition for a launch already below Mach 1"
10322            );
10323        }
10324    }
10325
10326    #[test]
10327    fn mach_transition_tracker_requires_a_downward_crossing() {
10328        fn record(mach_values: &[f64]) -> Vec<f64> {
10329            let mut tracker = MachTransitionTracker::default();
10330            let mut distances = Vec::new();
10331            for (index, mach) in mach_values.iter().copied().enumerate() {
10332                tracker.record_downward_crossings(mach, index as f64 * 10.0, &mut distances);
10333            }
10334            distances
10335        }
10336
10337        assert!(record(&[0.9, 0.8, 0.7]).is_empty());
10338        assert_eq!(record(&[1.1, 1.05, 0.99]), vec![20.0]);
10339        assert_eq!(record(&[1.2, 1.19, 1.0, 0.99]), vec![10.0, 30.0]);
10340        assert_eq!(record(&[0.9, 1.3, 1.1, 0.9, 1.3, 0.8]), vec![20.0, 30.0]);
10341        assert!(record(&[1.3, f64::NAN, 1.1]).is_empty());
10342    }
10343
10344    #[test]
10345    fn mach_transition_tracker_labels_0_9_without_touching_the_flat_vec() {
10346        // MBA-1405: the tracker gains a third (0.9) threshold, but it must NEVER be appended
10347        // to the flat `distances` Vec — only its own labeled field. Reuses the exact input
10348        // sequences pinned by `mach_transition_tracker_requires_a_downward_crossing` above (the
10349        // pre-change flat-Vec behavior for those sequences) and additionally asserts the
10350        // labeled fields.
10351        fn record(mach_values: &[f64]) -> (Vec<f64>, MachTransitionTracker) {
10352            let mut tracker = MachTransitionTracker::default();
10353            let mut distances = Vec::new();
10354            for (index, mach) in mach_values.iter().copied().enumerate() {
10355                tracker.record_downward_crossings(mach, index as f64 * 10.0, &mut distances);
10356            }
10357            (distances, tracker)
10358        }
10359
10360        // Already at/below 1.2 and 1.0 at the muzzle (never crosses those downward from
10361        // above), but DOES cross 0.9 downward at x=10 (previous_mach 0.9 >= 0.9, mach 0.8 < 0.9).
10362        let (distances, tracker) = record(&[0.9, 0.8, 0.7]);
10363        assert!(distances.is_empty()); // flat Vec unchanged (pinned pre-change value)
10364        assert_eq!(tracker.mach_1_2_distance_m, None);
10365        assert_eq!(tracker.mach_1_0_distance_m, None);
10366        assert_eq!(tracker.mach_0_9_distance_m, Some(10.0));
10367
10368        // Crosses 1.0 only (never reaches 1.2 from above, never reaches 0.9).
10369        let (distances, tracker) = record(&[1.1, 1.05, 0.99]);
10370        assert_eq!(distances, vec![20.0]);
10371        assert_eq!(tracker.mach_1_2_distance_m, None);
10372        assert_eq!(tracker.mach_1_0_distance_m, Some(20.0));
10373        assert_eq!(tracker.mach_0_9_distance_m, None);
10374
10375        // Crosses 1.2 then 1.0, never reaches 0.9 (lowest sample is 0.99).
10376        let (distances, tracker) = record(&[1.2, 1.19, 1.0, 0.99]);
10377        assert_eq!(distances, vec![10.0, 30.0]); // flat Vec unchanged
10378        assert_eq!(tracker.mach_1_2_distance_m, Some(10.0));
10379        assert_eq!(tracker.mach_1_0_distance_m, Some(30.0));
10380        assert_eq!(tracker.mach_0_9_distance_m, None);
10381
10382        // Crosses 1.2, then 1.0, then 0.9 — the flat Vec must be EXACTLY {20.0, 30.0} as
10383        // before (0.9 crossing at x=50.0 must NOT appear in it).
10384        let (distances, tracker) = record(&[0.9, 1.3, 1.1, 0.9, 1.3, 0.8]);
10385        assert_eq!(distances, vec![20.0, 30.0]); // flat Vec unchanged (pinned pre-change value)
10386        assert_eq!(tracker.mach_1_2_distance_m, Some(20.0));
10387        assert_eq!(tracker.mach_1_0_distance_m, Some(30.0));
10388        assert_eq!(tracker.mach_0_9_distance_m, Some(50.0));
10389        assert!(
10390            tracker.mach_1_2_distance_m < tracker.mach_1_0_distance_m
10391                && tracker.mach_1_0_distance_m < tracker.mach_0_9_distance_m,
10392            "labeled crossings must be strictly increasing downrange"
10393        );
10394
10395        // NAN resets tracking exactly as before; no labels set either.
10396        let (distances, tracker) = record(&[1.3, f64::NAN, 1.1]);
10397        assert!(distances.is_empty());
10398        assert_eq!(tracker.mach_1_2_distance_m, None);
10399        assert_eq!(tracker.mach_1_0_distance_m, None);
10400        assert_eq!(tracker.mach_0_9_distance_m, None);
10401    }
10402
10403    #[test]
10404    fn humidity_percent_is_a_percent_field_that_relative_humidity_validates_never_clamps() {
10405        // 0.50.0: the field is a PERCENT with the engine's one default, and the clamping
10406        // 0-1 -> 0-100 helper is gone. RelativeHumidity::try_percent is its validator: it keeps
10407        // 0..=100 bit for bit, reads a sensor reading within 5 points of it as its end, and
10408        // refuses anything farther out. 0.49.0's helper clamped 1.5 to 100 %.
10409        let inputs = BallisticInputs::default();
10410        assert_eq!(
10411            inputs.humidity_percent.to_bits(),
10412            DEFAULT_HUMIDITY_PERCENT.to_bits()
10413        );
10414        assert_eq!(
10415            inputs.humidity_percent.to_bits(),
10416            AtmosphericConditions::default().humidity.to_bits()
10417        );
10418        for percent in [0.0, 7.0, 50.0, 55.0, 100.0] {
10419            let validated = crate::RelativeHumidity::try_percent(percent).expect("in range");
10420            assert_eq!(validated.percent().to_bits(), percent.to_bits());
10421        }
10422        for percent in [150.0, -5.000_000_1, 105.000_000_1, f64::NAN, f64::INFINITY] {
10423            assert!(
10424                crate::RelativeHumidity::try_percent(percent).is_err(),
10425                "{percent} must be refused, not clamped"
10426            );
10427        }
10428        // A sensor reading within 5 points of the range is the end it reads as.
10429        for (percent, end) in [(-5.0, 0.0), (100.0001, 100.0)] {
10430            assert_eq!(
10431                crate::RelativeHumidity::try_percent(percent)
10432                    .expect("a reading in the band")
10433                    .percent()
10434                    .to_bits(),
10435                f64::to_bits(end),
10436                "{percent}"
10437            );
10438        }
10439    }
10440
10441    /// Vertical position (m) at a given downrange `range_m`, for a shot fired along
10442    /// compass bearing `shot_azimuth` (radians, 0=N) with Coriolis enabled.
10443    fn vertical_at(shot_azimuth: f64, range_m: f64) -> f64 {
10444        let inputs = BallisticInputs {
10445            muzzle_velocity: 800.0,
10446            bc_value: 0.5,
10447            bc_type: DragModel::G7,
10448            muzzle_angle: 0.02, // ~20 mrad so it carries well past range_m
10449            enable_coriolis: true,
10450            latitude: Some(45.0),
10451            shot_azimuth,
10452            ground_threshold: f64::NEG_INFINITY, // never terminate early
10453            ..BallisticInputs::default()
10454        };
10455        let mut solver = TrajectorySolver::new(
10456            inputs,
10457            WindConditions::default(),
10458            AtmosphericConditions::default(),
10459        );
10460        solver.set_max_range(range_m + 50.0);
10461        let r = solver.solve().expect("solve");
10462        let pts = &r.points;
10463        for i in 1..pts.len() {
10464            if pts[i].position.x >= range_m {
10465                let p1 = &pts[i - 1];
10466                let p2 = &pts[i];
10467                let t = (range_m - p1.position.x) / (p2.position.x - p1.position.x);
10468                return p1.position.y + t * (p2.position.y - p1.position.y);
10469            }
10470        }
10471        panic!("range {range_m} not reached");
10472    }
10473
10474    /// Regression for the shot-direction Coriolis bug: the Eötvös vertical term
10475    /// `a_up = +2Ω cosφ v_east` lifts an EAST shot and depresses a WEST shot, so at a
10476    /// common range east must sit HIGHER than west, with north in between. Before the
10477    /// fix, `--shot-direction` never reached the solver and E/W/N were identical.
10478    #[test]
10479    fn eotvos_east_higher_than_west() {
10480        let range = 600.0;
10481        let east = vertical_at(FRAC_PI_2, range); // 90° E
10482        let west = vertical_at(3.0 * FRAC_PI_2, range); // 270° W
10483        let north = vertical_at(0.0, range); // 0° N
10484        assert!(
10485            east > west,
10486            "east ({east:.5}) must be higher than west ({west:.5}) at {range} m (Eötvös)"
10487        );
10488        assert!(
10489            east > north && north > west,
10490            "north ({north:.5}) must lie between east ({east:.5}) and west ({west:.5})"
10491        );
10492        assert!(
10493            (east - west) > 1e-3,
10494            "E-W vertical separation ({:.6} m) should be physically meaningful, not FP noise",
10495            east - west
10496        );
10497    }
10498
10499    /// MBA-1405: labeled Mach-crossing distances on `TrajectoryResult`, pinned exactly against
10500    /// a capture of the (pre-change) flat `transonic_distances` Vec taken from this same
10501    /// muzzle_velocity=850/bc=0.2 G7/angle=0.03/max_range=2000 scenario, for all three solver
10502    /// paths. Because `MachTransitionTracker::record_downward_crossings` writes the labeled
10503    /// field and pushes to the flat Vec from the SAME `downrange_m` value at the SAME crossing,
10504    /// these pinned labels ARE the flat-Vec content for the 1.2/1.0 thresholds — proving the
10505    /// flat Vec is untouched by the 0.9 addition.
10506    #[test]
10507    fn labeled_mach_crossings_match_pinned_pre_change_flat_vec_across_solvers() {
10508        // (solver_name, use_rk4, use_adaptive_rk45, expected mach_1_2, expected mach_1_0)
10509        // Re-captured in 0.50.0 (the default 50 % RH aloft now holds the
10510        // station's water-vapour mole fraction, with a virtual-temperature lapse), old -> new: Mach
10511        // 1.2 at 670.9878683238721 -> 670.9870968186207, 671.7257336844475 -> 671.7249603175201 and
10512        // 672.4905711917901 -> 672.4897951903022 m; Mach 1.0 at 805.5274119916264 ->
10513        // 805.5261199258687, 805.933409072171 -> 805.9321158082175 and 806.5709746782849 ->
10514        // 806.5696791258861 m (Euler, RK4, RK45; -0.77 to -1.30 mm): this shot climbs above the
10515        // station, where the held vapour gives a faster sound speed, so Mach falls sooner.
10516        let cases = [
10517            (
10518                "Euler",
10519                false,
10520                false,
10521                670.9870968186207_f64,
10522                805.5261199258687_f64,
10523            ),
10524            (
10525                "RK4",
10526                true,
10527                false,
10528                671.7249603175201_f64,
10529                805.9321158082175_f64,
10530            ),
10531            (
10532                "RK45",
10533                true,
10534                true,
10535                672.4897951903022_f64,
10536                806.5696791258861_f64,
10537            ),
10538        ];
10539
10540        for (solver_name, use_rk4, use_adaptive_rk45, expected_1_2, expected_1_0) in cases {
10541            let inputs = BallisticInputs {
10542                muzzle_velocity: 850.0,
10543                bc_value: 0.2,
10544                bc_type: DragModel::G7,
10545                muzzle_angle: 0.03,
10546                use_rk4,
10547                use_adaptive_rk45,
10548                ..BallisticInputs::default()
10549            };
10550            let mut solver = TrajectorySolver::new(
10551                inputs,
10552                WindConditions::default(),
10553                AtmosphericConditions::default(),
10554            );
10555            solver.set_max_range(2000.0);
10556            let result = solver.solve().expect("solve should succeed");
10557
10558            assert_eq!(
10559                result.mach_1_2_distance_m,
10560                Some(expected_1_2),
10561                "{solver_name}: mach_1_2_distance_m must match its pin (the pre-change flat-Vec \
10562                 capture, re-captured for 0.50.0's aloft vapour model)"
10563            );
10564            assert_eq!(
10565                result.mach_1_0_distance_m,
10566                Some(expected_1_0),
10567                "{solver_name}: mach_1_0_distance_m must match its pin (the pre-change flat-Vec \
10568                 capture, re-captured for 0.50.0's aloft vapour model)"
10569            );
10570
10571            let mach_1_2 = result.mach_1_2_distance_m.expect("crosses 1.2");
10572            let mach_1_0 = result.mach_1_0_distance_m.expect("crosses 1.0");
10573            let mach_0_9 = result
10574                .mach_0_9_distance_m
10575                .expect("this trajectory also goes past 0.9 within 2000 m");
10576            assert!(
10577                mach_1_2 < mach_1_0 && mach_1_0 < mach_0_9,
10578                "{solver_name}: labeled crossings must be strictly increasing downrange \
10579                 (1.2={mach_1_2}, 1.0={mach_1_0}, 0.9={mach_0_9})"
10580            );
10581        }
10582    }
10583
10584    /// A trajectory that terminates while still well above Mach 1.2 must leave all three
10585    /// labeled crossings `None` (there is nothing to cross), across all three solver paths.
10586    #[test]
10587    fn labeled_mach_crossings_are_none_for_a_fully_supersonic_trajectory() {
10588        for (solver_name, use_rk4, use_adaptive_rk45) in [
10589            ("Euler", false, false),
10590            ("RK4", true, false),
10591            ("RK45", true, true),
10592        ] {
10593            let inputs = BallisticInputs {
10594                muzzle_velocity: 850.0,
10595                bc_value: 0.2,
10596                bc_type: DragModel::G7,
10597                muzzle_angle: 0.03,
10598                use_rk4,
10599                use_adaptive_rk45,
10600                ..BallisticInputs::default()
10601            };
10602            let mut solver = TrajectorySolver::new(
10603                inputs,
10604                WindConditions::default(),
10605                AtmosphericConditions::default(),
10606            );
10607            // Well short of the ~671 m downward 1.2 crossing measured for this load.
10608            solver.set_max_range(200.0);
10609            let result = solver.solve().expect("solve should succeed");
10610
10611            assert_eq!(
10612                result.mach_1_2_distance_m, None,
10613                "{solver_name}: must not report a 1.2 crossing that never happens"
10614            );
10615            assert_eq!(
10616                result.mach_1_0_distance_m, None,
10617                "{solver_name}: must not report a 1.0 crossing that never happens"
10618            );
10619            assert_eq!(
10620                result.mach_0_9_distance_m, None,
10621                "{solver_name}: must not report a 0.9 crossing that never happens"
10622            );
10623        }
10624    }
10625}
10626
10627#[cfg(test)]
10628mod cant_tests {
10629    use super::*;
10630
10631    fn base_inputs() -> BallisticInputs {
10632        BallisticInputs {
10633            muzzle_velocity: 800.0,
10634            bc_value: 0.5,
10635            bc_type: DragModel::G7,
10636            bullet_mass: 0.0109,
10637            bullet_diameter: 0.00782,
10638            bullet_length: 0.0309,
10639            sight_height: 0.05,
10640            twist_rate: 10.0,
10641            use_rk4: true,
10642            ..BallisticInputs::default()
10643        }
10644    }
10645
10646    fn solve_with(inputs: BallisticInputs, max_range: f64) -> TrajectoryResult {
10647        let mut s = TrajectorySolver::new(
10648            inputs,
10649            WindConditions::default(),
10650            AtmosphericConditions::default(),
10651        );
10652        s.set_max_range(max_range);
10653        s.solve().expect("solve")
10654    }
10655
10656    /// Interpolate (y, z) at downrange x.
10657    fn yz_at(result: &TrajectoryResult, x: f64) -> (f64, f64) {
10658        let pts = &result.points;
10659        for i in 1..pts.len() {
10660            if pts[i].position.x >= x {
10661                let (p1, p2) = (&pts[i - 1], &pts[i]);
10662                let dx = p2.position.x - p1.position.x;
10663                let t = if dx.abs() < 1e-12 {
10664                    0.0
10665                } else {
10666                    (x - p1.position.x) / dx
10667                };
10668                return (
10669                    p1.position.y + t * (p2.position.y - p1.position.y),
10670                    p1.position.z + t * (p2.position.z - p1.position.z),
10671                );
10672            }
10673        }
10674        panic!("trajectory never reached {x} m");
10675    }
10676
10677    #[test]
10678    fn cant_sign_clockwise_up_offset_goes_right_and_low() {
10679        // Upward zero offset + clockwise cant => POI right (+z) and low vs un-canted.
10680        let mut level = base_inputs();
10681        level.muzzle_angle = 0.003; // ~10 MOA up
10682        let mut canted = level.clone();
10683        canted.cant_angle = 10f64.to_radians();
10684
10685        let (y0, z0) = yz_at(&solve_with(level, 400.0), 300.0);
10686        let (y1, z1) = yz_at(&solve_with(canted, 400.0), 300.0);
10687        assert!(
10688            z1 > z0 + 0.01,
10689            "clockwise cant must move POI right: z0={z0} z1={z1}"
10690        );
10691        assert!(
10692            y1 < y0 - 0.001,
10693            "clockwise cant must move POI low: y0={y0} y1={y1}"
10694        );
10695    }
10696
10697    #[test]
10698    fn pure_cant_shows_bore_offset_near_range() {
10699        // No aim offset: the only lateral source near the muzzle is the swung bore,
10700        // z0 = -sight_height*sin(cant) (left of the aim plane for clockwise cant).
10701        let mut i = base_inputs();
10702        i.muzzle_angle = 0.0;
10703        i.cant_angle = 10f64.to_radians();
10704        let sh = i.sight_height;
10705        let r = solve_with(i, 60.0);
10706        let first = &r.points[1]; // just past the muzzle
10707        let expected = -sh * 10f64.to_radians().sin();
10708        assert!(
10709            (first.position.z - expected).abs() < 0.005,
10710            "near-muzzle lateral {} should be ~bore offset {expected}",
10711            first.position.z
10712        );
10713    }
10714
10715    #[test]
10716    fn zero_angle_is_independent_of_cant() {
10717        let a = base_inputs();
10718        let mut b = base_inputs();
10719        b.cant_angle = 15f64.to_radians();
10720        let za = calculate_zero_angle(a.clone(), 100.0, 0.0).expect("zero a");
10721        let zb = calculate_zero_angle(b.clone(), 100.0, 0.0).expect("zero b");
10722        assert_eq!(
10723            za.to_bits(),
10724            zb.to_bits(),
10725            "zeroing must ignore cant: {za} vs {zb}"
10726        );
10727        // silence unused warnings
10728        let _ = (a.cant_angle, b.cant_angle);
10729    }
10730
10731    #[test]
10732    fn nonfinite_cant_is_rejected() {
10733        let mut i = base_inputs();
10734        i.cant_angle = f64::NAN;
10735        let s = TrajectorySolver::new(
10736            i,
10737            WindConditions::default(),
10738            AtmosphericConditions::default(),
10739        );
10740        assert!(s.solve().is_err());
10741    }
10742
10743    #[test]
10744    fn incline_and_cant_compose_without_breaking() {
10745        // 15-degree incline + 10-degree cant: finite result, cant still pushes right.
10746        let mut flat = base_inputs();
10747        flat.muzzle_angle = 0.003;
10748        flat.shooting_angle = 15f64.to_radians();
10749        let mut canted = flat.clone();
10750        canted.cant_angle = 10f64.to_radians();
10751        let (_, z_flat) = yz_at(&solve_with(flat, 400.0), 300.0);
10752        let (_, z_cant) = yz_at(&solve_with(canted, 400.0), 300.0);
10753        assert!(
10754            z_cant > z_flat,
10755            "cant must still deflect right on an incline"
10756        );
10757    }
10758}
10759
10760#[cfg(test)]
10761mod vertical_wind_tests {
10762    use super::*;
10763
10764    fn base_inputs() -> BallisticInputs {
10765        BallisticInputs {
10766            muzzle_velocity: 800.0,
10767            bc_value: 0.5,
10768            bc_type: DragModel::G7,
10769            bullet_mass: 0.0109,
10770            bullet_diameter: 0.00782,
10771            bullet_length: 0.0309,
10772            sight_height: 0.05,
10773            twist_rate: 10.0,
10774            use_rk4: true,
10775            ..BallisticInputs::default()
10776        }
10777    }
10778
10779    /// Interpolate trajectory height (McCoy Y) at downrange distance `x`.
10780    fn y_at(result: &TrajectoryResult, x: f64) -> f64 {
10781        let pts = &result.points;
10782        for i in 1..pts.len() {
10783            if pts[i].position.x >= x {
10784                let (p1, p2) = (&pts[i - 1], &pts[i]);
10785                let dx = p2.position.x - p1.position.x;
10786                let t = if dx.abs() < 1e-12 {
10787                    0.0
10788                } else {
10789                    (x - p1.position.x) / dx
10790                };
10791                return p1.position.y + t * (p2.position.y - p1.position.y);
10792            }
10793        }
10794        panic!("trajectory never reached {x} m");
10795    }
10796
10797    fn solve_with(
10798        inputs: BallisticInputs,
10799        wind: WindConditions,
10800        max_range: f64,
10801    ) -> TrajectoryResult {
10802        let mut s = TrajectorySolver::new(inputs, wind, AtmosphericConditions::default());
10803        s.set_max_range(max_range);
10804        s.solve().expect("solve")
10805    }
10806
10807    #[test]
10808    fn updraft_raises_poi_downrange() {
10809        // No shear, no segments: this exercises the constant-wind sites in
10810        // solve_euler/solve_rk4/solve_rk45 directly (MBA-728).
10811        let calm_inputs = base_inputs();
10812        let calm_wind = WindConditions::default();
10813        let updraft = WindConditions {
10814            vertical_speed: 5.0,
10815            ..Default::default()
10816        };
10817
10818        let calm = solve_with(calm_inputs.clone(), calm_wind, 500.0);
10819        let updraft_result = solve_with(calm_inputs, updraft, 500.0);
10820
10821        let y_calm = y_at(&calm, 400.0);
10822        let y_updraft = y_at(&updraft_result, 400.0);
10823        assert!(
10824            y_updraft > y_calm,
10825            "5 m/s updraft must raise POI at 400m: calm={y_calm}, updraft={y_updraft}"
10826        );
10827    }
10828
10829    #[test]
10830    fn zero_vertical_is_default_and_finite_required() {
10831        assert_eq!(WindConditions::default().vertical_speed, 0.0);
10832
10833        let inputs = base_inputs();
10834        let wind = WindConditions {
10835            vertical_speed: f64::NAN,
10836            ..Default::default()
10837        };
10838        let s = TrajectorySolver::new(inputs, wind, AtmosphericConditions::default());
10839        assert!(
10840            s.solve().is_err(),
10841            "NaN wind.vertical_speed must be rejected by validate_for_solve"
10842        );
10843    }
10844}
10845
10846/// MBA-1365: declare whether a BC is ICAO- or Army-Standard-Metro-referenced.
10847#[cfg(test)]
10848mod bc_reference_standard_tests {
10849    use super::*;
10850
10851    fn base_inputs() -> BallisticInputs {
10852        BallisticInputs {
10853            muzzle_velocity: 800.0,
10854            bc_value: 0.5,
10855            bc_type: DragModel::G7,
10856            bullet_mass: 0.0109,
10857            bullet_diameter: 0.00782,
10858            bullet_length: 0.0309,
10859            sight_height: 0.05,
10860            twist_rate: 10.0,
10861            use_rk4: true,
10862            ..BallisticInputs::default()
10863        }
10864    }
10865
10866    /// Interpolate trajectory height (McCoy Y) and speed at downrange distance `x`.
10867    fn y_and_speed_at(result: &TrajectoryResult, x: f64) -> (f64, f64) {
10868        let pts = &result.points;
10869        for i in 1..pts.len() {
10870            if pts[i].position.x >= x {
10871                let (p1, p2) = (&pts[i - 1], &pts[i]);
10872                let dx = p2.position.x - p1.position.x;
10873                let t = if dx.abs() < 1e-12 {
10874                    0.0
10875                } else {
10876                    (x - p1.position.x) / dx
10877                };
10878                return (
10879                    p1.position.y + t * (p2.position.y - p1.position.y),
10880                    p1.velocity_magnitude + t * (p2.velocity_magnitude - p1.velocity_magnitude),
10881                );
10882            }
10883        }
10884        panic!("trajectory never reached {x} m");
10885    }
10886
10887    // ---- The constant itself -----------------------------------------------------------
10888
10889    #[test]
10890    fn asm_to_icao_ratio_matches_documented_value() {
10891        assert!(
10892            (crate::constants::ASM_TO_ICAO_BC - 0.98237).abs() < 1e-5,
10893            "ASM_TO_ICAO_BC = {} must equal 0.98237 to 5 decimal places",
10894            crate::constants::ASM_TO_ICAO_BC
10895        );
10896        // Derived from the two named densities, not a bare literal. (The ratio being < 1.0
10897        // — a denser reference atmosphere implying a numerically smaller ICAO-equivalent
10898        // BC — is already established by the 0.98237 check above; a bare `assert!` on a
10899        // const-only comparison here would be compiled away, so it isn't repeated.)
10900        assert_eq!(
10901            crate::constants::ASM_TO_ICAO_BC,
10902            crate::constants::ASM_DENSITY_LB_FT3 / crate::constants::ICAO_DENSITY_LB_FT3
10903        );
10904    }
10905
10906    // ---- Default / byte-identical --------------------------------------------------------
10907
10908    #[test]
10909    fn default_bc_reference_standard_is_icao() {
10910        assert_eq!(
10911            BallisticInputs::default().bc_reference_standard,
10912            BcReferenceStandard::Icao
10913        );
10914    }
10915
10916    /// RED (pre-MBA-1365) would not compile at all — there was no field to normalize.
10917    /// GREEN: with the field defaulted to `Icao`, `TrajectorySolver::new` must never
10918    /// touch `bc_value` — bit-for-bit, not just approximately — so every existing
10919    /// caller that never sets this field is byte-identical to today.
10920    #[test]
10921    fn icao_reference_leaves_bc_value_bit_identical() {
10922        let raw_bc: f64 = 0.4372911; // an arbitrary, non-round value
10923        let inputs = BallisticInputs {
10924            bc_value: raw_bc,
10925            bc_reference_standard: BcReferenceStandard::Icao,
10926            ..base_inputs()
10927        };
10928        let solver = TrajectorySolver::new(
10929            inputs,
10930            WindConditions::default(),
10931            AtmosphericConditions::default(),
10932        );
10933        assert_eq!(solver.inputs.bc_value.to_bits(), raw_bc.to_bits());
10934    }
10935
10936    #[test]
10937    fn default_inputs_solve_is_unaffected_by_the_new_field_existing() {
10938        // A solve built entirely from BallisticInputs::default() (which now carries
10939        // bc_reference_standard: Icao) must match a solve of an equivalent struct that
10940        // never mentions the field at all in its literal (relying on ..default()).
10941        let a = TrajectorySolver::new(
10942            base_inputs(),
10943            WindConditions::default(),
10944            AtmosphericConditions::default(),
10945        )
10946        .solve()
10947        .expect("solve a");
10948        let b = TrajectorySolver::new(
10949            BallisticInputs { ..base_inputs() },
10950            WindConditions::default(),
10951            AtmosphericConditions::default(),
10952        )
10953        .solve()
10954        .expect("solve b");
10955        assert_eq!(a.impact_velocity.to_bits(), b.impact_velocity.to_bits());
10956        assert_eq!(a.max_range.to_bits(), b.max_range.to_bits());
10957    }
10958
10959    // ---- ArmyStandardMetro normalization --------------------------------------------------
10960
10961    #[test]
10962    fn army_standard_metro_scales_bc_value_by_exactly_the_derived_ratio() {
10963        let raw_bc = 0.5;
10964        let inputs = BallisticInputs {
10965            bc_value: raw_bc,
10966            bc_reference_standard: BcReferenceStandard::ArmyStandardMetro,
10967            ..base_inputs()
10968        };
10969        let solver = TrajectorySolver::new(
10970            inputs,
10971            WindConditions::default(),
10972            AtmosphericConditions::default(),
10973        );
10974        assert_eq!(
10975            solver.inputs.bc_value,
10976            raw_bc * crate::constants::ASM_TO_ICAO_BC
10977        );
10978    }
10979
10980    #[test]
10981    fn army_standard_metro_scales_mach_keyed_bc_segments() {
10982        let inputs = BallisticInputs {
10983            bc_reference_standard: BcReferenceStandard::ArmyStandardMetro,
10984            bc_segments: Some(vec![(0.5, 0.40), (1.5, 0.30)]),
10985            ..base_inputs()
10986        };
10987        let solver = TrajectorySolver::new(
10988            inputs,
10989            WindConditions::default(),
10990            AtmosphericConditions::default(),
10991        );
10992        let segments = solver.inputs.bc_segments.as_ref().expect("segments");
10993        assert_eq!(segments[0], (0.5, 0.40 * crate::constants::ASM_TO_ICAO_BC));
10994        assert_eq!(segments[1], (1.5, 0.30 * crate::constants::ASM_TO_ICAO_BC));
10995    }
10996
10997    #[test]
10998    fn army_standard_metro_scales_velocity_keyed_bc_segments_data() {
10999        let inputs = BallisticInputs {
11000            bc_reference_standard: BcReferenceStandard::ArmyStandardMetro,
11001            bc_segments_data: Some(vec![
11002                crate::BCSegmentData {
11003                    velocity_min: 0.0,
11004                    velocity_max: 500.0,
11005                    bc_value: 0.40,
11006                },
11007                crate::BCSegmentData {
11008                    velocity_min: 500.0,
11009                    velocity_max: 900.0,
11010                    bc_value: 0.45,
11011                },
11012            ]),
11013            ..base_inputs()
11014        };
11015        let solver = TrajectorySolver::new(
11016            inputs,
11017            WindConditions::default(),
11018            AtmosphericConditions::default(),
11019        );
11020        let segments = solver.inputs.bc_segments_data.as_ref().expect("segments");
11021        assert_eq!(
11022            segments[0].bc_value,
11023            0.40 * crate::constants::ASM_TO_ICAO_BC
11024        );
11025        assert_eq!(
11026            segments[1].bc_value,
11027            0.45 * crate::constants::ASM_TO_ICAO_BC
11028        );
11029        // Non-BC fields must be untouched.
11030        assert_eq!(segments[0].velocity_min, 0.0);
11031        assert_eq!(segments[1].velocity_max, 900.0);
11032    }
11033
11034    /// Empirically verify the drag DIRECTION (not just the arithmetic): declaring the
11035    /// SAME raw BC number as Army-Standard-Metro must produce MORE drop and LOWER
11036    /// remaining velocity downrange than declaring it ICAO, because the normalized
11037    /// (smaller) BC feeds MORE drag into the ICAO-calibrated retardation formula.
11038    #[test]
11039    fn army_standard_metro_moves_impact_in_the_more_drag_direction() {
11040        let solve_at = |standard: BcReferenceStandard| {
11041            let inputs = BallisticInputs {
11042                bc_value: 0.475,
11043                bc_reference_standard: standard,
11044                ..base_inputs()
11045            };
11046            let mut solver = TrajectorySolver::new(
11047                inputs,
11048                WindConditions::default(),
11049                AtmosphericConditions::default(),
11050            );
11051            solver.set_max_range(500.0);
11052            solver.solve().expect("solve")
11053        };
11054
11055        let icao = solve_at(BcReferenceStandard::Icao);
11056        let asm = solve_at(BcReferenceStandard::ArmyStandardMetro);
11057
11058        let (y_icao, v_icao) = y_and_speed_at(&icao, 400.0);
11059        let (y_asm, v_asm) = y_and_speed_at(&asm, 400.0);
11060
11061        assert!(
11062            y_asm < y_icao,
11063            "ArmyStandardMetro must drop MORE (lower y) at 400m than Icao for the same raw \
11064             bc_value: icao_y={y_icao}, asm_y={y_asm}"
11065        );
11066        assert!(
11067            v_asm < v_icao,
11068            "ArmyStandardMetro must retain LESS velocity at 400m than Icao for the same raw \
11069             bc_value: icao_v={v_icao}, asm_v={v_asm}"
11070        );
11071    }
11072
11073    // ---- Downstream inheritance: Monte Carlo ----------------------------------------------
11074
11075    /// Monte Carlo must inherit the exact same normalization with zero duplicated math:
11076    /// with every std-dev pinned to 0 (so every sample is deterministically the base
11077    /// input, unperturbed), a single-sample MC run must match a plain direct solve of the
11078    /// identical base inputs bit-for-bit.
11079    #[test]
11080    fn monte_carlo_inherits_the_normalized_bc_reference() {
11081        let base_inputs_asm = BallisticInputs {
11082            bc_value: 0.475,
11083            bc_reference_standard: BcReferenceStandard::ArmyStandardMetro,
11084            ..base_inputs()
11085        };
11086        let wind = WindConditions::default();
11087
11088        // Match run_monte_carlo_with_wind_and_direction_std_dev_using_rng's own
11089        // solver_max_range derivation exactly (target_hint.max(1000.0) * 2.0, with
11090        // target_hint = base_inputs.target_distance since MonteCarloParams.target_distance
11091        // is None below) — otherwise the two solves integrate to different caps and a
11092        // level, non-ground-impacting shot legitimately reports a different max_range.
11093        let mut direct_solver = TrajectorySolver::new(
11094            base_inputs_asm.clone(),
11095            wind.clone(),
11096            AtmosphericConditions::default(),
11097        );
11098        direct_solver.set_max_range(base_inputs_asm.target_distance.max(1000.0) * 2.0);
11099        let direct = direct_solver.solve().expect("direct solve");
11100
11101        let mc_params = MonteCarloParams {
11102            num_simulations: 1,
11103            velocity_std_dev: 0.0,
11104            angle_std_dev: 0.0,
11105            bc_std_dev: 0.0,
11106            wind_speed_std_dev: 0.0,
11107            target_distance: None,
11108            base_wind_speed: 0.0,
11109            base_wind_direction: 0.0,
11110            azimuth_std_dev: 0.0,
11111        };
11112        let mc = run_monte_carlo_with_wind_and_direction_std_dev_seeded(
11113            base_inputs_asm,
11114            wind,
11115            mc_params,
11116            0.0,
11117            42,
11118        )
11119        .expect("monte carlo");
11120
11121        assert_eq!(mc.ranges.len(), 1);
11122        assert_eq!(
11123            mc.ranges[0].to_bits(),
11124            direct.max_range.to_bits(),
11125            "a zero-dispersion single MC sample must match a plain solve of the same \
11126             ASM-referenced inputs bit-for-bit"
11127        );
11128        assert_eq!(
11129            mc.impact_velocities[0].to_bits(),
11130            direct.impact_velocity.to_bits()
11131        );
11132    }
11133
11134    // ---- Downstream inheritance: estimate-bc fitting --------------------------------------
11135
11136    /// `estimate_bc_fit` always builds its internal search trials from
11137    /// `BallisticInputs { ..Default::default() }`, which defaults to `Icao` — so a fitted
11138    /// BC is always ICAO-referenced regardless of any other configuration in the process.
11139    /// Prove it by generating synthetic drop data from a KNOWN Icao-referenced bc_value and
11140    /// confirming the fit recovers that same value (not an ASM-shifted one).
11141    #[test]
11142    fn estimate_bc_fit_recovers_an_icao_referenced_bc() {
11143        let known_bc = 0.475;
11144        let velocity = 800.0;
11145        let mass = 0.0109;
11146        let diameter = 0.00782;
11147        let atmosphere = AtmosphericConditions::default();
11148
11149        let synth_inputs = BallisticInputs {
11150            muzzle_velocity: velocity,
11151            bc_value: known_bc,
11152            bc_type: DragModel::G7,
11153            bullet_mass: mass,
11154            bullet_diameter: diameter,
11155            bullet_length: 0.0309,
11156            sight_height: 0.05,
11157            twist_rate: 10.0,
11158            use_rk4: true,
11159            bc_reference_standard: BcReferenceStandard::Icao,
11160            ..BallisticInputs::default()
11161        };
11162        let mut solver =
11163            TrajectorySolver::new(synth_inputs, WindConditions::default(), atmosphere.clone());
11164        solver.set_max_range(500.0);
11165        let trajectory = solver.solve().expect("synthetic solve");
11166
11167        let points: Vec<(f64, f64)> = [100.0, 200.0, 300.0, 400.0]
11168            .iter()
11169            .map(|&d| {
11170                let (y, _) = {
11171                    let pts = &trajectory.points;
11172                    let mut found = None;
11173                    for i in 1..pts.len() {
11174                        if pts[i].position.x >= d {
11175                            let (p1, p2) = (&pts[i - 1], &pts[i]);
11176                            let dx = p2.position.x - p1.position.x;
11177                            let t = if dx.abs() < 1e-12 {
11178                                0.0
11179                            } else {
11180                                (d - p1.position.x) / dx
11181                            };
11182                            found =
11183                                Some((p1.position.y + t * (p2.position.y - p1.position.y), 0.0));
11184                            break;
11185                        }
11186                    }
11187                    found.expect("trajectory reached observation distance")
11188                };
11189                (d, -y) // drop is positive-down
11190            })
11191            .collect();
11192
11193        let estimate = estimate_bc_fit(
11194            velocity,
11195            mass,
11196            diameter,
11197            &points,
11198            DragModel::G7,
11199            BcFitMode::Drop,
11200            atmosphere,
11201            None,
11202            0.05,
11203        )
11204        .expect("fit should converge");
11205
11206        assert!(
11207            (estimate.bc - known_bc).abs() < 0.02,
11208            "fit should recover the known ICAO-referenced bc={known_bc}, got {}",
11209            estimate.bc
11210        );
11211    }
11212
11213    // ---- Custom drag table: documented inert behavior -------------------------------------
11214
11215    #[test]
11216    fn custom_drag_table_makes_bc_reference_standard_numerically_inert() {
11217        let table =
11218            crate::drag::DragTable::try_new(vec![0.5, 1.0, 2.0, 3.0], vec![0.3, 0.4, 0.3, 0.2])
11219                .expect("valid table");
11220
11221        let solve_with = |standard: BcReferenceStandard| {
11222            let inputs = BallisticInputs {
11223                bc_value: 0.5, // irrelevant once a custom drag table is active
11224                bc_reference_standard: standard,
11225                custom_drag_table: Some(table.clone()),
11226                ..base_inputs()
11227            };
11228            let mut solver = TrajectorySolver::new(
11229                inputs,
11230                WindConditions::default(),
11231                AtmosphericConditions::default(),
11232            );
11233            solver.set_max_range(500.0);
11234            solver.solve().expect("solve")
11235        };
11236
11237        let icao = solve_with(BcReferenceStandard::Icao);
11238        let asm = solve_with(BcReferenceStandard::ArmyStandardMetro);
11239
11240        assert_eq!(
11241            icao.impact_velocity.to_bits(),
11242            asm.impact_velocity.to_bits(),
11243            "a custom drag table must make bc_reference_standard fully inert"
11244        );
11245        assert_eq!(icao.max_range.to_bits(), asm.max_range.to_bits());
11246    }
11247
11248    #[test]
11249    fn custom_drag_table_inert_warning_fires_only_for_army_standard_metro_with_a_table() {
11250        let table = crate::drag::DragTable::try_new(vec![0.5, 1.0, 2.0], vec![0.3, 0.4, 0.3])
11251            .expect("valid table");
11252
11253        // No table: never warns, regardless of the declared standard.
11254        let no_table_icao = base_inputs();
11255        assert!(no_table_icao
11256            .bc_reference_standard_inert_warning()
11257            .is_none());
11258        let no_table_asm = BallisticInputs {
11259            bc_reference_standard: BcReferenceStandard::ArmyStandardMetro,
11260            ..base_inputs()
11261        };
11262        assert!(no_table_asm.bc_reference_standard_inert_warning().is_none());
11263
11264        // Table + Icao: no conversion was ever going to apply, so no warning either.
11265        let table_icao = BallisticInputs {
11266            custom_drag_table: Some(table.clone()),
11267            ..base_inputs()
11268        };
11269        assert!(table_icao.bc_reference_standard_inert_warning().is_none());
11270
11271        // Table + ArmyStandardMetro: the one case that is actually inert -> warn.
11272        let table_asm = BallisticInputs {
11273            custom_drag_table: Some(table),
11274            bc_reference_standard: BcReferenceStandard::ArmyStandardMetro,
11275            ..base_inputs()
11276        };
11277        let warning = table_asm
11278            .bc_reference_standard_inert_warning()
11279            .expect("must warn");
11280        assert!(warning.contains("--bc-reference"));
11281        assert!(warning.contains("--drag-table"));
11282    }
11283}
11284
11285/// MBA-1423: the per-point effective drag coefficient.
11286///
11287/// These pin the DEFINITION (the projectile's own Cd, form-factor scaled) rather than the
11288/// plumbing, because the plumbing being present is not the risk — reporting a plausible number
11289/// that is not the one flown is.
11290#[cfg(test)]
11291mod effective_drag_coefficient_tests {
11292    use super::*;
11293
11294    fn inputs_175gr_g7() -> BallisticInputs {
11295        let mut inputs = BallisticInputs {
11296            bc_value: 0.243,
11297            bc_type: DragModel::G7,
11298            muzzle_velocity: 823.0,
11299            ..Default::default()
11300        };
11301        // Set the SI fields: TrajectorySolver::new re-derives caliber_inches/weight_grains
11302        // from bullet_diameter/bullet_mass, so setting only the imperial pair would be
11303        // silently overwritten by the SI defaults (a 154gr .30, not a 175gr .308).
11304        inputs.bullet_mass = 175.0 * crate::constants::GRAINS_TO_KG;
11305        inputs.bullet_diameter = 0.308 * 0.0254;
11306        inputs.weight_grains = 175.0;
11307        inputs.caliber_inches = 0.308;
11308        inputs
11309    }
11310
11311    fn solver(inputs: BallisticInputs) -> TrajectorySolver {
11312        TrajectorySolver::new(
11313            inputs,
11314            WindConditions::default(),
11315            AtmosphericConditions::default(),
11316        )
11317    }
11318
11319    /// The reported Cd is the projectile's own, i.e. the reference Cd scaled by the form factor
11320    /// SD/BC — not the reference table value itself, which would be identical for every bullet
11321    /// sharing a drag model and so useless for charting a specific load.
11322    #[test]
11323    fn reports_the_projectiles_own_cd_not_the_reference_tables() {
11324        let inputs = inputs_175gr_g7();
11325        let sd = inputs.sectional_density_lb_in2().expect("SD");
11326        let solver = solver(inputs);
11327
11328        let sos = 340.0;
11329        let velocity = 800.0;
11330        let mach = velocity / sos;
11331
11332        let reference = crate::drag::get_drag_coefficient(mach, &DragModel::G7);
11333        let reported = solver
11334            .effective_drag_coefficient(velocity, sos)
11335            .expect("mass and diameter are set");
11336
11337        let expected = reference * sd / 0.243;
11338        assert!(
11339            (reported - expected).abs() < 1e-12,
11340            "reported {reported} != Cd_ref * SD / BC {expected}"
11341        );
11342        // The form factor here is > 1, so the two genuinely differ: a test that passed with
11343        // `reported == reference` would not be testing anything.
11344        assert!(
11345            (reported - reference).abs() > 1e-6,
11346            "form factor collapsed to 1; this fixture no longer distinguishes the two values"
11347        );
11348    }
11349
11350    /// A custom drag table already supplies the projectile's actual Cd and divides by sectional
11351    /// density, so the form-factor scale must collapse to exactly 1 and pass the curve through.
11352    #[test]
11353    fn a_custom_drag_table_passes_through_unscaled() {
11354        let mut inputs = inputs_175gr_g7();
11355        inputs.custom_drag_table = Some(crate::drag::DragTable::new(
11356            vec![0.5, 3.0],
11357            vec![0.15, 0.40],
11358        ));
11359        let solver = solver(inputs);
11360
11361        let sos = 340.0;
11362        let velocity = 0.9 * sos;
11363        let table_value = solver
11364            .inputs
11365            .custom_drag_table
11366            .as_ref()
11367            .expect("table")
11368            .interpolate(0.9);
11369
11370        let reported = solver
11371            .effective_drag_coefficient(velocity, sos)
11372            .expect("mass and diameter are set");
11373        assert!(
11374            (reported - table_value).abs() < 1e-12,
11375            "custom table Cd {table_value} was rescaled to {reported}"
11376        );
11377    }
11378
11379    /// The band step a segmented BC produces is the whole reason this field exists: it is the
11380    /// one feature of a real load's drag curve a consumer cannot reconstruct from a published BC.
11381    #[test]
11382    fn a_velocity_segmented_bc_steps_the_reported_cd() {
11383        let mut inputs = inputs_175gr_g7();
11384        inputs.use_bc_segments = true;
11385        inputs.bc_segments_data = Some(vec![
11386            crate::BCSegmentData {
11387                velocity_min: 2400.0,
11388                velocity_max: 4000.0,
11389                bc_value: 0.243,
11390            },
11391            crate::BCSegmentData {
11392                velocity_min: 0.0,
11393                velocity_max: 2400.0,
11394                bc_value: 0.200,
11395            },
11396        ]);
11397        let solver = solver(inputs);
11398
11399        let sos = 340.0;
11400        // Straddle the 2400 fps boundary (fps -> m/s).
11401        let above = solver
11402            .effective_drag_coefficient(2500.0 / 3.28084, sos)
11403            .expect("cd");
11404        let below = solver
11405            .effective_drag_coefficient(2300.0 / 3.28084, sos)
11406            .expect("cd");
11407
11408        // Lower BC below the boundary means MORE drag for the same reference curve.
11409        assert!(
11410            below > above,
11411            "expected the 0.200 band to report a higher Cd than the 0.243 band; got {below} vs {above}"
11412        );
11413    }
11414
11415    /// Sectional density is undefined without both mass and diameter, and so is the projectile's
11416    /// own Cd. Reporting the reference value there would be a silently wrong number.
11417    #[test]
11418    fn is_absent_when_sectional_density_is_unknown() {
11419        let mut inputs = inputs_175gr_g7();
11420        inputs.weight_grains = 0.0;
11421        inputs.bullet_mass = 0.0;
11422        let solver = solver(inputs);
11423        assert!(solver.effective_drag_coefficient(800.0, 340.0).is_none());
11424    }
11425
11426    /// MBA-1427: the emit rule the browser terminal applies, pinned natively because the WASM
11427    /// emit site is cfg-gated out of every native build and so is never executed by CI. Three
11428    /// cases, and the third is the contract: absent — not null — when sectional density is
11429    /// unknown, even with the flag set.
11430    #[test]
11431    fn the_json_emit_rule_is_flag_gated_and_absent_when_cd_is_unknown() {
11432        let mut point = TrajectoryPoint {
11433            time: 0.0,
11434            position: nalgebra::Vector3::new(0.0, 0.0, 0.0),
11435            velocity_magnitude: 800.0,
11436            kinetic_energy: 3000.0,
11437            drag_coefficient: Some(0.31),
11438        };
11439        assert_eq!(point.drag_coefficient_json_value(true), Some(0.31));
11440        assert_eq!(
11441            point.drag_coefficient_json_value(false),
11442            None,
11443            "without the flag the key must not exist, so default JSON stays byte-identical"
11444        );
11445        point.drag_coefficient = None;
11446        assert_eq!(
11447            point.drag_coefficient_json_value(true),
11448            None,
11449            "unknown sectional density must yield an ABSENT key, not null"
11450        );
11451    }
11452
11453    /// Every solver family runs the same post-pass, so none may leave the field empty.
11454    #[test]
11455    fn every_point_of_a_solved_trajectory_carries_the_value() {
11456        let mut solver = solver(inputs_175gr_g7());
11457        solver.set_max_range(300.0);
11458        let result = solver.solve().expect("solve");
11459        assert!(!result.points.is_empty());
11460        assert!(
11461            result.points.iter().all(|p| p.drag_coefficient.is_some()),
11462            "the post-integration pass missed at least one point"
11463        );
11464    }
11465}
11466
11467#[cfg(test)]
11468mod boundary_layer_shear_height_tests {
11469    //! Boundary-layer shear keys off the bullet's height above the GROUND. `TrajectorySolver`
11470    //! measures y from the level `muzzle_height` is measured from and integrates an inclined
11471    //! shot in the shot frame, whose ground runs parallel to the line of sight (the plane its
11472    //! ground_threshold check uses), so the shear height is the shot-frame y plus the height of
11473    //! y = 0 above the ground: nothing when `muzzle_height` is set (y = 0 is the ground it was
11474    //! measured from), the assumed 1.5 m bore height when it is left at 0 (y = 0 is the bore).
11475    use super::*;
11476
11477    const MODELS: [&str; 2] = ["logarithmic", "power_law"];
11478
11479    fn ratio_rel_launch(height_rel_launch_m: f64, model: &str) -> f64 {
11480        crate::wind_shear::boundary_layer_speed_ratio(
11481            height_rel_launch_m,
11482            crate::wind_shear::boundary_layer_model_from_name(model),
11483        )
11484    }
11485
11486    /// Asserts that the boundary-layer multiplier `TrajectorySolver` applies at `position` is
11487    /// `expected_ratio`: its acceleration with shear on equals its acceleration with shear off
11488    /// and the wind scaled by that ratio. Both are evaluated at the same point, so the local
11489    /// atmosphere is the same in each.
11490    fn assert_solver_shear_ratio(
11491        model: &str,
11492        muzzle_height: f64,
11493        shooting_angle: f64,
11494        position: Vector3<f64>,
11495        expected_ratio: f64,
11496    ) {
11497        let inputs = BallisticInputs {
11498            muzzle_height,
11499            shooting_angle,
11500            enable_wind_shear: true,
11501            wind_shear_model: model.to_string(),
11502            ..BallisticInputs::default()
11503        };
11504        let wind = WindConditions {
11505            speed: 10.0,
11506            direction: std::f64::consts::FRAC_PI_2,
11507            vertical_speed: 0.0,
11508        };
11509        let sheared = TrajectorySolver::new(
11510            inputs.clone(),
11511            wind.clone(),
11512            AtmosphericConditions::default(),
11513        );
11514        let uniform = TrajectorySolver::new(
11515            BallisticInputs {
11516                enable_wind_shear: false,
11517                ..inputs
11518            },
11519            wind.clone(),
11520            AtmosphericConditions::default(),
11521        );
11522        let station = sheared.station_air().unwrap();
11523        let velocity = Vector3::new(700.0, 5.0, 0.0);
11524        let scaled_wind =
11525            crate::wind::wind_vector(wind.speed, wind.direction, 0.0) * expected_ratio;
11526
11527        let with_shear =
11528            sheared.calculate_acceleration(&position, &velocity, &Vector3::zeros(), &station);
11529        let with_scaled_wind =
11530            uniform.calculate_acceleration(&position, &velocity, &scaled_wind, &station);
11531        assert!(
11532            (with_shear - with_scaled_wind).norm() <= 1e-12,
11533            "{model}, muzzle_height {muzzle_height} m, shooting angle {shooting_angle} rad, \
11534             position {position:?}: the shear multiplier is not {expected_ratio} \
11535             (acceleration {with_shear:?}, with the wind scaled by it {with_scaled_wind:?})"
11536        );
11537    }
11538
11539    /// (a) One height above the ground reads one multiplier, whatever `muzzle_height` says.
11540    /// With `muzzle_height` 1.5 m, y = 60 m is 60 m above the ground; with it left at 0, y = 0
11541    /// is the bore, taken as 1.5 m up, so y = 58.5 m is. The bore height used to be counted
11542    /// twice in the first case (61.5 m).
11543    #[test]
11544    fn solver_shear_reads_one_multiplier_at_one_height_above_ground() {
11545        for model in MODELS {
11546            // Height relative to the bore plus the assumed 1.5 m: 60 m above the ground.
11547            let expected = ratio_rel_launch(58.5, model);
11548            assert!(
11549                expected > 1.2,
11550                "{model}: the fixture must be well above the floor"
11551            );
11552            assert_solver_shear_ratio(model, 1.5, 0.0, Vector3::new(1_000.0, 60.0, 0.0), expected);
11553            assert_solver_shear_ratio(model, 0.0, 0.0, Vector3::new(1_000.0, 58.5, 0.0), expected);
11554        }
11555    }
11556
11557    /// (b) On an inclined shot the shear height is the shot-frame y plus the height of y = 0
11558    /// above the ground: the ground runs parallel to the line of sight, as it does for the
11559    /// ground_threshold check, so the shooting angle does not enter. The world height above
11560    /// the shooter's level, x·sin θ + y·cos θ, would read this point as hundreds of metres up
11561    /// on the uphill shot and below the ground on the downhill one. The fast kernel and the
11562    /// RK45 kernel read the same multiplier at the same point:
11563    /// `fast_trajectory::tests::inclined_fast_shear_measures_height_along_the_line_of_sight`
11564    /// and `trajectory_integration::tests::inclined_kernel_shear_measures_height_along_the_line_of_sight`
11565    /// pin it on this fixture.
11566    #[test]
11567    fn inclined_solver_shear_measures_height_along_the_line_of_sight() {
11568        let (x, y) = (800.0, 60.0);
11569        for angle in [0.3_f64, -0.3] {
11570            let world_height = crate::atmosphere::shot_frame_altitude(0.0, x, y, angle);
11571            for model in MODELS {
11572                // muzzle_height 0: y = 0 is the bore, taken as 1.5 m up, which is the public
11573                // function's height-relative-to-launch reading.
11574                let bore_frame = ratio_rel_launch(y, model);
11575                // muzzle_height 1.5 m: y = 0 is the ground.
11576                let ground_frame = ratio_rel_launch(y - 1.5, model);
11577                assert!(
11578                    bore_frame > 1.25 && ground_frame > 1.25,
11579                    "{model}: fixture too low"
11580                );
11581                assert!(
11582                    (ratio_rel_launch(world_height, model) - bore_frame).abs() > 0.1,
11583                    "{model}, angle {angle}: the fixture must tell the world height apart"
11584                );
11585                assert_solver_shear_ratio(model, 0.0, angle, Vector3::new(x, y, 0.0), bore_frame);
11586                assert_solver_shear_ratio(model, 1.5, angle, Vector3::new(x, y, 0.0), ground_frame);
11587            }
11588        }
11589    }
11590
11591    fn solve_end(inputs: BallisticInputs, max_range: f64) -> (Vector3<f64>, f64) {
11592        let mut solver = TrajectorySolver::new(
11593            inputs,
11594            WindConditions {
11595                speed: 10.0,
11596                direction: std::f64::consts::FRAC_PI_2,
11597                vertical_speed: 0.0,
11598            },
11599            AtmosphericConditions::default(),
11600        );
11601        solver.set_max_range(max_range);
11602        let result = solver.solve().unwrap();
11603        let peak_y = result
11604            .points
11605            .iter()
11606            .map(|p| p.position.y)
11607            .fold(f64::NEG_INFINITY, f64::max);
11608        (result.points.last().unwrap().position, peak_y)
11609    }
11610
11611    /// A flat shot fired up or down a slope stays within a few metres of the ground running
11612    /// along its line of sight, below the 10 m reference height, so shear on must leave it
11613    /// exactly where shear off does. Read against level ground at the shooter's elevation, the
11614    /// 15° uphill shot climbed into wind nearly 50% stronger by 600 m (155 m up).
11615    #[test]
11616    fn inclined_flat_fire_keeps_the_operative_wind_with_shear_on() {
11617        for shooting_angle in [15.0_f64.to_radians(), (-10.0_f64).to_radians()] {
11618            let inputs = BallisticInputs {
11619                muzzle_height: 1.5,
11620                muzzle_angle: 0.002,
11621                shooting_angle,
11622                bc_type: DragModel::G7,
11623                ..BallisticInputs::default()
11624            };
11625            let (off, peak_y) = solve_end(inputs.clone(), 600.0);
11626            assert!(
11627                peak_y < 8.0 && off.z.abs() > 0.5,
11628                "the fixture must stay low and drift: peak y {peak_y} m, drift {} m",
11629                off.z
11630            );
11631            for model in MODELS {
11632                let (on, _) = solve_end(
11633                    BallisticInputs {
11634                        enable_wind_shear: true,
11635                        wind_shear_model: model.to_string(),
11636                        ..inputs.clone()
11637                    },
11638                    600.0,
11639                );
11640                assert_eq!(
11641                    (on.x.to_bits(), on.y.to_bits(), on.z.to_bits()),
11642                    (off.x.to_bits(), off.y.to_bits(), off.z.to_bits()),
11643                    "{model}, shooting angle {shooting_angle} rad: shear moved a flat shot \
11644                     ({on:?} vs {off:?})"
11645                );
11646            }
11647        }
11648    }
11649
11650    /// `wind_shear_model` `"none"` is no shear, as it is for `fast_integrate`, the RK45 kernel
11651    /// and `get_wind_at_position`, even with `enable_wind_shear` set (the CLI's
11652    /// `--enable-wind-shear --wind-shear-model none`). It used to fall into the unknown-name
11653    /// fallback and apply the power law.
11654    #[test]
11655    fn model_none_applies_no_shear_with_the_flag_set() {
11656        let inputs = BallisticInputs {
11657            muzzle_height: 1.5,
11658            muzzle_angle: 0.12,
11659            bc_type: DragModel::G7,
11660            ..BallisticInputs::default()
11661        };
11662        let (off, peak_y) = solve_end(inputs.clone(), 1_000.0);
11663        assert!(
11664            peak_y > 100.0,
11665            "the fixture must be lofted: peak y {peak_y} m"
11666        );
11667        let with_model = |model: &str| {
11668            solve_end(
11669                BallisticInputs {
11670                    enable_wind_shear: true,
11671                    wind_shear_model: model.to_string(),
11672                    ..inputs.clone()
11673                },
11674                1_000.0,
11675            )
11676            .0
11677        };
11678        let none = with_model("none");
11679        assert_eq!(
11680            (none.x.to_bits(), none.y.to_bits(), none.z.to_bits()),
11681            (off.x.to_bits(), off.y.to_bits(), off.z.to_bits()),
11682            "model none moved the shot: {none:?} vs shear off {off:?}"
11683        );
11684        let power_law = with_model("power_law");
11685        assert!(
11686            (power_law.z - off.z).abs() > 0.05,
11687            "the fixture must show shear: power law {} m vs off {} m",
11688            power_law.z,
11689            off.z
11690        );
11691        // An unrecognized name keeps the historical power-law fallback.
11692        assert_eq!(with_model("typo").z.to_bits(), power_law.z.to_bits());
11693    }
11694}
11695
11696#[cfg(test)]
11697mod station_air_tests {
11698    //! TrajectorySolver's station air comes from `StationAir`, and its per-step air from
11699    //! `atmosphere::air_at_with_gravity`. The end-to-end bits are pinned by the byte-identity
11700    //! byte-identity files; these check the station itself, that a humidity beyond the sensor
11701    //! band is refused, never clamped, and that a reading within it flies as its end.
11702    use super::*;
11703    use crate::atmosphere::{calculate_atmosphere, resolve_station_conditions_with_presence};
11704
11705    fn solver(
11706        atmosphere: AtmosphericConditions,
11707        presence: StationAtmospherePresence,
11708    ) -> TrajectorySolver {
11709        TrajectorySolver::new_with_station_presence(
11710            BallisticInputs::default(),
11711            WindConditions::default(),
11712            atmosphere,
11713            presence,
11714        )
11715    }
11716
11717    #[test]
11718    fn station_air_is_calculate_atmosphere_at_the_resolved_station() {
11719        let atmospheres = [
11720            (0.0, 15.0, 1013.25, 0.0),
11721            (0.0, 15.0, 1013.25, 50.0),
11722            (1_500.0, 25.0, 830.0, 100.0),
11723            // The legacy omission sentinels at altitude: NEITHER flies ICAO here, BOTH flies
11724            // the typed values, and the station must follow whichever was resolved.
11725            (1_500.0, 15.0, 1013.25, 37.5),
11726            (2_000.0, 15.0, 1013.25, 50.0),
11727        ];
11728        for presence in [
11729            StationAtmospherePresence::NEITHER,
11730            StationAtmospherePresence::BOTH,
11731        ] {
11732            for (altitude, temperature, pressure, humidity) in atmospheres {
11733                let solver = solver(
11734                    AtmosphericConditions {
11735                        temperature,
11736                        pressure,
11737                        humidity,
11738                        altitude,
11739                    },
11740                    presence,
11741                );
11742                let station = solver.station_air().expect("valid station");
11743                let (temp_c, pressure_hpa) = resolve_station_conditions_with_presence(
11744                    temperature,
11745                    pressure,
11746                    altitude,
11747                    PressureReferenceMode::Absolute,
11748                    presence,
11749                );
11750                let (density, sound) =
11751                    calculate_atmosphere(altitude, Some(temp_c), Some(pressure_hpa), humidity);
11752                let got = [
11753                    station.altitude_m(),
11754                    station.temperature_c(),
11755                    station.pressure_hpa(),
11756                    station.humidity().percent(),
11757                    station.density_kg_m3(),
11758                    station.density_ratio(),
11759                    station.speed_of_sound_mps(),
11760                ];
11761                let want = [
11762                    altitude,
11763                    temp_c,
11764                    pressure_hpa,
11765                    humidity,
11766                    density,
11767                    density / 1.225,
11768                    sound,
11769                ];
11770                assert_eq!(
11771                    got.map(f64::to_bits),
11772                    want.map(f64::to_bits),
11773                    "{presence:?} {altitude} m {temperature} C {pressure} hPa {humidity}%"
11774                );
11775                // The test-only tuple view reads the same station.
11776                assert_eq!(
11777                    [
11778                        solver.resolved_atmosphere().0,
11779                        solver.resolved_atmosphere().1,
11780                        solver.resolved_atmosphere().2,
11781                        solver.resolved_atmosphere().3,
11782                    ]
11783                    .map(f64::to_bits),
11784                    [density, sound, temp_c, pressure_hpa].map(f64::to_bits)
11785                );
11786            }
11787        }
11788    }
11789
11790    /// An out-of-range station RH (beyond the sensor band) is REJECTED, never clamped. 0.49.0
11791    /// flew 150 % as 100 % and -5 % as 0 %; `validate_for_solve` now refuses both, and the
11792    /// station itself (`station_air`) refuses them through `StationAir::new` too, so no solve
11793    /// path can fly an unvalidated humidity.
11794    #[test]
11795    fn out_of_range_station_humidity_is_rejected_never_clamped() {
11796        // Beyond the 5-point sensor band (a reading within it is the next test's).
11797        for humidity in [150.0, -5.000_000_1, 105.000_000_1, f64::NAN, f64::INFINITY] {
11798            let mut solver = solver(
11799                AtmosphericConditions {
11800                    humidity,
11801                    temperature: 30.0,
11802                    ..AtmosphericConditions::default()
11803                },
11804                StationAtmospherePresence::BOTH,
11805            );
11806            solver.set_max_range(600.0);
11807            let station = solver
11808                .station_air()
11809                .expect_err(&format!("RH {humidity}: the station refuses it"));
11810            assert!(
11811                station.to_string().contains("atmosphere.humidity"),
11812                "{station}"
11813            );
11814            let solve = solver
11815                .solve()
11816                .expect_err(&format!("RH {humidity}: the solve refuses it"));
11817            assert!(solve.to_string().contains("atmosphere.humidity"), "{solve}");
11818        }
11819        // The ends of the range are humidities and fly as given, with no clamp in between.
11820        for humidity in [0.0, 100.0] {
11821            let solver = solver(
11822                AtmosphericConditions {
11823                    humidity,
11824                    temperature: 30.0,
11825                    ..AtmosphericConditions::default()
11826                },
11827                StationAtmospherePresence::BOTH,
11828            );
11829            let station = solver.station_air().expect("a valid station");
11830            assert_eq!(station.humidity().percent().to_bits(), humidity.to_bits());
11831            solver.solve().expect("a valid humidity flies");
11832        }
11833    }
11834
11835    /// The sensor band (owner decision 2026-11-01): a station reading within 5 points of the range
11836    /// is sensor error in saturated or dry air, so the station is the end it reads as, and the
11837    /// solve flies that end to the bit, on every integrator: the 0.49.0 clamp's numbers, now for
11838    /// the band only.
11839    #[test]
11840    fn a_station_reading_within_five_points_of_the_range_flies_the_end_bit_for_bit() {
11841        let flight = |humidity: f64, rk4: bool, rk45: bool| -> Vec<u64> {
11842            let mut solver = TrajectorySolver::new_with_station_presence(
11843                BallisticInputs {
11844                    use_rk4: rk4,
11845                    use_adaptive_rk45: rk45,
11846                    ..BallisticInputs::default()
11847                },
11848                WindConditions::default(),
11849                AtmosphericConditions {
11850                    humidity,
11851                    temperature: 30.0,
11852                    ..AtmosphericConditions::default()
11853                },
11854                StationAtmospherePresence::BOTH,
11855            );
11856            solver.set_max_range(600.0);
11857            let station = solver
11858                .station_air()
11859                .expect("a reading in the band is a station");
11860            let result = solver.solve().expect("a reading in the band flies");
11861            let mut bits = vec![
11862                station.humidity().percent().to_bits(),
11863                station.density_kg_m3().to_bits(),
11864                station.speed_of_sound_mps().to_bits(),
11865            ];
11866            for point in &result.points {
11867                bits.extend([
11868                    point.time.to_bits(),
11869                    point.position.x.to_bits(),
11870                    point.position.y.to_bits(),
11871                    point.position.z.to_bits(),
11872                    point.velocity_magnitude.to_bits(),
11873                ]);
11874            }
11875            bits
11876        };
11877        for (rk4, rk45) in [(false, false), (true, false), (true, true)] {
11878            for (reading, end) in [
11879                (100.0001, 100.0),
11880                (101.7, 100.0),
11881                (105.0, 100.0),
11882                (-0.0001, 0.0),
11883                (-2.0, 0.0),
11884                (-5.0, 0.0),
11885            ] {
11886                assert_eq!(
11887                    flight(reading, rk4, rk45),
11888                    flight(end, rk4, rk45),
11889                    "RH {reading} must fly {end} (rk4 {rk4}, rk45 {rk45})"
11890                );
11891            }
11892        }
11893    }
11894}
11895
11896// The humidity class guard: every solver family flies TrajectorySolver's humid air, at every
11897// step. A child module so it can drive the solver's own per-step acceleration.
11898#[cfg(test)]
11899mod humidity_consistency_tests;
11900
11901// Builder pins: every builder of a BallisticInputs leaves the humidity in it as the percent the
11902// engine flies. A child module so it can read the solver's and the Monte Carlo sampler's own
11903// inputs.
11904#[cfg(test)]
11905mod humidity_inputs_tests;