Skip to main content

ballistics_engine/
ffi.rs

1//! FFI bindings for iOS/Swift integration
2//!
3//! # Station temperature and pressure: this ABI uses the legacy default sentinels
4//!
5//! Every export here that takes an [`FFIAtmosphericConditions`] resolves its `temperature`
6//! and `pressure` through [`crate::atmosphere::resolve_station_conditions`] — the
7//! `StationAtmosphereResolution::LegacyDefaultSentinels` behaviour of
8//! [`crate::cli_api::TrajectorySolver::new`]. Concretely: at an `altitude` above 1 m, a
9//! `temperature` of 15 °C (±0.1) or a `pressure` of 1013.25 hPa (±0.5) is read as "not
10//! supplied — give me the ICAO standard atmosphere at this altitude", NOT as a station
11//! reading of exactly 15 °C / 1013.25 hPa.
12//!
13//! solve-json ([`crate::solve_json`], [`mod@crate::solve_v1`]) does the opposite: it builds through
14//! [`crate::cli_api::TrajectorySolver::new_with_resolved_station_atmosphere`], so a supplied
15//! `temperature_k`/`pressure_pa` is authoritative even when it happens to equal a sentinel
16//! value. The two surfaces therefore return DIFFERENT numbers for the same nominal inputs —
17//! a 300 m zero at 2000 m with 15 °C / 1013.25 hPa differs by about 0.29 MOA, because this
18//! ABI is solving it at the ICAO 2.00 °C / 795.01 hPa instead.
19//!
20//! This divergence is deliberate, and is the only correct answer for each surface. The
21//! difference is the input type, not the physics: `AtmosphereV1` carries `Option<f64>` behind a
22//! presence-preserving deserializer, so a JSON caller can say "omitted" directly and needs no
23//! heuristic (MBA-1397). [`FFIAtmosphericConditions`] is a `repr(C)` struct of plain
24//! `c_double`s with no presence channel at all, so the sentinel IS how a C caller says
25//! "omitted" — and it is what `tests/test_ffi.c` and every shipped example do. Making the C
26//! ABI authoritative would leave those callers computing sea-level density at altitude and
27//! under-stating drop, which is the exact defect `resolve_station_pressure` /
28//! `resolve_station_temperature` were introduced to fix. A C caller that genuinely IS at
29//! 15 °C at 2000 m must perturb the value (e.g. 15.2 °C) to escape the sentinel band, or use
30//! the JSON bridge (`crate::bridge`, behind the `bridge` feature) instead.
31//!
32//! `tests/ffi_atmosphere_resolution.rs` pins both halves of this.
33
34use crate::{
35    calculate_zero_angle_with_conditions, run_monte_carlo_with_direction_std_dev,
36    AtmosphericConditions, BallisticInputs, DragModel, MonteCarloParams, TrajectorySolver,
37    WindConditions,
38};
39use std::os::raw::{c_char, c_double, c_int};
40use std::ptr;
41
42/// Minimum C-ABI trajectory `step_size`, in milliseconds (0.1 ms = 0.0001 s).
43///
44/// Smaller steps are rejected before integration because fixed-step solves retain one public
45/// trajectory point per step. All in-repository FFI examples use values in `[0.1, 1.0]` ms.
46pub const MIN_FFI_STEP_SIZE_MS: c_double = 0.1;
47
48/// Maximum C-ABI custom drag-table row count.
49///
50/// `drag_table_from_raw` copies both caller arrays before validation; an unbounded
51/// `len` lets a single call request two multi-gigabyte allocations and abort the
52/// process (MBA-1407). Real Cd decks are two to three orders of magnitude smaller
53/// (the embedded G1/G7 references are under 100 rows; doppler exports run a few
54/// hundred), so 4096 is far above any legitimate deck.
55pub const MAX_FFI_DRAG_TABLE_LEN: c_int = 4096;
56
57// FFI-safe structures with C-compatible layouts
58
59#[repr(C)]
60pub struct FFIBallisticInputs {
61    pub muzzle_velocity: c_double,         // m/s
62    pub muzzle_angle: c_double,            // radians (launch angle)
63    pub bc_value: c_double,                // ballistic coefficient
64    pub bullet_mass: c_double,             // kg
65    pub bullet_diameter: c_double,         // meters
66    pub bc_type: c_int,                    // 0=G1, 1=G7, 2=G2, 3=G5, 4=G6, 5=G8, 6=GI, 7=GS, 8=RA4 (MBA-1386; unrecognized -> G1)
67    pub sight_height: c_double,            // meters
68    pub target_distance: c_double,         // meters
69    pub temperature: c_double,             // Celsius
70    pub twist_rate: c_double,              // inches per turn
71    pub is_twist_right: c_int,             // 0=false, 1=true
72    pub shooting_angle: c_double,          // uphill/downhill angle in radians
73    pub altitude: c_double,                // meters
74    pub latitude: c_double,                // degrees (use NAN if not provided)
75    pub azimuth_angle: c_double,           // horizontal aiming angle in radians
76    pub use_rk4: c_int,                    // 0=Euler, 1=RK4
77    pub use_adaptive_rk45: c_int,          // 0=false, 1=true (adaptive RK45)
78    pub enable_wind_shear: c_int,          // 0=false, 1=true
79    pub enable_trajectory_sampling: c_int, // 0=false, 1=true
80    pub sample_interval: c_double,         // meters
81    pub enable_pitch_damping: c_int,       // 0=false, 1=true
82    pub enable_precession_nutation: c_int, // 0=false, 1=true
83    pub enable_spin_drift: c_int,          // 0=false, 1=true
84    pub enable_magnus: c_int,              // 0=false, 1=true
85    pub enable_coriolis: c_int,            // 0=false, 1=true
86    // Appended (keeps existing field offsets): compass bearing the shot is fired
87    // along, radians, 0=North, PI/2=East. Drives the Coriolis Eötvös/drift azimuth.
88    // Distinct from azimuth_angle (the small aiming offset). 0.0 if unset.
89    pub shot_azimuth: c_double,
90    // Appended (keeps existing field offsets): rifle cant angle in RADIANS about the line
91    // of sight, positive = clockwise from the shooter. Rotates the sight-frame aim offsets
92    // and bore geometry ("zeroed level, fired canted" -> POI right and low). 0.0 if unset.
93    pub cant_angle: c_double,
94    // Appended (keeps existing field offsets): deliberate vertical POI offset AT the zero
95    // range, METERS (MBA-1359, Kestrel "zero height"): positive = the rifle is deliberately
96    // zeroed to impact HIGH by this much at the zero distance. Applied by the zero-angle
97    // solve as an angular bias on the solved angle. 0.0 if unset (identical to absent).
98    pub zero_poi_vertical: c_double,
99    // Appended (keeps existing field offsets): deliberate horizontal POI offset AT the zero
100    // range, METERS (MBA-1359, Kestrel "zero offset"): positive = impacts RIGHT by this much
101    // at the zero distance. 0.0 if unset (identical to absent).
102    pub zero_poi_horizontal: c_double,
103    // Appended (keeps existing field offsets): lateral sight-to-bore mount offset, METERS
104    // (MBA-1396, offset-mounted optics): positive = the sight sits RIGHT of the bore, so
105    // the trajectory starts that far LEFT of the line of sight. 0.0 if unset (identical to
106    // absent). NOTE for callers pairing ballistics_calculate_zero_angle with a trajectory
107    // call: the returned zero angle carries the VERTICAL zero_poi bias, but the horizontal
108    // terms are azimuth corrections a bare elevation angle cannot carry — a caller
109    // replicating an auto-zero flow must add
110    // (zero_poi_horizontal + sight_offset_lateral) / zero_distance to azimuth_angle itself.
111    pub sight_offset_lateral: c_double,
112    // NOT plumbed (deliberately): BallisticInputs.drops_reference (MBA-1403) is an
113    // OUTPUT-mode toggle for the trajectory sampler's drop column, not physics. This FFI
114    // surface exposes raw kinematic samples only (world-frame positions — no drop/dial
115    // outputs), so there is nothing for the toggle to act on; C callers wanting
116    // target-plane drops divide their own LOS drop by cos(shooting_angle).
117}
118
119#[repr(C)]
120pub struct FFIWindConditions {
121    pub speed: c_double, // m/s
122    // radians, wind-FROM convention: 0 = headwind, PI/2 = from the right,
123    // PI = tailwind, 3*PI/2 = from the left (matches WindConditions / WindSock).
124    // ALWAYS shooter-relative: the FFI deliberately has NO earth-fixed compass mode
125    // (MBA-1368 decision — bindings stay shooter-relative numeric); a caller holding a
126    // compass bearing converts it BEFORE the call as
127    // (bearing_rad - shot_azimuth_rad).rem_euclid(2*PI), which is exactly what the
128    // CLI/WASM/solve-json `--wind-ref compass` surfaces do internally.
129    pub direction: c_double,
130    // Appended (keeps existing field offsets): vertical wind m/s, positive = updraft;
131    // 0.0 if unset.
132    pub vertical_speed: c_double,
133}
134
135/// Station atmosphere for the C ABI.
136///
137/// `temperature` and `pressure` are resolved through the LEGACY DEFAULT SENTINELS: at a
138/// nonzero `altitude`, 15 °C and/or 1013.25 hPa mean "omitted, use the ICAO standard at this
139/// altitude" rather than a literal station reading. This struct has no presence channel, so
140/// that sentinel is the only way a C caller can express omission — see this module's
141/// documentation for why solve-json deliberately does NOT behave this way, and for the size
142/// of the resulting divergence.
143#[repr(C)]
144pub struct FFIAtmosphericConditions {
145    pub temperature: c_double, // Celsius
146    pub pressure: c_double,    // hPa
147    pub humidity: c_double,    // percentage (0-100)
148    pub altitude: c_double,    // meters
149}
150
151#[repr(C)]
152pub struct FFITrajectorySample {
153    pub distance: c_double,       // meters
154    pub time: c_double,           // seconds
155    pub velocity_mps: c_double,   // meters per second
156    pub energy_joules: c_double,  // joules
157    pub drop_meters: c_double,    // meters
158    pub windage_meters: c_double, // meters
159    pub mach: c_double,           // Mach number
160    pub spin_rate_rps: c_double,  // revolutions per second
161}
162
163/// One integrated trajectory point, in the launch frame.
164///
165/// **Axis convention — read this before indexing the positions.** All three are ABSOLUTE
166/// positions in METERS, measured from the muzzle (the bore exit is the origin):
167///
168/// | field | axis | sign |
169/// |-------|------|------|
170/// | `position_x` | DOWNRANGE, toward the target | increases with range; bracket on this to find a given distance |
171/// | `position_y` | VERTICAL height | `+` up, `-` down (below the muzzle) |
172/// | `position_z` | LATERAL windage | `+` right as seen by the shooter, `-` left |
173///
174/// Two traps this ordering sets for consumers:
175///
176/// - It is **not** the "Z is downrange, X is lateral" convention. Engine 0.13.x used that
177///   opposite convention, and consumers and API layers written against those releases may
178///   still document it, so code ported from one must swap X and Z. Nothing fails loudly if you
179///   do not — all three fields stay valid `double`s, so a mix-up silently plots range as
180///   windage instead of erroring. Take the convention from this struct, not from a downstream
181///   document.
182/// - `position_y` is a height, not a drop. It is positive UP and relative to the muzzle,
183///   whereas [`FFITrajectorySample::drop_meters`] is positive DOWN and relative to the line
184///   of sight. The two disagree in both origin and sign; they are not interchangeable.
185///
186/// Enforced in this file's tests: `zero_then_fly_with_same_deck_is_consistent` brackets the
187/// zero distance on `position_x`, and `ffi_cant_angle_deflects_laterally` asserts `position_z`
188/// grows rightward under cant.
189#[repr(C)]
190pub struct FFITrajectoryPoint {
191    pub time: c_double,
192    /// Downrange distance from the muzzle, meters. See the [struct docs](FFITrajectoryPoint).
193    pub position_x: c_double,
194    /// Height above the muzzle, meters, positive up (NOT a drop). See the
195    /// [struct docs](FFITrajectoryPoint).
196    pub position_y: c_double,
197    /// Lateral offset from the bore line, meters, positive right. See the
198    /// [struct docs](FFITrajectoryPoint).
199    pub position_z: c_double,
200    pub velocity_magnitude: c_double,
201    pub kinetic_energy: c_double,
202}
203
204#[repr(C)]
205pub struct FFITrajectoryResult {
206    pub max_range: c_double,
207    pub max_height: c_double,
208    pub time_of_flight: c_double,
209    pub impact_velocity: c_double,
210    pub impact_energy: c_double,
211    pub points: *mut FFITrajectoryPoint,
212    pub point_count: c_int,
213    pub sampled_points: *mut FFITrajectorySample,
214    pub sampled_point_count: c_int,
215    pub min_pitch_damping: c_double,    // NAN if not calculated
216    pub transonic_mach: c_double,       // NAN if not reached
217    pub final_pitch_angle: c_double,    // NAN if not calculated
218    pub final_yaw_angle: c_double,      // NAN if not calculated
219    pub max_yaw_angle: c_double,        // NAN if not calculated
220    pub max_precession_angle: c_double, // NAN if not calculated
221}
222
223// Monte Carlo simulation parameters
224#[repr(C)]
225pub struct FFIMonteCarloParams {
226    pub num_simulations: c_int,
227    pub velocity_std_dev: c_double,
228    pub angle_std_dev: c_double,
229    pub bc_std_dev: c_double,
230    pub wind_speed_std_dev: c_double,
231    pub target_distance: c_double,     // Use NAN if not specified
232    pub base_wind_speed: c_double,     // Base wind speed in m/s
233    pub base_wind_direction: c_double, // Base wind direction in radians
234    pub azimuth_std_dev: c_double,     // Horizontal aiming variation in radians
235}
236
237/// Monte Carlo simulation results, one entry per simulated shot.
238///
239/// Every array holds `num_results` `double`s and all of them are indexed by the same sample
240/// number.
241///
242/// **The `impact_positions_*` arrays are DEVIATIONS, not positions.** Each triple is the
243/// sample's offset from the baseline point of aim, measured in the target plane (the plane at
244/// the requested target distance), in METERS — see [`crate::MonteCarloResults::impact_positions`].
245/// A triple of zeros means "exactly on the point of aim", not "at the muzzle".
246///
247/// Axes follow [`FFITrajectoryPoint`]:
248///
249/// | field | axis | use for dispersion? |
250/// |-------|------|---------------------|
251/// | `impact_positions_z` | HORIZONTAL / windage deviation, `+` right | YES — this is the horizontal dispersion axis |
252/// | `impact_positions_y` | VERTICAL deviation, `+` up | YES — this is the vertical dispersion axis |
253/// | `impact_positions_x` | downrange, and the target plane sits at a FIXED downrange | NO — never a dispersion axis |
254///
255/// Consumers ported from engine 0.13.x (`X` lateral, `Z` downrange) commonly read
256/// `impact_positions_x` as the horizontal spread. Under this convention that reads the
257/// downrange component instead, which is not scatter, and it fails silently.
258///
259/// # Filter the shortfall sentinel before computing any statistic
260///
261/// A sample that never reached the target plane has no deviation to report, so it is encoded as
262/// `(0, TARGET_NOT_REACHED_SENTINEL_M, 0)` — the Y component is
263/// [`crate::TARGET_NOT_REACHED_SENTINEL_M`] (`-1.0e9` meters) — which keeps these arrays the same
264/// length as `ranges` and `impact_velocities`. The engine does NOT drop those entries for you.
265/// A sample is a finite arrival exactly when
266/// [`crate::MonteCarloResults::position_reached_target`] accepts it: every component finite AND
267/// the Y component not equal to the sentinel.
268///
269/// Feeding an unfiltered array into a mean or standard deviation drags the result toward
270/// `-1e9` and produces a plainly absurd group size. Exclude sentinel samples from dispersion
271/// statistics, but keep them in the denominator for hit probability — they are definite misses,
272/// which is how `hit_probability` already counts them.
273#[repr(C)]
274pub struct FFIMonteCarloResults {
275    pub ranges: *mut c_double,
276    pub impact_velocities: *mut c_double,
277    /// Downrange component of the target-plane deviation, meters. NOT a dispersion axis; see
278    /// the [struct docs](FFIMonteCarloResults).
279    pub impact_positions_x: *mut c_double,
280    /// VERTICAL deviation from the point of aim, meters, positive up — and the field carrying
281    /// the shortfall marker: [`crate::TARGET_NOT_REACHED_SENTINEL_M`] (`-1.0e9`) marks a sample
282    /// that did not reach the target plane. Exclude those from dispersion statistics but retain
283    /// them as misses for probability calculations. See the [struct docs](FFIMonteCarloResults).
284    pub impact_positions_y: *mut c_double,
285    /// HORIZONTAL / windage deviation from the point of aim, meters, positive right. This is
286    /// the horizontal dispersion axis; see the [struct docs](FFIMonteCarloResults).
287    pub impact_positions_z: *mut c_double,
288    pub num_results: c_int,
289    pub mean_range: c_double,
290    pub std_dev_range: c_double,
291    pub mean_impact_velocity: c_double,
292    pub std_dev_impact_velocity: c_double,
293    pub hit_probability: c_double, // If target_distance was specified
294}
295
296// Helper function to convert FFI inputs to internal types
297#[allow(clippy::field_reassign_with_default)] // Keep the C-to-Rust field mapping sequential/auditable.
298fn convert_inputs(inputs: &FFIBallisticInputs) -> BallisticInputs {
299    let mut ballistic_inputs = BallisticInputs::default();
300
301    ballistic_inputs.muzzle_velocity = inputs.muzzle_velocity;
302    ballistic_inputs.muzzle_angle = inputs.muzzle_angle;
303    ballistic_inputs.azimuth_angle = inputs.azimuth_angle;
304    ballistic_inputs.shot_azimuth = inputs.shot_azimuth;
305    ballistic_inputs.cant_angle = inputs.cant_angle;
306    ballistic_inputs.zero_poi_vertical_m = inputs.zero_poi_vertical;
307    ballistic_inputs.zero_poi_horizontal_m = inputs.zero_poi_horizontal;
308    ballistic_inputs.sight_offset_lateral_m = inputs.sight_offset_lateral;
309    ballistic_inputs.use_rk4 = inputs.use_rk4 != 0;
310    ballistic_inputs.use_adaptive_rk45 = inputs.use_adaptive_rk45 != 0;
311    ballistic_inputs.bc_value = inputs.bc_value;
312    ballistic_inputs.bullet_mass = inputs.bullet_mass;
313    ballistic_inputs.bullet_diameter = inputs.bullet_diameter;
314    ballistic_inputs.bc_type = match inputs.bc_type {
315        1 => DragModel::G7,
316        2 => DragModel::G2,
317        3 => DragModel::G5,
318        4 => DragModel::G6,
319        5 => DragModel::G8,
320        6 => DragModel::GI,
321        7 => DragModel::GS,
322        // MBA-1386: additive slot for the new RA4 family. Existing callers passing
323        // 0-7 are unaffected; any other/unrecognized value still falls back to G1.
324        8 => DragModel::RA4,
325        _ => DragModel::G1,
326    };
327    ballistic_inputs.sight_height = inputs.sight_height;
328    ballistic_inputs.target_distance = inputs.target_distance;
329    ballistic_inputs.temperature = inputs.temperature;
330    ballistic_inputs.twist_rate = inputs.twist_rate;
331    ballistic_inputs.is_twist_right = inputs.is_twist_right != 0;
332    ballistic_inputs.shooting_angle = inputs.shooting_angle;
333    ballistic_inputs.altitude = inputs.altitude;
334
335    if !inputs.latitude.is_nan() {
336        ballistic_inputs.latitude = Some(inputs.latitude);
337    }
338
339    // Set derived values
340    ballistic_inputs.caliber_inches = inputs.bullet_diameter / 0.0254;
341    ballistic_inputs.weight_grains = inputs.bullet_mass / crate::constants::GRAINS_TO_KG;
342    // MBA-1135: mass-based length estimate (was a mass-blind 4.5-caliber default). The C ABI does
343    // not carry a bullet length, so derive it from diameter + mass; fall back to 4.5-cal if mass<=0.
344    ballistic_inputs.bullet_length = {
345        let est = crate::stability::estimate_bullet_length_m(
346            ballistic_inputs.bullet_diameter,
347            ballistic_inputs.bullet_mass,
348        );
349        if est > 0.0 {
350            est
351        } else {
352            ballistic_inputs.bullet_diameter * 4.5
353        }
354    };
355
356    // New advanced physics flags
357    ballistic_inputs.enable_wind_shear = inputs.enable_wind_shear != 0;
358    // FFIBallisticInputs carries no model name, so a C ABI caller asking for shear
359    // would otherwise inherit BallisticInputs' default "none" — and the two solvers
360    // read that oppositely. TrajectorySolver::get_wind_at_altitude falls unknown
361    // names onto PowerLaw, so the trajectory path has always applied the power law;
362    // fast_integrate resolves them through boundary_layer_model_from_name to
363    // WindShearModel::None and then drops the model entirely, so the Monte Carlo
364    // path applied NOTHING and the caller's flag was silently inert. Name the
365    // profile the trajectory path already used, so both agree.
366    if ballistic_inputs.enable_wind_shear {
367        ballistic_inputs.wind_shear_model = "power_law".to_string();
368    }
369    ballistic_inputs.enable_trajectory_sampling = inputs.enable_trajectory_sampling != 0;
370    ballistic_inputs.sample_interval = inputs.sample_interval;
371    ballistic_inputs.enable_pitch_damping = inputs.enable_pitch_damping != 0;
372    ballistic_inputs.enable_precession_nutation = inputs.enable_precession_nutation != 0;
373    ballistic_inputs.use_enhanced_spin_drift = inputs.enable_spin_drift != 0;
374    ballistic_inputs.enable_advanced_effects =
375        inputs.enable_magnus != 0 || inputs.enable_coriolis != 0;
376    // Gate Magnus and Coriolis independently so enabling one does not enable the other.
377    ballistic_inputs.enable_magnus = inputs.enable_magnus != 0;
378    ballistic_inputs.enable_coriolis = inputs.enable_coriolis != 0;
379
380    ballistic_inputs
381}
382
383/// Build a validated [`crate::drag::DragTable`] from borrowed C arrays.
384///
385/// Both arrays must contain `len` elements, with `len` in `[2, MAX_FFI_DRAG_TABLE_LEN]`.
386/// The data is copied; the caller retains ownership. Returns `Err(())` for null
387/// pointers, `len` outside that range, or any deck that fails
388/// [`crate::drag::DragTable::try_new`] validation (non-ascending Mach, non-positive
389/// or non-finite Cd). No error detail crosses the ABI, matching the null/NAN
390/// error convention of this module.
391///
392/// # Safety
393///
394/// When non-null, `mach` and `cd` must each point to `len` readable `f64` values
395/// that remain valid and unmutated for the duration of the call.
396unsafe fn drag_table_from_raw(
397    mach: *const c_double,
398    cd: *const c_double,
399    len: c_int,
400) -> Result<crate::drag::DragTable, ()> {
401    if mach.is_null() || cd.is_null() || !(2..=MAX_FFI_DRAG_TABLE_LEN).contains(&len) {
402        return Err(());
403    }
404    let len = len as usize;
405    let mach = unsafe { std::slice::from_raw_parts(mach, len) }.to_vec();
406    let cd = unsafe { std::slice::from_raw_parts(cd, len) }.to_vec();
407    crate::drag::DragTable::try_new(mach, cd).map_err(|_| ())
408}
409
410/// Shared implementation for the trajectory exports. `custom_drag_table`, when
411/// present, replaces the G-model + BC drag (the deck's Cd is divided by sectional
412/// density — see `BallisticInputs::custom_drag_denominator`). `cd_scale` multiplies the
413/// deck's interpolated Cd (MBA-1356); callers that don't expose a scale pass `1.0`
414/// (neutral, byte-identical to no scale). It is inert when `custom_drag_table` is `None`.
415unsafe fn calculate_trajectory_impl(
416    inputs: *const FFIBallisticInputs,
417    wind: *const FFIWindConditions,
418    atmosphere: *const FFIAtmosphericConditions,
419    max_range: c_double,
420    step_size: c_double,
421    custom_drag_table: Option<crate::drag::DragTable>,
422    cd_scale: c_double,
423) -> *mut FFITrajectoryResult {
424    if inputs.is_null() {
425        return ptr::null_mut();
426    }
427    if !step_size.is_finite() || step_size < MIN_FFI_STEP_SIZE_MS {
428        return ptr::null_mut();
429    }
430
431    let inputs = unsafe { &*inputs };
432    let mut ballistic_inputs = convert_inputs(inputs);
433    ballistic_inputs.custom_drag_table = custom_drag_table;
434    ballistic_inputs.cd_scale = cd_scale;
435    let twist_rate_in = ballistic_inputs.twist_rate;
436
437    let wind_conditions = if wind.is_null() {
438        WindConditions::default()
439    } else {
440        let wind = unsafe { &*wind };
441        WindConditions {
442            speed: wind.speed,
443            direction: wind.direction,
444            vertical_speed: wind.vertical_speed,
445        }
446    };
447
448    let atmospheric_conditions = if atmosphere.is_null() {
449        AtmosphericConditions::default()
450    } else {
451        let atmo = unsafe { &*atmosphere };
452        AtmosphericConditions {
453            temperature: atmo.temperature,
454            pressure: atmo.pressure,
455            humidity: atmo.humidity,
456            altitude: atmo.altitude,
457        }
458    };
459
460    // Create solver and calculate trajectory
461    let (sample_temp_c, sample_pressure_hpa) = crate::atmosphere::resolve_station_conditions(
462        atmospheric_conditions.temperature,
463        atmospheric_conditions.pressure,
464        atmospheric_conditions.altitude,
465    );
466    let (_, sample_speed_of_sound) = crate::atmosphere::calculate_atmosphere(
467        atmospheric_conditions.altitude,
468        Some(sample_temp_c),
469        Some(sample_pressure_hpa),
470        atmospheric_conditions.humidity,
471    );
472
473    let mut solver =
474        TrajectorySolver::new(ballistic_inputs, wind_conditions, atmospheric_conditions);
475
476    // Set max range and time step
477    solver.set_max_range(max_range);
478    solver.set_time_step(step_size / 1000.0); // milliseconds -> seconds
479
480    match solver.solve() {
481        Ok(result) => {
482            // Convert trajectory points to FFI format
483            let point_count = result.points.len();
484            let points = if point_count > 0 {
485                let mut ffi_points = Vec::with_capacity(point_count);
486                for point in result.points.iter() {
487                    ffi_points.push(FFITrajectoryPoint {
488                        time: point.time,
489                        position_x: point.position[0],
490                        position_y: point.position[1],
491                        position_z: point.position[2],
492                        velocity_magnitude: point.velocity_magnitude,
493                        kinetic_energy: point.kinetic_energy,
494                    });
495                }
496                let points_ptr = ffi_points.as_mut_ptr();
497                std::mem::forget(ffi_points); // Prevent deallocation
498                points_ptr
499            } else {
500                ptr::null_mut()
501            };
502
503            // Convert sampled points if available
504            let (sampled_points, sampled_point_count) =
505                if let Some(ref samples) = result.sampled_points {
506                    let mut ffi_samples = Vec::with_capacity(samples.len());
507                    for sample in samples {
508                        ffi_samples.push(FFITrajectorySample {
509                            distance: sample.distance_m,
510                            time: sample.time_s,
511                            velocity_mps: sample.velocity_mps,
512                            energy_joules: sample.energy_j,
513                            drop_meters: sample.drop_m,
514                            windage_meters: sample.wind_drift_m,
515                            mach: if sample_speed_of_sound > 0.0 {
516                                sample.velocity_mps / sample_speed_of_sound
517                            } else {
518                                0.0
519                            },
520                            spin_rate_rps: if twist_rate_in > 0.0 {
521                                sample.velocity_mps / (twist_rate_in * 0.0254)
522                            } else {
523                                0.0
524                            },
525                        });
526                    }
527                    let count = ffi_samples.len() as c_int;
528                    let samples_ptr = ffi_samples.as_mut_ptr();
529                    std::mem::forget(ffi_samples);
530                    (samples_ptr, count)
531                } else {
532                    (ptr::null_mut(), 0)
533                };
534
535            // Extract angular state values if available
536            let (final_pitch, final_yaw, max_yaw, max_prec) =
537                if let Some(ref angular) = result.angular_state {
538                    (
539                        angular.pitch_angle,
540                        angular.yaw_angle,
541                        result.max_yaw_angle.unwrap_or(f64::NAN),
542                        result.max_precession_angle.unwrap_or(f64::NAN),
543                    )
544                } else {
545                    (f64::NAN, f64::NAN, f64::NAN, f64::NAN)
546                };
547
548            // Create result on heap
549            let ffi_result = Box::new(FFITrajectoryResult {
550                max_range: result.max_range,
551                max_height: result.max_height,
552                time_of_flight: result.time_of_flight,
553                impact_velocity: result.impact_velocity,
554                impact_energy: result.impact_energy,
555                points,
556                point_count: point_count as c_int,
557                sampled_points,
558                sampled_point_count,
559                min_pitch_damping: result.min_pitch_damping.unwrap_or(f64::NAN),
560                transonic_mach: result.transonic_mach.unwrap_or(f64::NAN),
561                final_pitch_angle: final_pitch,
562                final_yaw_angle: final_yaw,
563                max_yaw_angle: max_yaw,
564                max_precession_angle: max_prec,
565            });
566
567            Box::into_raw(ffi_result)
568        }
569        Err(_) => ptr::null_mut(),
570    }
571}
572
573/// Calculate a trajectory through the C ABI.
574///
575/// `step_size` is expressed in milliseconds and must be finite and at least
576/// [`MIN_FFI_STEP_SIZE_MS`]. This boundary contract is validated for every solver mode, although
577/// adaptive RK45 chooses its integration steps internally. Invalid values return null without
578/// starting a solve. A solve that would exceed [`crate::MAX_TRAJECTORY_POINTS`] also returns null;
579/// an enabled sampling grid above [`crate::MAX_TRAJECTORY_SAMPLES`] does likewise. Callers can
580/// increase `step_size`, reduce `max_range`, or select adaptive RK45.
581///
582/// # Safety
583///
584/// `inputs` may be null, in which case this function returns null. When non-null,
585/// it must point to a valid, properly aligned [`FFIBallisticInputs`] that remains
586/// readable and is not mutated for the duration of this call. `wind` and
587/// `atmosphere` may also be null; each non-null pointer has the same requirements
588/// for its corresponding type.
589/// The returned pointer, when non-null, must be released exactly once with
590/// [`ballistics_free_trajectory_result`].
591#[no_mangle]
592pub unsafe extern "C" fn ballistics_calculate_trajectory(
593    inputs: *const FFIBallisticInputs,
594    wind: *const FFIWindConditions,
595    atmosphere: *const FFIAtmosphericConditions,
596    max_range: c_double,
597    step_size: c_double,
598) -> *mut FFITrajectoryResult {
599    unsafe { calculate_trajectory_impl(inputs, wind, atmosphere, max_range, step_size, None, 1.0) }
600}
601
602/// [`ballistics_calculate_trajectory`] with a caller-supplied custom drag deck
603/// (Cd vs Mach, e.g. Hornady CDM / Doppler-radar data). The deck REPLACES the
604/// G-model + BC for drag: `bc_type`/`bc_value` are ignored, and the retardation
605/// denominator becomes the projectile's sectional density (mass and diameter in
606/// `inputs` must therefore be positive). Mach values must be strictly ascending
607/// with `drag_table_len` in `[2, MAX_FFI_DRAG_TABLE_LEN]` and finite positive Cd;
608/// outside the deck's Mach domain the nearest endpoint Cd is held.
609///
610/// Returns null for an invalid deck (null arrays, `drag_table_len` outside
611/// `[2, MAX_FFI_DRAG_TABLE_LEN]`, or failed validation), in addition to every
612/// failure mode of the base function.
613///
614/// # Safety
615///
616/// Same contract as [`ballistics_calculate_trajectory`] for `inputs`, `wind`, and
617/// `atmosphere`. Additionally, when non-null, `drag_mach` and `drag_cd` must each
618/// point to `drag_table_len` readable `f64` values, borrowed only for the duration
619/// of this call (the deck is copied; the caller retains ownership — no new free
620/// function is required). The returned pointer, when non-null, must be released
621/// exactly once with [`ballistics_free_trajectory_result`].
622#[no_mangle]
623pub unsafe extern "C" fn ballistics_calculate_trajectory_with_drag_table(
624    inputs: *const FFIBallisticInputs,
625    wind: *const FFIWindConditions,
626    atmosphere: *const FFIAtmosphericConditions,
627    max_range: c_double,
628    step_size: c_double,
629    drag_mach: *const c_double,
630    drag_cd: *const c_double,
631    drag_table_len: c_int,
632) -> *mut FFITrajectoryResult {
633    let table = match unsafe { drag_table_from_raw(drag_mach, drag_cd, drag_table_len) } {
634        Ok(t) => t,
635        Err(()) => return ptr::null_mut(),
636    };
637    unsafe {
638        calculate_trajectory_impl(
639            inputs, wind, atmosphere, max_range, step_size, Some(table), 1.0,
640        )
641    }
642}
643
644/// [`ballistics_calculate_trajectory_with_drag_table`] with an additional whole-curve
645/// drag scale (MBA-1356): the deck's interpolated Cd is multiplied by `cd_scale` at the
646/// same site the base export uses, i.e. `Cd_used = table.interpolate(mach) * cd_scale`.
647/// `cd_scale = 1.0` is neutral and produces byte-identical output to
648/// [`ballistics_calculate_trajectory_with_drag_table`] on the same deck. Typical truing
649/// values are in `[0.90, 1.10]`; values outside that band are accepted here (the engine
650/// only rejects non-finite or non-positive) — an "unusually large" warning is a CLI-only
651/// concern (Task 2), not part of this frozen C ABI.
652///
653/// Returns null when `cd_scale` is not finite or not `> 0`, in addition to every failure
654/// mode of [`ballistics_calculate_trajectory_with_drag_table`] (matching that export's
655/// null sentinel for an invalid deck).
656///
657/// # Safety
658///
659/// Same contract as [`ballistics_calculate_trajectory_with_drag_table`].
660#[no_mangle]
661pub unsafe extern "C" fn ballistics_calculate_trajectory_with_drag_table_scaled(
662    inputs: *const FFIBallisticInputs,
663    wind: *const FFIWindConditions,
664    atmosphere: *const FFIAtmosphericConditions,
665    max_range: c_double,
666    step_size: c_double,
667    drag_mach: *const c_double,
668    drag_cd: *const c_double,
669    drag_table_len: c_int,
670    cd_scale: c_double,
671) -> *mut FFITrajectoryResult {
672    if !cd_scale.is_finite() || cd_scale <= 0.0 {
673        return ptr::null_mut();
674    }
675    let table = match unsafe { drag_table_from_raw(drag_mach, drag_cd, drag_table_len) } {
676        Ok(t) => t,
677        Err(()) => return ptr::null_mut(),
678    };
679    unsafe {
680        calculate_trajectory_impl(
681            inputs, wind, atmosphere, max_range, step_size, Some(table), cd_scale,
682        )
683    }
684}
685
686/// Release a trajectory result allocated by [`ballistics_calculate_trajectory`].
687///
688/// # Safety
689///
690/// `result` must be null or a pointer returned by
691/// [`ballistics_calculate_trajectory`] that has not already been freed. Its
692/// embedded pointers and counts must be unchanged from the returned values.
693/// After this call, the result and its point arrays must not be accessed again.
694#[no_mangle]
695pub unsafe extern "C" fn ballistics_free_trajectory_result(result: *mut FFITrajectoryResult) {
696    if !result.is_null() {
697        unsafe {
698            let result = Box::from_raw(result);
699            if !result.points.is_null() && result.point_count > 0 {
700                let points = Vec::from_raw_parts(
701                    result.points,
702                    result.point_count as usize,
703                    result.point_count as usize,
704                );
705                drop(points);
706            }
707            if !result.sampled_points.is_null() && result.sampled_point_count > 0 {
708                let samples = Vec::from_raw_parts(
709                    result.sampled_points,
710                    result.sampled_point_count as usize,
711                    result.sampled_point_count as usize,
712                );
713                drop(samples);
714            }
715            drop(result);
716        }
717    }
718}
719
720/// Shared implementation for the zero-angle exports. `custom_drag_table`, when
721/// present, replaces the G-model + BC drag (the deck's Cd is divided by sectional
722/// density — see `BallisticInputs::custom_drag_denominator`), matching the deck
723/// semantics of [`calculate_trajectory_impl`] so a zero solved with a deck and a
724/// trajectory flown with the same deck agree. `cd_scale` multiplies the deck's
725/// interpolated Cd (MBA-1356); callers that don't expose a scale pass `1.0` (neutral).
726unsafe fn calculate_zero_angle_impl(
727    inputs: *const FFIBallisticInputs,
728    wind: *const FFIWindConditions,
729    atmosphere: *const FFIAtmosphericConditions,
730    zero_distance: c_double,
731    custom_drag_table: Option<crate::drag::DragTable>,
732    cd_scale: c_double,
733) -> c_double {
734    if inputs.is_null() {
735        return f64::NAN;
736    }
737
738    let inputs = unsafe { &*inputs };
739    let mut ballistic_inputs = convert_inputs(inputs);
740    ballistic_inputs.custom_drag_table = custom_drag_table;
741    ballistic_inputs.cd_scale = cd_scale;
742
743    let wind_conditions = if wind.is_null() {
744        WindConditions::default()
745    } else {
746        let wind = unsafe { &*wind };
747        WindConditions {
748            speed: wind.speed,
749            direction: wind.direction,
750            vertical_speed: wind.vertical_speed,
751        }
752    };
753
754    let atmospheric_conditions = if atmosphere.is_null() {
755        AtmosphericConditions::default()
756    } else {
757        let atmo = unsafe { &*atmosphere };
758        AtmosphericConditions {
759            temperature: atmo.temperature,
760            pressure: atmo.pressure,
761            humidity: atmo.humidity,
762            altitude: atmo.altitude,
763        }
764    };
765
766    // For zero angle, we want the bullet to hit at sight height at the zero distance
767    // This means the bullet crosses the line of sight at the zero distance
768    let target_height = ballistic_inputs.sight_height;
769
770    calculate_zero_angle_with_conditions(
771        ballistic_inputs,
772        zero_distance,
773        target_height,
774        wind_conditions,
775        atmospheric_conditions,
776    )
777    .unwrap_or(f64::NAN)
778}
779
780/// Calculate the zero angle for a target distance through the C ABI.
781///
782/// Solves to the classic sight-line zero contract (`ZeroTargetFrame::SightLine`, MBA-1412):
783/// the target height is sight geometry and the rifle zeroes LEVEL. `inputs.shooting_angle`
784/// applies to the subsequent shot, not to the zero.
785///
786/// # How this relates to solve-json's `zero_distance_m`
787///
788/// Both surfaces aim the search at the same place. This export passes the caller's
789/// `sight_height` as the target height; solve-json, handed a `zero_distance_m` with no
790/// `target_height_m`, defaults to the line of sight, `muzzle_height_m + sight_height_m`
791/// (MBA-1537 — before that it defaulted to a flat `0` and the two disagreed by a full sight
792/// height at the zero). For a level rifle at the same station conditions the two now return the
793/// same angle; `tests/zero_sight_line_default.rs` pins that.
794///
795/// Two deliberate differences remain, neither of which is a defect — see the module
796/// documentation for the reasoning and for the numbers:
797///
798/// * Atmosphere. This export goes through
799///   [`crate::calculate_zero_angle_with_conditions`], which applies the legacy
800///   default-sentinel heuristic to `atmosphere`. solve-json goes through
801///   [`crate::cli_api::TrajectorySolver::new_with_resolved_station_atmosphere`] and trusts a
802///   supplied station temperature/pressure as given. Feeding both surfaces 15 °C /
803///   1013.25 hPa at 2000 m is about a 0.29 MOA disagreement on a 300 m zero.
804/// * Target frame. solve-json's documented contract (`docs/SOLVE_JSON_V1.md`) is
805///   `WorldVertical` — an absolute height above the ground datum, with inclined zeroing
806///   projected into the world frame — not this export's `SightLine`, which zeroes level and
807///   treats `inputs.shooting_angle` as a shot-time condition. The frames coincide for a level
808///   rifle and diverge once `shooting_angle` is nonzero.
809///
810/// A caller that needs solve-json's semantics over a C ABI should use the JSON bridge
811/// (`crate::bridge`, `src/bridge/ffi.rs`) rather than this export.
812///
813/// # Safety
814///
815/// `inputs` may be null, in which case this function returns NaN. When non-null,
816/// it must point to a valid, properly aligned [`FFIBallisticInputs`] that remains
817/// readable and is not mutated for the duration of this call. `wind` and
818/// `atmosphere` may also be null; each non-null pointer has the same requirements
819/// for its corresponding type.
820#[no_mangle]
821pub unsafe extern "C" fn ballistics_calculate_zero_angle(
822    inputs: *const FFIBallisticInputs,
823    wind: *const FFIWindConditions,
824    atmosphere: *const FFIAtmosphericConditions,
825    zero_distance: c_double,
826) -> c_double {
827    unsafe { calculate_zero_angle_impl(inputs, wind, atmosphere, zero_distance, None, 1.0) }
828}
829
830/// [`ballistics_calculate_zero_angle`] with a caller-supplied custom drag deck
831/// (Cd vs Mach, e.g. Hornady CDM / Doppler-radar data). The deck REPLACES the
832/// G-model + BC for drag: `bc_type`/`bc_value` are ignored, and the retardation
833/// denominator becomes the projectile's sectional density (mass and diameter in
834/// `inputs` must therefore be positive). Mach values must be strictly ascending
835/// with `drag_table_len` in `[2, MAX_FFI_DRAG_TABLE_LEN]` and finite positive Cd;
836/// outside the deck's Mach domain the nearest endpoint Cd is held. Pair this with
837/// [`ballistics_calculate_trajectory_with_drag_table`] using the same deck to fly
838/// the solved angle — the two exports share identical deck semantics.
839///
840/// Returns NaN for an invalid deck (null arrays, `drag_table_len` outside
841/// `[2, MAX_FFI_DRAG_TABLE_LEN]`, or failed validation), in addition to every
842/// failure mode of the base function.
843///
844/// # Safety
845///
846/// Same contract as [`ballistics_calculate_zero_angle`] for `inputs`, `wind`, and
847/// `atmosphere`. Additionally, when non-null, `drag_mach` and `drag_cd` must each
848/// point to `drag_table_len` readable `f64` values, borrowed only for the duration
849/// of this call (the deck is copied; the caller retains ownership — no new free
850/// function is required).
851#[no_mangle]
852pub unsafe extern "C" fn ballistics_calculate_zero_angle_with_drag_table(
853    inputs: *const FFIBallisticInputs,
854    wind: *const FFIWindConditions,
855    atmosphere: *const FFIAtmosphericConditions,
856    zero_distance: c_double,
857    drag_mach: *const c_double,
858    drag_cd: *const c_double,
859    drag_table_len: c_int,
860) -> c_double {
861    let table = match unsafe { drag_table_from_raw(drag_mach, drag_cd, drag_table_len) } {
862        Ok(t) => t,
863        Err(()) => return f64::NAN,
864    };
865    unsafe {
866        calculate_zero_angle_impl(inputs, wind, atmosphere, zero_distance, Some(table), 1.0)
867    }
868}
869
870/// [`ballistics_calculate_zero_angle_with_drag_table`] with an additional whole-curve
871/// drag scale (MBA-1356): the deck's interpolated Cd is multiplied by `cd_scale` at the
872/// same site the base export uses, i.e. `Cd_used = table.interpolate(mach) * cd_scale`.
873/// `cd_scale = 1.0` is neutral and produces byte-identical output to
874/// [`ballistics_calculate_zero_angle_with_drag_table`] on the same deck. Pair this with
875/// [`ballistics_calculate_trajectory_with_drag_table_scaled`] using the same deck AND the
876/// same `cd_scale` to fly the solved angle. Typical truing values are in `[0.90, 1.10]`;
877/// values outside that band are accepted here (the engine only rejects non-finite or
878/// non-positive) — an "unusually large" warning is a CLI-only concern (Task 2).
879///
880/// Returns NaN when `cd_scale` is not finite or not `> 0`, in addition to every failure
881/// mode of [`ballistics_calculate_zero_angle_with_drag_table`] (matching that export's
882/// NaN sentinel for an invalid deck).
883///
884/// # Safety
885///
886/// Same contract as [`ballistics_calculate_zero_angle_with_drag_table`].
887#[no_mangle]
888pub unsafe extern "C" fn ballistics_calculate_zero_angle_with_drag_table_scaled(
889    inputs: *const FFIBallisticInputs,
890    wind: *const FFIWindConditions,
891    atmosphere: *const FFIAtmosphericConditions,
892    zero_distance: c_double,
893    drag_mach: *const c_double,
894    drag_cd: *const c_double,
895    drag_table_len: c_int,
896    cd_scale: c_double,
897) -> c_double {
898    if !cd_scale.is_finite() || cd_scale <= 0.0 {
899        return f64::NAN;
900    }
901    let table = match unsafe { drag_table_from_raw(drag_mach, drag_cd, drag_table_len) } {
902        Ok(t) => t,
903        Err(()) => return f64::NAN,
904    };
905    unsafe {
906        calculate_zero_angle_impl(
907            inputs,
908            wind,
909            atmosphere,
910            zero_distance,
911            Some(table),
912            cd_scale,
913        )
914    }
915}
916
917// Simple trajectory calculation for quick results
918#[no_mangle]
919#[allow(clippy::field_reassign_with_default)] // Preserve the staged zero-angle workflow below.
920pub extern "C" fn ballistics_quick_trajectory(
921    muzzle_velocity: c_double,
922    bc: c_double,
923    sight_height: c_double,
924    zero_distance: c_double,
925    target_distance: c_double,
926) -> c_double {
927    // This provides a simple drop calculation at target distance
928    // Using simplified ballistic calculations
929
930    let mut inputs = BallisticInputs::default();
931    inputs.muzzle_velocity = muzzle_velocity;
932    inputs.bc_value = bc;
933    inputs.sight_height = sight_height;
934    inputs.target_distance = target_distance;
935
936    let wind = WindConditions::default();
937    let atmo = AtmosphericConditions::default();
938
939    // First calculate zero angle
940    let zero_angle = match calculate_zero_angle_with_conditions(
941        inputs.clone(),
942        zero_distance,
943        sight_height,
944        wind.clone(),
945        atmo.clone(),
946    ) {
947        Ok(angle) => angle,
948        Err(_) => return f64::NAN,
949    };
950
951    // Now calculate trajectory with that zero angle
952    inputs.muzzle_angle = zero_angle;
953
954    let mut solver = TrajectorySolver::new(inputs, wind, atmo);
955    solver.set_max_range(target_distance * 1.1);
956
957    match solver.solve() {
958        Ok(result) => {
959            // Find the drop at target distance
960            for point in result.points {
961                if point.position[0] >= target_distance {
962                    return sight_height - point.position[1];
963                }
964            }
965            f64::NAN
966        }
967        Err(_) => f64::NAN,
968    }
969}
970
971/// Run a Monte Carlo simulation through the C ABI.
972///
973/// # Safety
974///
975/// `inputs` and `params` may be null, in which case this function returns null.
976/// Each non-null pointer must point to a valid, properly aligned value of its
977/// corresponding FFI type that remains readable and is not mutated for the
978/// duration of this call. `atmosphere` may be null; a non-null pointer has the
979/// same requirements for [`FFIAtmosphericConditions`]. The returned pointer,
980/// when non-null, must be released exactly once with
981/// [`ballistics_free_monte_carlo_results`].
982#[no_mangle]
983pub unsafe extern "C" fn ballistics_monte_carlo(
984    inputs: *const FFIBallisticInputs,
985    atmosphere: *const FFIAtmosphericConditions,
986    params: *const FFIMonteCarloParams,
987) -> *mut FFIMonteCarloResults {
988    unsafe { ballistics_monte_carlo_impl(inputs, atmosphere, params, 0.0) }
989}
990
991/// Run a Monte Carlo simulation with independent wind-direction uncertainty through the C ABI.
992///
993/// `wind_direction_std_dev` is in radians. This additive entry point keeps
994/// [`FFIMonteCarloParams`] and [`ballistics_monte_carlo`] binary-compatible; the older function
995/// delegates with zero wind-direction uncertainty.
996///
997/// # Safety
998///
999/// The pointer and ownership requirements are identical to [`ballistics_monte_carlo`].
1000#[no_mangle]
1001pub unsafe extern "C" fn ballistics_monte_carlo_with_direction_std_dev(
1002    inputs: *const FFIBallisticInputs,
1003    atmosphere: *const FFIAtmosphericConditions,
1004    params: *const FFIMonteCarloParams,
1005    wind_direction_std_dev: c_double,
1006) -> *mut FFIMonteCarloResults {
1007    unsafe { ballistics_monte_carlo_impl(inputs, atmosphere, params, wind_direction_std_dev) }
1008}
1009
1010unsafe fn ballistics_monte_carlo_impl(
1011    inputs: *const FFIBallisticInputs,
1012    atmosphere: *const FFIAtmosphericConditions,
1013    params: *const FFIMonteCarloParams,
1014    wind_direction_std_dev: f64,
1015) -> *mut FFIMonteCarloResults {
1016    if inputs.is_null() || params.is_null() {
1017        return ptr::null_mut();
1018    }
1019
1020    let inputs = unsafe { &*inputs };
1021    let params = unsafe { &*params };
1022
1023    // Reject an out-of-range simulation count. num_simulations is a c_int (i32) cast straight to
1024    // usize: a negative value would wrap to a near-max usize, and even a large positive value (up
1025    // to i32::MAX ~ 2.1e9) would drive billions of iterations with the result arrays scaling to
1026    // match — an unbounded-loop / OOM DoS from a single FFI call. Bound it to a sane maximum.
1027    // (n == 0 also yields NaN stats and a zero-size allocation.)
1028    const MAX_SIMULATIONS: c_int = 1_000_000;
1029    if params.num_simulations <= 0 || params.num_simulations > MAX_SIMULATIONS {
1030        return ptr::null_mut();
1031    }
1032
1033    // Convert FFI inputs to internal types
1034    let mut ballistic_inputs = convert_inputs(inputs);
1035    ballistic_inputs.muzzle_height = 1.5;
1036    ballistic_inputs.ground_threshold = 0.0;
1037    if !atmosphere.is_null() {
1038        let atmo = unsafe { &*atmosphere };
1039        ballistic_inputs.temperature = atmo.temperature;
1040        ballistic_inputs.pressure = atmo.pressure;
1041        ballistic_inputs.humidity = (atmo.humidity / 100.0).clamp(0.0, 1.0);
1042        ballistic_inputs.altitude = atmo.altitude;
1043    }
1044
1045    // Create Monte Carlo parameters
1046    let mc_params = MonteCarloParams {
1047        num_simulations: params.num_simulations as usize,
1048        velocity_std_dev: params.velocity_std_dev,
1049        angle_std_dev: params.angle_std_dev,
1050        bc_std_dev: params.bc_std_dev,
1051        wind_speed_std_dev: params.wind_speed_std_dev,
1052        target_distance: if params.target_distance.is_nan() {
1053            None
1054        } else {
1055            Some(params.target_distance)
1056        },
1057        base_wind_speed: params.base_wind_speed,
1058        base_wind_direction: params.base_wind_direction,
1059        azimuth_std_dev: params.azimuth_std_dev,
1060    };
1061
1062    // Run Monte Carlo simulation
1063    match run_monte_carlo_with_direction_std_dev(
1064        ballistic_inputs,
1065        mc_params,
1066        wind_direction_std_dev,
1067    ) {
1068        Ok(results) => {
1069            let num_results = results.ranges.len() as c_int;
1070
1071            // Calculate statistics
1072            let mean_range: f64 = results.ranges.iter().sum::<f64>() / num_results as f64;
1073            let variance_range: f64 = results
1074                .ranges
1075                .iter()
1076                .map(|r| (r - mean_range).powi(2))
1077                .sum::<f64>()
1078                / num_results as f64;
1079            let std_dev_range = variance_range.sqrt();
1080
1081            let mean_velocity: f64 =
1082                results.impact_velocities.iter().sum::<f64>() / num_results as f64;
1083            let variance_velocity: f64 = results
1084                .impact_velocities
1085                .iter()
1086                .map(|v| (v - mean_velocity).powi(2))
1087                .sum::<f64>()
1088                / num_results as f64;
1089            let std_dev_velocity = variance_velocity.sqrt();
1090
1091            // Calculate hit probability if target distance was specified. MBA-971: use the shared
1092            // position-based criterion (fraction within DEFAULT_HIT_RADIUS_M of the point of aim
1093            // at the target plane). The old inline version had a redundant `distance < target`
1094            // clause comparing a ~meter deviation to the ~hundreds-of-meters target distance
1095            // (effectively always true), and the CLI used a different range-based notion entirely.
1096            let hit_probability = if params.target_distance.is_nan() {
1097                0.0
1098            } else {
1099                results.hit_probability(crate::DEFAULT_HIT_RADIUS_M)
1100            };
1101
1102            // Allocate memory for arrays
1103            let ranges_ptr = unsafe {
1104                let ptr = std::alloc::alloc(
1105                    std::alloc::Layout::array::<c_double>(num_results as usize).unwrap(),
1106                ) as *mut c_double;
1107                for (i, &range) in results.ranges.iter().enumerate() {
1108                    *ptr.add(i) = range;
1109                }
1110                ptr
1111            };
1112
1113            let velocities_ptr = unsafe {
1114                let ptr = std::alloc::alloc(
1115                    std::alloc::Layout::array::<c_double>(num_results as usize).unwrap(),
1116                ) as *mut c_double;
1117                for (i, &vel) in results.impact_velocities.iter().enumerate() {
1118                    *ptr.add(i) = vel;
1119                }
1120                ptr
1121            };
1122
1123            let pos_x_ptr = unsafe {
1124                let ptr = std::alloc::alloc(
1125                    std::alloc::Layout::array::<c_double>(num_results as usize).unwrap(),
1126                ) as *mut c_double;
1127                for (i, pos) in results.impact_positions.iter().enumerate() {
1128                    *ptr.add(i) = pos.x;
1129                }
1130                ptr
1131            };
1132
1133            let pos_y_ptr = unsafe {
1134                let ptr = std::alloc::alloc(
1135                    std::alloc::Layout::array::<c_double>(num_results as usize).unwrap(),
1136                ) as *mut c_double;
1137                for (i, pos) in results.impact_positions.iter().enumerate() {
1138                    *ptr.add(i) = pos.y;
1139                }
1140                ptr
1141            };
1142
1143            let pos_z_ptr = unsafe {
1144                let ptr = std::alloc::alloc(
1145                    std::alloc::Layout::array::<c_double>(num_results as usize).unwrap(),
1146                ) as *mut c_double;
1147                for (i, pos) in results.impact_positions.iter().enumerate() {
1148                    *ptr.add(i) = pos.z;
1149                }
1150                ptr
1151            };
1152
1153            // Create result structure
1154            let result = Box::new(FFIMonteCarloResults {
1155                ranges: ranges_ptr,
1156                impact_velocities: velocities_ptr,
1157                impact_positions_x: pos_x_ptr,
1158                impact_positions_y: pos_y_ptr,
1159                impact_positions_z: pos_z_ptr,
1160                num_results,
1161                mean_range,
1162                std_dev_range,
1163                mean_impact_velocity: mean_velocity,
1164                std_dev_impact_velocity: std_dev_velocity,
1165                hit_probability,
1166            });
1167
1168            Box::into_raw(result)
1169        }
1170        Err(_) => ptr::null_mut(),
1171    }
1172}
1173
1174/// Release Monte Carlo results allocated by either Monte Carlo C entry point.
1175///
1176/// # Safety
1177///
1178/// `results` must be null or a pointer returned by [`ballistics_monte_carlo`] or
1179/// [`ballistics_monte_carlo_with_direction_std_dev`] that has not already been freed. Its
1180/// embedded pointers and result count must be unchanged from the returned values. After this
1181/// call, the result and all of its arrays must not be accessed again.
1182#[no_mangle]
1183pub unsafe extern "C" fn ballistics_free_monte_carlo_results(results: *mut FFIMonteCarloResults) {
1184    if results.is_null() {
1185        return;
1186    }
1187
1188    unsafe {
1189        let results = Box::from_raw(results);
1190        let num = results.num_results as usize;
1191
1192        // Free arrays
1193        if !results.ranges.is_null() {
1194            std::alloc::dealloc(
1195                results.ranges as *mut u8,
1196                std::alloc::Layout::array::<c_double>(num).unwrap(),
1197            );
1198        }
1199
1200        if !results.impact_velocities.is_null() {
1201            std::alloc::dealloc(
1202                results.impact_velocities as *mut u8,
1203                std::alloc::Layout::array::<c_double>(num).unwrap(),
1204            );
1205        }
1206
1207        if !results.impact_positions_x.is_null() {
1208            std::alloc::dealloc(
1209                results.impact_positions_x as *mut u8,
1210                std::alloc::Layout::array::<c_double>(num).unwrap(),
1211            );
1212        }
1213
1214        if !results.impact_positions_y.is_null() {
1215            std::alloc::dealloc(
1216                results.impact_positions_y as *mut u8,
1217                std::alloc::Layout::array::<c_double>(num).unwrap(),
1218            );
1219        }
1220
1221        if !results.impact_positions_z.is_null() {
1222            std::alloc::dealloc(
1223                results.impact_positions_z as *mut u8,
1224                std::alloc::Layout::array::<c_double>(num).unwrap(),
1225            );
1226        }
1227
1228        // Box automatically deallocates the result structure
1229    }
1230}
1231
1232/// Which standard atmosphere a `bc` value passed to [`ballistics_bc_for_reference_standard`]
1233/// is referenced to (MBA-1365). `0` = ICAO (the default every other export in this module
1234/// assumes), `1` = Army Standard Metro (some vendor-published BCs, notably many
1235/// Sierra/Hornady/Barnes bullets). Any other value is treated as `0` (ICAO), matching the
1236/// permissive unrecognized-value convention `convert_inputs` already uses for `bc_type`.
1237pub const FFI_BC_REFERENCE_ICAO: c_int = 0;
1238pub const FFI_BC_REFERENCE_ARMY_STANDARD_METRO: c_int = 1;
1239
1240/// Convert a ballistic coefficient declared under `reference_standard` to the ICAO-referenced
1241/// value every `FFIBallisticInputs.bc_value` in this module expects (MBA-1365).
1242///
1243/// `FFIBallisticInputs` is an ABI-frozen `repr(C)` struct (an iOS-consumer contract enforced
1244/// by a regression test) with no room to add a reference-standard field, so this is a
1245/// standalone pure conversion instead of a struct setter: call it once on a raw BC before
1246/// writing the result into `FFIBallisticInputs.bc_value`, then use every existing
1247/// `ballistics_calculate_trajectory*`/`ballistics_calculate_zero_angle*`/`ballistics_monte_carlo*`
1248/// export completely unchanged. `reference_standard == FFI_BC_REFERENCE_ICAO` (`0`) is a
1249/// no-op, so every existing caller that never calls this function is unaffected — this is a
1250/// pure addition to the ABI, not a modification, so no recompile is required unless a caller
1251/// opts into the new symbol.
1252///
1253/// `reference_standard == FFI_BC_REFERENCE_ARMY_STANDARD_METRO` (`1`) multiplies by
1254/// [`crate::constants::ASM_TO_ICAO_BC`], the same constant and the same single multiply
1255/// [`crate::cli_api::TrajectorySolver::new`] applies for the CLI/WASM/Rust-native surfaces.
1256/// A non-finite `bc` is returned unchanged (this function performs no validation; the
1257/// existing `bc_value must be finite and greater than zero` solve-time check still applies).
1258#[no_mangle]
1259pub extern "C" fn ballistics_bc_for_reference_standard(
1260    bc: c_double,
1261    reference_standard: c_int,
1262) -> c_double {
1263    if reference_standard == FFI_BC_REFERENCE_ARMY_STANDARD_METRO {
1264        bc * crate::constants::ASM_TO_ICAO_BC
1265    } else {
1266        bc
1267    }
1268}
1269
1270/// Reduce a sea-level-corrected altimeter setting (QNH, in hPa) to the station pressure at
1271/// `altitude_m` (MBA-1397; see [`crate::atmosphere::reduce_qnh_to_station_pressure`] for the
1272/// formula). `FFIAtmosphericConditions.pressure` has always meant absolute station pressure,
1273/// and remains a frozen `repr(C)` struct enforced by an ABI regression test with no room to
1274/// add a pressure-reference-mode field, so this is a standalone pure conversion instead of a
1275/// struct setter — exactly the same pattern as [`ballistics_bc_for_reference_standard`]: call
1276/// it once on a caller-declared QNH reading before writing the result into
1277/// `FFIAtmosphericConditions.pressure`, then use every existing
1278/// `ballistics_calculate_trajectory*`/`ballistics_calculate_zero_angle*`/`ballistics_monte_carlo*`
1279/// export completely unchanged — every one of them reads `pressure` as absolute station
1280/// pressure already, so feeding it an already-reduced value is a pure addition to the ABI,
1281/// not a modification. No existing caller that never calls this function is affected, and no
1282/// recompile is required for callers that don't opt into QNH support.
1283///
1284/// A non-finite `qnh_hpa` or `altitude_m` is returned unchanged (this function performs no
1285/// validation; the existing per-export input checks still apply to whatever ends up in
1286/// `FFIAtmosphericConditions.pressure`).
1287#[no_mangle]
1288pub extern "C" fn ballistics_reduce_qnh_pressure(
1289    qnh_hpa: c_double,
1290    altitude_m: c_double,
1291) -> c_double {
1292    if !qnh_hpa.is_finite() || !altitude_m.is_finite() {
1293        return qnh_hpa;
1294    }
1295    crate::atmosphere::reduce_qnh_to_station_pressure(qnh_hpa, altitude_m)
1296}
1297
1298/// Sentinel `explicit_temperature_c` value meaning "no explicit temperature override" for the
1299/// `ballistics_density_altitude_*` exports below (MBA-1366) — same NaN-means-absent convention
1300/// [`FFIBallisticInputs::latitude`] already uses. Any NaN bit pattern is accepted (checked via
1301/// `is_nan()`, not equality), matching that precedent.
1302pub const FFI_NO_EXPLICIT_TEMPERATURE: c_double = f64::NAN;
1303
1304/// Back-solve the station TEMPERATURE (Celsius) an ISA-equivalent atmosphere at
1305/// `density_altitude_m` implies (MBA-1366; see
1306/// [`crate::atmosphere::resolve_atmosphere_for_density_altitude`] for the full derivation).
1307///
1308/// `FFIAtmosphericConditions` is an ABI-frozen `repr(C)` struct (the same iOS-consumer contract
1309/// enforced by a regression test as [`ballistics_reduce_qnh_pressure`]/
1310/// [`ballistics_bc_for_reference_standard`]) with no room for a density-altitude field, so this
1311/// is a standalone pure conversion — call it (and its two companions below) once on a declared
1312/// density altitude, then write the three results into `FFIAtmosphericConditions.temperature`/
1313/// `.pressure`/`.altitude` before calling any existing `ballistics_calculate_trajectory*`/
1314/// `ballistics_calculate_zero_angle*`/`ballistics_monte_carlo*` export unchanged — a pure
1315/// addition to the C ABI requiring no recompile for existing callers.
1316///
1317/// `explicit_temperature_c`: pass [`FFI_NO_EXPLICIT_TEMPERATURE`] (NaN) for the ISA-at-density-
1318/// altitude default, or a real Celsius value to have it honored exactly (density is still
1319/// honored either way — only the implied pressure/altitude differ; see the Rust doc comment).
1320/// A non-finite `density_altitude_m` returns NaN for all three exports (there is no plausible
1321/// station value to fall back to, unlike the QNH/BC conversions above, which return their input
1322/// unchanged).
1323#[no_mangle]
1324pub extern "C" fn ballistics_density_altitude_temperature_c(
1325    density_altitude_m: c_double,
1326    explicit_temperature_c: c_double,
1327) -> c_double {
1328    if !density_altitude_m.is_finite() {
1329        return f64::NAN;
1330    }
1331    let explicit = (!explicit_temperature_c.is_nan()).then_some(explicit_temperature_c);
1332    crate::atmosphere::resolve_atmosphere_for_density_altitude(density_altitude_m, explicit).1
1333}
1334
1335/// Companion to [`ballistics_density_altitude_temperature_c`]: the back-solved station PRESSURE
1336/// (hPa) for the same `(density_altitude_m, explicit_temperature_c)` pair.
1337#[no_mangle]
1338pub extern "C" fn ballistics_density_altitude_pressure_hpa(
1339    density_altitude_m: c_double,
1340    explicit_temperature_c: c_double,
1341) -> c_double {
1342    if !density_altitude_m.is_finite() {
1343        return f64::NAN;
1344    }
1345    let explicit = (!explicit_temperature_c.is_nan()).then_some(explicit_temperature_c);
1346    crate::atmosphere::resolve_atmosphere_for_density_altitude(density_altitude_m, explicit).2
1347}
1348
1349/// Companion to [`ballistics_density_altitude_temperature_c`]: the back-solved station ALTITUDE
1350/// (meters, geometric) for the same `(density_altitude_m, explicit_temperature_c)` pair. This is
1351/// NOT necessarily equal to `density_altitude_m` — it only is when `explicit_temperature_c` is
1352/// [`FFI_NO_EXPLICIT_TEMPERATURE`] (see the Rust doc comment's algebraic identity).
1353#[no_mangle]
1354pub extern "C" fn ballistics_density_altitude_altitude_m(
1355    density_altitude_m: c_double,
1356    explicit_temperature_c: c_double,
1357) -> c_double {
1358    if !density_altitude_m.is_finite() {
1359        return f64::NAN;
1360    }
1361    let explicit = (!explicit_temperature_c.is_nan()).then_some(explicit_temperature_c);
1362    crate::atmosphere::resolve_atmosphere_for_density_altitude(density_altitude_m, explicit).0
1363}
1364
1365/// Largest `marks_len` [`ballistics_hold_point_in_reticle`] will accept (MBA-1361).
1366///
1367/// Mirrors [`MAX_FFI_DRAG_TABLE_LEN`] and exists for the same reason (MBA-1407): the
1368/// export copies a caller-owned array whose length it cannot otherwise verify, so an
1369/// unbounded `len` would let one call request a multi-gigabyte read. It is also
1370/// [`crate::reticle::MAX_RETICLE_MARKS`], so the C ABI and the Rust API reject the same
1371/// inputs. Real reticles carry tens of marks; a dense tree carries a few hundred.
1372pub const MAX_FFI_RETICLE_MARKS: c_int = crate::reticle::MAX_RETICLE_MARKS as c_int;
1373
1374/// `focal_plane` value selecting a FIRST-focal-plane reticle (subtensions constant across
1375/// magnification). Any value other than [`FFI_RETICLE_SECOND_FOCAL_PLANE`] is treated as FFP.
1376pub const FFI_RETICLE_FIRST_FOCAL_PLANE: c_int = 0;
1377/// `focal_plane` value selecting a SECOND-focal-plane reticle (subtensions scale as
1378/// `reference_magnification / magnification`).
1379pub const FFI_RETICLE_SECOND_FOCAL_PLANE: c_int = 1;
1380
1381/// [`ballistics_hold_point_in_reticle`] succeeded and `out` was written.
1382pub const FFI_RETICLE_OK: c_int = 0;
1383/// A null pointer, or a `marks_len` outside `1..=`[`MAX_FFI_RETICLE_MARKS`].
1384pub const FFI_RETICLE_ERR_INVALID_ARGUMENT: c_int = -1;
1385/// `magnification` was not finite and greater than zero.
1386pub const FFI_RETICLE_ERR_MAGNIFICATION: c_int = -2;
1387/// A second-focal-plane call carried a non-finite or non-positive `reference_magnification`.
1388pub const FFI_RETICLE_ERR_REFERENCE_MAGNIFICATION: c_int = -3;
1389/// A mark coordinate, or the supplied firing solution, was not finite.
1390pub const FFI_RETICLE_ERR_NON_FINITE: c_int = -4;
1391
1392/// Where a firing solution lands in a reticle (MBA-1361).
1393///
1394/// A NEW appended struct — no existing `repr(C)` layout is touched by this addition, so
1395/// existing callers need no recompile. All angles are milliradians from the optical
1396/// center; `down` is positive BELOW center and `right` is positive to the shooter's
1397/// RIGHT (see [`crate::reticle`] for the full convention block).
1398#[repr(C)]
1399pub struct FFIReticleHold {
1400    /// True angular milliradians below center. Equals the supplied `drop_mil`.
1401    pub down_mil: c_double,
1402    /// True angular milliradians right of center. Equals the supplied `wind_mil`.
1403    pub right_mil: c_double,
1404    /// Index of the nearest mark in the caller's array, or `-1` when there is none
1405    /// (unreachable today: an empty mark array is rejected before the search).
1406    pub nearest_mark: c_int,
1407    /// Distance from the hold to that mark, milliradians, measured in TRUE angular space
1408    /// (i.e. after second-focal-plane scaling).
1409    pub nearest_mark_distance_mil: c_double,
1410    /// `1` when the hold falls outside the marks' bounding box grown by 20% of its span
1411    /// per axis, `0` otherwise.
1412    pub off_reticle: c_int,
1413    /// The subtension scale applied to the marks: `reference_magnification / magnification`
1414    /// for a second-focal-plane reticle, exactly `1.0` for first focal plane.
1415    pub mark_scale: c_double,
1416}
1417
1418/// Place an angular firing solution in a reticle (MBA-1361).
1419///
1420/// `marks` is a FLAT array of `2 * marks_len` doubles laid out as
1421/// `[down_0, right_0, down_1, right_1, ...]` in NOMINAL milliradians (as etched; for a
1422/// second-focal-plane reticle that means "true at `reference_magnification`").
1423/// `focal_plane` is [`FFI_RETICLE_FIRST_FOCAL_PLANE`] or
1424/// [`FFI_RETICLE_SECOND_FOCAL_PLANE`]; `reference_magnification` is consulted only in the
1425/// second-focal-plane case.
1426///
1427/// Returns [`FFI_RETICLE_OK`] and writes `out` on success, or one of the negative
1428/// `FFI_RETICLE_ERR_*` codes, in which case `out` is left untouched.
1429///
1430/// # Safety
1431///
1432/// `marks` must point to at least `2 * marks_len` readable `double`s and `out` to one
1433/// writable [`FFIReticleHold`]. `marks_len` is validated against
1434/// `1..=`[`MAX_FFI_RETICLE_MARKS`] BEFORE any element is read (MBA-1407 lesson: the
1435/// bound is the only thing standing between a caller typo and an out-of-range read).
1436#[no_mangle]
1437// A newer clippy stable added `chunks_exact_to_as_chunks`, which flags a constant chunk
1438// size and suggests `as_chunks`. Suppressed rather than restructured: this is binary-format
1439// parsing, `as_chunks` changes the element type from `&[u8]` to `&[u8; N]` and so ripples
1440// into every use inside the loop, and the change would land in the middle of a 13-platform
1441// release. `unknown_lints` is allowed alongside it so toolchains predating the lint do not
1442// warn on the name. Adopting `as_chunks` properly is a follow-up.
1443#[allow(unknown_lints, clippy::chunks_exact_to_as_chunks)]
1444pub unsafe extern "C" fn ballistics_hold_point_in_reticle(
1445    drop_mil: c_double,
1446    wind_mil: c_double,
1447    magnification: c_double,
1448    marks: *const c_double,
1449    marks_len: c_int,
1450    focal_plane: c_int,
1451    reference_magnification: c_double,
1452    out: *mut FFIReticleHold,
1453) -> c_int {
1454    use crate::reticle::{
1455        hold_point_in_reticle, FocalPlane, MarkKind, ReticleDescription, ReticleError, ReticleMark,
1456    };
1457
1458    if marks.is_null() || out.is_null() || !(1..=MAX_FFI_RETICLE_MARKS).contains(&marks_len) {
1459        return FFI_RETICLE_ERR_INVALID_ARGUMENT;
1460    }
1461    let count = marks_len as usize;
1462    // Length validated above, so this read stays inside the caller's declared array.
1463    let flat = unsafe { std::slice::from_raw_parts(marks, count * 2) };
1464
1465    let description = ReticleDescription {
1466        name: String::new(),
1467        focal_plane: if focal_plane == FFI_RETICLE_SECOND_FOCAL_PLANE {
1468            FocalPlane::Second
1469        } else {
1470            FocalPlane::First
1471        },
1472        reference_magnification,
1473        marks: flat
1474            .chunks_exact(2)
1475            .map(|pair| ReticleMark::new(pair[0], pair[1], MarkKind::Dot))
1476            .collect(),
1477    };
1478
1479    let hold = match hold_point_in_reticle(drop_mil, wind_mil, magnification, &description) {
1480        Ok(hold) => hold,
1481        Err(ReticleError::NonPositiveMagnification { .. }) => return FFI_RETICLE_ERR_MAGNIFICATION,
1482        Err(ReticleError::NonPositiveReferenceMagnification { .. }) => {
1483            return FFI_RETICLE_ERR_REFERENCE_MAGNIFICATION
1484        }
1485        Err(ReticleError::NonFiniteMark { .. }) | Err(ReticleError::NonFiniteHold { .. }) => {
1486            return FFI_RETICLE_ERR_NON_FINITE
1487        }
1488        Err(_) => return FFI_RETICLE_ERR_INVALID_ARGUMENT,
1489    };
1490
1491    unsafe {
1492        *out = FFIReticleHold {
1493            down_mil: hold.down_mil,
1494            right_mil: hold.right_mil,
1495            nearest_mark: hold.nearest_mark.map_or(-1, |index| index as c_int),
1496            nearest_mark_distance_mil: hold.nearest_mark_distance_mil,
1497            off_reticle: c_int::from(hold.off_reticle),
1498            mark_scale: hold.mark_scale,
1499        };
1500    }
1501    FFI_RETICLE_OK
1502}
1503
1504// Get library version
1505#[no_mangle]
1506pub extern "C" fn ballistics_get_version() -> *const c_char {
1507    // Return a pointer to a static NUL-terminated string (the caller must NOT free it).
1508    // Previously this leaked a freshly-allocated CString on every call and reported a
1509    // stale hardcoded "0.3.0"; use the real crate version with no allocation.
1510    concat!(env!("CARGO_PKG_VERSION"), "\0").as_ptr() as *const c_char
1511}
1512
1513#[cfg(test)]
1514mod tests {
1515    use super::*;
1516
1517    fn valid_trajectory_inputs() -> FFIBallisticInputs {
1518        FFIBallisticInputs {
1519            muzzle_velocity: 800.0,
1520            muzzle_angle: 0.0,
1521            bc_value: 0.5,
1522            bullet_mass: 0.01,
1523            bullet_diameter: 0.00762,
1524            bc_type: 0,
1525            sight_height: 0.05,
1526            target_distance: 1.0,
1527            temperature: 15.0,
1528            twist_rate: 12.0,
1529            is_twist_right: 1,
1530            shooting_angle: 0.0,
1531            altitude: 0.0,
1532            latitude: f64::NAN,
1533            azimuth_angle: 0.0,
1534            use_rk4: 1,
1535            use_adaptive_rk45: 0,
1536            enable_wind_shear: 0,
1537            enable_trajectory_sampling: 0,
1538            sample_interval: 10.0,
1539            enable_pitch_damping: 0,
1540            enable_precession_nutation: 0,
1541            enable_spin_drift: 0,
1542            enable_magnus: 0,
1543            enable_coriolis: 0,
1544            shot_azimuth: 0.0,
1545            cant_angle: 0.0,
1546            zero_poi_vertical: 0.0,
1547            zero_poi_horizontal: 0.0,
1548            sight_offset_lateral: 0.0,
1549        }
1550    }
1551
1552    #[allow(dead_code)]
1553    #[repr(C)]
1554    struct LegacyFFIMonteCarloParams {
1555        num_simulations: c_int,
1556        velocity_std_dev: c_double,
1557        angle_std_dev: c_double,
1558        bc_std_dev: c_double,
1559        wind_speed_std_dev: c_double,
1560        target_distance: c_double,
1561        base_wind_speed: c_double,
1562        base_wind_direction: c_double,
1563        azimuth_std_dev: c_double,
1564    }
1565
1566    #[test]
1567    fn monte_carlo_params_legacy_abi_size_is_unchanged() {
1568        assert_eq!(
1569            std::mem::size_of::<FFIMonteCarloParams>(),
1570            std::mem::size_of::<LegacyFFIMonteCarloParams>()
1571        );
1572        assert_eq!(
1573            std::mem::align_of::<FFIMonteCarloParams>(),
1574            std::mem::align_of::<LegacyFFIMonteCarloParams>()
1575        );
1576    }
1577
1578    /// MBA-1361: the reticle export is APPEND-ONLY — a new struct and a new function.
1579    /// This pins that no pre-existing `repr(C)` layout moved when it landed.
1580    #[test]
1581    fn reticle_addition_does_not_disturb_existing_layouts() {
1582        assert_eq!(
1583            std::mem::size_of::<FFIMonteCarloParams>(),
1584            std::mem::size_of::<LegacyFFIMonteCarloParams>()
1585        );
1586        // The new struct is 6 fields: 4 doubles + 2 ints, C-laid-out.
1587        assert_eq!(std::mem::align_of::<FFIReticleHold>(), 8);
1588    }
1589
1590    /// Asking for shear over the C ABI has to survive model resolution.
1591    ///
1592    /// `FFIBallisticInputs` carries no model name, so a caller that set the flag
1593    /// used to inherit `BallisticInputs`' default `"none"` — and the two solvers
1594    /// read that oppositely. `TrajectorySolver::get_wind_at_altitude` falls
1595    /// unknown names onto `PowerLaw`, so the trajectory path always applied the
1596    /// power law; `fast_integrate` resolves them to `WindShearModel::None` and
1597    /// then drops the model, so the Monte Carlo path applied nothing at all and
1598    /// the flag was silently inert. The assertion that matters is the second one:
1599    /// the name has to be one the fast path KEEPS.
1600    #[test]
1601    fn asking_for_shear_over_the_c_abi_names_a_profile_the_fast_path_keeps() {
1602        let mut inputs = valid_trajectory_inputs();
1603        inputs.enable_wind_shear = 1;
1604
1605        let converted = convert_inputs(&inputs);
1606
1607        assert!(converted.enable_wind_shear);
1608        assert_ne!(
1609            crate::wind_shear::boundary_layer_model_from_name(&converted.wind_shear_model),
1610            crate::wind_shear::WindShearModel::None,
1611            "the fast-integrate path would drop this model and leave the flag inert"
1612        );
1613        // power_law specifically, because that is what the trajectory path has
1614        // always applied for an unset name — this makes the two agree rather than
1615        // moving either one onto a new profile.
1616        assert_eq!(converted.wind_shear_model, "power_law");
1617    }
1618
1619    /// The behaviour the naming exists for: Monte Carlo must actually move.
1620    ///
1621    /// Deterministic by construction — every std dev is zero, so the samples are
1622    /// one repeated trajectory and any difference is the shear itself. The shot
1623    /// is lofted on purpose: `boundary_layer_speed_ratio` floors at 1.0 below
1624    /// H_REF = 10 m, so a flat-fire Monte Carlo is bit-identical either way and
1625    /// would prove nothing.
1626    #[test]
1627    fn shear_moves_the_monte_carlo_result_it_used_to_leave_untouched() {
1628        let mut lofted = valid_trajectory_inputs();
1629        lofted.muzzle_angle = 0.15; // mirrors the engine's own shear fixture: ~186 m apex
1630
1631        // Built independently rather than cloned: FFIBallisticInputs is a public
1632        // C-ABI struct and does not derive Clone, which a test has no business changing.
1633        let mut sheared = valid_trajectory_inputs();
1634        sheared.muzzle_angle = lofted.muzzle_angle;
1635        sheared.enable_wind_shear = 1;
1636
1637        let atmo = FFIAtmosphericConditions {
1638            temperature: 15.0,
1639            pressure: 1013.25,
1640            humidity: 50.0,
1641            altitude: 0.0,
1642        };
1643        let params = FFIMonteCarloParams {
1644            num_simulations: 4,
1645            velocity_std_dev: 0.0,
1646            angle_std_dev: 0.0,
1647            bc_std_dev: 0.0,
1648            wind_speed_std_dev: 0.0,
1649            target_distance: 2500.0,
1650            base_wind_speed: 10.0,
1651            // radians; from the right, so the whole wind is crosswind
1652            base_wind_direction: std::f64::consts::FRAC_PI_2,
1653            azimuth_std_dev: 0.0,
1654        };
1655
1656        unsafe {
1657            let off = ballistics_monte_carlo(&lofted, &atmo, &params);
1658            let on = ballistics_monte_carlo(&sheared, &atmo, &params);
1659            assert!(!off.is_null() && !on.is_null());
1660            assert!((*off).num_results > 0 && (*on).num_results > 0);
1661
1662            // mean_range, not impact_positions_*: those arrays stay unpopulated in
1663            // this configuration (x, y and z are all zero for every sample), so they
1664            // would report "no difference" no matter what the solver did.
1665            let range_off = (*off).mean_range;
1666            let range_on = (*on).mean_range;
1667
1668            assert!(
1669                (range_off - range_on).abs() > 1.0e-2,
1670                "the shear flag must change the Monte Carlo result; it was inert until \
1671                 convert_inputs named a profile: off={range_off} on={range_on}"
1672            );
1673
1674            ballistics_free_monte_carlo_results(off);
1675            ballistics_free_monte_carlo_results(on);
1676        }
1677    }
1678
1679    /// Not asking must stay not asking: the default may not acquire a profile.
1680    #[test]
1681    fn leaving_shear_off_over_the_c_abi_names_no_profile() {
1682        let mut inputs = valid_trajectory_inputs();
1683        inputs.enable_wind_shear = 0;
1684
1685        let converted = convert_inputs(&inputs);
1686
1687        assert!(!converted.enable_wind_shear);
1688        assert_eq!(
1689            crate::wind_shear::boundary_layer_model_from_name(&converted.wind_shear_model),
1690            crate::wind_shear::WindShearModel::None
1691        );
1692    }
1693
1694    fn zeroed_hold() -> FFIReticleHold {
1695        FFIReticleHold {
1696            down_mil: 0.0,
1697            right_mil: 0.0,
1698            nearest_mark: -99,
1699            nearest_mark_distance_mil: -1.0,
1700            off_reticle: -1,
1701            mark_scale: -1.0,
1702        }
1703    }
1704
1705    #[test]
1706    fn ffi_hold_point_matches_the_rust_api_on_both_focal_planes() {
1707        // down/right pairs: center, 2 mil, 4 mil, and a windage dot.
1708        let marks: [c_double; 8] = [0.0, 0.0, 2.0, 0.0, 4.0, 0.0, 2.0, 1.0];
1709        let mut out = zeroed_hold();
1710
1711        // FFP at any magnification: marks are used as etched.
1712        let code = unsafe {
1713            ballistics_hold_point_in_reticle(
1714                4.0,
1715                0.0,
1716                6.0,
1717                marks.as_ptr(),
1718                4,
1719                FFI_RETICLE_FIRST_FOCAL_PLANE,
1720                0.0,
1721                &mut out,
1722            )
1723        };
1724        assert_eq!(code, FFI_RETICLE_OK);
1725        assert_eq!(out.down_mil, 4.0);
1726        assert_eq!(out.nearest_mark, 2);
1727        assert_eq!(out.nearest_mark_distance_mil, 0.0);
1728        assert_eq!(out.mark_scale, 1.0);
1729        assert_eq!(out.off_reticle, 0);
1730
1731        // SFP at half the reference magnification: the 2 mil mark reads 4 mil true.
1732        let mut out = zeroed_hold();
1733        let code = unsafe {
1734            ballistics_hold_point_in_reticle(
1735                4.0,
1736                0.0,
1737                5.0,
1738                marks.as_ptr(),
1739                4,
1740                FFI_RETICLE_SECOND_FOCAL_PLANE,
1741                10.0,
1742                &mut out,
1743            )
1744        };
1745        assert_eq!(code, FFI_RETICLE_OK);
1746        assert_eq!(out.nearest_mark, 1);
1747        assert_eq!(out.nearest_mark_distance_mil, 0.0);
1748        assert_eq!(out.mark_scale, 2.0);
1749    }
1750
1751    /// The MBA-1407 lesson applied to the new export: `marks_len` is validated against a
1752    /// stated bound BEFORE a single element is read, and a null pointer is rejected.
1753    #[test]
1754    fn ffi_hold_point_bounds_check_marks_len_before_reading() {
1755        let marks: [c_double; 4] = [0.0, 0.0, 2.0, 0.0];
1756        let mut out = zeroed_hold();
1757        let call = |len: c_int, ptr: *const c_double, out: &mut FFIReticleHold| unsafe {
1758            ballistics_hold_point_in_reticle(
1759                1.0,
1760                0.0,
1761                10.0,
1762                ptr,
1763                len,
1764                FFI_RETICLE_FIRST_FOCAL_PLANE,
1765                0.0,
1766                out,
1767            )
1768        };
1769
1770        assert_eq!(call(0, marks.as_ptr(), &mut out), FFI_RETICLE_ERR_INVALID_ARGUMENT);
1771        assert_eq!(call(-1, marks.as_ptr(), &mut out), FFI_RETICLE_ERR_INVALID_ARGUMENT);
1772        assert_eq!(
1773            call(MAX_FFI_RETICLE_MARKS + 1, marks.as_ptr(), &mut out),
1774            FFI_RETICLE_ERR_INVALID_ARGUMENT
1775        );
1776        assert_eq!(call(c_int::MAX, marks.as_ptr(), &mut out), FFI_RETICLE_ERR_INVALID_ARGUMENT);
1777        assert_eq!(call(2, std::ptr::null(), &mut out), FFI_RETICLE_ERR_INVALID_ARGUMENT);
1778        // `out` is untouched on every rejection.
1779        assert_eq!(out.nearest_mark, -99);
1780
1781        // A null `out` is rejected too, without reading the marks.
1782        assert_eq!(
1783            unsafe {
1784                ballistics_hold_point_in_reticle(
1785                    1.0,
1786                    0.0,
1787                    10.0,
1788                    marks.as_ptr(),
1789                    2,
1790                    FFI_RETICLE_FIRST_FOCAL_PLANE,
1791                    0.0,
1792                    std::ptr::null_mut(),
1793                )
1794            },
1795            FFI_RETICLE_ERR_INVALID_ARGUMENT
1796        );
1797    }
1798
1799    #[test]
1800    fn ffi_hold_point_maps_each_error_class_to_its_own_code() {
1801        let marks: [c_double; 4] = [0.0, 0.0, 2.0, 0.0];
1802        let bad_marks: [c_double; 4] = [0.0, 0.0, f64::NAN, 0.0];
1803        let mut out = zeroed_hold();
1804        let call = |drop: c_double, mag: c_double, plane: c_int, ref_mag: c_double,
1805                    m: &[c_double], out: &mut FFIReticleHold| unsafe {
1806            ballistics_hold_point_in_reticle(
1807                drop,
1808                0.0,
1809                mag,
1810                m.as_ptr(),
1811                (m.len() / 2) as c_int,
1812                plane,
1813                ref_mag,
1814                out,
1815            )
1816        };
1817
1818        assert_eq!(
1819            call(1.0, 0.0, FFI_RETICLE_FIRST_FOCAL_PLANE, 0.0, &marks, &mut out),
1820            FFI_RETICLE_ERR_MAGNIFICATION
1821        );
1822        assert_eq!(
1823            call(1.0, 10.0, FFI_RETICLE_SECOND_FOCAL_PLANE, 0.0, &marks, &mut out),
1824            FFI_RETICLE_ERR_REFERENCE_MAGNIFICATION
1825        );
1826        assert_eq!(
1827            call(f64::NAN, 10.0, FFI_RETICLE_FIRST_FOCAL_PLANE, 0.0, &marks, &mut out),
1828            FFI_RETICLE_ERR_NON_FINITE
1829        );
1830        assert_eq!(
1831            call(1.0, 10.0, FFI_RETICLE_FIRST_FOCAL_PLANE, 0.0, &bad_marks, &mut out),
1832            FFI_RETICLE_ERR_NON_FINITE
1833        );
1834        assert_eq!(out.nearest_mark, -99, "out stays untouched on every error");
1835    }
1836
1837    /// MBA-1386 scope addition: `bc_type` gains an additive numeric slot (8) for the
1838    /// new RA4 family, appended after the existing 0-7 mapping (G1, G7, G2, G5, G6,
1839    /// G8, GI, GS). No existing caller's value changes meaning; `8` is simply new,
1840    /// and anything still outside 0-8 keeps falling back to G1.
1841    #[test]
1842    fn bc_type_8_maps_to_ra4() {
1843        let mut inputs = valid_trajectory_inputs();
1844        inputs.bc_type = 8;
1845        assert_eq!(convert_inputs(&inputs).bc_type, DragModel::RA4);
1846
1847        // Every pre-existing code is unaffected by the addition.
1848        let expected = [
1849            (0, DragModel::G1),
1850            (1, DragModel::G7),
1851            (2, DragModel::G2),
1852            (3, DragModel::G5),
1853            (4, DragModel::G6),
1854            (5, DragModel::G8),
1855            (6, DragModel::GI),
1856            (7, DragModel::GS),
1857        ];
1858        for (code, model) in expected {
1859            let mut inputs = valid_trajectory_inputs();
1860            inputs.bc_type = code;
1861            assert_eq!(convert_inputs(&inputs).bc_type, model, "code {code}");
1862        }
1863
1864        // Unrecognized codes (including ones above the new 8) still fall back to G1.
1865        for code in [9, 42, -1] {
1866            let mut inputs = valid_trajectory_inputs();
1867            inputs.bc_type = code;
1868            assert_eq!(convert_inputs(&inputs).bc_type, DragModel::G1, "code {code}");
1869        }
1870    }
1871
1872    #[test]
1873    fn null_pointer_contracts_return_sentinels_and_free_safely() {
1874        unsafe {
1875            assert!(ballistics_calculate_trajectory(
1876                std::ptr::null(),
1877                std::ptr::null(),
1878                std::ptr::null(),
1879                1_000.0,
1880                1.0,
1881            )
1882            .is_null());
1883            assert!(ballistics_calculate_zero_angle(
1884                std::ptr::null(),
1885                std::ptr::null(),
1886                std::ptr::null(),
1887                100.0,
1888            )
1889            .is_nan());
1890            assert!(ballistics_calculate_trajectory_with_drag_table(
1891                std::ptr::null(),
1892                std::ptr::null(),
1893                std::ptr::null(),
1894                1_000.0,
1895                1.0,
1896                DECK_MACH.as_ptr(),
1897                DECK_CD_LOW.as_ptr(),
1898                DECK_MACH.len() as c_int,
1899            )
1900            .is_null());
1901            assert!(ballistics_calculate_zero_angle_with_drag_table(
1902                std::ptr::null(),
1903                std::ptr::null(),
1904                std::ptr::null(),
1905                100.0,
1906                DECK_MACH.as_ptr(),
1907                DECK_CD_LOW.as_ptr(),
1908                DECK_MACH.len() as c_int,
1909            )
1910            .is_nan());
1911            assert!(
1912                ballistics_monte_carlo(std::ptr::null(), std::ptr::null(), std::ptr::null(),)
1913                    .is_null()
1914            );
1915            assert!(ballistics_monte_carlo_with_direction_std_dev(
1916                std::ptr::null(),
1917                std::ptr::null(),
1918                std::ptr::null(),
1919                0.1,
1920            )
1921            .is_null());
1922
1923            ballistics_free_trajectory_result(std::ptr::null_mut());
1924            ballistics_free_monte_carlo_results(std::ptr::null_mut());
1925        }
1926    }
1927
1928    #[test]
1929    fn mba1283_ffi_enforces_step_floor_for_every_solver_mode() {
1930        for (mode, use_rk4, use_adaptive_rk45) in [("Euler", 0, 0), ("RK4", 1, 0), ("RK45", 1, 1)] {
1931            for step_size in [
1932                f64::NAN,
1933                f64::INFINITY,
1934                f64::NEG_INFINITY,
1935                -1.0,
1936                -0.0,
1937                0.0,
1938                0.001,
1939                MIN_FFI_STEP_SIZE_MS - 0.001,
1940            ] {
1941                let mut inputs = valid_trajectory_inputs();
1942                inputs.use_rk4 = use_rk4;
1943                inputs.use_adaptive_rk45 = use_adaptive_rk45;
1944                let result = unsafe {
1945                    ballistics_calculate_trajectory(
1946                        &inputs,
1947                        std::ptr::null(),
1948                        std::ptr::null(),
1949                        0.01,
1950                        step_size,
1951                    )
1952                };
1953                assert!(
1954                    result.is_null(),
1955                    "{mode} step_size={step_size:?} bypassed the FFI floor"
1956                );
1957            }
1958
1959            let mut inputs = valid_trajectory_inputs();
1960            inputs.use_rk4 = use_rk4;
1961            inputs.use_adaptive_rk45 = use_adaptive_rk45;
1962            let result = unsafe {
1963                ballistics_calculate_trajectory(
1964                    &inputs,
1965                    std::ptr::null(),
1966                    std::ptr::null(),
1967                    0.01,
1968                    MIN_FFI_STEP_SIZE_MS,
1969                )
1970            };
1971            assert!(
1972                !result.is_null(),
1973                "the documented minimum step must remain usable in {mode}"
1974            );
1975            unsafe {
1976                assert!((*result).point_count >= 0);
1977                assert!((*result).point_count as usize <= crate::MAX_TRAJECTORY_POINTS);
1978                ballistics_free_trajectory_result(result);
1979            }
1980        }
1981    }
1982
1983    /// A tiny valid deck: strictly ascending Mach, positive Cd.
1984    const DECK_MACH: [f64; 4] = [0.5, 1.0, 2.0, 3.0];
1985    /// Deliberately LOW drag so the deck measurably increases impact velocity vs G1.
1986    const DECK_CD_LOW: [f64; 4] = [0.05, 0.08, 0.06, 0.05];
1987
1988    #[test]
1989    fn trajectory_with_drag_table_applies_the_deck() {
1990        let inputs = valid_trajectory_inputs();
1991        unsafe {
1992            let plain = ballistics_calculate_trajectory(
1993                &inputs,
1994                std::ptr::null(),
1995                std::ptr::null(),
1996                300.0,
1997                1.0,
1998            );
1999            let decked = ballistics_calculate_trajectory_with_drag_table(
2000                &inputs,
2001                std::ptr::null(),
2002                std::ptr::null(),
2003                300.0,
2004                1.0,
2005                DECK_MACH.as_ptr(),
2006                DECK_CD_LOW.as_ptr(),
2007                DECK_MACH.len() as c_int,
2008            );
2009            assert!(!plain.is_null() && !decked.is_null());
2010            // The low-drag deck must retain materially more velocity than the G-model.
2011            assert!(
2012                (*decked).impact_velocity > (*plain).impact_velocity + 1.0,
2013                "deck did not change the solve: plain={} decked={}",
2014                (*plain).impact_velocity,
2015                (*decked).impact_velocity
2016            );
2017            ballistics_free_trajectory_result(plain);
2018            ballistics_free_trajectory_result(decked);
2019        }
2020    }
2021
2022    #[test]
2023    fn trajectory_with_drag_table_rejects_invalid_decks() {
2024        let inputs = valid_trajectory_inputs();
2025        let descending = [3.0, 2.0, 1.0, 0.5];
2026        let negative_cd = [0.05, -0.08, 0.06, 0.05];
2027        unsafe {
2028            // null arrays
2029            assert!(ballistics_calculate_trajectory_with_drag_table(
2030                &inputs,
2031                std::ptr::null(),
2032                std::ptr::null(),
2033                300.0,
2034                1.0,
2035                std::ptr::null(),
2036                DECK_CD_LOW.as_ptr(),
2037                4,
2038            )
2039            .is_null());
2040            assert!(ballistics_calculate_trajectory_with_drag_table(
2041                &inputs,
2042                std::ptr::null(),
2043                std::ptr::null(),
2044                300.0,
2045                1.0,
2046                DECK_MACH.as_ptr(),
2047                std::ptr::null(),
2048                4,
2049            )
2050            .is_null());
2051            // too few points
2052            assert!(ballistics_calculate_trajectory_with_drag_table(
2053                &inputs,
2054                std::ptr::null(),
2055                std::ptr::null(),
2056                300.0,
2057                1.0,
2058                DECK_MACH.as_ptr(),
2059                DECK_CD_LOW.as_ptr(),
2060                1,
2061            )
2062            .is_null());
2063            // non-ascending Mach
2064            assert!(ballistics_calculate_trajectory_with_drag_table(
2065                &inputs,
2066                std::ptr::null(),
2067                std::ptr::null(),
2068                300.0,
2069                1.0,
2070                descending.as_ptr(),
2071                DECK_CD_LOW.as_ptr(),
2072                4,
2073            )
2074            .is_null());
2075            // non-positive Cd
2076            assert!(ballistics_calculate_trajectory_with_drag_table(
2077                &inputs,
2078                std::ptr::null(),
2079                std::ptr::null(),
2080                300.0,
2081                1.0,
2082                DECK_MACH.as_ptr(),
2083                negative_cd.as_ptr(),
2084                4,
2085            )
2086            .is_null());
2087            // null inputs still rejected
2088            assert!(ballistics_calculate_trajectory_with_drag_table(
2089                std::ptr::null(),
2090                std::ptr::null(),
2091                std::ptr::null(),
2092                300.0,
2093                1.0,
2094                DECK_MACH.as_ptr(),
2095                DECK_CD_LOW.as_ptr(),
2096                4,
2097            )
2098            .is_null());
2099        }
2100    }
2101
2102    #[test]
2103    fn zero_angle_with_drag_table_applies_the_deck() {
2104        // A realistic zeroing setup: 100 m zero.
2105        let inputs = valid_trajectory_inputs();
2106        unsafe {
2107            let plain =
2108                ballistics_calculate_zero_angle(&inputs, std::ptr::null(), std::ptr::null(), 100.0);
2109            let decked = ballistics_calculate_zero_angle_with_drag_table(
2110                &inputs,
2111                std::ptr::null(),
2112                std::ptr::null(),
2113                100.0,
2114                DECK_MACH.as_ptr(),
2115                DECK_CD_LOW.as_ptr(),
2116                DECK_MACH.len() as c_int,
2117            );
2118            assert!(plain.is_finite() && decked.is_finite());
2119            // A much lower-drag deck needs a flatter (smaller) zero angle; at minimum it
2120            // must differ measurably from the G-model zero.
2121            assert!(
2122                (plain - decked).abs() > 1e-6,
2123                "deck did not change the zero: plain={plain} decked={decked}"
2124            );
2125        }
2126    }
2127
2128    #[test]
2129    fn zero_angle_with_drag_table_rejects_invalid_decks() {
2130        let inputs = valid_trajectory_inputs();
2131        let descending = [3.0, 2.0, 1.0, 0.5];
2132        unsafe {
2133            assert!(ballistics_calculate_zero_angle_with_drag_table(
2134                &inputs,
2135                std::ptr::null(),
2136                std::ptr::null(),
2137                100.0,
2138                std::ptr::null(),
2139                DECK_CD_LOW.as_ptr(),
2140                4,
2141            )
2142            .is_nan());
2143            assert!(ballistics_calculate_zero_angle_with_drag_table(
2144                &inputs,
2145                std::ptr::null(),
2146                std::ptr::null(),
2147                100.0,
2148                DECK_MACH.as_ptr(),
2149                DECK_CD_LOW.as_ptr(),
2150                0,
2151            )
2152            .is_nan());
2153            assert!(ballistics_calculate_zero_angle_with_drag_table(
2154                &inputs,
2155                std::ptr::null(),
2156                std::ptr::null(),
2157                100.0,
2158                descending.as_ptr(),
2159                DECK_CD_LOW.as_ptr(),
2160                4,
2161            )
2162            .is_nan());
2163            // null inputs still rejected
2164            assert!(ballistics_calculate_zero_angle_with_drag_table(
2165                std::ptr::null(),
2166                std::ptr::null(),
2167                std::ptr::null(),
2168                100.0,
2169                DECK_MACH.as_ptr(),
2170                DECK_CD_LOW.as_ptr(),
2171                4,
2172            )
2173            .is_nan());
2174        }
2175    }
2176
2177    #[test]
2178    fn zero_then_fly_with_same_deck_is_consistent() {
2179        // The pair-use case the two exports exist for: zero with the deck, fly with the
2180        // deck at the solved angle; the trajectory must cross near sight height at the
2181        // zero distance (i.e. the two functions share identical deck semantics).
2182        let mut inputs = valid_trajectory_inputs();
2183        unsafe {
2184            let angle = ballistics_calculate_zero_angle_with_drag_table(
2185                &inputs,
2186                std::ptr::null(),
2187                std::ptr::null(),
2188                100.0,
2189                DECK_MACH.as_ptr(),
2190                DECK_CD_LOW.as_ptr(),
2191                DECK_MACH.len() as c_int,
2192            );
2193            assert!(angle.is_finite());
2194            inputs.muzzle_angle = angle;
2195            let result = ballistics_calculate_trajectory_with_drag_table(
2196                &inputs,
2197                std::ptr::null(),
2198                std::ptr::null(),
2199                150.0,
2200                1.0,
2201                DECK_MACH.as_ptr(),
2202                DECK_CD_LOW.as_ptr(),
2203                DECK_MACH.len() as c_int,
2204            );
2205            assert!(!result.is_null());
2206            // Interpolate y at exactly the zero distance (100 m) rather than snapping to the
2207            // nearest raw trajectory sample, so the residual reflects only zero-solver
2208            // convergence, not the sampling grid's x-offset from 100 m.
2209            let zero_distance = 100.0;
2210            let pts = std::slice::from_raw_parts((*result).points, (*result).point_count as usize);
2211            let bracket = pts
2212                .windows(2)
2213                .find(|w| w[0].position_x <= zero_distance && w[1].position_x >= zero_distance)
2214                .expect("trajectory brackets the zero distance");
2215            let (lo, hi) = (&bracket[0], &bracket[1]);
2216            let y_at_zero = if hi.position_x > lo.position_x {
2217                let t = (zero_distance - lo.position_x) / (hi.position_x - lo.position_x);
2218                lo.position_y + t * (hi.position_y - lo.position_y)
2219            } else {
2220                lo.position_y
2221            };
2222            assert!(
2223                (y_at_zero - inputs.sight_height).abs() < 0.002,
2224                "zeroed flight missed the line of sight at 100 m: y={} (sight_height={})",
2225                y_at_zero,
2226                inputs.sight_height
2227            );
2228            ballistics_free_trajectory_result(result);
2229        }
2230    }
2231
2232    #[test]
2233    fn drag_table_len_above_cap_is_rejected() {
2234        // A valid, monotonically increasing deck that is simply too long: the cap
2235        // must reject it BEFORE the to_vec() copies, returning the null sentinel.
2236        let n = (MAX_FFI_DRAG_TABLE_LEN + 1) as usize;
2237        let mach: Vec<f64> = (0..n).map(|i| 0.01 + i as f64 * 0.001).collect();
2238        let cd: Vec<f64> = vec![0.3; n];
2239        let inputs = valid_trajectory_inputs();
2240        unsafe {
2241            let r = ballistics_calculate_trajectory_with_drag_table(
2242                &inputs,
2243                std::ptr::null(),
2244                std::ptr::null(),
2245                300.0,
2246                1.0,
2247                mach.as_ptr(),
2248                cd.as_ptr(),
2249                n as c_int,
2250            );
2251            assert!(r.is_null(), "len {n} must be rejected by the cap");
2252        }
2253    }
2254
2255    #[test]
2256    fn drag_table_len_at_cap_is_accepted() {
2257        let n = MAX_FFI_DRAG_TABLE_LEN as usize;
2258        let mach: Vec<f64> = (0..n).map(|i| 0.01 + i as f64 * 0.001).collect();
2259        let cd: Vec<f64> = vec![0.3; n];
2260        let inputs = valid_trajectory_inputs();
2261        unsafe {
2262            let r = ballistics_calculate_trajectory_with_drag_table(
2263                &inputs,
2264                std::ptr::null(),
2265                std::ptr::null(),
2266                300.0,
2267                1.0,
2268                mach.as_ptr(),
2269                cd.as_ptr(),
2270                n as c_int,
2271            );
2272            assert!(!r.is_null(), "len == cap must be accepted");
2273            ballistics_free_trajectory_result(r);
2274        }
2275    }
2276
2277    #[test]
2278    fn ffi_cant_angle_deflects_laterally() {
2279        let mut level = valid_trajectory_inputs();
2280        level.muzzle_angle = 0.003;
2281        let mut canted = valid_trajectory_inputs();
2282        canted.muzzle_angle = 0.003;
2283        canted.cant_angle = 10f64.to_radians();
2284        unsafe {
2285            let a = ballistics_calculate_trajectory(&level, std::ptr::null(), std::ptr::null(), 400.0, 1.0);
2286            let b = ballistics_calculate_trajectory(&canted, std::ptr::null(), std::ptr::null(), 400.0, 1.0);
2287            assert!(!a.is_null() && !b.is_null());
2288            let za = std::slice::from_raw_parts((*a).points, (*a).point_count as usize).last().unwrap().position_z;
2289            let zb = std::slice::from_raw_parts((*b).points, (*b).point_count as usize).last().unwrap().position_z;
2290            assert!(zb > za + 0.005, "FFI cant must deflect right: level={za} canted={zb}");
2291            ballistics_free_trajectory_result(a);
2292            ballistics_free_trajectory_result(b);
2293        }
2294    }
2295
2296    #[test]
2297    fn ffi_vertical_wind_raises_trajectory() {
2298        let inputs = valid_trajectory_inputs();
2299        let no_wind = FFIWindConditions {
2300            speed: 0.0,
2301            direction: 0.0,
2302            vertical_speed: 0.0,
2303        };
2304        let updraft = FFIWindConditions {
2305            speed: 0.0,
2306            direction: 0.0,
2307            vertical_speed: 5.0,
2308        };
2309        unsafe {
2310            let a = ballistics_calculate_trajectory(&inputs, &no_wind, std::ptr::null(), 400.0, 1.0);
2311            let b = ballistics_calculate_trajectory(&inputs, &updraft, std::ptr::null(), 400.0, 1.0);
2312            assert!(!a.is_null() && !b.is_null());
2313            let ya = std::slice::from_raw_parts((*a).points, (*a).point_count as usize).last().unwrap().position_y;
2314            let yb = std::slice::from_raw_parts((*b).points, (*b).point_count as usize).last().unwrap().position_y;
2315            assert!(yb > ya + 0.01, "FFI updraft must raise the trajectory: no_wind={ya} updraft={yb}");
2316            ballistics_free_trajectory_result(a);
2317            ballistics_free_trajectory_result(b);
2318        }
2319    }
2320
2321    // --- MBA-1356: cd_scale `_scaled` FFI variants ---
2322
2323    #[test]
2324    fn trajectory_scaled_at_one_matches_unscaled_export() {
2325        let inputs = valid_trajectory_inputs();
2326        unsafe {
2327            let unscaled = ballistics_calculate_trajectory_with_drag_table(
2328                &inputs,
2329                std::ptr::null(),
2330                std::ptr::null(),
2331                300.0,
2332                1.0,
2333                DECK_MACH.as_ptr(),
2334                DECK_CD_LOW.as_ptr(),
2335                DECK_MACH.len() as c_int,
2336            );
2337            let scaled = ballistics_calculate_trajectory_with_drag_table_scaled(
2338                &inputs,
2339                std::ptr::null(),
2340                std::ptr::null(),
2341                300.0,
2342                1.0,
2343                DECK_MACH.as_ptr(),
2344                DECK_CD_LOW.as_ptr(),
2345                DECK_MACH.len() as c_int,
2346                1.0,
2347            );
2348            assert!(!unscaled.is_null() && !scaled.is_null());
2349            assert_eq!(
2350                (*unscaled).impact_velocity.to_bits(),
2351                (*scaled).impact_velocity.to_bits(),
2352                "cd_scale=1.0 must be byte-identical to the unscaled export: unscaled={} scaled={}",
2353                (*unscaled).impact_velocity,
2354                (*scaled).impact_velocity
2355            );
2356            ballistics_free_trajectory_result(unscaled);
2357            ballistics_free_trajectory_result(scaled);
2358        }
2359    }
2360
2361    #[test]
2362    fn trajectory_scaled_at_1_10_lowers_impact_velocity() {
2363        let inputs = valid_trajectory_inputs();
2364        unsafe {
2365            let baseline = ballistics_calculate_trajectory_with_drag_table_scaled(
2366                &inputs,
2367                std::ptr::null(),
2368                std::ptr::null(),
2369                300.0,
2370                1.0,
2371                DECK_MACH.as_ptr(),
2372                DECK_CD_LOW.as_ptr(),
2373                DECK_MACH.len() as c_int,
2374                1.0,
2375            );
2376            let scaled_up = ballistics_calculate_trajectory_with_drag_table_scaled(
2377                &inputs,
2378                std::ptr::null(),
2379                std::ptr::null(),
2380                300.0,
2381                1.0,
2382                DECK_MACH.as_ptr(),
2383                DECK_CD_LOW.as_ptr(),
2384                DECK_MACH.len() as c_int,
2385                1.10,
2386            );
2387            assert!(!baseline.is_null() && !scaled_up.is_null());
2388            assert!(
2389                (*scaled_up).impact_velocity < (*baseline).impact_velocity,
2390                "cd_scale=1.10 must increase drag -> lower impact velocity: base={} scaled={}",
2391                (*baseline).impact_velocity,
2392                (*scaled_up).impact_velocity
2393            );
2394            ballistics_free_trajectory_result(baseline);
2395            ballistics_free_trajectory_result(scaled_up);
2396        }
2397    }
2398
2399    #[test]
2400    fn trajectory_scaled_rejects_invalid_cd_scale() {
2401        let inputs = valid_trajectory_inputs();
2402        unsafe {
2403            for bad in [0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
2404                let r = ballistics_calculate_trajectory_with_drag_table_scaled(
2405                    &inputs,
2406                    std::ptr::null(),
2407                    std::ptr::null(),
2408                    300.0,
2409                    1.0,
2410                    DECK_MACH.as_ptr(),
2411                    DECK_CD_LOW.as_ptr(),
2412                    DECK_MACH.len() as c_int,
2413                    bad,
2414                );
2415                assert!(r.is_null(), "cd_scale={bad} must be rejected (null sentinel)");
2416            }
2417        }
2418    }
2419
2420    #[test]
2421    fn zero_angle_scaled_at_one_matches_unscaled_export() {
2422        let inputs = valid_trajectory_inputs();
2423        unsafe {
2424            let unscaled = ballistics_calculate_zero_angle_with_drag_table(
2425                &inputs,
2426                std::ptr::null(),
2427                std::ptr::null(),
2428                100.0,
2429                DECK_MACH.as_ptr(),
2430                DECK_CD_LOW.as_ptr(),
2431                DECK_MACH.len() as c_int,
2432            );
2433            let scaled = ballistics_calculate_zero_angle_with_drag_table_scaled(
2434                &inputs,
2435                std::ptr::null(),
2436                std::ptr::null(),
2437                100.0,
2438                DECK_MACH.as_ptr(),
2439                DECK_CD_LOW.as_ptr(),
2440                DECK_MACH.len() as c_int,
2441                1.0,
2442            );
2443            assert!(unscaled.is_finite() && scaled.is_finite());
2444            assert_eq!(
2445                unscaled.to_bits(),
2446                scaled.to_bits(),
2447                "cd_scale=1.0 must be byte-identical to the unscaled export: unscaled={unscaled} scaled={scaled}"
2448            );
2449        }
2450    }
2451
2452    #[test]
2453    fn zero_angle_scaled_at_1_10_differs_from_baseline() {
2454        let inputs = valid_trajectory_inputs();
2455        unsafe {
2456            let baseline = ballistics_calculate_zero_angle_with_drag_table_scaled(
2457                &inputs,
2458                std::ptr::null(),
2459                std::ptr::null(),
2460                100.0,
2461                DECK_MACH.as_ptr(),
2462                DECK_CD_LOW.as_ptr(),
2463                DECK_MACH.len() as c_int,
2464                1.0,
2465            );
2466            let scaled_up = ballistics_calculate_zero_angle_with_drag_table_scaled(
2467                &inputs,
2468                std::ptr::null(),
2469                std::ptr::null(),
2470                100.0,
2471                DECK_MACH.as_ptr(),
2472                DECK_CD_LOW.as_ptr(),
2473                DECK_MACH.len() as c_int,
2474                1.10,
2475            );
2476            assert!(baseline.is_finite() && scaled_up.is_finite());
2477            // More drag needs a steeper (larger) zero angle to still reach 100 m.
2478            assert!(
2479                scaled_up > baseline,
2480                "cd_scale=1.10 must need a larger zero angle: base={baseline} scaled={scaled_up}"
2481            );
2482        }
2483    }
2484
2485    #[test]
2486    fn zero_angle_scaled_rejects_invalid_cd_scale() {
2487        let inputs = valid_trajectory_inputs();
2488        unsafe {
2489            for bad in [0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
2490                let angle = ballistics_calculate_zero_angle_with_drag_table_scaled(
2491                    &inputs,
2492                    std::ptr::null(),
2493                    std::ptr::null(),
2494                    100.0,
2495                    DECK_MACH.as_ptr(),
2496                    DECK_CD_LOW.as_ptr(),
2497                    DECK_MACH.len() as c_int,
2498                    bad,
2499                );
2500                assert!(angle.is_nan(), "cd_scale={bad} must be rejected (NaN sentinel)");
2501            }
2502        }
2503    }
2504
2505    /// Legacy exports must remain byte-identical: the same deck through the unscaled
2506    /// export must be unaffected by the new cd_scale plumbing (a regression guard
2507    /// alongside the pre-existing, untouched drag-table tests above).
2508    #[test]
2509    fn legacy_drag_table_exports_unaffected_by_cd_scale_plumbing() {
2510        let inputs = valid_trajectory_inputs();
2511        unsafe {
2512            let a = ballistics_calculate_trajectory_with_drag_table(
2513                &inputs,
2514                std::ptr::null(),
2515                std::ptr::null(),
2516                300.0,
2517                1.0,
2518                DECK_MACH.as_ptr(),
2519                DECK_CD_LOW.as_ptr(),
2520                DECK_MACH.len() as c_int,
2521            );
2522            let b = ballistics_calculate_trajectory_with_drag_table(
2523                &inputs,
2524                std::ptr::null(),
2525                std::ptr::null(),
2526                300.0,
2527                1.0,
2528                DECK_MACH.as_ptr(),
2529                DECK_CD_LOW.as_ptr(),
2530                DECK_MACH.len() as c_int,
2531            );
2532            assert!(!a.is_null() && !b.is_null());
2533            assert_eq!((*a).impact_velocity.to_bits(), (*b).impact_velocity.to_bits());
2534            ballistics_free_trajectory_result(a);
2535            ballistics_free_trajectory_result(b);
2536
2537            let za = ballistics_calculate_zero_angle_with_drag_table(
2538                &inputs,
2539                std::ptr::null(),
2540                std::ptr::null(),
2541                100.0,
2542                DECK_MACH.as_ptr(),
2543                DECK_CD_LOW.as_ptr(),
2544                DECK_MACH.len() as c_int,
2545            );
2546            let zb = ballistics_calculate_zero_angle_with_drag_table(
2547                &inputs,
2548                std::ptr::null(),
2549                std::ptr::null(),
2550                100.0,
2551                DECK_MACH.as_ptr(),
2552                DECK_CD_LOW.as_ptr(),
2553                DECK_MACH.len() as c_int,
2554            );
2555            assert!(za.is_finite() && zb.is_finite());
2556            assert_eq!(za.to_bits(), zb.to_bits());
2557        }
2558    }
2559
2560    // ---- MBA-1365: ballistics_bc_for_reference_standard --------------------------------
2561
2562    #[test]
2563    fn bc_for_reference_standard_icao_is_a_byte_identical_no_op() {
2564        let bc = 0.475;
2565        assert_eq!(
2566            ballistics_bc_for_reference_standard(bc, FFI_BC_REFERENCE_ICAO).to_bits(),
2567            bc.to_bits()
2568        );
2569    }
2570
2571    #[test]
2572    fn bc_for_reference_standard_unrecognized_value_falls_back_to_icao() {
2573        // Mirrors convert_inputs' permissive unrecognized-bc_type convention: an unknown
2574        // reference_standard is treated as ICAO (0), not rejected.
2575        let bc = 0.475;
2576        assert_eq!(
2577            ballistics_bc_for_reference_standard(bc, 99).to_bits(),
2578            bc.to_bits()
2579        );
2580    }
2581
2582    #[test]
2583    fn bc_for_reference_standard_army_standard_metro_applies_the_documented_ratio() {
2584        let bc = 0.475;
2585        let converted =
2586            ballistics_bc_for_reference_standard(bc, FFI_BC_REFERENCE_ARMY_STANDARD_METRO);
2587        assert_eq!(converted, bc * crate::constants::ASM_TO_ICAO_BC);
2588        // Smaller BC == more drag under this engine's ICAO-calibrated retardation math.
2589        assert!(converted < bc);
2590    }
2591
2592    // ---- MBA-1397: ballistics_reduce_qnh_pressure + FFIAtmosphericConditions.pressure ---
2593
2594    #[test]
2595    fn reduce_qnh_pressure_matches_the_library_function_and_lowers_pressure() {
2596        let reduced = ballistics_reduce_qnh_pressure(1030.0, 1500.0);
2597        assert_eq!(
2598            reduced,
2599            crate::atmosphere::reduce_qnh_to_station_pressure(1030.0, 1500.0)
2600        );
2601        assert!(reduced < 1030.0);
2602    }
2603
2604    #[test]
2605    fn reduce_qnh_pressure_passes_through_non_finite_inputs() {
2606        assert!(ballistics_reduce_qnh_pressure(f64::NAN, 1500.0).is_nan());
2607        assert_eq!(ballistics_reduce_qnh_pressure(1030.0, f64::INFINITY), 1030.0);
2608    }
2609
2610    /// The FFI trajectory/Monte Carlo exports have always treated
2611    /// `FFIAtmosphericConditions.pressure` as absolute station pressure. A caller declaring a
2612    /// QNH (sea-level-corrected altimeter setting) reading MUST reduce it with
2613    /// `ballistics_reduce_qnh_pressure` before writing `pressure` -- this proves the reduced
2614    /// value actually reaches the solve (a materially different, and correct -- flatter,
2615    /// less-drop -- trajectory than feeding the raw, unreduced QNH straight through, which
2616    /// would silently over-state air density).
2617    #[test]
2618    fn ffi_trajectory_uses_the_reduced_pressure_not_the_raw_qnh() {
2619        let inputs = valid_trajectory_inputs();
2620        let altitude_m = 1500.0;
2621        let qnh_hpa = 1030.0;
2622        let reduced = ballistics_reduce_qnh_pressure(qnh_hpa, altitude_m);
2623        assert!(reduced < qnh_hpa);
2624
2625        let atmo_reduced = FFIAtmosphericConditions {
2626            temperature: 15.0,
2627            pressure: reduced,
2628            humidity: 50.0,
2629            altitude: altitude_m,
2630        };
2631        let atmo_raw_qnh = FFIAtmosphericConditions {
2632            temperature: 15.0,
2633            pressure: qnh_hpa,
2634            humidity: 50.0,
2635            altitude: altitude_m,
2636        };
2637
2638        unsafe {
2639            let a = ballistics_calculate_trajectory(
2640                &inputs,
2641                std::ptr::null(),
2642                &atmo_reduced,
2643                400.0,
2644                1.0,
2645            );
2646            let b = ballistics_calculate_trajectory(
2647                &inputs,
2648                std::ptr::null(),
2649                &atmo_raw_qnh,
2650                400.0,
2651                1.0,
2652            );
2653            assert!(!a.is_null() && !b.is_null());
2654            let drop_a = std::slice::from_raw_parts((*a).points, (*a).point_count as usize)
2655                .last()
2656                .unwrap()
2657                .position_y;
2658            let drop_b = std::slice::from_raw_parts((*b).points, (*b).point_count as usize)
2659                .last()
2660                .unwrap()
2661                .position_y;
2662            assert!(
2663                (drop_a - drop_b).abs() > 1e-6,
2664                "reduced vs. raw-QNH pressure must produce materially different trajectories: \
2665                 {drop_a} vs {drop_b}"
2666            );
2667            ballistics_free_trajectory_result(a);
2668            ballistics_free_trajectory_result(b);
2669        }
2670    }
2671
2672    /// Same proof as above, for the Monte Carlo FFI path (`ballistics_monte_carlo`), which
2673    /// reads `FFIAtmosphericConditions.pressure` into `BallisticInputs.pressure` directly
2674    /// (`ballistics_monte_carlo_impl`) before running the shared `run_monte_carlo_*` core.
2675    #[test]
2676    fn ffi_monte_carlo_uses_the_reduced_pressure_not_the_raw_qnh() {
2677        let inputs = valid_trajectory_inputs();
2678        let altitude_m = 1500.0;
2679        let qnh_hpa = 1030.0;
2680        let reduced = ballistics_reduce_qnh_pressure(qnh_hpa, altitude_m);
2681
2682        let atmo_reduced = FFIAtmosphericConditions {
2683            temperature: 15.0,
2684            pressure: reduced,
2685            humidity: 50.0,
2686            altitude: altitude_m,
2687        };
2688        let atmo_raw_qnh = FFIAtmosphericConditions {
2689            temperature: 15.0,
2690            pressure: qnh_hpa,
2691            humidity: 50.0,
2692            altitude: altitude_m,
2693        };
2694        let params = FFIMonteCarloParams {
2695            num_simulations: 200,
2696            velocity_std_dev: 1.0,
2697            angle_std_dev: 0.0,
2698            bc_std_dev: 0.0,
2699            wind_speed_std_dev: 0.0,
2700            target_distance: f64::NAN,
2701            base_wind_speed: 0.0,
2702            base_wind_direction: 0.0,
2703            azimuth_std_dev: 0.0,
2704        };
2705
2706        unsafe {
2707            let a = ballistics_monte_carlo(&inputs, &atmo_reduced, &params);
2708            let b = ballistics_monte_carlo(&inputs, &atmo_raw_qnh, &params);
2709            assert!(!a.is_null() && !b.is_null());
2710            assert!(
2711                ((*a).mean_range - (*b).mean_range).abs() > 0.5,
2712                "reduced vs. raw-QNH pressure must change MC mean range materially: \
2713                 {} vs {}",
2714                (*a).mean_range,
2715                (*b).mean_range
2716            );
2717            ballistics_free_monte_carlo_results(a);
2718            ballistics_free_monte_carlo_results(b);
2719        }
2720    }
2721
2722    // ---- MBA-1366: ballistics_density_altitude_* + FFIAtmosphericConditions parity --------
2723
2724    #[test]
2725    fn density_altitude_ffi_exports_match_the_library_function() {
2726        let da_m = 1000.0 * 0.3048;
2727        let expected = crate::atmosphere::resolve_atmosphere_for_density_altitude(da_m, None);
2728        assert_eq!(
2729            ballistics_density_altitude_altitude_m(da_m, FFI_NO_EXPLICIT_TEMPERATURE),
2730            expected.0
2731        );
2732        assert_eq!(
2733            ballistics_density_altitude_temperature_c(da_m, FFI_NO_EXPLICIT_TEMPERATURE),
2734            expected.1
2735        );
2736        assert_eq!(
2737            ballistics_density_altitude_pressure_hpa(da_m, FFI_NO_EXPLICIT_TEMPERATURE),
2738            expected.2
2739        );
2740
2741        // With no explicit temperature the resolved altitude must equal the input exactly.
2742        assert!((ballistics_density_altitude_altitude_m(da_m, FFI_NO_EXPLICIT_TEMPERATURE) - da_m).abs() < 1e-6);
2743    }
2744
2745    #[test]
2746    fn density_altitude_ffi_explicit_temperature_is_honored_exactly() {
2747        let da_m = 500.0;
2748        let explicit_temp_c = 30.0;
2749        let expected =
2750            crate::atmosphere::resolve_atmosphere_for_density_altitude(da_m, Some(explicit_temp_c));
2751        assert_eq!(
2752            ballistics_density_altitude_temperature_c(da_m, explicit_temp_c),
2753            explicit_temp_c
2754        );
2755        assert_eq!(
2756            ballistics_density_altitude_temperature_c(da_m, explicit_temp_c),
2757            expected.1
2758        );
2759        assert_eq!(
2760            ballistics_density_altitude_pressure_hpa(da_m, explicit_temp_c),
2761            expected.2
2762        );
2763        assert_eq!(
2764            ballistics_density_altitude_altitude_m(da_m, explicit_temp_c),
2765            expected.0
2766        );
2767    }
2768
2769    #[test]
2770    fn density_altitude_ffi_non_finite_input_returns_nan() {
2771        assert!(
2772            ballistics_density_altitude_temperature_c(f64::INFINITY, FFI_NO_EXPLICIT_TEMPERATURE)
2773                .is_nan()
2774        );
2775        assert!(
2776            ballistics_density_altitude_pressure_hpa(f64::NAN, FFI_NO_EXPLICIT_TEMPERATURE).is_nan()
2777        );
2778        assert!(
2779            ballistics_density_altitude_altitude_m(f64::NEG_INFINITY, FFI_NO_EXPLICIT_TEMPERATURE)
2780                .is_nan()
2781        );
2782    }
2783
2784    /// Same proof shape as the QNH FFI tests above: writing the density-altitude-derived
2785    /// station values into `FFIAtmosphericConditions` before an existing trajectory export
2786    /// reaches the solve (a materially different, lower-density trajectory at a higher DA than
2787    /// at sea level, exactly like the QNH-vs-absolute divergence proof).
2788    #[test]
2789    fn ffi_trajectory_uses_the_density_altitude_derived_station_values() {
2790        let inputs = valid_trajectory_inputs();
2791        let da_m = 3000.0 * 0.3048; // 3000 ft density altitude
2792        let altitude_m =
2793            ballistics_density_altitude_altitude_m(da_m, FFI_NO_EXPLICIT_TEMPERATURE);
2794        let temperature_c =
2795            ballistics_density_altitude_temperature_c(da_m, FFI_NO_EXPLICIT_TEMPERATURE);
2796        let pressure_hpa =
2797            ballistics_density_altitude_pressure_hpa(da_m, FFI_NO_EXPLICIT_TEMPERATURE);
2798
2799        let atmo_da = FFIAtmosphericConditions {
2800            temperature: temperature_c,
2801            pressure: pressure_hpa,
2802            humidity: 50.0,
2803            altitude: altitude_m,
2804        };
2805        let atmo_sea_level = FFIAtmosphericConditions {
2806            temperature: 15.0,
2807            pressure: 1013.25,
2808            humidity: 50.0,
2809            altitude: 0.0,
2810        };
2811
2812        unsafe {
2813            let a = ballistics_calculate_trajectory(
2814                &inputs,
2815                std::ptr::null(),
2816                &atmo_da,
2817                400.0,
2818                1.0,
2819            );
2820            let b = ballistics_calculate_trajectory(
2821                &inputs,
2822                std::ptr::null(),
2823                &atmo_sea_level,
2824                400.0,
2825                1.0,
2826            );
2827            assert!(!a.is_null() && !b.is_null());
2828            let drop_a = std::slice::from_raw_parts((*a).points, (*a).point_count as usize)
2829                .last()
2830                .unwrap()
2831                .position_y;
2832            let drop_b = std::slice::from_raw_parts((*b).points, (*b).point_count as usize)
2833                .last()
2834                .unwrap()
2835                .position_y;
2836            assert!(
2837                (drop_a - drop_b).abs() > 1e-6,
2838                "density-altitude-derived vs sea-level atmosphere must produce materially \
2839                 different trajectories: {drop_a} vs {drop_b}"
2840            );
2841            ballistics_free_trajectory_result(a);
2842            ballistics_free_trajectory_result(b);
2843        }
2844    }
2845}