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::get_local_atmosphere_humid,
8    constants::{G_ACCEL_MPS2, MPS_TO_FPS},
9    drag::get_drag_coefficient,
10    wind::WindSock,
11    BCSegmentData, DragModel, InternalBallisticInputs as BallisticInputs,
12};
13use nalgebra::Vector3;
14
15/// Fast solution container matching Python implementation
16#[derive(Debug, Clone)]
17pub struct FastSolution {
18    /// Time points
19    pub t: Vec<f64>,
20    /// State vectors at each time point [6 x n_points]
21    pub y: Vec<Vec<f64>>,
22    /// Event times [target_hit, max_ord, ground_hit]
23    pub t_events: [Vec<f64>; 3],
24    /// Whether integration succeeded
25    pub success: bool,
26}
27
28impl FastSolution {
29    /// Interpolate solution at time t
30    pub fn sol(&self, t_query: &[f64]) -> Vec<Vec<f64>> {
31        let mut result = vec![vec![0.0; t_query.len()]; 6];
32
33        for (i, &tq) in t_query.iter().enumerate() {
34            // Find the right interval using binary search
35            // Use unwrap_or to safely handle NaN values by treating them as greater
36            let idx = match self
37                .t
38                .binary_search_by(|&t| t.partial_cmp(&tq).unwrap_or(std::cmp::Ordering::Greater))
39            {
40                Ok(idx) => idx,
41                Err(idx) => idx,
42            };
43
44            if idx == 0 {
45                // Before first point
46                for j in 0..6 {
47                    result[j][i] = self.y[j][0];
48                }
49            } else if idx >= self.t.len() {
50                // After last point
51                for j in 0..6 {
52                    result[j][i] = self.y[j][self.t.len() - 1];
53                }
54            } else {
55                // Linear interpolation
56                let t0 = self.t[idx - 1];
57                let t1 = self.t[idx];
58                let span = t1 - t0;
59
60                for j in 0..6 {
61                    let y0 = self.y[j][idx - 1];
62                    let y1 = self.y[j][idx];
63                    result[j][i] = if span.abs() < f64::EPSILON {
64                        y1
65                    } else {
66                        let frac = (tq - t0) / span;
67                        y0 + frac * (y1 - y0)
68                    };
69                }
70            }
71        }
72
73        result
74    }
75
76    /// Convert from row-major to column-major format for compatibility
77    pub fn from_trajectory_data(
78        times: Vec<f64>,
79        states: Vec<[f64; 6]>,
80        t_events: [Vec<f64>; 3],
81    ) -> Self {
82        let n_points = times.len();
83        let mut y = vec![vec![0.0; n_points]; 6];
84
85        for (i, state) in states.iter().enumerate() {
86            for j in 0..6 {
87                y[j][i] = state[j];
88            }
89        }
90
91        FastSolution {
92            t: times,
93            y,
94            t_events,
95            success: true,
96        }
97    }
98
99    /// A clearly-failed solution carrying only the launch state, with `success = false`.
100    /// Used when inputs are too degenerate to integrate (e.g. non-physical atmosphere),
101    /// so callers see `success = false` instead of a stub trajectory reported as success.
102    fn degenerate(initial_state: &[f64; 6]) -> Self {
103        let mut y = vec![Vec::new(); 6];
104        for (j, slot) in y.iter_mut().enumerate() {
105            slot.push(initial_state[j]);
106        }
107        FastSolution {
108            t: vec![0.0],
109            y,
110            t_events: [Vec::new(), Vec::new(), Vec::new()],
111            success: false,
112        }
113    }
114}
115
116/// True if `atmo_params` can yield a finite, positive air density. `atmo_params` has TWO
117/// modes that `compute_derivatives` distinguishes:
118///   * **Standard**: `(base_alt_m, base_temp_c, base_pressure_hPa, base_density_ratio)` —
119///     positive station pressure. (Slot 3 is a density RATIO, not humidity, despite the
120///     `humidity` field it lands in via `build_inputs`.)
121///   * **Direct**: `(air_density, speed_of_sound, 0.0, 0.0)` — slots 2 and 3 are `0.0`
122///     sentinels, with a real density (< 2.0 kg/m³) and speed of sound (> 200 m/s).
123///
124/// A pressure <= 0 that ISN'T the direct-mode sentinel (or any non-finite value) — often a
125/// unit mistake like inHg where hPa is expected — gives zero/NaN density and would silently
126/// truncate the integration to a single point, so it's rejected. (Earlier this guard also
127/// rejected legitimate direct-mode input; the direct-mode allowance below fixes that.)
128fn atmo_is_physical(atmo_params: (f64, f64, f64, f64)) -> bool {
129    let (a, b, c, d) = atmo_params;
130    if !(a.is_finite() && b.is_finite() && c.is_finite() && d.is_finite()) {
131        return false;
132    }
133    // Direct-atmosphere mode: (density, speed_of_sound, 0, 0). Constants mirror
134    // derivatives.rs (MAX_REALISTIC_DENSITY = 2.0 kg/m³, MIN_REALISTIC_SPEED_OF_SOUND = 200 m/s).
135    let direct_mode = c == 0.0 && d == 0.0 && a > 0.0 && a < 2.0 && b > 200.0;
136    // Standard mode: positive station pressure (hPa).
137    direct_mode || c > 0.0
138}
139
140/// Fast trajectory integration parameters
141pub struct FastIntegrationParams {
142    pub horiz: f64,
143    pub vert: f64,
144    pub initial_state: [f64; 6],
145    pub t_span: (f64, f64),
146    /// Dual-mode atmosphere tuple — see [`atmo_is_physical`]. Standard mode is
147    /// `(base_alt_m, base_temp_c, base_pressure_hPa, base_density_ratio)` (slot 3 is a density
148    /// RATIO, not humidity); direct mode is `(air_density, speed_of_sound, 0.0, 0.0)`.
149    pub atmo_params: (f64, f64, f64, f64),
150}
151
152/// Aerodynamic-jump vertical launch-angle offset (radians) for the fast-integrate path.
153///
154/// Bryan Litz's crosswind estimator (`Y = 0.01*Sg - 0.0024*L + 0.032` MOA/mph) fed by the
155/// engine's Miller Sg. The fast path receives a prebuilt initial velocity (no muzzle angle),
156/// so the caller rotates that velocity by this offset. Returns 0 when the feature is off or
157/// the inputs are degenerate. Crosswind is taken from `wind_speed`/`wind_angle`
158/// (BallisticInputs convention: 0 = headwind, +90deg = from the right). MBA-959, EXPERIMENTAL.
159pub fn aerodynamic_jump_launch_offset_rad(
160    inputs: &BallisticInputs,
161    atmo_params: (f64, f64, f64, f64),
162) -> f64 {
163    if !inputs.enable_aerodynamic_jump {
164        return 0.0;
165    }
166    let diameter = inputs.bullet_diameter;
167    if !(inputs.twist_rate.is_finite() && inputs.twist_rate != 0.0)
168        || !(diameter.is_finite() && diameter > 0.0)
169        || !(inputs.bullet_length.is_finite() && inputs.bullet_length > 0.0)
170        || !inputs.muzzle_velocity.is_finite()
171    {
172        return 0.0;
173    }
174    let sg = crate::stability::compute_stability_coefficient(inputs, atmo_params);
175    if !(sg.is_finite() && sg > 0.0) {
176        return 0.0;
177    }
178    let length_cal = inputs.bullet_length / diameter;
179    const MS_TO_MPH: f64 = 2.236_936_292_054_4;
180    let crosswind_from_right_mph = inputs.wind_speed * inputs.wind_angle.sin() * MS_TO_MPH;
181    let vertical_moa = crate::aerodynamic_jump::litz_crosswind_jump_moa(
182        sg,
183        length_cal,
184        crosswind_from_right_mph,
185        inputs.is_twist_right,
186    );
187    if !vertical_moa.is_finite() {
188        return 0.0;
189    }
190    const MOA_PER_RAD: f64 = 3437.7467707849;
191    vertical_moa / MOA_PER_RAD
192}
193
194/// Rotate a McCoy-frame state's velocity (indices 3..6) by `theta_rad` in the vertical
195/// (downrange–vertical) plane, preserving speed and horizontal heading. Positive = up.
196fn rotate_launch_velocity(state: &mut [f64; 6], theta_rad: f64) {
197    let (vx, vy, vz) = (state[3], state[4], state[5]);
198    let speed = (vx * vx + vy * vy + vz * vz).sqrt();
199    if speed <= 0.0 {
200        return;
201    }
202    let h = (vx * vx + vz * vz).sqrt(); // horizontal (downrange+lateral) speed
203    let new_elev = vy.atan2(h) + theta_rad;
204    state[4] = speed * new_elev.sin();
205    let new_h = speed * new_elev.cos();
206    let scale = if h > 1e-12 { new_h / h } else { 0.0 };
207    state[3] = vx * scale;
208    state[5] = vz * scale;
209}
210
211/// Fast fixed-step integration for longer trajectories
212pub fn fast_integrate(
213    inputs: &BallisticInputs,
214    wind_sock: &WindSock,
215    params: FastIntegrationParams,
216) -> FastSolution {
217    // Degenerate atmosphere -> non-physical air density would silently stub the run.
218    if !atmo_is_physical(params.atmo_params) {
219        return FastSolution::degenerate(&params.initial_state);
220    }
221    let mut effective_inputs = inputs.clone();
222    if params.atmo_params.2 > 0.0 {
223        effective_inputs.altitude = params.atmo_params.0;
224        effective_inputs.temperature = params.atmo_params.1;
225        effective_inputs.pressure = params.atmo_params.2;
226        effective_inputs.humidity = params.atmo_params.3;
227    }
228    let inputs = &effective_inputs;
229    // Extract parameters
230    let _mass_kg = inputs.bullet_mass; // SI (kg)
231    let bc = inputs.bc_value;
232    let drag_model = &inputs.bc_type;
233
234    // Check for BC segments
235    let has_bc_segments =
236        inputs.bc_segments.is_some() && !inputs.bc_segments.as_ref().unwrap().is_empty();
237    let has_bc_segments_data =
238        inputs.bc_segments_data.is_some() && !inputs.bc_segments_data.as_ref().unwrap().is_empty();
239
240    // Time step - adjust based on distance
241    let dt = if params.horiz > 200.0 {
242        0.001
243    } else if params.horiz > 100.0 {
244        0.0005
245    } else {
246        0.0001
247    };
248
249    // MBA-959: aerodynamic jump perturbs the prebuilt launch velocity vertically (this path is
250    // handed an initial_state, not a muzzle angle). A no-op returning the original when disabled.
251    let mut initial_state = params.initial_state;
252    let aj_offset = aerodynamic_jump_launch_offset_rad(inputs, params.atmo_params);
253    if aj_offset != 0.0 {
254        rotate_launch_velocity(&mut initial_state, aj_offset);
255    }
256    let vx = initial_state[3]; // horizontal (downrange) velocity
257
258    // MBA-1145: decouple the integration-loop ceiling from the pre-allocation heuristic.
259    // Previously t_max = min(4*horiz/vx, t_span.1) bounded BOTH the Vec sizing AND the loop
260    // itself, so the 4x-horiz/vx estimate doubled as the loop cap. That estimate is only a
261    // heuristic — extreme high-drag or high-launch-angle shots exceed it, and the loop then
262    // terminated BEFORE hit_target/hit_ground, silently truncating the trajectory tail (Monte
263    // Carlo reported impact metrics short of the real range). The loop already breaks on
264    // hit_target (pos.x >= horiz) and hit_ground (pos.y <= ground_threshold), and any real
265    // trajectory descends below the ground threshold within a few seconds of apex, so the loop
266    // bound's only job is a runaway safety ceiling: use the full t_span.1 (default 30 s). The
267    // 4x estimate is retained ONLY to size the pre-allocation (keeps the small-allocation fast
268    // path for short shots); the Vec grows for the rare long run because the loop bound is n_steps.
269    let n_steps = ((params.t_span.1 / dt) as usize) + 1;
270    let est_steps = if vx > 1e-6 && params.horiz > 0.0 {
271        (((4.0 * params.horiz / vx) / dt) as usize) + 1
272    } else {
273        n_steps
274    };
275    let cap = est_steps.min(n_steps);
276    let mut times = Vec::with_capacity(cap);
277    let mut states = Vec::with_capacity(cap);
278
279    // Initial state (with the aerodynamic-jump launch perturbation applied above)
280    times.push(0.0);
281    states.push(initial_state);
282
283    // Base drag density = the muzzle (shooter-altitude) density. atmo_params.3 is base_ratio
284    // = air_density/1.225 at the shooter altitude (the MC caller computes it via
285    // calculate_atmosphere). Previously this called get_local_atmosphere with query alt 0.0
286    // while base_alt = shooter altitude, which re-scaled that ratio DOWN to sea level —
287    // discarding the correct altitude density and inflating drag for every elevated MC run.
288    // Guard a missing/absent ratio (base_ratio <= 0, e.g. legacy or uninitialized atmo_params):
289    // fall back to the standard sea-level density rather than 0, so a zero ratio cannot collapse
290    // density_scale to 0 and silently disable drag entirely. (atmo_params.0 is base_alt here, not
291    // a density, so it is not a usable fallback.)
292    let base_density = if params.atmo_params.3 > 0.0 {
293        params.atmo_params.3 * 1.225
294    } else {
295        1.225 // standard sea-level air density (kg/m^3)
296    };
297
298    // Hoist invariants out of compute_derivatives (called 4x per step). Both the drag-model name
299    // and the projectile shape depend only on inputs, not on state/mach, so computing them per
300    // call wasted an allocation + heuristic every k1..k4. Mirrors cli_api.rs exactly.
301
302    // Drag-model name as a borrowed &'static str. DragModel's Display goes via Debug, which
303    // heap-allocates a String on every call; this match is bit-identical (Display == Debug ==
304    // variant name) with no per-step allocation.
305    let drag_model_str: &str = match drag_model {
306        DragModel::G1 => "G1",
307        DragModel::G2 => "G2",
308        DragModel::G5 => "G5",
309        DragModel::G6 => "G6",
310        DragModel::G7 => "G7",
311        DragModel::G8 => "G8",
312        DragModel::GI => "GI",
313        DragModel::GS => "GS",
314    };
315
316    // SI fallbacks for caliber/weight (SI-only MC callers may leave the imperial fields 0).
317    let caliber_in = if inputs.caliber_inches > 0.0 {
318        inputs.caliber_inches
319    } else {
320        inputs.bullet_diameter / 0.0254
321    };
322    let weight_gr = if inputs.weight_grains > 0.0 {
323        inputs.weight_grains
324    } else {
325        inputs.bullet_mass / 0.00006479891
326    };
327
328    // Projectile shape for transonic corrections (MBA-949: shared resolver — bullet_model name
329    // first, then the caliber/weight/drag-model heuristic).
330    let projectile_shape = crate::transonic_drag::resolve_projectile_shape(
331        inputs.bullet_model.as_deref(),
332        caliber_in,
333        weight_gr,
334        drag_model_str,
335    );
336
337    // Coriolis omega (Earth rotation), hoisted (invariant over the flight). MBA-957:
338    // fast_integrate — the Monte Carlo / Python-binding path — previously applied NO Coriolis.
339    // Mirror the validated cli_api solver exactly: McCoy frame X=downrange, Y=up, Z=lateral;
340    // azimuth 0 = North; omega.Z is NEGATIVE (Omega.East = -Omega cos(lat) sin(az)); applied as
341    // the physical -2 Omega x v inside compute_derivatives.
342    let omega_vector = if inputs.enable_coriolis && inputs.latitude.is_some() {
343        let omega_earth = 7.2921159e-5_f64; // rad/s
344        let lat = inputs.latitude.unwrap().to_radians();
345        let az = inputs.shot_azimuth; // compass bearing (0=N), NOT the aiming offset
346        Some(Vector3::new(
347            omega_earth * lat.cos() * az.cos(),  // X: downrange
348            omega_earth * lat.sin(),             // Y: vertical
349            -omega_earth * lat.cos() * az.sin(), // Z: lateral (corrected sign)
350        ))
351    } else {
352        None
353    };
354
355    // Integration loop
356    let mut hit_target = false;
357    let mut hit_ground = false;
358    let mut max_ord_time = None;
359    let mut max_ord_y = 0.0;
360    let ground_threshold = inputs.ground_threshold;
361
362    // RK4 integration
363    for i in 0..n_steps - 1 {
364        let t = i as f64 * dt;
365        let state = states[i];
366
367        let pos = Vector3::new(state[0], state[1], state[2]);
368        let _vel = Vector3::new(state[3], state[4], state[5]);
369
370        // Check termination conditions (X is downrange, McCoy)
371        if pos.x >= params.horiz {
372            hit_target = true;
373            break;
374        }
375
376        if pos.y <= ground_threshold {
377            hit_ground = true;
378            break;
379        }
380
381        // Track maximum ordinate
382        if pos.y > max_ord_y {
383            max_ord_y = pos.y;
384            max_ord_time = Some(t);
385        }
386
387        // RK4 step
388        let k1 = compute_derivatives(
389            &state,
390            inputs,
391            wind_sock,
392            base_density,
393            drag_model,
394            projectile_shape,
395            bc,
396            has_bc_segments,
397            has_bc_segments_data,
398            omega_vector,
399        );
400
401        let mut state2 = state;
402        for j in 0..6 {
403            state2[j] = state[j] + 0.5 * dt * k1[j];
404        }
405        let k2 = compute_derivatives(
406            &state2,
407            inputs,
408            wind_sock,
409            base_density,
410            drag_model,
411            projectile_shape,
412            bc,
413            has_bc_segments,
414            has_bc_segments_data,
415            omega_vector,
416        );
417
418        let mut state3 = state;
419        for j in 0..6 {
420            state3[j] = state[j] + 0.5 * dt * k2[j];
421        }
422        let k3 = compute_derivatives(
423            &state3,
424            inputs,
425            wind_sock,
426            base_density,
427            drag_model,
428            projectile_shape,
429            bc,
430            has_bc_segments,
431            has_bc_segments_data,
432            omega_vector,
433        );
434
435        let mut state4 = state;
436        for j in 0..6 {
437            state4[j] = state[j] + dt * k3[j];
438        }
439        let k4 = compute_derivatives(
440            &state4,
441            inputs,
442            wind_sock,
443            base_density,
444            drag_model,
445            projectile_shape,
446            bc,
447            has_bc_segments,
448            has_bc_segments_data,
449            omega_vector,
450        );
451
452        // Update state
453        let mut new_state = state;
454        for j in 0..6 {
455            new_state[j] = state[j] + dt * (k1[j] + 2.0 * k2[j] + 2.0 * k3[j] + k4[j]) / 6.0;
456        }
457
458        times.push(t + dt);
459        states.push(new_state);
460    }
461
462    // Create event arrays
463    let t_events = [
464        if hit_target {
465            vec![*times.last().unwrap()]
466        } else {
467            vec![]
468        },
469        if let Some(t) = max_ord_time {
470            vec![t]
471        } else {
472            vec![]
473        },
474        if hit_ground {
475            vec![*times.last().unwrap()]
476        } else {
477            vec![]
478        },
479    ];
480
481    // MBA-1134 (rank 10) — regression fix: apply the canonical empirical Litz drift as a
482    // post-process to the lateral (McCoy Z) here too. The derivatives kernel no longer
483    // integrates spin drift, and this plain fast_integrate is the single-shot fast path
484    // (solve_trajectory_rust / the API), so without this it would carry NO spin drift and
485    // twist direction would have no effect (the Magnus term is also suppressed when
486    // use_enhanced_spin_drift is set). Mirrors fast_integrate_with_segments,
487    // cli_api::apply_spin_drift and the Monte-Carlo path so all solver families agree; uses
488    // the SAME muzzle Sg (spin_drift::effective_sg_from_inputs).
489    if inputs.use_enhanced_spin_drift {
490        // Standard-mode atmo_params is (base_alt, temp_c, press_hpa, ratio); direct mode
491        // (density, sound, 0, 0) carries no explicit temp/pressure, so fall back to sea-level
492        // standard (the Sg density correction is a no-op there).
493        let (sd_temp_c, sd_press_hpa) = if params.atmo_params.2 > 0.0 {
494            (params.atmo_params.1, params.atmo_params.2)
495        } else {
496            (15.0, 1013.25)
497        };
498        let sg = crate::spin_drift::effective_sg_from_inputs(inputs, sd_temp_c, sd_press_hpa);
499        for (t, state) in times.iter().zip(states.iter_mut()) {
500            if *t > 0.0 {
501                state[2] += crate::spin_drift::litz_drift_meters(sg, *t, inputs.is_twist_right);
502            }
503        }
504    }
505
506    FastSolution::from_trajectory_data(times, states, t_events)
507}
508
509/// Compute derivatives for the state vector
510fn compute_derivatives(
511    state: &[f64; 6],
512    inputs: &BallisticInputs,
513    wind_sock: &WindSock,
514    base_density: f64,
515    drag_model: &DragModel,
516    projectile_shape: crate::transonic_drag::ProjectileShape,
517    bc: f64,
518    has_bc_segments: bool,
519    has_bc_segments_data: bool,
520    omega: Option<Vector3<f64>>,
521) -> [f64; 6] {
522    let pos = Vector3::new(state[0], state[1], state[2]);
523    let vel = Vector3::new(state[3], state[4], state[5]);
524
525    // Get wind vector (based on downrange distance, which is X coordinate, McCoy)
526    let wind_vector = wind_sock.vector_for_range_stateless(pos.x);
527
528    // Velocity relative to air
529    let vel_adjusted = vel - wind_vector;
530    let v_mag = vel_adjusted.norm();
531
532    // Gravity acceleration vector, rotated into the shot-aligned frame by shooting_angle
533    // (uphill/downhill inclined fire), matching cli_api::TrajectorySolver::gravity_acceleration.
534    let theta = inputs.shooting_angle;
535    let accel_gravity = Vector3::new(
536        -G_ACCEL_MPS2 * theta.sin(),
537        -G_ACCEL_MPS2 * theta.cos(),
538        0.0,
539    );
540
541    // Calculate acceleration
542    let mut accel = if v_mag < 1e-6 {
543        accel_gravity
544    } else {
545        // Calculate drag
546        let v_fps = v_mag * MPS_TO_FPS;
547
548        // Calculate speed of sound from altitude using standard lapse rate.
549        // atmo_params: (base_alt, base_temp_c, base_press_hpa, base_ratio).
550        // MBA-1136 (rank 9): route the local speed of sound through the moist-air formula. Only
551        // the speed of sound is used here (density is discarded), so the base_ratio arg is inert
552        // (pass 1.0). Humidity is NOT plumbed to this call site: on the fast path
553        // (fast_integrate) the `humidity` FIELD is overwritten with atmo_params.3 (the density
554        // RATIO), so `inputs.humidity` is not a real RH — pass 0.0 (dry) rather than fabricate.
555        let altitude = inputs.altitude + pos.y;
556        let (_, speed_of_sound) = get_local_atmosphere_humid(
557            altitude,
558            inputs.altitude, // base_alt approximation
559            inputs.temperature,
560            inputs.pressure,
561            1.0, // base_ratio inert (density discarded)
562            0.0, // humidity not available here (see note above)
563        );
564        let mach = v_mag / speed_of_sound;
565
566        // Get BC value (potentially from segments)
567        let bc_current = if has_bc_segments_data && inputs.bc_segments_data.is_some() {
568            get_bc_from_velocity_segments(v_fps, inputs.bc_segments_data.as_ref().unwrap())
569        } else if has_bc_segments && inputs.bc_segments.is_some() {
570            crate::derivatives::interpolated_bc(
571                mach,
572                inputs.bc_segments.as_ref().unwrap(),
573                Some(inputs),
574            )
575        } else {
576            bc
577        };
578        // Guard bc_value == 0 (allowed on FFI/WASM/public MC surfaces): the division below
579        // would be Inf -> NaN. Mirrors cli_api's effective_bc.max(1e-6); inert for valid BCs.
580        let bc_current = bc_current.max(1e-6);
581
582        // Apply the transonic drag-rise correction once (mirrors derivatives.rs / cli_api) so
583        // the Monte Carlo / fast path doesn't under-predict drag near Mach 1. The projectile
584        // shape is invariant for the whole integration, so it is hoisted into fast_integrate and
585        // passed in rather than recomputed per call. wave_drag=false: the G1/G7 tables already
586        // embed the rise.
587        // MBA-940: a user-supplied custom drag table is the final Cd, used as-is (no G-model
588        // lookup, transonic, or form-factor correction — the curve already encodes the true drag).
589        // Its Cd is the projectile's ACTUAL drag coefficient, so the retardation denominator
590        // must be the sectional density (lb/in²), not a BC: Cd_own / SD == Cd_ref / BC
591        // (see BallisticInputs::custom_drag_denominator).
592        let (drag_factor, retard_denom) = if let Some(ref table) = inputs.custom_drag_table {
593            (
594                table.interpolate(mach),
595                inputs.custom_drag_denominator(bc_current),
596            )
597        } else {
598            let base_cd = get_drag_coefficient(mach, drag_model);
599            let cd =
600                crate::transonic_drag::transonic_correction(mach, base_cd, projectile_shape, false);
601            // MBA-948: honor use_form_factor in the fast path too (was derivatives.rs-only). No-op
602            // when the flag is false (apply_form_factor_to_drag short-circuits), as it is on every
603            // current consumer surface.
604            let cd = crate::form_factor::apply_form_factor_to_drag(
605                cd,
606                inputs.bullet_model.as_deref(),
607                &inputs.bc_type,
608                inputs.use_form_factor,
609            );
610            (cd, bc_current)
611        };
612
613        // Calculate drag acceleration using proper ballistics formula
614        let cd_to_retard = crate::constants::CD_TO_RETARD;
615        let standard_factor = drag_factor * cd_to_retard;
616        let density_scale = base_density / 1.225;
617
618        // Drag acceleration in ft/s^2
619        let a_drag_ft_s2 = (v_fps * v_fps) * standard_factor * density_scale / retard_denom;
620
621        // Convert to m/s^2 and apply to velocity vector
622        let a_drag_m_s2 = a_drag_ft_s2 * 0.3048; // ft/s^2 to m/s^2
623        let accel_drag = -a_drag_m_s2 * (vel_adjusted / v_mag);
624
625        // Total acceleration
626        accel_drag + accel_gravity
627    };
628
629    // Coriolis (Earth rotation), MBA-957. omega already carries the corrected lateral sign; use
630    // the ground-frame velocity and the physical -2 Omega x v, exactly as the validated cli_api.
631    if let Some(omega) = omega {
632        accel += -2.0 * omega.cross(&vel);
633    }
634
635    // Return derivatives [vx, vy, vz, ax, ay, az]
636    [vel.x, vel.y, vel.z, accel.x, accel.y, accel.z]
637}
638
639/// Get BC from velocity-based segments
640fn get_bc_from_velocity_segments(velocity_fps: f64, segments: &[BCSegmentData]) -> f64 {
641    for segment in segments {
642        if velocity_fps >= segment.velocity_min && velocity_fps <= segment.velocity_max {
643            return segment.bc_value;
644        }
645    }
646
647    // If no matching segment, use the BC from the closest segment
648    if let Some(first) = segments.first() {
649        if velocity_fps < first.velocity_min {
650            return first.bc_value;
651        }
652    }
653
654    if let Some(last) = segments.last() {
655        if velocity_fps > last.velocity_max {
656            return last.bc_value;
657        }
658    }
659
660    // Fallback (shouldn't reach here if segments are properly defined)
661    0.5
662}
663
664/// Fast integration with explicit wind segments using RK45
665/// MBA-155: Upstreamed from ballistics_rust
666pub fn fast_integrate_with_segments(
667    inputs: &BallisticInputs,
668    wind_segments: Vec<crate::wind::WindSegment>,
669    params: FastIntegrationParams,
670) -> FastSolution {
671    // Use the RK45 implementation from trajectory_integration module
672    use crate::trajectory_integration::{integrate_trajectory, TrajectoryParams};
673
674    // Degenerate atmosphere -> non-physical air density would silently stub the run.
675    if !atmo_is_physical(params.atmo_params) {
676        return FastSolution::degenerate(&params.initial_state);
677    }
678
679    // Extract parameters
680    let mass_kg = inputs.bullet_mass; // SI (kg)
681    let bc = inputs.bc_value;
682    let drag_model = inputs.bc_type;
683
684    // Coriolis omega — gated on enable_coriolis (+ a latitude), INDEPENDENT of
685    // spin-drift/Magnus. A caller can now request Coriolis-only (enable_coriolis=true
686    // with enable_advanced_effects=false) instead of being forced to enable all three.
687    let omega_vector = if inputs.enable_coriolis && inputs.latitude.is_some() {
688        // Calculate omega based on latitude and shot azimuth
689        // The Earth's rotation vector must be projected into the shooter's
690        // local frame which depends on azimuth (shooting direction).
691        // azimuth_angle: 0 = North, pi/2 = East
692        let omega_earth = 7.2921159e-5; // rad/s
693        let lat_rad = inputs.latitude.unwrap_or(0.0).to_radians();
694        let azimuth = inputs.shot_azimuth; // compass bearing (0=N), NOT the aiming offset
695        Some(Vector3::new(
696            omega_earth * lat_rad.cos() * azimuth.cos(), // X: downrange component
697            omega_earth * lat_rad.sin(),                 // Y: vertical component
698            -omega_earth * lat_rad.cos() * azimuth.sin(), // Z: lateral (MBA-957: corrected sign)
699        ))
700    } else {
701        None
702    };
703
704    // Set up trajectory parameters
705    let traj_params = TrajectoryParams {
706        mass_kg,
707        bc,
708        drag_model,
709        wind_segments,
710        atmos_params: params.atmo_params,
711        omega_vector,
712        enable_spin_drift: inputs.enable_advanced_effects,
713        enable_magnus: inputs.enable_magnus,
714        enable_coriolis: inputs.enable_coriolis,
715        target_distance_m: params.horiz,
716        enable_wind_shear: inputs.enable_wind_shear,
717        wind_shear_model: inputs.wind_shear_model.clone(),
718        shooter_altitude_m: inputs.altitude,
719        is_twist_right: inputs.is_twist_right,
720        shooting_angle: inputs.shooting_angle,
721        // MBA-717: carry the real bullet geometry so spin-drift / Magnus use it.
722        bullet_diameter: inputs.bullet_diameter,
723        bullet_length: inputs.bullet_length,
724        twist_rate: inputs.twist_rate,
725        custom_drag_table: inputs.custom_drag_table.clone(),
726        bc_segments: inputs.bc_segments.clone(),
727        use_bc_segments: inputs.use_bc_segments,
728        // MBA-954: keep the historical -1000.0 here (behavior-preserving for this binding path);
729        // threading inputs.ground_threshold would change the default ground plane for existing
730        // callers. Direct TrajectoryParams constructors can now configure it.
731        ground_threshold: -1000.0,
732    };
733
734    // Use RK45 adaptive integration
735    let trajectory = integrate_trajectory(
736        params.initial_state,
737        params.t_span,
738        traj_params,
739        "RK45", // Use RK45 implementation
740        1e-6,   // tolerance
741        0.01,   // max_step
742    );
743
744    // Convert trajectory to FastSolution format
745    let n_points = trajectory.len();
746    let mut times = Vec::with_capacity(n_points);
747    let mut states = Vec::with_capacity(n_points);
748
749    let mut target_hit_time: Option<f64> = None;
750    let mut ground_hit_time: Option<f64> = None;
751    let mut max_ord_time = None;
752    let mut max_ord_y = 0.0;
753
754    for (t, state_vec) in trajectory {
755        // Convert Vector6 to array
756        let state = [
757            state_vec[0],
758            state_vec[1],
759            state_vec[2],
760            state_vec[3],
761            state_vec[4],
762            state_vec[5],
763        ];
764
765        // Check termination conditions
766        // McCoy: state[0]=downrange, state[1]=vertical, state[2]=lateral
767
768        // Record FIRST time target is hit
769        if target_hit_time.is_none() && state[0] >= params.horiz {
770            target_hit_time = Some(t);
771        }
772
773        // Record ground hit
774        if ground_hit_time.is_none() && state[1] <= inputs.ground_threshold {
775            ground_hit_time = Some(t);
776        }
777
778        // Track maximum ordinate
779        if state[1] > max_ord_y {
780            max_ord_y = state[1];
781            max_ord_time = Some(t);
782        }
783
784        times.push(t);
785        states.push(state);
786    }
787
788    // Create event arrays
789    let t_events = [
790        if let Some(t) = target_hit_time {
791            vec![t]
792        } else {
793            vec![]
794        },
795        if let Some(t) = max_ord_time {
796            vec![t]
797        } else {
798            vec![]
799        },
800        if let Some(t) = ground_hit_time {
801            vec![t]
802        } else {
803            vec![]
804        },
805    ];
806
807    // MBA-1134 (rank 10): the derivatives kernel no longer integrates spin drift, so apply the
808    // canonical empirical Litz drift as a post-process to the lateral (McCoy Z) of every point at
809    // its time of flight — matching cli_api::apply_spin_drift and the Monte-Carlo path so all three
810    // solver families agree. Uses the SAME muzzle Sg (spin_drift::effective_sg_from_inputs).
811    if inputs.use_enhanced_spin_drift {
812        // Standard-mode atmo_params is (base_alt, temp_c, press_hpa, ratio); direct mode
813        // (density, sound, 0, 0) carries no explicit temp/pressure, so fall back to sea-level
814        // standard (the Sg density correction is a no-op there).
815        let (sd_temp_c, sd_press_hpa) = if params.atmo_params.2 > 0.0 {
816            (params.atmo_params.1, params.atmo_params.2)
817        } else {
818            (15.0, 1013.25)
819        };
820        let sg = crate::spin_drift::effective_sg_from_inputs(inputs, sd_temp_c, sd_press_hpa);
821        for (t, state) in times.iter().zip(states.iter_mut()) {
822            if *t > 0.0 {
823                state[2] += crate::spin_drift::litz_drift_meters(sg, *t, inputs.is_twist_right);
824            }
825        }
826    }
827
828    FastSolution::from_trajectory_data(times, states, t_events)
829}
830
831#[cfg(test)]
832mod tests {
833    use super::*;
834
835    #[test]
836    fn test_fast_solution_interpolation() {
837        let times = vec![0.0, 1.0, 2.0];
838        let states = vec![
839            [0.0, 0.0, 0.0, 100.0, 50.0, 0.0],
840            [100.0, 45.0, 0.0, 99.0, 40.0, 0.0],
841            [198.0, 80.0, 0.0, 98.0, 30.0, 0.0],
842        ];
843
844        let solution = FastSolution::from_trajectory_data(times, states, [vec![], vec![], vec![]]);
845
846        // Test interpolation at t=1.5
847        let result = solution.sol(&[1.5]);
848
849        assert!((result[0][0] - 149.0).abs() < 1e-10); // x position
850        assert!((result[1][0] - 62.5).abs() < 1e-10); // y position
851        assert!((result[3][0] - 98.5).abs() < 1e-10); // vx velocity
852    }
853
854    #[test]
855    fn test_bc_from_velocity_segments() {
856        let segments = vec![
857            BCSegmentData {
858                velocity_min: 0.0,
859                velocity_max: 1000.0,
860                bc_value: 0.5,
861            },
862            BCSegmentData {
863                velocity_min: 1000.0,
864                velocity_max: 2000.0,
865                bc_value: 0.52,
866            },
867            BCSegmentData {
868                velocity_min: 2000.0,
869                velocity_max: 3000.0,
870                bc_value: 0.55,
871            },
872        ];
873
874        assert_eq!(get_bc_from_velocity_segments(500.0, &segments), 0.5);
875        assert_eq!(get_bc_from_velocity_segments(1500.0, &segments), 0.52);
876        assert_eq!(get_bc_from_velocity_segments(2500.0, &segments), 0.55);
877
878        // Test edge cases
879        assert_eq!(get_bc_from_velocity_segments(-100.0, &segments), 0.5); // Below min
880        assert_eq!(get_bc_from_velocity_segments(3500.0, &segments), 0.55); // Above max
881    }
882
883    #[test]
884    fn test_fast_solution_interpolation_edge_cases() {
885        let times = vec![0.0, 1.0, 2.0, 3.0];
886        let states = vec![
887            [0.0, 0.0, 0.0, 800.0, 50.0, 0.0],
888            [800.0, 40.0, 100.0, 750.0, 30.0, 0.0],
889            [1550.0, 60.0, 200.0, 700.0, 10.0, 0.0],
890            [2250.0, 50.0, 300.0, 650.0, -10.0, 0.0],
891        ];
892
893        let solution = FastSolution::from_trajectory_data(times, states, [vec![], vec![], vec![]]);
894
895        // Test interpolation before first point
896        let result_before = solution.sol(&[-0.5]);
897        assert!((result_before[0][0] - 0.0).abs() < 1e-10); // Should clamp to first
898
899        // Test interpolation after last point
900        let result_after = solution.sol(&[5.0]);
901        assert!((result_after[0][0] - 2250.0).abs() < 1e-10); // Should clamp to last
902
903        // Test interpolation at exact points
904        let result_exact = solution.sol(&[1.0]);
905        assert!((result_exact[0][0] - 800.0).abs() < 1e-10);
906
907        // Test multiple query points
908        let result_multi = solution.sol(&[0.5, 1.5, 2.5]);
909        assert_eq!(result_multi[0].len(), 3);
910    }
911
912    #[test]
913    fn test_fast_solution_from_trajectory_data() {
914        let times = vec![0.0, 0.5, 1.0];
915        let states = vec![
916            [0.0, 1.0, 2.0, 3.0, 4.0, 5.0],
917            [10.0, 11.0, 12.0, 13.0, 14.0, 15.0],
918            [20.0, 21.0, 22.0, 23.0, 24.0, 25.0],
919        ];
920        let t_events = [vec![1.0], vec![0.5], vec![]];
921
922        let solution = FastSolution::from_trajectory_data(times.clone(), states, t_events);
923
924        // Check that data is stored correctly
925        assert_eq!(solution.t, times);
926        assert_eq!(solution.y.len(), 6); // 6 state components
927        assert_eq!(solution.y[0].len(), 3); // 3 time points
928        assert!(solution.success);
929
930        // Verify column-major storage
931        assert_eq!(solution.y[0][0], 0.0); // x at t=0
932        assert_eq!(solution.y[1][0], 1.0); // y at t=0
933        assert_eq!(solution.y[0][2], 20.0); // x at t=1.0
934    }
935
936    #[test]
937    fn test_bc_segments_boundary_conditions() {
938        // Test with single segment
939        let single_segment = vec![BCSegmentData {
940            velocity_min: 1000.0,
941            velocity_max: 2000.0,
942            bc_value: 0.5,
943        }];
944
945        assert_eq!(get_bc_from_velocity_segments(500.0, &single_segment), 0.5); // Below
946        assert_eq!(get_bc_from_velocity_segments(1500.0, &single_segment), 0.5); // In range
947        assert_eq!(get_bc_from_velocity_segments(2500.0, &single_segment), 0.5); // Above
948
949        // Test with exact boundary values
950        // Note: When velocity matches boundary, first matching segment wins
951        let segments = vec![
952            BCSegmentData {
953                velocity_min: 0.0,
954                velocity_max: 999.0, // Exclusive upper bound to avoid overlap
955                bc_value: 0.45,
956            },
957            BCSegmentData {
958                velocity_min: 1000.0,
959                velocity_max: 2000.0,
960                bc_value: 0.50,
961            },
962        ];
963
964        assert_eq!(get_bc_from_velocity_segments(1000.0, &segments), 0.50); // At second segment start
965        assert_eq!(get_bc_from_velocity_segments(0.0, &segments), 0.45); // At min
966        assert_eq!(get_bc_from_velocity_segments(999.0, &segments), 0.45); // At first segment max
967    }
968
969    #[test]
970    fn test_bc_segments_empty_fallback() {
971        let empty_segments: Vec<BCSegmentData> = vec![];
972
973        // With empty segments, should return fallback value
974        let result = get_bc_from_velocity_segments(1500.0, &empty_segments);
975        assert_eq!(result, 0.5); // Fallback value
976    }
977
978    #[test]
979    fn test_fast_integration_params() {
980        // Verify FastIntegrationParams struct can be constructed
981        let params = FastIntegrationParams {
982            horiz: 1000.0,
983            vert: 0.0,
984            initial_state: [0.0, 0.0, 0.0, 800.0, 50.0, 0.0], // McCoy: vx=downrange
985            t_span: (0.0, 5.0),
986            atmo_params: (0.0, 59.0, 29.92, 0.0),
987        };
988
989        assert_eq!(params.horiz, 1000.0);
990        assert_eq!(params.t_span.0, 0.0);
991        assert_eq!(params.t_span.1, 5.0);
992        assert_eq!(params.initial_state[3], 800.0); // vx (downrange, McCoy)
993    }
994
995    #[test]
996    fn test_fast_solution_event_arrays() {
997        let times = vec![0.0, 1.0, 2.0];
998        let states = vec![
999            [0.0, 0.0, 0.0, 800.0, 50.0, 0.0],
1000            [800.0, 40.0, 500.0, 750.0, 30.0, 0.0],
1001            [1500.0, 20.0, 1000.0, 700.0, 10.0, 0.0],
1002        ];
1003
1004        // Create solution with events
1005        let t_events = [
1006            vec![2.0], // target_hit at t=2
1007            vec![0.5], // max_ord at t=0.5
1008            vec![],    // no ground_hit
1009        ];
1010
1011        let solution = FastSolution::from_trajectory_data(times, states, t_events);
1012
1013        assert_eq!(solution.t_events[0], vec![2.0]); // Target hit
1014        assert_eq!(solution.t_events[1], vec![0.5]); // Max ordinate
1015        assert!(solution.t_events[2].is_empty()); // No ground hit
1016    }
1017
1018    #[test]
1019    fn fast_path_coriolis_uses_shot_direction() {
1020        // Regression: fast_integrate_with_segments (the path the Python binding uses)
1021        // built its Coriolis omega from azimuth_angle (the aiming offset, always ~0)
1022        // instead of shot_azimuth, so east and west shots came out identical. After the
1023        // fix they must differ with the correct Eotvos sign (east lifted, higher).
1024        use std::f64::consts::FRAC_PI_2;
1025        // Returns (final_downrange, final_vertical) for a shot fired along `shot_az`.
1026        fn final_xy(shot_az: f64) -> (f64, f64) {
1027            let mut inputs = BallisticInputs::default();
1028            inputs.muzzle_velocity = 800.0;
1029            inputs.bc_value = 0.5;
1030            inputs.bc_type = DragModel::G7;
1031            inputs.enable_advanced_effects = true; // gates the omega vector
1032            inputs.enable_coriolis = true;
1033            inputs.latitude = Some(45.0);
1034            inputs.shot_azimuth = shot_az;
1035            let v = 800.0_f64;
1036            let elev = 0.02_f64;
1037            let params = FastIntegrationParams {
1038                horiz: 1000.0,
1039                vert: 0.0,
1040                initial_state: [0.0, 0.0, 0.0, v * elev.cos(), v * elev.sin(), 0.0],
1041                t_span: (0.0, 5.0),
1042                atmo_params: (0.0, 59.0, 29.92, 0.0),
1043            };
1044            let sol = fast_integrate_with_segments(&inputs, vec![], params);
1045            let n = sol.y[0].len();
1046            (sol.y[0][n - 1], sol.y[1][n - 1])
1047        }
1048        let (ex, ey) = final_xy(FRAC_PI_2); // east
1049        let (wx, wy) = final_xy(3.0 * FRAC_PI_2); // west
1050                                                  // Both shots cover essentially the same downrange (Coriolis barely affects x),
1051                                                  // so comparing the final vertical is apples-to-apples.
1052        assert!(
1053            (ex - wx).abs() < 0.5,
1054            "east/west downrange should be ~equal (ex={ex:.4}, wx={wx:.4})"
1055        );
1056        // Pre-fix the fast path was North-locked, making these byte-identical. The Eotvos
1057        // term now lifts the east shot above the west shot.
1058        assert!(
1059            ey > wy,
1060            "fast-path east ({ey:.6}) must be higher than west ({wy:.6}) (Eotvos)"
1061        );
1062        assert!(
1063            (ey - wy) > 1e-5,
1064            "fast-path E-W vertical separation ({:.8} m) should be non-zero (the pre-fix bug was exact equality)",
1065            ey - wy
1066        );
1067    }
1068
1069    #[test]
1070    fn fast_path_coriolis_independent_of_advanced_effects() {
1071        // Coriolis is now gated on enable_coriolis (+ latitude), NOT enable_advanced_effects.
1072        // So a caller can request Coriolis-only without being forced to enable spin/Magnus.
1073        use std::f64::consts::FRAC_PI_2;
1074        fn final_y(coriolis: bool, shot_az: f64) -> f64 {
1075            let mut inputs = BallisticInputs::default();
1076            inputs.muzzle_velocity = 800.0;
1077            inputs.bc_value = 0.5;
1078            inputs.bc_type = DragModel::G7;
1079            inputs.enable_coriolis = coriolis;
1080            inputs.enable_advanced_effects = false; // explicitly OFF — Coriolis must still work
1081            inputs.latitude = Some(45.0);
1082            inputs.shot_azimuth = shot_az;
1083            let v = 800.0_f64;
1084            let elev = 0.02_f64;
1085            let params = FastIntegrationParams {
1086                horiz: 1000.0,
1087                vert: 0.0,
1088                initial_state: [0.0, 0.0, 0.0, v * elev.cos(), v * elev.sin(), 0.0],
1089                t_span: (0.0, 5.0),
1090                atmo_params: (0.0, 59.0, 29.92, 0.0),
1091            };
1092            let sol = fast_integrate_with_segments(&inputs, vec![], params);
1093            let n = sol.y[0].len();
1094            sol.y[1][n - 1]
1095        }
1096        // enable_coriolis=true with advanced effects OFF: directional Coriolis still applies.
1097        let e = final_y(true, FRAC_PI_2);
1098        let w = final_y(true, 3.0 * FRAC_PI_2);
1099        assert!(
1100            e > w && (e - w) > 1e-5,
1101            "Coriolis-only (no advanced effects) must still be directional: E={e} W={w}"
1102        );
1103        // enable_coriolis=false: no Coriolis at all, east == west.
1104        let e2 = final_y(false, FRAC_PI_2);
1105        let w2 = final_y(false, 3.0 * FRAC_PI_2);
1106        assert!(
1107            (e2 - w2).abs() < 1e-9,
1108            "with enable_coriolis=false, east/west must be identical: E={e2} W={w2}"
1109        );
1110    }
1111
1112    #[test]
1113    fn fast_path_rejects_degenerate_atmosphere() {
1114        let mut inputs = BallisticInputs::default();
1115        inputs.muzzle_velocity = 800.0;
1116        inputs.bc_value = 0.5;
1117        inputs.bc_type = DragModel::G7;
1118        let v = 800.0_f64;
1119        let e = 0.02_f64;
1120        let mk = |atmo: (f64, f64, f64, f64)| FastIntegrationParams {
1121            horiz: 500.0,
1122            vert: 0.0,
1123            initial_state: [0.0, 0.0, 0.0, v * e.cos(), v * e.sin(), 0.0],
1124            t_span: (0.0, 5.0),
1125            atmo_params: atmo,
1126        };
1127        // pressure <= 0 -> fail loudly (success=false) instead of a 1-point stub as success.
1128        let zero_p = fast_integrate_with_segments(&inputs, vec![], mk((0.0, 15.0, 0.0, 50.0)));
1129        assert!(
1130            !zero_p.success,
1131            "pressure=0 atmosphere must yield success=false"
1132        );
1133        // non-finite pressure -> also rejected.
1134        let nan_p = fast_integrate_with_segments(&inputs, vec![], mk((0.0, 15.0, f64::NAN, 50.0)));
1135        assert!(!nan_p.success, "NaN pressure must yield success=false");
1136        // realistic atmosphere -> success.
1137        let good = fast_integrate_with_segments(&inputs, vec![], mk((0.0, 15.0, 1013.25, 50.0)));
1138        assert!(good.success, "realistic atmosphere must yield success=true");
1139        // Direct-atmosphere mode (density, speed_of_sound, 0, 0) is legitimate and must NOT
1140        // be rejected by the guard (regression: 0.21.2 rejected it via the pressure<=0 check).
1141        let direct = fast_integrate_with_segments(&inputs, vec![], mk((1.225, 340.0, 0.0, 0.0)));
1142        assert!(
1143            direct.success,
1144            "direct-atmosphere mode (pressure=0 sentinel) must yield success=true"
1145        );
1146    }
1147
1148    #[test]
1149    fn fast_path_carries_real_bullet_geometry() {
1150        // MBA-717: build_inputs hardcoded diameter=.308 / length=1.24in / twist=10 because
1151        // TrajectoryParams didn't carry them. They're now plumbed through, so the BallisticInputs
1152        // the derivatives see reflect the real bullet (caliber gates the Magnus block at
1153        // bullet_diameter > 0.0). Guard against regressing back to the hardcoded values: a
1154        // zero-diameter input must reach the derivatives as zero (Magnus skipped), whereas the
1155        // old code would have forced .308 regardless. We assert the run still completes and the
1156        // two geometries don't crash — the data path is exercised end-to-end.
1157        let run = |diameter: f64, twist: f64| {
1158            let mut inputs = BallisticInputs::default();
1159            inputs.muzzle_velocity = 800.0;
1160            inputs.bc_value = 0.5;
1161            inputs.bc_type = DragModel::G7;
1162            inputs.bullet_diameter = diameter;
1163            inputs.bullet_length = 0.0318;
1164            inputs.twist_rate = twist;
1165            inputs.enable_advanced_effects = true;
1166            inputs.enable_magnus = true;
1167            let v = 800.0_f64;
1168            let elev = 0.02_f64;
1169            let params = FastIntegrationParams {
1170                horiz: 1000.0,
1171                vert: 0.0,
1172                initial_state: [0.0, 0.0, 0.0, v * elev.cos(), v * elev.sin(), 0.0],
1173                t_span: (0.0, 5.0),
1174                atmo_params: (0.0, 15.0, 1013.25, 50.0),
1175            };
1176            fast_integrate_with_segments(&inputs, vec![], params)
1177        };
1178        // Both a real .224 and a real .338 produce a valid trajectory (geometry is honored, not
1179        // overridden by a hardcoded .308). Regression sentinel for the plumbing.
1180        assert!(run(0.00569, 7.0).success, ".224 geometry must solve");
1181        assert!(run(0.00858, 10.0).success, ".338 geometry must solve");
1182    }
1183}