Skip to main content

ballistics_engine/
fast_trajectory.rs

1//! Fast trajectory solver for longer ranges.
2//!
3//! This is a Rust implementation of the fast fixed-step trajectory solver
4//! that provides significant performance improvements for long-range calculations.
5
6use crate::{
7    atmosphere::{calculate_air_density_cimp, get_local_atmosphere_humid, AtmoSock},
8    bc_estimation::velocity_segment_bc,
9    constants::{G_ACCEL_MPS2, MPS_TO_FPS, STANDARD_AIR_DENSITY},
10    drag::get_drag_coefficient,
11    wind::WindSock,
12    DragModel, InternalBallisticInputs as BallisticInputs,
13};
14use nalgebra::Vector3;
15
16/// Fast solution container matching Python implementation
17#[derive(Debug, Clone)]
18pub struct FastSolution {
19    /// Time points
20    pub t: Vec<f64>,
21    /// State vectors at each time point [6 x n_points]
22    pub y: Vec<Vec<f64>>,
23    /// Event times [target_hit, max_ord, ground_hit]
24    pub t_events: [Vec<f64>; 3],
25    /// Whether integration succeeded
26    pub success: bool,
27}
28
29impl FastSolution {
30    /// Interpolate solution at time t
31    pub fn sol(&self, t_query: &[f64]) -> Vec<Vec<f64>> {
32        let mut result = vec![vec![0.0; t_query.len()]; 6];
33
34        for (i, &tq) in t_query.iter().enumerate() {
35            // Find the right interval using binary search
36            // Use unwrap_or to safely handle NaN values by treating them as greater
37            let idx = match self
38                .t
39                .binary_search_by(|&t| t.partial_cmp(&tq).unwrap_or(std::cmp::Ordering::Greater))
40            {
41                Ok(idx) => idx,
42                Err(idx) => idx,
43            };
44
45            if idx == 0 {
46                // Before first point
47                for (result_component, source_component) in result.iter_mut().zip(&self.y) {
48                    result_component[i] = source_component[0];
49                }
50            } else if idx >= self.t.len() {
51                // After last point
52                for (result_component, source_component) in result.iter_mut().zip(&self.y) {
53                    result_component[i] = source_component[self.t.len() - 1];
54                }
55            } else {
56                // Linear interpolation
57                let t0 = self.t[idx - 1];
58                let t1 = self.t[idx];
59                let span = t1 - t0;
60
61                for (result_component, source_component) in result.iter_mut().zip(&self.y) {
62                    let y0 = source_component[idx - 1];
63                    let y1 = source_component[idx];
64                    result_component[i] = if span.abs() < f64::EPSILON {
65                        y1
66                    } else {
67                        let frac = (tq - t0) / span;
68                        y0 + frac * (y1 - y0)
69                    };
70                }
71            }
72        }
73
74        result
75    }
76
77    /// Convert from row-major to column-major format for compatibility
78    pub fn from_trajectory_data(
79        times: Vec<f64>,
80        states: Vec<[f64; 6]>,
81        t_events: [Vec<f64>; 3],
82    ) -> Self {
83        let n_points = times.len();
84        let mut y = vec![vec![0.0; n_points]; 6];
85
86        for (i, state) in states.iter().enumerate() {
87            for j in 0..6 {
88                y[j][i] = state[j];
89            }
90        }
91
92        FastSolution {
93            t: times,
94            y,
95            t_events,
96            success: true,
97        }
98    }
99
100    /// A clearly-failed solution carrying only the launch state, with `success = false`.
101    /// Used when inputs are too degenerate to integrate (e.g. non-physical atmosphere),
102    /// so callers see `success = false` instead of a stub trajectory reported as success.
103    fn degenerate(initial_state: &[f64; 6]) -> Self {
104        let mut y = vec![Vec::new(); 6];
105        for (j, slot) in y.iter_mut().enumerate() {
106            slot.push(initial_state[j]);
107        }
108        FastSolution {
109            t: vec![0.0],
110            y,
111            t_events: [Vec::new(), Vec::new(), Vec::new()],
112            success: false,
113        }
114    }
115}
116
117fn direct_atmosphere_values(atmo_params: (f64, f64, f64, f64)) -> Option<(f64, f64)> {
118    let (a, b, c, d) = atmo_params;
119    (a.is_finite() && b.is_finite() && c == 0.0 && d == 0.0 && a > 0.0 && a < 2.0 && b > 200.0)
120        .then_some((a, b))
121}
122
123fn stability_atmosphere_params(atmo_params: (f64, f64, f64, f64)) -> (f64, f64, f64, f64) {
124    if let Some((air_density, _)) = direct_atmosphere_values(atmo_params) {
125        // compute_stability_coefficient consumes standard-mode temperature/pressure, whose
126        // Miller correction is rho_ref/rho. At the 15 C reference temperature, scaling pressure
127        // by rho/rho_ref supplies that exact correction without misreading sound speed as temp.
128        (0.0, 15.0, 1013.25 * air_density / STANDARD_AIR_DENSITY, 1.0)
129    } else {
130        atmo_params
131    }
132}
133
134const MAX_STANDARD_DENSITY_RATIO: f64 = 2.0;
135
136/// True if `atmo_params` can yield a finite, positive air density. `atmo_params` has TWO
137/// modes that `compute_derivatives` distinguishes:
138///   * **Standard**: `(base_alt_m, base_temp_c, base_pressure_hPa, base_density_ratio)` —
139///     positive station pressure. Slot 3 is a density RATIO, not humidity, despite the
140///     `humidity` field it lands in via `build_inputs`. A nonpositive ratio means "not supplied"
141///     and falls back to `1.0`; a supplied ratio must be below `2.0`.
142///   * **Direct**: `(air_density, speed_of_sound, 0.0, 0.0)` — slots 2 and 3 are `0.0`
143///     sentinels, with a real density (< 2.0 kg/m³) and speed of sound (> 200 m/s).
144///
145/// A pressure <= 0 that ISN'T the direct-mode sentinel, an overlarge supplied density ratio, or
146/// any non-finite value would yield a non-physical atmosphere, so it is rejected. (Earlier this
147/// guard also rejected legitimate direct-mode input; the direct-mode allowance below fixes that.)
148fn atmo_is_physical(atmo_params: (f64, f64, f64, f64)) -> bool {
149    let (a, b, c, d) = atmo_params;
150    if !(a.is_finite() && b.is_finite() && c.is_finite() && d.is_finite()) {
151        return false;
152    }
153    // Direct-atmosphere mode: (density, speed_of_sound, 0, 0). Constants mirror
154    // derivatives.rs (MAX_REALISTIC_DENSITY = 2.0 kg/m³, MIN_REALISTIC_SPEED_OF_SOUND = 200 m/s).
155    // Standard mode: positive station pressure (hPa), plus either the documented missing-ratio
156    // sentinel or a supplied ratio below the physical ceiling.
157    direct_atmosphere_values(atmo_params).is_some() || (c > 0.0 && d < MAX_STANDARD_DENSITY_RATIO)
158}
159
160#[derive(Debug, Clone, Copy)]
161enum FastAtmosphere {
162    Direct {
163        air_density: f64,
164        speed_of_sound: f64,
165    },
166    Standard {
167        base_density: f64,
168    },
169}
170
171/// Fast trajectory integration parameters
172pub struct FastIntegrationParams {
173    pub horiz: f64,
174    pub vert: f64,
175    pub initial_state: [f64; 6],
176    pub t_span: (f64, f64),
177    /// Dual-mode atmosphere tuple. Standard mode is
178    /// `(base_alt_m, base_temp_c, base_pressure_hPa, base_density_ratio)` (slot 3 is a density
179    /// RATIO, not humidity; nonpositive means "not supplied" and falls back to `1.0`, while a
180    /// supplied ratio must be below `2.0`). Direct mode is
181    /// `(air_density, speed_of_sound, 0.0, 0.0)`.
182    pub atmo_params: (f64, f64, f64, f64),
183    /// MBA-1137: optional downrange-segmented atmosphere. When `Some`, the per-substep drag
184    /// density samples the base (station-referenced) T/P/H for the zone at the current downrange
185    /// distance before applying the altitude lapse. `None` (default) keeps the single-station
186    /// base and — combined with the MBA-1137 density-freeze fix — varies density with altitude only.
187    pub atmo_sock: Option<AtmoSock>,
188}
189
190/// Aerodynamic-jump vertical launch-angle offset (radians) for the fast-integrate path.
191///
192/// Bryan Litz's crosswind estimator (`Y = 0.01*Sg - 0.0024*L + 0.032` MOA/mph) fed by the
193/// engine's Miller Sg. The fast path receives a prebuilt initial velocity (no muzzle angle),
194/// so the caller rotates that velocity by this offset. Returns 0 when the feature is off or
195/// the inputs are degenerate. Crosswind is taken from `wind_speed`/`wind_angle`
196/// (BallisticInputs convention: 0 = headwind, +PI/2 = from the right). MBA-959, EXPERIMENTAL.
197pub fn aerodynamic_jump_launch_offset_rad(
198    inputs: &BallisticInputs,
199    atmo_params: (f64, f64, f64, f64),
200) -> f64 {
201    let crosswind_from_right_mps = inputs.wind_speed * inputs.wind_angle.sin();
202    aerodynamic_jump_launch_offset_for_crosswind_rad(inputs, atmo_params, crosswind_from_right_mps)
203}
204
205fn aerodynamic_jump_launch_offset_for_crosswind_rad(
206    inputs: &BallisticInputs,
207    atmo_params: (f64, f64, f64, f64),
208    crosswind_from_right_mps: f64,
209) -> f64 {
210    if !inputs.enable_aerodynamic_jump {
211        return 0.0;
212    }
213    let diameter = inputs.bullet_diameter;
214    if !(inputs.twist_rate.is_finite()
215        && inputs.twist_rate != 0.0
216        && diameter.is_finite()
217        && diameter > 0.0
218        && inputs.bullet_length.is_finite()
219        && inputs.bullet_length > 0.0
220        && inputs.muzzle_velocity.is_finite())
221    {
222        return 0.0;
223    }
224    let stability_atmo = stability_atmosphere_params(atmo_params);
225    let sg = crate::stability::compute_stability_coefficient(inputs, stability_atmo);
226    if !(sg.is_finite() && sg > 0.0) {
227        return 0.0;
228    }
229    let length_cal = inputs.bullet_length / diameter;
230    const MS_TO_MPH: f64 = 2.236_936_292_054_4;
231    let crosswind_from_right_mph = crosswind_from_right_mps * MS_TO_MPH;
232    let vertical_moa = crate::aerodynamic_jump::litz_crosswind_jump_moa(
233        sg,
234        length_cal,
235        crosswind_from_right_mph,
236        inputs.is_twist_right,
237    );
238    if !vertical_moa.is_finite() {
239        return 0.0;
240    }
241    const MOA_PER_RAD: f64 = 3437.7467707849;
242    vertical_moa / MOA_PER_RAD
243}
244
245/// Rotate a McCoy-frame state's velocity (indices 3..6) by `theta_rad` in the vertical
246/// (downrange–vertical) plane, preserving speed and horizontal heading. Positive = up.
247fn rotate_launch_velocity(state: &mut [f64; 6], theta_rad: f64) {
248    let (vx, vy, vz) = (state[3], state[4], state[5]);
249    let speed = (vx * vx + vy * vy + vz * vz).sqrt();
250    if speed <= 0.0 {
251        return;
252    }
253    let h = (vx * vx + vz * vz).sqrt(); // horizontal (downrange+lateral) speed
254    let new_elev = vy.atan2(h) + theta_rad;
255    state[4] = speed * new_elev.sin();
256    let new_h = speed * new_elev.cos();
257    let scale = if h > 1e-12 { new_h / h } else { 0.0 };
258    state[3] = vx * scale;
259    state[5] = vz * scale;
260}
261
262fn launch_state_with_aerodynamic_jump(
263    inputs: &BallisticInputs,
264    atmo_params: (f64, f64, f64, f64),
265    segmented_crosswind_from_right_mps: Option<f64>,
266    mut initial_state: [f64; 6],
267) -> [f64; 6] {
268    let offset = match segmented_crosswind_from_right_mps {
269        Some(crosswind) => {
270            aerodynamic_jump_launch_offset_for_crosswind_rad(inputs, atmo_params, crosswind)
271        }
272        None => aerodynamic_jump_launch_offset_rad(inputs, atmo_params),
273    };
274    if offset != 0.0 {
275        rotate_launch_velocity(&mut initial_state, offset);
276    }
277    initial_state
278}
279
280/// Fast fixed-step integration for longer trajectories
281pub fn fast_integrate(
282    inputs: &BallisticInputs,
283    wind_sock: &WindSock,
284    params: FastIntegrationParams,
285) -> FastSolution {
286    // Malformed wind or a degenerate atmosphere would otherwise silently stub or poison the run.
287    if wind_sock.validate_segments().is_err() || !atmo_is_physical(params.atmo_params) {
288        return FastSolution::degenerate(&params.initial_state);
289    }
290    let mut effective_inputs = inputs.clone();
291    // MBA-1415: this is a public entry point that external bindings call directly, bypassing
292    // TrajectorySolver::new. It must therefore carry every input-conditioning step itself, or a
293    // caller setting a conditioned field gets no error and no effect. Idempotent, so inputs that
294    // already passed through a solver are unaffected.
295    effective_inputs.normalize_for_solve();
296    if params.atmo_params.2 > 0.0 {
297        effective_inputs.altitude = params.atmo_params.0;
298        effective_inputs.temperature = params.atmo_params.1;
299        effective_inputs.pressure = params.atmo_params.2;
300        effective_inputs.humidity = params.atmo_params.3;
301    }
302    let inputs = &effective_inputs;
303    // Extract parameters
304    let _mass_kg = inputs.bullet_mass; // SI (kg)
305    let bc = inputs.bc_value;
306    let drag_model = &inputs.bc_type;
307
308    // Check for BC segments
309    let has_bc_segments =
310        inputs.bc_segments.is_some() && !inputs.bc_segments.as_ref().unwrap().is_empty();
311    let has_bc_segments_data =
312        inputs.bc_segments_data.is_some() && !inputs.bc_segments_data.as_ref().unwrap().is_empty();
313
314    // Time step - adjust based on distance
315    let dt = if params.horiz > 200.0 {
316        0.001
317    } else if params.horiz > 100.0 {
318        0.0005
319    } else {
320        0.0001
321    };
322
323    // MBA-959: aerodynamic jump perturbs the prebuilt launch velocity vertically (this path is
324    // handed an initial_state, not a muzzle angle). A no-op returning the original when disabled.
325    let segmented_crosswind_from_right_mps = if inputs.enable_aerodynamic_jump {
326        wind_sock.muzzle_crosswind_from_right_mps()
327    } else {
328        None
329    };
330    let initial_state = launch_state_with_aerodynamic_jump(
331        inputs,
332        params.atmo_params,
333        segmented_crosswind_from_right_mps,
334        params.initial_state,
335    );
336    let vx = initial_state[3]; // horizontal (downrange) velocity
337
338    // MBA-1145: decouple the integration-loop ceiling from the pre-allocation heuristic.
339    // Previously t_max = min(4*horiz/vx, t_span.1) bounded BOTH the Vec sizing AND the loop
340    // itself, so the 4x-horiz/vx estimate doubled as the loop cap. That estimate is only a
341    // heuristic — extreme high-drag or high-launch-angle shots exceed it, and the loop then
342    // terminated BEFORE hit_target/hit_ground, silently truncating the trajectory tail (Monte
343    // Carlo reported impact metrics short of the real range). The loop already breaks on
344    // hit_target (pos.x >= horiz) and hit_ground (pos.y <= ground_threshold), and any real
345    // trajectory descends below the ground threshold within a few seconds of apex, so the loop
346    // bound's only job is a runaway safety ceiling: use the full t_span.1 (default 30 s). The
347    // 4x estimate is retained ONLY to size the pre-allocation (keeps the small-allocation fast
348    // path for short shots); the Vec grows for the rare long run because the loop bound is n_steps.
349    let n_steps = ((params.t_span.1 / dt) as usize) + 1;
350    let est_steps = if vx > 1e-6 && params.horiz > 0.0 {
351        (((4.0 * params.horiz / vx) / dt) as usize) + 1
352    } else {
353        n_steps
354    };
355    let cap = est_steps.min(n_steps);
356    let mut times = Vec::with_capacity(cap);
357    let mut states = Vec::with_capacity(cap);
358
359    // Initial state (with the aerodynamic-jump launch perturbation applied above)
360    times.push(0.0);
361    states.push(initial_state);
362
363    // Direct mode supplies a fixed density and speed of sound. Standard mode supplies station
364    // conditions plus base_ratio; its local density/sound speed are lapsed at every substep.
365    // Guard a missing standard-mode ratio by falling back to sea-level density (MBA-1157 owns
366    // stricter validation of that separate contract).
367    let atmosphere =
368        if let Some((air_density, speed_of_sound)) = direct_atmosphere_values(params.atmo_params) {
369            FastAtmosphere::Direct {
370                air_density,
371                speed_of_sound,
372            }
373        } else {
374            let base_density = if params.atmo_params.3 > 0.0 {
375                params.atmo_params.3 * 1.225
376            } else {
377                1.225
378            };
379            FastAtmosphere::Standard { base_density }
380        };
381
382    // MBA-1137: borrow the optional downrange-segmented atmosphere once (queried 4x per step).
383    let atmo_sock = params.atmo_sock.as_ref();
384
385    // Hoist invariants out of compute_derivatives (called 4x per step). Both the drag-model name
386    // and the projectile shape depend only on inputs, not on state/mach, so computing them per
387    // call wasted an allocation + heuristic every k1..k4. Mirrors cli_api.rs exactly.
388
389    // Drag-model name as a borrowed &'static str. DragModel's Display goes via Debug, which
390    // heap-allocates a String on every call; this match is bit-identical (Display == Debug ==
391    // variant name) with no per-step allocation.
392    let drag_model_str: &str = match drag_model {
393        DragModel::G1 => "G1",
394        DragModel::G2 => "G2",
395        DragModel::G5 => "G5",
396        DragModel::G6 => "G6",
397        DragModel::G7 => "G7",
398        DragModel::G8 => "G8",
399        DragModel::GI => "GI",
400        DragModel::GS => "GS",
401        DragModel::RA4 => "RA4",
402    };
403
404    // SI fallbacks for caliber/weight (SI-only MC callers may leave the imperial fields 0).
405    let caliber_in = if inputs.caliber_inches > 0.0 {
406        inputs.caliber_inches
407    } else {
408        inputs.bullet_diameter / 0.0254
409    };
410    let weight_gr = if inputs.weight_grains > 0.0 {
411        inputs.weight_grains
412    } else {
413        inputs.bullet_mass / crate::constants::GRAINS_TO_KG
414    };
415
416    // Projectile shape for transonic corrections (MBA-949: shared resolver — bullet_model name
417    // first, then the caliber/weight/drag-model heuristic).
418    let projectile_shape = crate::transonic_drag::resolve_projectile_shape(
419        inputs.bullet_model.as_deref(),
420        caliber_in,
421        weight_gr,
422        drag_model_str,
423    );
424
425    // Coriolis omega (Earth rotation), hoisted (invariant over the flight). MBA-957:
426    // fast_integrate — the Monte Carlo / Python-binding path — previously applied NO Coriolis.
427    // First project into level downrange/up/lateral axes: azimuth 0 = North; omega.Z is NEGATIVE
428    // (Omega.East = -Omega cos(lat) sin(az)). The derivative kernel then projects this vector into
429    // the inclined shot frame and applies the physical -2 Omega x v.
430    let omega_vector = match inputs.latitude {
431        Some(latitude) if inputs.enable_coriolis => {
432            let omega_earth = 7.2921159e-5_f64; // rad/s
433            let lat = latitude.to_radians();
434            let az = inputs.shot_azimuth; // compass bearing (0=N), NOT the aiming offset
435            Some(Vector3::new(
436                omega_earth * lat.cos() * az.cos(),  // X: downrange
437                omega_earth * lat.sin(),             // Y: vertical
438                -omega_earth * lat.cos() * az.sin(), // Z: lateral (corrected sign)
439            ))
440        }
441        _ => None,
442    };
443    // Parse the string model once; the derivative kernel is called four times per RK4 step.
444    let wind_shear_model = if inputs.enable_wind_shear {
445        let model = crate::wind_shear::boundary_layer_model_from_name(&inputs.wind_shear_model);
446        (model != crate::wind_shear::WindShearModel::None).then_some(model)
447    } else {
448        None
449    };
450
451    // Integration loop
452    let mut hit_target = false;
453    let mut hit_ground = false;
454    let mut max_ord_time = None;
455    let mut max_ord_y = 0.0;
456    let ground_threshold = inputs.ground_threshold;
457
458    // RK4 integration
459    for i in 0..n_steps - 1 {
460        let t = i as f64 * dt;
461        let state = states[i];
462
463        let pos = Vector3::new(state[0], state[1], state[2]);
464        let _vel = Vector3::new(state[3], state[4], state[5]);
465
466        // Check termination conditions (X is downrange, McCoy)
467        if pos.x >= params.horiz {
468            hit_target = true;
469            break;
470        }
471
472        if pos.y <= ground_threshold {
473            hit_ground = true;
474            break;
475        }
476
477        // Track maximum ordinate
478        if pos.y > max_ord_y {
479            max_ord_y = pos.y;
480            max_ord_time = Some(t);
481        }
482
483        // RK4 step
484        let k1 = compute_derivatives(
485            &state,
486            inputs,
487            wind_sock,
488            atmosphere,
489            drag_model,
490            projectile_shape,
491            bc,
492            has_bc_segments,
493            has_bc_segments_data,
494            omega_vector,
495            wind_shear_model,
496            atmo_sock,
497        );
498
499        let mut state2 = state;
500        for j in 0..6 {
501            state2[j] = state[j] + 0.5 * dt * k1[j];
502        }
503        let k2 = compute_derivatives(
504            &state2,
505            inputs,
506            wind_sock,
507            atmosphere,
508            drag_model,
509            projectile_shape,
510            bc,
511            has_bc_segments,
512            has_bc_segments_data,
513            omega_vector,
514            wind_shear_model,
515            atmo_sock,
516        );
517
518        let mut state3 = state;
519        for j in 0..6 {
520            state3[j] = state[j] + 0.5 * dt * k2[j];
521        }
522        let k3 = compute_derivatives(
523            &state3,
524            inputs,
525            wind_sock,
526            atmosphere,
527            drag_model,
528            projectile_shape,
529            bc,
530            has_bc_segments,
531            has_bc_segments_data,
532            omega_vector,
533            wind_shear_model,
534            atmo_sock,
535        );
536
537        let mut state4 = state;
538        for j in 0..6 {
539            state4[j] = state[j] + dt * k3[j];
540        }
541        let k4 = compute_derivatives(
542            &state4,
543            inputs,
544            wind_sock,
545            atmosphere,
546            drag_model,
547            projectile_shape,
548            bc,
549            has_bc_segments,
550            has_bc_segments_data,
551            omega_vector,
552            wind_shear_model,
553            atmo_sock,
554        );
555
556        // Update state
557        let mut new_state = state;
558        for j in 0..6 {
559            new_state[j] = state[j] + dt * (k1[j] + 2.0 * k2[j] + 2.0 * k3[j] + k4[j]) / 6.0;
560        }
561
562        if state[0] < params.horiz && new_state[0] >= params.horiz {
563            // Keep every terminal metric on the requested target plane. The former top-of-loop
564            // check retained this full-step endpoint, biasing time, drop, and velocity past it.
565            let alpha = (params.horiz - state[0]) / (new_state[0] - state[0]);
566            let mut target_state = state;
567            for j in 0..6 {
568                target_state[j] = state[j] + alpha * (new_state[j] - state[j]);
569            }
570            target_state[0] = params.horiz;
571            times.push(t + alpha * dt);
572            states.push(target_state);
573            hit_target = true;
574            break;
575        }
576
577        times.push(t + dt);
578        states.push(new_state);
579    }
580
581    // Create event arrays
582    let t_events = [
583        if hit_target {
584            vec![*times.last().unwrap()]
585        } else {
586            vec![]
587        },
588        if let Some(t) = max_ord_time {
589            vec![t]
590        } else {
591            vec![]
592        },
593        if hit_ground {
594            vec![*times.last().unwrap()]
595        } else {
596            vec![]
597        },
598    ];
599
600    // MBA-1134 (rank 10) — regression fix: apply the canonical empirical Litz drift as a
601    // post-process to the lateral (McCoy Z) here too. The derivatives kernel no longer
602    // integrates spin drift, and this plain fast_integrate is the single-shot fast path
603    // (solve_trajectory_rust / the API), so without this it would carry NO spin drift and
604    // twist direction would have no effect (the Magnus term is also suppressed when
605    // use_enhanced_spin_drift is set). Mirrors fast_integrate_with_segments,
606    // cli_api::apply_spin_drift and the Monte-Carlo path so all solver families agree; uses
607    // the SAME muzzle Sg (spin_drift::effective_sg_from_inputs).
608    if inputs.use_enhanced_spin_drift {
609        // Standard-mode atmo_params is (base_alt, temp_c, press_hpa, ratio); direct mode
610        // (density, sound, 0, 0) carries no explicit temp/pressure, so fall back to sea-level
611        // standard (the Sg density correction is a no-op there).
612        let (sd_temp_c, sd_press_hpa) = if params.atmo_params.2 > 0.0 {
613            (params.atmo_params.1, params.atmo_params.2)
614        } else {
615            (15.0, 1013.25)
616        };
617        let sg = crate::spin_drift::effective_sg_from_inputs(inputs, sd_temp_c, sd_press_hpa);
618        for (t, state) in times.iter().zip(states.iter_mut()) {
619            if *t > 0.0 {
620                state[2] += crate::spin_drift::litz_drift_meters(sg, *t, inputs.is_twist_right);
621            }
622        }
623    }
624
625    FastSolution::from_trajectory_data(times, states, t_events)
626}
627
628fn fast_magnus_acceleration(
629    inputs: &BallisticInputs,
630    air_velocity: Vector3<f64>,
631    air_density: f64,
632    mach: f64,
633    gravity_acceleration: Vector3<f64>,
634) -> Vector3<f64> {
635    if !inputs.enable_magnus
636        || inputs.use_enhanced_spin_drift
637        || inputs.bullet_diameter <= 0.0
638        || inputs.twist_rate <= 0.0
639        || inputs.bullet_mass <= 0.0
640    {
641        return Vector3::zeros();
642    }
643
644    let speed_air = air_velocity.norm();
645    let diameter_m = inputs.bullet_diameter;
646    let (spin_rate_rad_s, spin_param) = crate::spin_drift::calculate_magnus_spin_state(
647        inputs.muzzle_velocity,
648        speed_air,
649        inputs.twist_rate,
650        diameter_m,
651    );
652    let d_in = if inputs.caliber_inches > 0.0 {
653        inputs.caliber_inches
654    } else {
655        diameter_m / 0.0254
656    };
657    let m_gr = if inputs.weight_grains > 0.0 {
658        inputs.weight_grains
659    } else {
660        inputs.bullet_mass / crate::constants::GRAINS_TO_KG
661    };
662    let l_in = if inputs.bullet_length > 0.0 {
663        inputs.bullet_length / 0.0254
664    } else {
665        let estimated = crate::stability::estimate_bullet_length_m(diameter_m, inputs.bullet_mass);
666        if estimated > 0.0 {
667            estimated / 0.0254
668        } else {
669            4.5 * d_in.max(1e-9)
670        }
671    };
672    let sg = crate::spin_drift::calculate_dynamic_stability(
673        m_gr,
674        speed_air,
675        spin_rate_rad_s,
676        d_in,
677        l_in,
678        air_density,
679    );
680    let (yaw_rad, _) = crate::spin_drift::calculate_yaw_of_repose(
681        sg,
682        speed_air,
683        spin_rate_rad_s,
684        0.0,
685        0.0,
686        air_density,
687        d_in,
688        l_in,
689        m_gr,
690        mach,
691        "match",
692        false,
693    );
694    let area = std::f64::consts::PI * (diameter_m / 2.0).powi(2);
695    let c_np = crate::derivatives::calculate_magnus_moment_coefficient(mach);
696    let force = 0.5 * air_density * speed_air.powi(2) * area * c_np * spin_param * yaw_rad.sin();
697    if force <= 1e-12 {
698        return Vector3::zeros();
699    }
700
701    crate::derivatives::yaw_of_repose_magnus_direction(
702        air_velocity,
703        gravity_acceleration,
704        inputs.is_twist_right,
705    )
706    .map_or_else(Vector3::zeros, |direction| {
707        (force / inputs.bullet_mass) * direction
708    })
709}
710
711fn interpolated_vertical_apex(
712    previous_time: f64,
713    previous: &[f64; 6],
714    current_time: f64,
715    current: &[f64; 6],
716) -> Option<(f64, [f64; 6])> {
717    let dt = current_time - previous_time;
718    let previous_vy = previous[4];
719    let current_vy = current[4];
720    if !dt.is_finite()
721        || dt <= 0.0
722        || !previous_vy.is_finite()
723        || !current_vy.is_finite()
724        || previous_vy <= 0.0
725        || current_vy > 0.0
726    {
727        return None;
728    }
729
730    let denominator = previous_vy - current_vy;
731    if !denominator.is_finite() || denominator <= 0.0 {
732        return None;
733    }
734    let alpha = previous_vy / denominator;
735    // An exact endpoint root is already retained as the current saved point. Only synthesize a
736    // strictly interior point so the solution remains ordered without duplicate event times.
737    if !alpha.is_finite() || !(0.0..1.0).contains(&alpha) {
738        return None;
739    }
740
741    let mut apex = [0.0; 6];
742    for component in 0..6 {
743        apex[component] = previous[component] + alpha * (current[component] - previous[component]);
744    }
745
746    // Cubic Hermite interpolation uses each endpoint's position and velocity, avoiding the
747    // chord-height bias that linear interpolation has around a stationary point.
748    let alpha2 = alpha * alpha;
749    let alpha3 = alpha2 * alpha;
750    let h00 = 2.0 * alpha3 - 3.0 * alpha2 + 1.0;
751    let h10 = alpha3 - 2.0 * alpha2 + alpha;
752    let h01 = -2.0 * alpha3 + 3.0 * alpha2;
753    let h11 = alpha3 - alpha2;
754    for axis in 0..3 {
755        apex[axis] = h00 * previous[axis]
756            + h10 * dt * previous[axis + 3]
757            + h01 * current[axis]
758            + h11 * dt * current[axis + 3];
759    }
760    apex[4] = 0.0;
761
762    apex.iter()
763        .all(|component| component.is_finite())
764        .then_some((previous_time + alpha * dt, apex))
765}
766
767/// Compute derivatives for the state vector
768#[allow(clippy::too_many_arguments)]
769fn compute_derivatives(
770    state: &[f64; 6],
771    inputs: &BallisticInputs,
772    wind_sock: &WindSock,
773    atmosphere: FastAtmosphere,
774    drag_model: &DragModel,
775    projectile_shape: crate::transonic_drag::ProjectileShape,
776    bc: f64,
777    has_bc_segments: bool,
778    has_bc_segments_data: bool,
779    omega: Option<Vector3<f64>>,
780    wind_shear_model: Option<crate::wind_shear::WindShearModel>,
781    // MBA-1137: optional downrange-segmented atmosphere (zone base swapped by pos.x before lapse).
782    atmo_sock: Option<&AtmoSock>,
783) -> [f64; 6] {
784    let pos = Vector3::new(state[0], state[1], state[2]);
785    let vel = Vector3::new(state[3], state[4], state[5]);
786
787    // Resolve the cached downrange wind in level axes, then apply boundary-layer shear using
788    // height gained above launch. Site elevation is MSL and intentionally does not enter shear.
789    let level_wind = wind_sock.vector_for_range_stateless(pos.x);
790    let level_wind = if let Some(model) = wind_shear_model {
791        let height_rel_launch =
792            crate::atmosphere::shot_frame_altitude(0.0, pos.x, pos.y, inputs.shooting_angle);
793        crate::wind_shear::apply_boundary_layer_shear(level_wind, height_rel_launch, model)
794    } else {
795        level_wind
796    };
797    let wind_vector =
798        crate::derivatives::level_vector_to_shot_frame(level_wind, inputs.shooting_angle);
799
800    // Velocity relative to air
801    let vel_adjusted = vel - wind_vector;
802    let v_mag = vel_adjusted.norm();
803
804    // Gravity acceleration vector, rotated into the shot-aligned frame by shooting_angle
805    // (uphill/downhill inclined fire), matching cli_api::TrajectorySolver::gravity_acceleration.
806    let theta = inputs.shooting_angle;
807    let accel_gravity = Vector3::new(
808        -G_ACCEL_MPS2 * theta.sin(),
809        -G_ACCEL_MPS2 * theta.cos(),
810        0.0,
811    );
812
813    // Calculate acceleration
814    let mut accel = if v_mag < 1e-6 {
815        accel_gravity
816    } else {
817        // Calculate drag
818        let v_fps = v_mag * MPS_TO_FPS;
819
820        // Resolve LOCAL density and speed of sound. Direct mode uses its supplied fixed values;
821        // standard mode evaluates the substep altitude with the lapse-rate pipeline.
822        // `inputs.temperature`/`inputs.pressure` are the standard-mode base (station) T/P set by
823        // fast_integrate from atmo_params; `base_density` is the station-altitude density, so
824        // `base_density / 1.225` recovers the station base_ratio the lapse pipeline expects.
825        //
826        // MBA-1137 (density-freeze fix): previously ONLY the speed of sound was taken from this
827        // call and `density_scale` used the flight-constant `base_density`, so the fast/MC path
828        // held density frozen for the whole flight (density did NOT vary with altitude — a latent
829        // bug the cli_api/derivatives paths already avoid). Now the LOCAL density is used for
830        // `density_scale` below, so the fast path varies density with altitude too.
831        //
832        // MBA-1137 (zones): when a downrange-segmented atmosphere is present, swap the BASE
833        // (station-referenced) temp/pressure/ratio for the zone at the current downrange distance
834        // (pos.x), recomputing the zone base_ratio via CIPM, BEFORE the altitude lapse — so
835        // downrange-zone selection and the world-vertical lapse compose without double-counting.
836        // `None` keeps the single-station base.
837        //
838        // Humidity is NOT plumbed to this call site: on the fast path (fast_integrate) the
839        // `humidity` FIELD is overwritten with atmo_params.3 (the density RATIO), so
840        // `inputs.humidity` is not a real RH — pass 0.0 (dry) rather than fabricate.
841        let (local_density, speed_of_sound) = match atmosphere {
842            FastAtmosphere::Direct {
843                air_density,
844                speed_of_sound,
845            } => (air_density, speed_of_sound),
846            FastAtmosphere::Standard { base_density } => {
847                let altitude = crate::atmosphere::shot_frame_altitude(
848                    inputs.altitude,
849                    pos.x,
850                    pos.y,
851                    inputs.shooting_angle,
852                );
853                let (base_temp_c, base_press_hpa, base_ratio) = match atmo_sock {
854                    Some(sock) => {
855                        let (zt, zp, zh) = sock.atmo_for_range(pos.x);
856                        (zt, zp, calculate_air_density_cimp(zt, zp, zh) / 1.225)
857                    }
858                    None => (inputs.temperature, inputs.pressure, base_density / 1.225),
859                };
860                get_local_atmosphere_humid(
861                    altitude,
862                    inputs.altitude, // base_alt approximation
863                    base_temp_c,
864                    base_press_hpa,
865                    base_ratio,
866                    0.0, // humidity not available here (see note above)
867                )
868            }
869        };
870        let mach = v_mag / speed_of_sound;
871
872        // Get BC value (potentially from segments)
873        let bc_current = match (
874            inputs.bc_segments_data.as_ref(),
875            inputs.bc_segments.as_ref(),
876        ) {
877            (Some(segments_data), _) if inputs.use_bc_segments && has_bc_segments_data => {
878                velocity_segment_bc(v_fps, segments_data, bc)
879            }
880            (_, Some(segments)) if has_bc_segments => {
881                crate::derivatives::interpolated_bc(mach, segments, Some(inputs))
882            }
883            _ => bc,
884        };
885        // Guard bc_value == 0 (allowed on FFI/WASM/public MC surfaces): the division below
886        // would be Inf -> NaN. Mirrors cli_api's effective_bc.max(1e-6); inert for valid BCs.
887        let bc_current = bc_current.max(1e-6);
888
889        // Apply the transonic drag-rise correction once (mirrors derivatives.rs / cli_api) so
890        // the Monte Carlo / fast path doesn't under-predict drag near Mach 1. The projectile
891        // shape is invariant for the whole integration, so it is hoisted into fast_integrate and
892        // passed in rather than recomputed per call. wave_drag=false: the G1/G7 tables already
893        // embed the rise.
894        // MBA-940: a user-supplied custom drag table is the final Cd, used as-is (no G-model
895        // lookup, transonic, or form-factor correction — the curve already encodes the true drag).
896        // Its Cd is the projectile's ACTUAL drag coefficient, so the retardation denominator
897        // must be the sectional density (lb/in²), not a BC: Cd_own / SD == Cd_ref / BC
898        // (see BallisticInputs::custom_drag_denominator).
899        let (drag_factor, retard_denom) = if let Some(ref table) = inputs.custom_drag_table {
900            (
901                // MBA-1357: cd_scale is a single whole-curve drag multiplier applied here, at
902                // the Cd lookup site. The Mach-keyed DSF table (truing_dsf.rs) is a SEPARATE,
903                // drop-only post-processing correction applied to a solved TrajectoryResult's
904                // points after integration finishes — it never touches this drag computation.
905                table.interpolate(mach) * inputs.cd_scale,
906                inputs.custom_drag_denominator(bc_current),
907            )
908        } else {
909            let base_cd = get_drag_coefficient(mach, drag_model);
910            let cd =
911                crate::transonic_drag::transonic_correction(mach, base_cd, projectile_shape, false);
912            (cd, bc_current)
913        };
914
915        // Calculate drag acceleration using proper ballistics formula
916        let cd_to_retard = crate::constants::CD_TO_RETARD;
917        let standard_factor = drag_factor * cd_to_retard;
918        // MBA-1137: use the LOCAL (per-substep) density, not the frozen flight-constant
919        // `base_density`, so drag varies with altitude AND downrange zone.
920        let density_scale = local_density / 1.225;
921
922        // Drag acceleration in ft/s^2
923        let a_drag_ft_s2 = (v_fps * v_fps) * standard_factor * density_scale / retard_denom;
924
925        // Convert to m/s^2 and apply to velocity vector
926        let a_drag_m_s2 = a_drag_ft_s2 * 0.3048; // ft/s^2 to m/s^2
927        let accel_drag = -a_drag_m_s2 * (vel_adjusted / v_mag);
928
929        // The Litz post-process owns the gyroscopic effect whenever it is enabled. Otherwise,
930        // honor the explicit Magnus flag with the same dynamic-Sg/yaw model as sibling solvers.
931        let accel_magnus =
932            fast_magnus_acceleration(inputs, vel_adjusted, local_density, mach, accel_gravity);
933
934        // Total acceleration
935        accel_drag + accel_gravity + accel_magnus
936    };
937
938    // Coriolis (Earth rotation), MBA-957. Omega arrives in level downrange/up/lateral axes;
939    // project it into the inclined shot frame before applying the physical -2 Omega x v.
940    if let Some(omega) = omega {
941        let omega = crate::derivatives::level_vector_to_shot_frame(omega, inputs.shooting_angle);
942        accel += -2.0 * omega.cross(&vel);
943    }
944
945    // Return derivatives [vx, vy, vz, ax, ay, az]
946    [vel.x, vel.y, vel.z, accel.x, accel.y, accel.z]
947}
948
949/// Fast integration with explicit wind segments using RK45
950/// MBA-155: Upstreamed from ballistics_rust
951///
952/// A velocity-keyed `bc_segments_data` ladder is flown when `use_bc_segments` is on
953/// (MBA-1602). With the flag on and no ladder (None or empty) and no Mach `bc_segments`, this
954/// RK45 path auto-estimates a ladder from diameter, mass and BC, unlike `TrajectorySolver` and
955/// [`fast_integrate`], which fly the scalar BC.
956pub fn fast_integrate_with_segments(
957    inputs: &BallisticInputs,
958    wind_segments: Vec<crate::wind::WindSegment>,
959    params: FastIntegrationParams,
960) -> FastSolution {
961    // Use the RK45 implementation from trajectory_integration module
962    use crate::trajectory_integration::{integrate_trajectory, TrajectoryParams};
963
964    // Malformed wind or a degenerate atmosphere would otherwise silently stub or poison the run.
965    if crate::wind::validate_wind_segments(&wind_segments).is_err()
966        || !atmo_is_physical(params.atmo_params)
967    {
968        return FastSolution::degenerate(&params.initial_state);
969    }
970
971    // MBA-1415: like plain fast_integrate, this is a public entry point external bindings call
972    // directly, so it must apply every input-conditioning step rather than relying on
973    // TrajectorySolver::new. Shadowing `inputs` here means every read below — mass, bc_value,
974    // drag model, the launch state — sees the conditioned values, with no site left to miss.
975    // Idempotent, so inputs that already passed through a solver are unaffected.
976    let mut normalized_inputs = inputs.clone();
977    normalized_inputs.normalize_for_solve();
978    let inputs = &normalized_inputs;
979
980    // Match plain fast_integrate: this entry point also receives a prebuilt launch state, so
981    // apply the experimental aerodynamic-jump angle exactly once before the low-level integrator.
982    let segmented_crosswind_from_right_mps =
983        if inputs.enable_aerodynamic_jump && !wind_segments.is_empty() {
984            WindSock::new(wind_segments.clone()).muzzle_crosswind_from_right_mps()
985        } else {
986            None
987        };
988    let initial_state = launch_state_with_aerodynamic_jump(
989        inputs,
990        params.atmo_params,
991        segmented_crosswind_from_right_mps,
992        params.initial_state,
993    );
994
995    // Extract parameters
996    let mass_kg = inputs.bullet_mass; // SI (kg)
997    let bc = inputs.bc_value;
998    let drag_model = inputs.bc_type;
999
1000    // Coriolis omega — gated on enable_coriolis (+ a latitude), INDEPENDENT of
1001    // spin-drift/Magnus. A caller can now request Coriolis-only (enable_coriolis=true
1002    // with enable_advanced_effects=false) instead of being forced to enable all three.
1003    let omega_vector = if inputs.enable_coriolis && inputs.latitude.is_some() {
1004        // Calculate omega based on latitude and shot azimuth
1005        // First project Earth's rotation into level downrange/up/lateral axes based on azimuth;
1006        // the derivative kernel handles the additional inclined-shot projection.
1007        // azimuth_angle: 0 = North, pi/2 = East
1008        let omega_earth = 7.2921159e-5; // rad/s
1009        let lat_rad = inputs.latitude.unwrap_or(0.0).to_radians();
1010        let azimuth = inputs.shot_azimuth; // compass bearing (0=N), NOT the aiming offset
1011        Some(Vector3::new(
1012            omega_earth * lat_rad.cos() * azimuth.cos(), // X: downrange component
1013            omega_earth * lat_rad.sin(),                 // Y: vertical component
1014            -omega_earth * lat_rad.cos() * azimuth.sin(), // Z: lateral (MBA-957: corrected sign)
1015        ))
1016    } else {
1017        None
1018    };
1019
1020    // Set up trajectory parameters
1021    let traj_params = TrajectoryParams {
1022        mass_kg,
1023        bc,
1024        drag_model,
1025        wind_segments,
1026        atmos_params: params.atmo_params,
1027        omega_vector,
1028        enable_spin_drift: inputs.use_enhanced_spin_drift,
1029        enable_magnus: inputs.enable_magnus,
1030        enable_coriolis: inputs.enable_coriolis,
1031        target_distance_m: params.horiz,
1032        enable_wind_shear: inputs.enable_wind_shear,
1033        wind_shear_model: inputs.wind_shear_model.clone(),
1034        shooter_altitude_m: inputs.altitude,
1035        is_twist_right: inputs.is_twist_right,
1036        shooting_angle: inputs.shooting_angle,
1037        // MBA-717: carry the real bullet geometry so spin-drift / Magnus use it.
1038        bullet_diameter: inputs.bullet_diameter,
1039        bullet_length: inputs.bullet_length,
1040        twist_rate: inputs.twist_rate,
1041        cd_scale: inputs.cd_scale,
1042        custom_drag_table: inputs.custom_drag_table.clone(),
1043        bc_segments: inputs.bc_segments.clone(),
1044        use_bc_segments: inputs.use_bc_segments,
1045        // MBA-1602: the caller's velocity ladder, read from the normalized inputs so an
1046        // Army-Standard-Metro ladder arrives ICAO-converted like the scalar.
1047        bc_segments_data: inputs.bc_segments_data.clone(),
1048        // MBA-954: keep the historical -1000.0 here (behavior-preserving for this binding path);
1049        // threading inputs.ground_threshold would change the default ground plane for existing
1050        // callers. Direct TrajectoryParams constructors can now configure it.
1051        ground_threshold: -1000.0,
1052        // MBA-1137: forward the downrange-segmented atmosphere to the RK45 derivatives path.
1053        atmo_sock: params.atmo_sock,
1054    };
1055
1056    // Use RK45 adaptive integration
1057    let trajectory = integrate_trajectory(
1058        initial_state,
1059        params.t_span,
1060        traj_params,
1061        "RK45", // Use RK45 implementation
1062        1e-6,   // tolerance
1063        0.01,   // max_step
1064    );
1065
1066    // Convert trajectory to FastSolution format
1067    let n_points = trajectory.len();
1068    let mut times = Vec::with_capacity(n_points + 1);
1069    let mut states = Vec::with_capacity(n_points + 1);
1070
1071    let mut target_hit_time: Option<f64> = None;
1072    let mut ground_hit_time: Option<f64> = None;
1073    let mut max_ord_time = None;
1074    let mut max_ord_y = 0.0;
1075
1076    for (t, state_vec) in trajectory {
1077        // Convert Vector6 to array
1078        let state = [
1079            state_vec[0],
1080            state_vec[1],
1081            state_vec[2],
1082            state_vec[3],
1083            state_vec[4],
1084            state_vec[5],
1085        ];
1086
1087        // Check termination conditions
1088        // McCoy: state[0]=downrange, state[1]=vertical, state[2]=lateral
1089
1090        // The RK45 integrator intentionally returns only ~50 range-spaced states. Use vertical
1091        // velocity to recover an apex between adjacent saves, and retain the synthetic point so
1092        // FastSolution::sol(max_ord_time) returns its Hermite-interpolated height rather than the
1093        // lower straight chord between coarse samples.
1094        if let Some((&previous_time, &previous_state)) = times.last().zip(states.last()) {
1095            if let Some((apex_time, apex_state)) =
1096                interpolated_vertical_apex(previous_time, &previous_state, t, &state)
1097            {
1098                if apex_state[1] > max_ord_y {
1099                    max_ord_y = apex_state[1];
1100                    max_ord_time = Some(apex_time);
1101                }
1102                times.push(apex_time);
1103                states.push(apex_state);
1104            }
1105        }
1106
1107        // Record FIRST time target is hit
1108        if target_hit_time.is_none() && state[0] >= params.horiz {
1109            target_hit_time = Some(t);
1110        }
1111
1112        // Record ground hit
1113        if ground_hit_time.is_none() && state[1] <= inputs.ground_threshold {
1114            ground_hit_time = Some(t);
1115        }
1116
1117        // Track maximum ordinate
1118        if state[1] > max_ord_y {
1119            max_ord_y = state[1];
1120            max_ord_time = Some(t);
1121        }
1122
1123        times.push(t);
1124        states.push(state);
1125    }
1126
1127    // Create event arrays
1128    let t_events = [
1129        if let Some(t) = target_hit_time {
1130            vec![t]
1131        } else {
1132            vec![]
1133        },
1134        if let Some(t) = max_ord_time {
1135            vec![t]
1136        } else {
1137            vec![]
1138        },
1139        if let Some(t) = ground_hit_time {
1140            vec![t]
1141        } else {
1142            vec![]
1143        },
1144    ];
1145
1146    // MBA-1134 (rank 10): the derivatives kernel no longer integrates spin drift, so apply the
1147    // canonical empirical Litz drift as a post-process to the lateral (McCoy Z) of every point at
1148    // its time of flight — matching cli_api::apply_spin_drift and the Monte-Carlo path so all three
1149    // solver families agree. Uses the SAME muzzle Sg (spin_drift::effective_sg_from_inputs).
1150    if inputs.use_enhanced_spin_drift {
1151        // Standard-mode atmo_params is (base_alt, temp_c, press_hpa, ratio); direct mode
1152        // (density, sound, 0, 0) carries no explicit temp/pressure, so fall back to sea-level
1153        // standard (the Sg density correction is a no-op there).
1154        let (sd_temp_c, sd_press_hpa) = if params.atmo_params.2 > 0.0 {
1155            (params.atmo_params.1, params.atmo_params.2)
1156        } else {
1157            (15.0, 1013.25)
1158        };
1159        let sg = crate::spin_drift::effective_sg_from_inputs(inputs, sd_temp_c, sd_press_hpa);
1160        for (t, state) in times.iter().zip(states.iter_mut()) {
1161            if *t > 0.0 {
1162                state[2] += crate::spin_drift::litz_drift_meters(sg, *t, inputs.is_twist_right);
1163            }
1164        }
1165    }
1166
1167    FastSolution::from_trajectory_data(times, states, t_events)
1168}
1169
1170#[cfg(test)]
1171mod tests {
1172    use super::*;
1173    use crate::BCSegmentData;
1174
1175    fn expected_shot_frame_vector(level: Vector3<f64>, angle: f64) -> Vector3<f64> {
1176        let (sin_angle, cos_angle) = angle.sin_cos();
1177        Vector3::new(
1178            level.x * cos_angle + level.y * sin_angle,
1179            -level.x * sin_angle + level.y * cos_angle,
1180            level.z,
1181        )
1182    }
1183
1184    #[test]
1185    fn measured_bc_fast_drag_ignores_name_based_form_factor_flag() {
1186        let derivatives_with_flag = |use_form_factor| {
1187            let inputs = BallisticInputs {
1188                bc_value: 0.462,
1189                bc_type: DragModel::G1,
1190                bullet_model: Some("168gr SMK Match".to_string()),
1191                use_form_factor,
1192                temperature: 15.0,
1193                pressure: 1013.25,
1194                ..BallisticInputs::default()
1195            };
1196
1197            compute_derivatives(
1198                &[0.0, 0.0, 0.0, 600.0, 0.0, 0.0],
1199                &inputs,
1200                &WindSock::new(vec![]),
1201                FastAtmosphere::Standard {
1202                    base_density: 1.225,
1203                },
1204                &inputs.bc_type,
1205                crate::transonic_drag::ProjectileShape::Spitzer,
1206                inputs.bc_value,
1207                false,
1208                false,
1209                None,
1210                None,
1211                None,
1212            )
1213        };
1214
1215        let baseline = derivatives_with_flag(false);
1216        let flagged = derivatives_with_flag(true);
1217
1218        for component in 3..6 {
1219            assert_eq!(
1220                flagged[component].to_bits(),
1221                baseline[component].to_bits(),
1222                "published BC already encodes form factor: component {component}, baseline={} flagged={}",
1223                baseline[component],
1224                flagged[component]
1225            );
1226        }
1227    }
1228
1229    #[test]
1230    fn velocity_bc_data_requires_opt_in_in_plain_fast_kernel() {
1231        let acceleration = |inputs: &BallisticInputs| {
1232            let has_mach_segments = inputs
1233                .bc_segments
1234                .as_ref()
1235                .is_some_and(|segments| !segments.is_empty());
1236            let has_velocity_segments = inputs
1237                .bc_segments_data
1238                .as_ref()
1239                .is_some_and(|segments| !segments.is_empty());
1240            compute_derivatives(
1241                &[0.0, 0.0, 0.0, 600.0, 0.0, 0.0],
1242                inputs,
1243                &WindSock::new(vec![]),
1244                FastAtmosphere::Standard {
1245                    base_density: 1.225,
1246                },
1247                &inputs.bc_type,
1248                crate::transonic_drag::ProjectileShape::Spitzer,
1249                inputs.bc_value,
1250                has_mach_segments,
1251                has_velocity_segments,
1252                None,
1253                None,
1254                None,
1255            )
1256        };
1257
1258        let scalar_inputs = BallisticInputs {
1259            bc_value: 0.5,
1260            bc_type: DragModel::G7,
1261            temperature: 15.0,
1262            pressure: 1013.25,
1263            ..BallisticInputs::default()
1264        };
1265        let mut disabled_inputs = scalar_inputs.clone();
1266        disabled_inputs.bc_segments_data = Some(vec![BCSegmentData {
1267            velocity_min: 0.0,
1268            velocity_max: 4_000.0,
1269            bc_value: 0.46,
1270        }]);
1271        disabled_inputs.use_bc_segments = false;
1272        let mut enabled_inputs = disabled_inputs.clone();
1273        enabled_inputs.use_bc_segments = true;
1274        let mut mach_only_inputs = scalar_inputs.clone();
1275        mach_only_inputs.bc_segments = Some(vec![(0.0, 0.4), (3.0, 0.4)]);
1276        let mut disabled_with_both = mach_only_inputs.clone();
1277        disabled_with_both.bc_segments_data = disabled_inputs.bc_segments_data.clone();
1278
1279        let scalar = acceleration(&scalar_inputs);
1280        let disabled = acceleration(&disabled_inputs);
1281        let enabled = acceleration(&enabled_inputs);
1282        let mach_only = acceleration(&mach_only_inputs);
1283        let disabled_with_both = acceleration(&disabled_with_both);
1284
1285        assert_eq!(
1286            disabled[3].to_bits(),
1287            scalar[3].to_bits(),
1288            "a populated velocity table must not change drag while use_bc_segments is false"
1289        );
1290        assert!(
1291            enabled[3] < disabled[3] - 1.0,
1292            "enabling the lower BC table must increase drag: disabled ax={} enabled ax={}",
1293            disabled[3],
1294            enabled[3]
1295        );
1296        assert_eq!(
1297            disabled_with_both[3].to_bits(),
1298            mach_only[3].to_bits(),
1299            "disabling velocity data must fall through to an explicit Mach table"
1300        );
1301    }
1302
1303    #[test]
1304    fn inclined_positions_at_same_world_altitude_have_same_fast_acceleration() {
1305        let angle = std::f64::consts::FRAC_PI_6;
1306        let inputs = BallisticInputs {
1307            altitude: 100.0,
1308            temperature: 15.0,
1309            pressure: 1013.25,
1310            shooting_angle: angle,
1311            ..BallisticInputs::default()
1312        };
1313        let wind_sock = WindSock::new(vec![]);
1314        let atmosphere = FastAtmosphere::Standard {
1315            base_density: 1.225,
1316        };
1317        let state_along_slant = [1_000.0, 0.0, 0.0, 600.0, 0.0, 0.0];
1318        let state_across_slant = [0.0, 500.0 / angle.cos(), 0.0, 600.0, 0.0, 0.0];
1319
1320        let a = compute_derivatives(
1321            &state_along_slant,
1322            &inputs,
1323            &wind_sock,
1324            atmosphere,
1325            &inputs.bc_type,
1326            crate::transonic_drag::ProjectileShape::Spitzer,
1327            inputs.bc_value,
1328            false,
1329            false,
1330            None,
1331            None,
1332            None,
1333        );
1334        let b = compute_derivatives(
1335            &state_across_slant,
1336            &inputs,
1337            &wind_sock,
1338            atmosphere,
1339            &inputs.bc_type,
1340            crate::transonic_drag::ProjectileShape::Spitzer,
1341            inputs.bc_value,
1342            false,
1343            false,
1344            None,
1345            None,
1346            None,
1347        );
1348
1349        for component in 3..6 {
1350            assert!(
1351                (a[component] - b[component]).abs() < 1e-10,
1352                "fast derivative component {component} differs at equal world altitude: {} vs {}",
1353                a[component],
1354                b[component]
1355            );
1356        }
1357    }
1358
1359    #[test]
1360    fn inclined_headwind_is_rotated_into_solver_frame() {
1361        let angle = std::f64::consts::FRAC_PI_6;
1362        let inputs = BallisticInputs {
1363            shooting_angle: angle,
1364            ..BallisticInputs::default()
1365        };
1366        let speed_mps = 360.0 * (1000.0 / 3600.0);
1367        let level_headwind = Vector3::new(-speed_mps, 0.0, 0.0);
1368        let velocity = expected_shot_frame_vector(level_headwind, angle);
1369        let state = [0.0, 0.0, 0.0, velocity.x, velocity.y, velocity.z];
1370        let actual = compute_derivatives(
1371            &state,
1372            &inputs,
1373            &WindSock::new(vec![crate::wind::WindSegment::new(360.0, 0.0, 1000.0)]),
1374            FastAtmosphere::Direct {
1375                air_density: 1.225,
1376                speed_of_sound: 340.0,
1377            },
1378            &inputs.bc_type,
1379            crate::transonic_drag::ProjectileShape::Spitzer,
1380            inputs.bc_value,
1381            false,
1382            false,
1383            None,
1384            None,
1385            None,
1386        );
1387        let expected = Vector3::new(
1388            -G_ACCEL_MPS2 * angle.sin(),
1389            -G_ACCEL_MPS2 * angle.cos(),
1390            0.0,
1391        );
1392
1393        assert!(
1394            (Vector3::new(actual[3], actual[4], actual[5]) - expected).norm() < 1e-12,
1395            "co-moving horizontal wind must leave only shot-frame gravity: {actual:?}"
1396        );
1397    }
1398
1399    #[test]
1400    fn plain_fast_kernel_applies_power_law_wind_shear() {
1401        let state = [500.0, 100.0, 0.0, 700.0, 0.0, 0.0];
1402        let run = |enable_wind_shear: bool, model: &str, wind_speed_kmh: f64| {
1403            let inputs = BallisticInputs {
1404                bc_value: 0.5,
1405                bc_type: DragModel::G7,
1406                enable_wind_shear,
1407                wind_shear_model: model.to_string(),
1408                ..BallisticInputs::default()
1409            };
1410            let wind_shear_model = enable_wind_shear
1411                .then(|| crate::wind_shear::boundary_layer_model_from_name(model))
1412                .filter(|model| *model != crate::wind_shear::WindShearModel::None);
1413            compute_derivatives(
1414                &state,
1415                &inputs,
1416                &WindSock::new(vec![crate::wind::WindSegment::new(
1417                    wind_speed_kmh,
1418                    90.0,
1419                    2_000.0,
1420                )]),
1421                FastAtmosphere::Direct {
1422                    air_density: 1.225,
1423                    speed_of_sound: 340.0,
1424                },
1425                &inputs.bc_type,
1426                crate::transonic_drag::ProjectileShape::Spitzer,
1427                inputs.bc_value,
1428                false,
1429                false,
1430                None,
1431                wind_shear_model,
1432                None,
1433            )
1434        };
1435
1436        let uniform = run(false, "power_law", 36.0);
1437        let model_none = run(true, "none", 36.0);
1438        assert_eq!(model_none, uniform, "model=none must preserve uniform wind");
1439
1440        let sheared = run(true, "power_law", 36.0);
1441        assert!(
1442            sheared[5] < uniform[5],
1443            "stronger aloft crosswind must increase leftward acceleration: uniform={}, shear={}",
1444            uniform[5],
1445            sheared[5]
1446        );
1447
1448        let ratio = crate::wind_shear::boundary_layer_speed_ratio(
1449            state[1],
1450            crate::wind_shear::WindShearModel::PowerLaw,
1451        );
1452        let equivalent_uniform = run(false, "none", 36.0 * ratio);
1453        for component in 3..6 {
1454            assert!(
1455                (sheared[component] - equivalent_uniform[component]).abs() < 1e-12,
1456                "shear component {component} must equal base wind scaled by {ratio}: shear={}, expected={}",
1457                sheared[component],
1458                equivalent_uniform[component]
1459            );
1460        }
1461    }
1462
1463    #[test]
1464    fn plain_fast_path_wind_shear_changes_high_arc_drift() {
1465        let run = |enable_wind_shear: bool, model: &str| {
1466            let inputs = BallisticInputs {
1467                muzzle_velocity: 800.0,
1468                bc_value: 0.5,
1469                bc_type: DragModel::G7,
1470                bullet_mass: 168.0 * crate::constants::GRAINS_TO_KG,
1471                bullet_diameter: 0.308 * 0.0254,
1472                enable_wind_shear,
1473                wind_shear_model: model.to_string(),
1474                ground_threshold: -100.0,
1475                ..BallisticInputs::default()
1476            };
1477            let elevation = 0.12_f64;
1478            let solution = fast_integrate(
1479                &inputs,
1480                &WindSock::new(vec![crate::wind::WindSegment::new(36.0, 90.0, 2_000.0)]),
1481                FastIntegrationParams {
1482                    horiz: 1_000.0,
1483                    vert: 0.0,
1484                    initial_state: [
1485                        0.0,
1486                        0.0,
1487                        0.0,
1488                        inputs.muzzle_velocity * elevation.cos(),
1489                        inputs.muzzle_velocity * elevation.sin(),
1490                        0.0,
1491                    ],
1492                    t_span: (0.0, 5.0),
1493                    atmo_params: (0.0, 15.0, 1013.25, 1.0),
1494                    atmo_sock: None,
1495                },
1496            );
1497            let last = solution.t.len() - 1;
1498            assert_eq!(solution.y[0][last].to_bits(), 1_000.0_f64.to_bits());
1499            solution.y[2][last]
1500        };
1501
1502        let uniform = run(false, "power_law");
1503        let model_none = run(true, "none");
1504        assert_eq!(model_none.to_bits(), uniform.to_bits());
1505        let sheared = run(true, "power_law");
1506        assert!(
1507            sheared.abs() > uniform.abs() + 0.01,
1508            "aloft shear must increase drift magnitude: uniform={uniform}, shear={sheared}"
1509        );
1510    }
1511
1512    #[test]
1513    fn inclined_coriolis_is_rotated_into_solver_frame() {
1514        let angle = std::f64::consts::FRAC_PI_6;
1515        let inputs = BallisticInputs {
1516            shooting_angle: angle,
1517            ..BallisticInputs::default()
1518        };
1519        let velocity = Vector3::new(600.0, 20.0, 5.0);
1520        let state = [0.0, 0.0, 0.0, velocity.x, velocity.y, velocity.z];
1521        let level_omega = Vector3::new(3.0e-5, 6.0e-5, -2.0e-5);
1522        let run = |omega| {
1523            compute_derivatives(
1524                &state,
1525                &inputs,
1526                &WindSock::new(vec![]),
1527                FastAtmosphere::Direct {
1528                    air_density: 1.225,
1529                    speed_of_sound: 340.0,
1530                },
1531                &inputs.bc_type,
1532                crate::transonic_drag::ProjectileShape::Spitzer,
1533                inputs.bc_value,
1534                false,
1535                false,
1536                omega,
1537                None,
1538                None,
1539            )
1540        };
1541        let baseline = run(None);
1542        let with_coriolis = run(Some(level_omega));
1543        let actual = Vector3::new(
1544            with_coriolis[3] - baseline[3],
1545            with_coriolis[4] - baseline[4],
1546            with_coriolis[5] - baseline[5],
1547        );
1548        let expected = -2.0 * expected_shot_frame_vector(level_omega, angle).cross(&velocity);
1549
1550        assert!(
1551            (actual - expected).norm() < 1e-12,
1552            "inclined Coriolis mismatch: actual={actual:?}, expected={expected:?}"
1553        );
1554    }
1555
1556    #[test]
1557    fn test_fast_solution_interpolation() {
1558        let times = vec![0.0, 1.0, 2.0];
1559        let states = vec![
1560            [0.0, 0.0, 0.0, 100.0, 50.0, 0.0],
1561            [100.0, 45.0, 0.0, 99.0, 40.0, 0.0],
1562            [198.0, 80.0, 0.0, 98.0, 30.0, 0.0],
1563        ];
1564
1565        let solution = FastSolution::from_trajectory_data(times, states, [vec![], vec![], vec![]]);
1566
1567        // Test interpolation at t=1.5
1568        let result = solution.sol(&[1.5]);
1569
1570        assert!((result[0][0] - 149.0).abs() < 1e-10); // x position
1571        assert!((result[1][0] - 62.5).abs() < 1e-10); // y position
1572        assert!((result[3][0] - 98.5).abs() < 1e-10); // vx velocity
1573    }
1574
1575    #[test]
1576    fn test_bc_from_velocity_segments() {
1577        let segments = vec![
1578            BCSegmentData {
1579                velocity_min: 0.0,
1580                velocity_max: 1000.0,
1581                bc_value: 0.5,
1582            },
1583            BCSegmentData {
1584                velocity_min: 1000.0,
1585                velocity_max: 2000.0,
1586                bc_value: 0.52,
1587            },
1588            BCSegmentData {
1589                velocity_min: 2000.0,
1590                velocity_max: 3000.0,
1591                bc_value: 0.55,
1592            },
1593        ];
1594
1595        // MBA-1404: every one of these query points is >25 fps (half the 50 fps-capped
1596        // margin on all three 1000 fps-wide bands) away from the nearest boundary/coverage
1597        // edge, so none of them fall inside a smoothstep blend window -- values are
1598        // unchanged from the pre-MBA-1404 step behavior.
1599        assert_eq!(velocity_segment_bc(500.0, &segments, 0.5), 0.5);
1600        assert_eq!(velocity_segment_bc(1500.0, &segments, 0.5), 0.52);
1601        assert_eq!(velocity_segment_bc(2500.0, &segments, 0.5), 0.55);
1602
1603        // Test edge cases
1604        assert_eq!(velocity_segment_bc(-100.0, &segments, 0.5), 0.5); // Below min
1605        assert_eq!(velocity_segment_bc(3500.0, &segments, 0.5), 0.55); // Above max
1606    }
1607
1608    #[test]
1609    fn test_fast_solution_interpolation_edge_cases() {
1610        let times = vec![0.0, 1.0, 2.0, 3.0];
1611        let states = vec![
1612            [0.0, 0.0, 0.0, 800.0, 50.0, 0.0],
1613            [800.0, 40.0, 100.0, 750.0, 30.0, 0.0],
1614            [1550.0, 60.0, 200.0, 700.0, 10.0, 0.0],
1615            [2250.0, 50.0, 300.0, 650.0, -10.0, 0.0],
1616        ];
1617
1618        let solution = FastSolution::from_trajectory_data(times, states, [vec![], vec![], vec![]]);
1619
1620        // Test interpolation before first point
1621        let result_before = solution.sol(&[-0.5]);
1622        assert!((result_before[0][0] - 0.0).abs() < 1e-10); // Should clamp to first
1623
1624        // Test interpolation after last point
1625        let result_after = solution.sol(&[5.0]);
1626        assert!((result_after[0][0] - 2250.0).abs() < 1e-10); // Should clamp to last
1627
1628        // Test interpolation at exact points
1629        let result_exact = solution.sol(&[1.0]);
1630        assert!((result_exact[0][0] - 800.0).abs() < 1e-10);
1631
1632        // Test multiple query points
1633        let result_multi = solution.sol(&[0.5, 1.5, 2.5]);
1634        assert_eq!(result_multi[0].len(), 3);
1635    }
1636
1637    #[test]
1638    fn test_fast_solution_from_trajectory_data() {
1639        let times = vec![0.0, 0.5, 1.0];
1640        let states = vec![
1641            [0.0, 1.0, 2.0, 3.0, 4.0, 5.0],
1642            [10.0, 11.0, 12.0, 13.0, 14.0, 15.0],
1643            [20.0, 21.0, 22.0, 23.0, 24.0, 25.0],
1644        ];
1645        let t_events = [vec![1.0], vec![0.5], vec![]];
1646
1647        let solution = FastSolution::from_trajectory_data(times.clone(), states, t_events);
1648
1649        // Check that data is stored correctly
1650        assert_eq!(solution.t, times);
1651        assert_eq!(solution.y.len(), 6); // 6 state components
1652        assert_eq!(solution.y[0].len(), 3); // 3 time points
1653        assert!(solution.success);
1654
1655        // Verify column-major storage
1656        assert_eq!(solution.y[0][0], 0.0); // x at t=0
1657        assert_eq!(solution.y[1][0], 1.0); // y at t=0
1658        assert_eq!(solution.y[0][2], 20.0); // x at t=1.0
1659    }
1660
1661    #[test]
1662    fn test_bc_segments_boundary_conditions() {
1663        // Test with single segment
1664        // MBA-1404: a single-segment table has no adjacent band to blend against, so this
1665        // stays byte-identical to the pre-MBA-1404 step/clamp lookup everywhere.
1666        let single_segment = vec![BCSegmentData {
1667            velocity_min: 1000.0,
1668            velocity_max: 2000.0,
1669            bc_value: 0.5,
1670        }];
1671
1672        assert_eq!(velocity_segment_bc(500.0, &single_segment, 0.5), 0.5); // Below
1673        assert_eq!(velocity_segment_bc(1500.0, &single_segment, 0.5), 0.5); // In range
1674        assert_eq!(velocity_segment_bc(2500.0, &single_segment, 0.5), 0.5); // Above
1675
1676        // Test with exact boundary values
1677        // Half-open bands make a shared boundary belong to the band that starts there.
1678        // A ends at 999, B starts at 1000: a 1 fps interior gap falls back to bc=0.7.
1679        let segments = vec![
1680            BCSegmentData {
1681                velocity_min: 0.0,
1682                velocity_max: 999.0, // Exclusive upper bound to avoid overlap
1683                bc_value: 0.45,
1684            },
1685            BCSegmentData {
1686                velocity_min: 1000.0,
1687                velocity_max: 2000.0,
1688                bc_value: 0.50,
1689            },
1690        ];
1691
1692        // MBA-1404: the 1 fps gap caps both of its edges' margins to
1693        // min(50, 0.25*1) = 0.25 fps (half-margin 0.125 fps either side of 999 and 1000).
1694        // v=1000.0 is now the gap-entry boundary's exact center (t=0.5): it blends halfway
1695        // between the gap's fallback (0.7) and band B (0.50) instead of hard-stepping to
1696        // band B alone. This is a deliberate, exact-value update -- not a loosened
1697        // tolerance -- and would fail against the old step behavior (0.50).
1698        assert_eq!(velocity_segment_bc(1000.0, &segments, 0.7), 0.6); // At second segment start (blended)
1699                                                                      // v=0.0 is the coverage-entry boundary's center, but that edge is a no-op blend:
1700                                                                      // the clamp below band A returns the same value band A itself would, so this stays
1701                                                                      // exactly flat and is unchanged from before MBA-1404.
1702        assert_eq!(velocity_segment_bc(0.0, &segments, 0.7), 0.45); // At min (coverage edge: still flat, no jump to smooth)
1703                                                                    // v=998.999 is inside the gap-exit boundary's [998.875, 999.125] margin window
1704                                                                    // (t=0.496), partway through the smoothstep blend from band A (0.45) toward the
1705                                                                    // gap's fallback (0.7).
1706        assert_eq!(
1707            velocity_segment_bc(998.999, &segments, 0.7),
1708            0.5735000320000354
1709        ); // Just below exclusive max (blending toward the gap)
1710           // v=999.0 is the gap-exit boundary's exact center (t=0.5): halfway between band A
1711           // (0.45) and the fallback (0.7), not the old hard fallback value (0.7) alone.
1712        assert_eq!(velocity_segment_bc(999.0, &segments, 0.7), 0.575); // Gap starts at exclusive max (blended)
1713    }
1714
1715    #[test]
1716    fn velocity_segment_gaps_and_clamps_do_not_depend_on_order() {
1717        let fallback_bc = 0.73;
1718        let ascending_with_gap = vec![
1719            BCSegmentData {
1720                velocity_min: 0.0,
1721                velocity_max: 999.0,
1722                bc_value: 0.6,
1723            },
1724            BCSegmentData {
1725                velocity_min: 1000.0,
1726                velocity_max: 2000.0,
1727                bc_value: 0.8,
1728            },
1729        ];
1730        // MBA-1404: v=999.5 is dead center of the 1 fps gap, 0.5 fps from each edge --
1731        // comfortably outside either edge's +/-0.125 fps blend margin (min(50, 0.25*1)) --
1732        // so this stays exactly the fallback, unchanged from before MBA-1404.
1733        assert_eq!(
1734            velocity_segment_bc(999.5, &ascending_with_gap, fallback_bc),
1735            fallback_bc,
1736            "coverage gaps must use the projectile's base BC"
1737        );
1738
1739        let mut descending = ascending_with_gap.clone();
1740        descending.reverse();
1741        // MBA-1404: -100/2500 are far outside the +/-25 fps coverage-entry/exit margins
1742        // (min(50, 0.25*999) and min(50, 0.25*1000)), so these clamps are unchanged too.
1743        assert_eq!(
1744            velocity_segment_bc(-100.0, &descending, fallback_bc),
1745            0.6,
1746            "below coverage must clamp to the lowest-velocity band"
1747        );
1748        assert_eq!(
1749            velocity_segment_bc(2500.0, &descending, fallback_bc),
1750            0.8,
1751            "above coverage must clamp to the highest-velocity band"
1752        );
1753    }
1754
1755    #[test]
1756    fn test_bc_segments_empty_fallback() {
1757        let empty_segments: Vec<BCSegmentData> = vec![];
1758
1759        // MBA-1404: an empty table has no adjacent bands to blend against, so this stays
1760        // byte-identical to the pre-MBA-1404 behavior (always the fallback).
1761        // With empty segments, should return fallback value
1762        let result = velocity_segment_bc(1500.0, &empty_segments, 0.73);
1763        assert_eq!(result, 0.73); // Caller-provided fallback value
1764    }
1765
1766    #[test]
1767    fn test_fast_integration_params() {
1768        // Verify FastIntegrationParams struct can be constructed
1769        let params = FastIntegrationParams {
1770            horiz: 1000.0,
1771            vert: 0.0,
1772            initial_state: [0.0, 0.0, 0.0, 800.0, 50.0, 0.0], // McCoy: vx=downrange
1773            t_span: (0.0, 5.0),
1774            atmo_params: (0.0, 15.0, 1013.25, 1.0),
1775            atmo_sock: None,
1776        };
1777
1778        assert_eq!(params.horiz, 1000.0);
1779        assert_eq!(params.t_span.0, 0.0);
1780        assert_eq!(params.t_span.1, 5.0);
1781        assert_eq!(params.initial_state[3], 800.0); // vx (downrange, McCoy)
1782    }
1783
1784    #[test]
1785    fn test_fast_solution_event_arrays() {
1786        let times = vec![0.0, 1.0, 2.0];
1787        let states = vec![
1788            [0.0, 0.0, 0.0, 800.0, 50.0, 0.0],
1789            [800.0, 40.0, 500.0, 750.0, 30.0, 0.0],
1790            [1500.0, 20.0, 1000.0, 700.0, 10.0, 0.0],
1791        ];
1792
1793        // Create solution with events
1794        let t_events = [
1795            vec![2.0], // target_hit at t=2
1796            vec![0.5], // max_ord at t=0.5
1797            vec![],    // no ground_hit
1798        ];
1799
1800        let solution = FastSolution::from_trajectory_data(times, states, t_events);
1801
1802        assert_eq!(solution.t_events[0], vec![2.0]); // Target hit
1803        assert_eq!(solution.t_events[1], vec![0.5]); // Max ordinate
1804        assert!(solution.t_events[2].is_empty()); // No ground hit
1805    }
1806
1807    #[test]
1808    fn segmented_fast_path_interpolates_max_ordinate_between_saved_points() {
1809        let expected_apex_time = 5.105_f64;
1810        let downrange_velocity = 100.0_f64;
1811        let vertical_velocity = G_ACCEL_MPS2 * expected_apex_time;
1812        let inputs = BallisticInputs {
1813            muzzle_velocity: downrange_velocity.hypot(vertical_velocity),
1814            bc_value: 0.5,
1815            bc_type: DragModel::G7,
1816            use_enhanced_spin_drift: false,
1817            ..BallisticInputs::default()
1818        };
1819        let solution = fast_integrate_with_segments(
1820            &inputs,
1821            vec![],
1822            FastIntegrationParams {
1823                horiz: 1_000.0,
1824                vert: 0.0,
1825                initial_state: [0.0, 0.0, 0.0, downrange_velocity, vertical_velocity, 0.0],
1826                t_span: (0.0, 12.0),
1827                // Negligible density makes this an analytic constant-gravity arc while retaining
1828                // the valid direct-atmosphere sentinel.
1829                atmo_params: (1e-12, 340.0, 0.0, 0.0),
1830                atmo_sock: None,
1831            },
1832        );
1833
1834        assert!(solution.success);
1835        assert_eq!(solution.t_events[1].len(), 1);
1836        let reported_time = solution.t_events[1][0];
1837        assert!(
1838            (reported_time - expected_apex_time).abs() < 0.006,
1839            "max-ordinate time must be interpolated between coarse saves: reported={reported_time} expected={expected_apex_time}"
1840        );
1841        let event_index = solution
1842            .t
1843            .iter()
1844            .position(|time| time.to_bits() == reported_time.to_bits())
1845            .expect("the interpolated apex must be retained in the solution");
1846        assert_eq!(solution.y[4][event_index].to_bits(), 0.0_f64.to_bits());
1847
1848        let expected_height = vertical_velocity * expected_apex_time
1849            - 0.5 * G_ACCEL_MPS2 * expected_apex_time.powi(2);
1850        let event_state = solution.sol(&[reported_time]);
1851        assert!(
1852            (event_state[1][0] - expected_height).abs() < 2e-4,
1853            "max-ordinate state must preserve the interpolated apex height: reported={} expected={expected_height}",
1854            event_state[1][0]
1855        );
1856    }
1857
1858    #[test]
1859    fn plain_fast_path_interpolates_the_target_crossing() {
1860        let target = 500.123456789;
1861        let initial_state = [0.0, 0.0, 0.25, 800.0, 12.0, -2.5];
1862        let inputs = BallisticInputs {
1863            muzzle_velocity: 800.0,
1864            bc_value: 0.5,
1865            bc_type: DragModel::G7,
1866            ground_threshold: -100.0,
1867            use_enhanced_spin_drift: false,
1868            ..BallisticInputs::default()
1869        };
1870        let run = |horiz| {
1871            fast_integrate(
1872                &inputs,
1873                &WindSock::new(vec![]),
1874                FastIntegrationParams {
1875                    horiz,
1876                    vert: 0.0,
1877                    initial_state,
1878                    t_span: (0.0, 2.0),
1879                    atmo_params: (0.0, 15.0, 1013.25, 1.0),
1880                    atmo_sock: None,
1881                },
1882            )
1883        };
1884
1885        // A longer run retains the two full RK4 samples bracketing the requested target.
1886        let reference = run(target + 2.0);
1887        let left = reference.y[0]
1888            .windows(2)
1889            .position(|x| x[0] < target && x[1] > target)
1890            .expect("reference trajectory must bracket target");
1891        let right = left + 1;
1892        let alpha =
1893            (target - reference.y[0][left]) / (reference.y[0][right] - reference.y[0][left]);
1894
1895        let solution = run(target);
1896        let last = solution.t.len() - 1;
1897        assert_eq!(solution.y[0][last].to_bits(), target.to_bits());
1898        let expected_time = reference.t[left] + alpha * (reference.t[right] - reference.t[left]);
1899        assert!((solution.t[last] - expected_time).abs() < 1e-12);
1900        assert_eq!(solution.t_events[0], vec![solution.t[last]]);
1901
1902        for component in 0..6 {
1903            assert_eq!(solution.y[component].len(), solution.t.len());
1904            let expected = reference.y[component][left]
1905                + alpha * (reference.y[component][right] - reference.y[component][left]);
1906            assert!(
1907                (solution.y[component][last] - expected).abs() < 1e-9,
1908                "component {component} is not at the crossing: actual={}, expected={expected}",
1909                solution.y[component][last]
1910            );
1911        }
1912    }
1913
1914    #[test]
1915    fn fast_path_coriolis_uses_shot_direction() {
1916        // Regression: fast_integrate_with_segments (the path the Python binding uses)
1917        // built its Coriolis omega from azimuth_angle (the aiming offset, always ~0)
1918        // instead of shot_azimuth, so east and west shots came out identical. After the
1919        // fix they must differ with the correct Eotvos sign (east lifted, higher).
1920        use std::f64::consts::FRAC_PI_2;
1921        // Returns (final_downrange, final_vertical) for a shot fired along `shot_az`.
1922        fn final_xy(shot_az: f64) -> (f64, f64) {
1923            let inputs = BallisticInputs {
1924                muzzle_velocity: 800.0,
1925                bc_value: 0.5,
1926                bc_type: DragModel::G7,
1927                enable_advanced_effects: true, // gates the omega vector
1928                enable_coriolis: true,
1929                latitude: Some(45.0),
1930                shot_azimuth: shot_az,
1931                ..BallisticInputs::default()
1932            };
1933            let v = 800.0_f64;
1934            let elev = 0.02_f64;
1935            let params = FastIntegrationParams {
1936                horiz: 1000.0,
1937                vert: 0.0,
1938                initial_state: [0.0, 0.0, 0.0, v * elev.cos(), v * elev.sin(), 0.0],
1939                t_span: (0.0, 5.0),
1940                atmo_params: (0.0, 15.0, 1013.25, 1.0),
1941                atmo_sock: None,
1942            };
1943            let sol = fast_integrate_with_segments(&inputs, vec![], params);
1944            let n = sol.y[0].len();
1945            (sol.y[0][n - 1], sol.y[1][n - 1])
1946        }
1947        let (ex, ey) = final_xy(FRAC_PI_2); // east
1948        let (wx, wy) = final_xy(3.0 * FRAC_PI_2); // west
1949                                                  // Both shots cover essentially the same downrange (Coriolis barely affects x),
1950                                                  // so comparing the final vertical is apples-to-apples.
1951        assert!(
1952            (ex - wx).abs() < 0.5,
1953            "east/west downrange should be ~equal (ex={ex:.4}, wx={wx:.4})"
1954        );
1955        // Pre-fix the fast path was North-locked, making these byte-identical. The Eotvos
1956        // term now lifts the east shot above the west shot.
1957        assert!(
1958            ey > wy,
1959            "fast-path east ({ey:.6}) must be higher than west ({wy:.6}) (Eotvos)"
1960        );
1961        assert!(
1962            (ey - wy) > 1e-5,
1963            "fast-path E-W vertical separation ({:.8} m) should be non-zero (the pre-fix bug was exact equality)",
1964            ey - wy
1965        );
1966    }
1967
1968    #[test]
1969    fn fast_path_coriolis_independent_of_advanced_effects() {
1970        // Coriolis is now gated on enable_coriolis (+ latitude), NOT enable_advanced_effects.
1971        // So a caller can request Coriolis-only without being forced to enable spin/Magnus.
1972        use std::f64::consts::FRAC_PI_2;
1973        fn final_y(coriolis: bool, shot_az: f64) -> f64 {
1974            let inputs = BallisticInputs {
1975                muzzle_velocity: 800.0,
1976                bc_value: 0.5,
1977                bc_type: DragModel::G7,
1978                enable_coriolis: coriolis,
1979                enable_advanced_effects: false, // explicitly OFF — Coriolis must still work
1980                latitude: Some(45.0),
1981                shot_azimuth: shot_az,
1982                ..BallisticInputs::default()
1983            };
1984            let v = 800.0_f64;
1985            let elev = 0.02_f64;
1986            let params = FastIntegrationParams {
1987                horiz: 1000.0,
1988                vert: 0.0,
1989                initial_state: [0.0, 0.0, 0.0, v * elev.cos(), v * elev.sin(), 0.0],
1990                t_span: (0.0, 5.0),
1991                atmo_params: (0.0, 15.0, 1013.25, 1.0),
1992                atmo_sock: None,
1993            };
1994            let sol = fast_integrate_with_segments(&inputs, vec![], params);
1995            let n = sol.y[0].len();
1996            sol.y[1][n - 1]
1997        }
1998        // enable_coriolis=true with advanced effects OFF: directional Coriolis still applies.
1999        let e = final_y(true, FRAC_PI_2);
2000        let w = final_y(true, 3.0 * FRAC_PI_2);
2001        assert!(
2002            e > w && (e - w) > 1e-5,
2003            "Coriolis-only (no advanced effects) must still be directional: E={e} W={w}"
2004        );
2005        // enable_coriolis=false: no Coriolis at all, east == west.
2006        let e2 = final_y(false, FRAC_PI_2);
2007        let w2 = final_y(false, 3.0 * FRAC_PI_2);
2008        assert!(
2009            (e2 - w2).abs() < 1e-9,
2010            "with enable_coriolis=false, east/west must be identical: E={e2} W={w2}"
2011        );
2012    }
2013
2014    #[test]
2015    fn fast_path_rejects_degenerate_atmosphere() {
2016        let inputs = BallisticInputs {
2017            muzzle_velocity: 800.0,
2018            bc_value: 0.5,
2019            bc_type: DragModel::G7,
2020            ..BallisticInputs::default()
2021        };
2022        let v = 800.0_f64;
2023        let e = 0.02_f64;
2024        let mk = |atmo: (f64, f64, f64, f64)| FastIntegrationParams {
2025            horiz: 500.0,
2026            vert: 0.0,
2027            initial_state: [0.0, 0.0, 0.0, v * e.cos(), v * e.sin(), 0.0],
2028            t_span: (0.0, 5.0),
2029            atmo_params: atmo,
2030            atmo_sock: None,
2031        };
2032        // pressure <= 0 -> fail loudly (success=false) instead of a 1-point stub as success.
2033        let zero_p = fast_integrate_with_segments(&inputs, vec![], mk((0.0, 15.0, 0.0, 1.0)));
2034        assert!(
2035            !zero_p.success,
2036            "pressure=0 atmosphere must yield success=false"
2037        );
2038        // non-finite pressure -> also rejected.
2039        let nan_p = fast_integrate_with_segments(&inputs, vec![], mk((0.0, 15.0, f64::NAN, 1.0)));
2040        assert!(!nan_p.success, "NaN pressure must yield success=false");
2041        // A supplied density ratio must imply a physically plausible density in both wrappers.
2042        let segmented_too_dense =
2043            fast_integrate_with_segments(&inputs, vec![], mk((0.0, 15.0, 1013.25, 50.0)));
2044        let plain_too_dense = fast_integrate(
2045            &inputs,
2046            &WindSock::new(vec![]),
2047            mk((0.0, 15.0, 1013.25, 50.0)),
2048        );
2049        assert!(
2050            !segmented_too_dense.success && !plain_too_dense.success,
2051            "ratio=50 atmosphere must fail in both wrappers: segmented={}, plain={}",
2052            segmented_too_dense.success,
2053            plain_too_dense.success
2054        );
2055        // realistic atmosphere -> success.
2056        let good = fast_integrate_with_segments(&inputs, vec![], mk((0.0, 15.0, 1013.25, 1.0)));
2057        assert!(good.success, "realistic atmosphere must yield success=true");
2058        // Direct-atmosphere mode (density, speed_of_sound, 0, 0) is legitimate and must NOT
2059        // be rejected by the guard (regression: 0.21.2 rejected it via the pressure<=0 check).
2060        let direct = fast_integrate_with_segments(&inputs, vec![], mk((1.225, 340.0, 0.0, 0.0)));
2061        assert!(
2062            direct.success,
2063            "direct-atmosphere mode (pressure=0 sentinel) must yield success=true"
2064        );
2065    }
2066
2067    #[test]
2068    fn fast_paths_reject_invalid_wind_segments() {
2069        let inputs = BallisticInputs {
2070            muzzle_velocity: 800.0,
2071            bc_value: 0.5,
2072            bc_type: DragModel::G7,
2073            ..BallisticInputs::default()
2074        };
2075        let mk = || FastIntegrationParams {
2076            horiz: 100.0,
2077            vert: 0.0,
2078            initial_state: [0.0, 0.0, 0.0, 800.0, 0.0, 0.0],
2079            t_span: (0.0, 5.0),
2080            atmo_params: (0.0, 15.0, 1013.25, 1.0),
2081            atmo_sock: None,
2082        };
2083        let invalid = crate::wind::WindSegment::new(10.0, 90.0, f64::NAN);
2084
2085        let plain = fast_integrate(&inputs, &WindSock::new(vec![invalid]), mk());
2086        let segmented = fast_integrate_with_segments(&inputs, vec![invalid], mk());
2087
2088        assert!(
2089            !plain.success && !segmented.success,
2090            "invalid segmented wind must fail in both fast wrappers: plain={}, segmented={}",
2091            plain.success,
2092            segmented.success
2093        );
2094    }
2095
2096    #[test]
2097    fn plain_fast_path_honors_direct_atmosphere_values() {
2098        fn final_speed(muzzle_velocity: f64, atmo_params: (f64, f64, f64, f64)) -> f64 {
2099            let inputs = BallisticInputs {
2100                muzzle_velocity,
2101                bc_value: 0.5,
2102                bc_type: DragModel::G7,
2103                ground_threshold: -100.0,
2104                ..BallisticInputs::default()
2105            };
2106
2107            let wind_sock = WindSock::new(vec![]);
2108            let solution = fast_integrate(
2109                &inputs,
2110                &wind_sock,
2111                FastIntegrationParams {
2112                    horiz: 10_000.0,
2113                    vert: 0.0,
2114                    initial_state: [0.0, 0.0, 0.0, muzzle_velocity, 0.0, 0.0],
2115                    t_span: (0.0, 0.2),
2116                    atmo_params,
2117                    atmo_sock: None,
2118                },
2119            );
2120            assert!(solution.success);
2121
2122            let last = solution.y[0].len() - 1;
2123            (solution.y[3][last].powi(2)
2124                + solution.y[4][last].powi(2)
2125                + solution.y[5][last].powi(2))
2126            .sqrt()
2127        }
2128
2129        let thin_air = final_speed(800.0, (0.905, 340.0, 0.0, 0.0));
2130        let dense_air = final_speed(800.0, (1.225, 340.0, 0.0, 0.0));
2131        assert!(
2132            thin_air > dense_air,
2133            "lower supplied density must retain more velocity: thin={thin_air}, dense={dense_air}"
2134        );
2135
2136        let low_sound_speed = final_speed(340.0, (1.0, 300.0, 0.0, 0.0));
2137        let high_sound_speed = final_speed(340.0, (1.0, 400.0, 0.0, 0.0));
2138        assert!(
2139            (low_sound_speed - high_sound_speed).abs() > 1e-6,
2140            "supplied sound speed must affect Mach-dependent drag"
2141        );
2142    }
2143
2144    #[test]
2145    fn segmented_fast_path_nonpositive_density_ratio_uses_standard_fallback() {
2146        fn terminal_velocity(base_ratio: f64) -> f64 {
2147            let inputs = BallisticInputs {
2148                muzzle_velocity: 800.0,
2149                bc_value: 0.5,
2150                bc_type: DragModel::G7,
2151                ground_threshold: -100.0,
2152                ..BallisticInputs::default()
2153            };
2154
2155            let solution = fast_integrate_with_segments(
2156                &inputs,
2157                vec![],
2158                FastIntegrationParams {
2159                    horiz: 500.0,
2160                    vert: 0.0,
2161                    initial_state: [0.0, 0.0, 0.0, 800.0, 0.0, 0.0],
2162                    t_span: (0.0, 5.0),
2163                    atmo_params: (0.0, 15.0, 1013.25, base_ratio),
2164                    atmo_sock: None,
2165                },
2166            );
2167            assert!(solution.success);
2168
2169            let last = solution.y[3].len() - 1;
2170            solution.y[3][last]
2171        }
2172
2173        let explicit_sea_level = terminal_velocity(1.0);
2174        for base_ratio in [0.0, -1.0] {
2175            let missing_ratio = terminal_velocity(base_ratio);
2176            assert!(
2177                missing_ratio < 800.0,
2178                "missing density ratio must not create a vacuum trajectory: {missing_ratio}"
2179            );
2180            assert!((missing_ratio - explicit_sea_level).abs() < 1e-9);
2181        }
2182    }
2183
2184    #[test]
2185    fn fast_path_carries_real_bullet_geometry() {
2186        // MBA-717: build_inputs hardcoded diameter=.308 / length=1.24in / twist=10 because
2187        // TrajectoryParams didn't carry them. They're now plumbed through, so the BallisticInputs
2188        // the derivatives see reflect the real bullet (caliber gates the Magnus block at
2189        // bullet_diameter > 0.0). Guard against regressing back to the hardcoded values: a
2190        // zero-diameter input must reach the derivatives as zero (Magnus skipped), whereas the
2191        // old code would have forced .308 regardless. We assert the run still completes and the
2192        // two geometries don't crash — the data path is exercised end-to-end.
2193        let run = |diameter: f64, twist: f64| {
2194            let inputs = BallisticInputs {
2195                muzzle_velocity: 800.0,
2196                bc_value: 0.5,
2197                bc_type: DragModel::G7,
2198                bullet_diameter: diameter,
2199                bullet_length: 0.0318,
2200                twist_rate: twist,
2201                enable_advanced_effects: true,
2202                enable_magnus: true,
2203                ..BallisticInputs::default()
2204            };
2205            let v = 800.0_f64;
2206            let elev = 0.02_f64;
2207            let params = FastIntegrationParams {
2208                horiz: 1000.0,
2209                vert: 0.0,
2210                initial_state: [0.0, 0.0, 0.0, v * elev.cos(), v * elev.sin(), 0.0],
2211                t_span: (0.0, 5.0),
2212                atmo_params: (0.0, 15.0, 1013.25, 1.0),
2213                atmo_sock: None,
2214            };
2215            fast_integrate_with_segments(&inputs, vec![], params)
2216        };
2217        // Both a real .224 and a real .338 produce a valid trajectory (geometry is honored, not
2218        // overridden by a hardcoded .308). Regression sentinel for the plumbing.
2219        assert!(run(0.00569, 7.0).success, ".224 geometry must solve");
2220        assert!(run(0.00858, 10.0).success, ".338 geometry must solve");
2221    }
2222
2223    #[test]
2224    fn segmented_fast_spin_flags_do_not_depend_on_advanced_umbrella() {
2225        fn endpoint(
2226            enable_advanced_effects: bool,
2227            enable_magnus: bool,
2228            use_enhanced_spin_drift: bool,
2229        ) -> Vector3<f64> {
2230            let inputs = BallisticInputs {
2231                muzzle_velocity: 823.0,
2232                bullet_mass: 168.0 * crate::constants::GRAINS_TO_KG,
2233                bullet_diameter: 0.308 * 0.0254,
2234                bullet_length: 1.215 * 0.0254,
2235                caliber_inches: 0.308,
2236                weight_grains: 168.0,
2237                bc_value: 0.475,
2238                bc_type: DragModel::G1,
2239                twist_rate: 12.0,
2240                is_twist_right: true,
2241                enable_advanced_effects,
2242                enable_magnus,
2243                use_enhanced_spin_drift,
2244                ..BallisticInputs::default()
2245            };
2246            let elevation = 0.02_f64;
2247            let solution = fast_integrate_with_segments(
2248                &inputs,
2249                vec![],
2250                FastIntegrationParams {
2251                    horiz: 1_000.0,
2252                    vert: 0.0,
2253                    initial_state: [
2254                        0.0,
2255                        0.0,
2256                        0.0,
2257                        inputs.muzzle_velocity * elevation.cos(),
2258                        inputs.muzzle_velocity * elevation.sin(),
2259                        0.0,
2260                    ],
2261                    t_span: (0.0, 5.0),
2262                    atmo_params: (0.0, 15.0, 1013.25, 1.0),
2263                    atmo_sock: None,
2264                },
2265            );
2266            assert!(solution.success);
2267            let last = solution.t.len() - 1;
2268            Vector3::new(
2269                solution.y[0][last],
2270                solution.y[1][last],
2271                solution.y[2][last],
2272            )
2273        }
2274
2275        let baseline = endpoint(false, false, false);
2276        let magnus_without_umbrella = endpoint(false, true, false);
2277        let magnus_with_umbrella = endpoint(true, true, false);
2278        assert!(
2279            (magnus_without_umbrella - baseline).norm() > 1e-5,
2280            "test shot must produce a measurable Magnus displacement"
2281        );
2282        assert!(
2283            (magnus_with_umbrella - magnus_without_umbrella).norm() < 1e-12,
2284            "the legacy umbrella must not suppress explicitly enabled Magnus: without={magnus_without_umbrella:?} with={magnus_with_umbrella:?}"
2285        );
2286
2287        let litz_only = endpoint(false, false, true);
2288        let litz_without_umbrella = endpoint(false, true, true);
2289        let litz_with_umbrella = endpoint(true, true, true);
2290        assert!(
2291            (litz_without_umbrella - litz_only).norm() < 1e-12,
2292            "Litz mode must suppress explicitly enabled Magnus: litz={litz_only:?} both={litz_without_umbrella:?}"
2293        );
2294        assert!(
2295            (litz_with_umbrella - litz_without_umbrella).norm() < 1e-12,
2296            "the legacy umbrella must not change Magnus suppression in Litz mode: without={litz_without_umbrella:?} with={litz_with_umbrella:?}"
2297        );
2298    }
2299
2300    /// MBA-1356: cd_scale — this module's custom-deck interpolation site.
2301    fn deck_test_inputs(cd_scale: f64) -> BallisticInputs {
2302        BallisticInputs {
2303            bullet_mass: 0.0106,
2304            bullet_diameter: 0.00782,
2305            muzzle_velocity: 850.0,
2306            custom_drag_table: Some(crate::drag::DragTable::new(
2307                vec![0.5, 1.0, 2.0, 3.0],
2308                vec![0.23, 0.40, 0.30, 0.26],
2309            )),
2310            cd_scale,
2311            temperature: 15.0,
2312            pressure: 1013.25,
2313            ..BallisticInputs::default()
2314        }
2315    }
2316
2317    fn deck_accel_x(cd_scale: f64) -> f64 {
2318        let inputs = deck_test_inputs(cd_scale);
2319        compute_derivatives(
2320            &[0.0, 0.0, 0.0, 700.0, 0.0, 0.0],
2321            &inputs,
2322            &WindSock::new(vec![]),
2323            FastAtmosphere::Standard {
2324                base_density: 1.225,
2325            },
2326            &inputs.bc_type,
2327            crate::transonic_drag::ProjectileShape::Spitzer,
2328            inputs.bc_value,
2329            false,
2330            false,
2331            None,
2332            None,
2333            None,
2334        )[3]
2335    }
2336
2337    #[test]
2338    fn cd_scale_default_is_one_and_absent_matches_explicit() {
2339        assert_eq!(BallisticInputs::default().cd_scale, 1.0);
2340
2341        let omitted_inputs = BallisticInputs {
2342            bullet_mass: 0.0106,
2343            bullet_diameter: 0.00782,
2344            muzzle_velocity: 850.0,
2345            custom_drag_table: Some(crate::drag::DragTable::new(
2346                vec![0.5, 1.0, 2.0, 3.0],
2347                vec![0.23, 0.40, 0.30, 0.26],
2348            )),
2349            temperature: 15.0,
2350            pressure: 1013.25,
2351            ..BallisticInputs::default()
2352        };
2353        assert_eq!(omitted_inputs.cd_scale, 1.0);
2354
2355        let a_omitted = compute_derivatives(
2356            &[0.0, 0.0, 0.0, 700.0, 0.0, 0.0],
2357            &omitted_inputs,
2358            &WindSock::new(vec![]),
2359            FastAtmosphere::Standard {
2360                base_density: 1.225,
2361            },
2362            &omitted_inputs.bc_type,
2363            crate::transonic_drag::ProjectileShape::Spitzer,
2364            omitted_inputs.bc_value,
2365            false,
2366            false,
2367            None,
2368            None,
2369            None,
2370        )[3];
2371        let a_explicit = deck_accel_x(1.0);
2372        assert_eq!(
2373            a_omitted.to_bits(),
2374            a_explicit.to_bits(),
2375            "omitted cd_scale (Default) must be bit-identical to an explicit 1.0"
2376        );
2377    }
2378
2379    /// (b) Scale-direction test, fast_trajectory path: cd_scale=1.10 must add more drag
2380    /// (a more negative x-acceleration) than 1.0; 0.90 must add less.
2381    #[test]
2382    fn cd_scale_direction_on_fast_trajectory_kernel() {
2383        let baseline = deck_accel_x(1.0);
2384        let scaled_up = deck_accel_x(1.10);
2385        let scaled_down = deck_accel_x(0.90);
2386
2387        assert!(
2388            scaled_up < baseline,
2389            "cd_scale=1.10 must increase drag deceleration (more negative ax): \
2390             base={baseline} up={scaled_up}"
2391        );
2392        assert!(
2393            scaled_down > baseline,
2394            "cd_scale=0.90 must decrease drag deceleration (less negative ax): \
2395             base={baseline} down={scaled_down}"
2396        );
2397    }
2398
2399    /// cd_scale must be inert on the standard G-model/BC path (no custom_drag_table).
2400    #[test]
2401    fn cd_scale_is_inert_without_a_custom_drag_table() {
2402        let make = |cd_scale: f64| BallisticInputs {
2403            bc_value: 0.5,
2404            bc_type: DragModel::G1,
2405            temperature: 15.0,
2406            pressure: 1013.25,
2407            cd_scale,
2408            ..BallisticInputs::default()
2409        };
2410        let accel = |cd_scale: f64| {
2411            let inputs = make(cd_scale);
2412            compute_derivatives(
2413                &[0.0, 0.0, 0.0, 700.0, 0.0, 0.0],
2414                &inputs,
2415                &WindSock::new(vec![]),
2416                FastAtmosphere::Standard {
2417                    base_density: 1.225,
2418                },
2419                &inputs.bc_type,
2420                crate::transonic_drag::ProjectileShape::Spitzer,
2421                inputs.bc_value,
2422                false,
2423                false,
2424                None,
2425                None,
2426                None,
2427            )[3]
2428        };
2429        assert_eq!(
2430            accel(1.0).to_bits(),
2431            accel(1.5).to_bits(),
2432            "cd_scale must not affect the G-model/BC drag path"
2433        );
2434    }
2435
2436    /// Fly `inputs` through the binding entry point and return the airspeed at t = 1.5 s.
2437    fn segmented_speed_at_1_5_s(inputs: &BallisticInputs) -> f64 {
2438        let v = inputs.muzzle_velocity;
2439        let elev = 0.012_f64;
2440        let solution = fast_integrate_with_segments(
2441            inputs,
2442            vec![],
2443            FastIntegrationParams {
2444                horiz: 1000.0,
2445                vert: 0.0,
2446                initial_state: [0.0, 0.0, 0.0, v * elev.cos(), v * elev.sin(), 0.0],
2447                t_span: (0.0, 5.0),
2448                atmo_params: (0.0, 15.0, 1013.25, 1.0),
2449                atmo_sock: None,
2450            },
2451        );
2452        assert!(solution.success);
2453        let s = solution.sol(&[1.5]);
2454        (s[3][0].powi(2) + s[4][0].powi(2) + s[5][0].powi(2)).sqrt()
2455    }
2456
2457    fn mba1602_308_inputs() -> BallisticInputs {
2458        BallisticInputs {
2459            muzzle_velocity: 792.48,
2460            bullet_mass: 0.01134,
2461            bullet_diameter: 0.0078232,
2462            bullet_length: 0.031496,
2463            bc_value: 0.505,
2464            bc_type: DragModel::G1,
2465            ..BallisticInputs::default()
2466        }
2467    }
2468
2469    #[test]
2470    fn segmented_fast_path_flies_caller_velocity_bc_ladder() {
2471        // MBA-1602: fast_integrate_with_segments (the Python binding's fast_integrate) built
2472        // its derivative inputs with bc_segments_data: None, so a caller's ladder was dropped
2473        // and, with use_bc_segments on, silently replaced by the auto-estimated one. A one-band
2474        // ladder at BC X must fly exactly like the scalar BC X.
2475        let base = mba1602_308_inputs();
2476        let mut ladder = base.clone();
2477        ladder.use_bc_segments = true;
2478        ladder.bc_segments_data = Some(vec![BCSegmentData {
2479            velocity_min: 0.0,
2480            velocity_max: 5000.0,
2481            bc_value: 0.300,
2482        }]);
2483        let scalar = BallisticInputs {
2484            bc_value: 0.300,
2485            ..base.clone()
2486        };
2487        let mut estimated = base.clone();
2488        estimated.use_bc_segments = true;
2489
2490        let flown = segmented_speed_at_1_5_s(&ladder);
2491        let expected = segmented_speed_at_1_5_s(&scalar);
2492        let auto = segmented_speed_at_1_5_s(&estimated);
2493        assert!(
2494            (flown - expected).abs() < 1e-9,
2495            "a one-band 0.300 ladder must fly as scalar BC 0.300: ladder={flown} scalar={expected}"
2496        );
2497        assert!(
2498            (flown - auto).abs() > 10.0,
2499            "the caller's ladder must not be replaced by the auto-estimate: ladder={flown} estimate={auto}"
2500        );
2501    }
2502
2503    #[test]
2504    fn segmented_fast_path_converts_army_standard_metro_caller_ladder() {
2505        // MBA-1602 + MBA-1365: the ladder is threaded AFTER normalize_for_solve, so an ASM ladder
2506        // flies as its ICAO equivalent, exactly like an ASM scalar.
2507        let base = mba1602_308_inputs();
2508        let mut ladder = base.clone();
2509        ladder.bc_reference_standard = crate::cli_api::BcReferenceStandard::ArmyStandardMetro;
2510        ladder.use_bc_segments = true;
2511        ladder.bc_segments_data = Some(vec![BCSegmentData {
2512            velocity_min: 0.0,
2513            velocity_max: 5000.0,
2514            bc_value: 0.300,
2515        }]);
2516        let scalar = BallisticInputs {
2517            bc_value: 0.300,
2518            bc_reference_standard: crate::cli_api::BcReferenceStandard::ArmyStandardMetro,
2519            ..base
2520        };
2521        let flown = segmented_speed_at_1_5_s(&ladder);
2522        let expected = segmented_speed_at_1_5_s(&scalar);
2523        assert!(
2524            (flown - expected).abs() < 1e-9,
2525            "an ASM ladder must be converted like an ASM scalar: ladder={flown} scalar={expected}"
2526        );
2527    }
2528
2529    #[test]
2530    fn segmented_fast_path_empty_ladder_matches_absent_ladder() {
2531        // MBA-1602: an empty ladder is no ladder. With use_bc_segments on, Some([]) must give the
2532        // byte-identical result None gives (today's auto-estimate on this path).
2533        let mut absent = mba1602_308_inputs();
2534        absent.use_bc_segments = true;
2535        let mut empty = absent.clone();
2536        empty.bc_segments_data = Some(Vec::new());
2537        assert_eq!(
2538            segmented_speed_at_1_5_s(&empty).to_bits(),
2539            segmented_speed_at_1_5_s(&absent).to_bits(),
2540            "Some(empty) must behave exactly like None"
2541        );
2542    }
2543}