Skip to main content

ballistics_engine/
trajectory_integration.rs

1//! Advanced trajectory integration methods (RK4, RK45)
2//!
3//! This module provides production-grade numerical integration for ballistic trajectories:
4//! - RK4: 4th-order Runge-Kutta (fixed step)
5//! - RK45: Dormand-Prince adaptive method (same as scipy.integrate.solve_ivp)
6//!
7//! MBA-155: Upstreamed from ballistics_rust for shared use
8
9use nalgebra::{Vector3, Vector6};
10use std::collections::HashMap;
11
12use crate::derivatives::compute_derivatives;
13use crate::wind::WindSegment;
14use crate::BallisticInputs;
15use crate::DragModel;
16
17const RK45_MIN_STEP: f64 = 1e-6;
18const RK45_DEFAULT_TOLERANCE: f64 = 1e-6;
19const RK45_SAFETY_FACTOR: f64 = 0.9;
20const RK45_MIN_SCALE: f64 = 0.1;
21const RK45_MAX_SCALE: f64 = 2.0;
22
23#[derive(Clone, Copy)]
24struct Rk45Control {
25    tolerance: f64,
26    min_step: f64,
27    max_step: f64,
28    max_trials: usize,
29}
30
31struct Rk45AcceptedStep {
32    state: Vector6<f64>,
33    used_dt: f64,
34    next_dt: f64,
35    error: f64,
36    trials: usize,
37}
38
39fn wind_vector_for_range(range_m: f64, wind_segments: &[WindSegment]) -> Vector3<f64> {
40    if range_m.is_nan() {
41        return Vector3::zeros();
42    }
43    for seg in wind_segments {
44        if range_m < seg.until_m {
45            let wind_speed_mps = seg.speed_kmh * 0.2777778; // km/h to m/s
46            let wind_angle_rad = seg.angle_deg.to_radians();
47            // MBA-728: per-segment vertical passes straight through (not derived from
48            // speed/angle), matching wind::WindSock::calc_vec.
49            return crate::wind::wind_vector(wind_speed_mps, wind_angle_rad, seg.vertical_mps);
50        }
51    }
52    Vector3::zeros()
53}
54
55/// RK4 integration step
56fn rk4_step(
57    state: &Vector6<f64>,
58    t: f64,
59    dt: f64,
60    params: &TrajectoryParams,
61    inputs: &BallisticInputs,
62) -> Vector6<f64> {
63    // RK4 integration
64    let k1 = compute_derivatives_vec(state, t, params, inputs);
65    let k2 = compute_derivatives_vec(&(state + dt * 0.5 * k1), t + dt * 0.5, params, inputs);
66    let k3 = compute_derivatives_vec(&(state + dt * 0.5 * k2), t + dt * 0.5, params, inputs);
67    let k4 = compute_derivatives_vec(&(state + dt * k3), t + dt, params, inputs);
68
69    state + (dt / 6.0) * (k1 + 2.0 * k2 + 2.0 * k3 + k4)
70}
71
72/// Weighted RMS error for a mixed position/velocity state.
73///
74/// Each component is scaled independently so a large downrange position cannot hide an error in
75/// a near-zero lateral velocity (and vice versa). The caller's tolerance therefore acts as both
76/// an absolute and relative tolerance in each component's own unit.
77pub(crate) fn rk45_error_norm(
78    state: &Vector6<f64>,
79    fifth_order: &Vector6<f64>,
80    fourth_order: &Vector6<f64>,
81) -> f64 {
82    let scaled_error_squared: f64 = (0..6)
83        .map(|index| {
84            let scale = 1.0 + state[index].abs().max(fifth_order[index].abs());
85            ((fifth_order[index] - fourth_order[index]) / scale).powi(2)
86        })
87        .sum();
88
89    (scaled_error_squared / 6.0).sqrt()
90}
91
92/// Adaptive RK45 integration step (Dormand-Prince method)
93fn rk45_step(
94    state: &Vector6<f64>,
95    t: f64,
96    dt: f64,
97    params: &TrajectoryParams,
98    inputs: &BallisticInputs,
99    tol: f64,
100) -> (Vector6<f64>, f64, f64) {
101    // Dormand-Prince coefficients (same as scipy.integrate.solve_ivp RK45)
102    const A21: f64 = 1.0 / 5.0;
103    const A31: f64 = 3.0 / 40.0;
104    const A32: f64 = 9.0 / 40.0;
105    const A41: f64 = 44.0 / 45.0;
106    const A42: f64 = -56.0 / 15.0;
107    const A43: f64 = 32.0 / 9.0;
108    const A51: f64 = 19372.0 / 6561.0;
109    const A52: f64 = -25360.0 / 2187.0;
110    const A53: f64 = 64448.0 / 6561.0;
111    const A54: f64 = -212.0 / 729.0;
112    const A61: f64 = 9017.0 / 3168.0;
113    const A62: f64 = -355.0 / 33.0;
114    const A63: f64 = 46732.0 / 5247.0;
115    const A64: f64 = 49.0 / 176.0;
116    const A65: f64 = -5103.0 / 18656.0;
117    const A71: f64 = 35.0 / 384.0;
118    const A73: f64 = 500.0 / 1113.0;
119    const A74: f64 = 125.0 / 192.0;
120    const A75: f64 = -2187.0 / 6784.0;
121    const A76: f64 = 11.0 / 84.0;
122
123    // 5th order coefficients
124    const B1: f64 = 35.0 / 384.0;
125    const B3: f64 = 500.0 / 1113.0;
126    const B4: f64 = 125.0 / 192.0;
127    const B5: f64 = -2187.0 / 6784.0;
128    const B6: f64 = 11.0 / 84.0;
129
130    // 4th order coefficients (for error estimation)
131    const B1_ERR: f64 = 5179.0 / 57600.0;
132    const B3_ERR: f64 = 7571.0 / 16695.0;
133    const B4_ERR: f64 = 393.0 / 640.0;
134    const B5_ERR: f64 = -92097.0 / 339200.0;
135    const B6_ERR: f64 = 187.0 / 2100.0;
136    const B7_ERR: f64 = 1.0 / 40.0;
137
138    // Compute stages
139    let k1 = compute_derivatives_vec(state, t, params, inputs);
140    let k2 = compute_derivatives_vec(&(state + dt * A21 * k1), t + dt * 0.2, params, inputs);
141    let k3 = compute_derivatives_vec(
142        &(state + dt * (A31 * k1 + A32 * k2)),
143        t + dt * 0.3,
144        params,
145        inputs,
146    );
147    let k4 = compute_derivatives_vec(
148        &(state + dt * (A41 * k1 + A42 * k2 + A43 * k3)),
149        t + dt * 0.8,
150        params,
151        inputs,
152    );
153    let k5 = compute_derivatives_vec(
154        &(state + dt * (A51 * k1 + A52 * k2 + A53 * k3 + A54 * k4)),
155        t + dt * 8.0 / 9.0,
156        params,
157        inputs,
158    );
159    let k6 = compute_derivatives_vec(
160        &(state + dt * (A61 * k1 + A62 * k2 + A63 * k3 + A64 * k4 + A65 * k5)),
161        t + dt,
162        params,
163        inputs,
164    );
165    let k7 = compute_derivatives_vec(
166        &(state + dt * (A71 * k1 + A73 * k3 + A74 * k4 + A75 * k5 + A76 * k6)),
167        t + dt,
168        params,
169        inputs,
170    );
171
172    // 5th order solution
173    let y_new = state + dt * (B1 * k1 + B3 * k3 + B4 * k4 + B5 * k5 + B6 * k6);
174
175    // 4th order solution for error estimate
176    let y_err = state
177        + dt * (B1_ERR * k1 + B3_ERR * k3 + B4_ERR * k4 + B5_ERR * k5 + B6_ERR * k6 + B7_ERR * k7);
178
179    let error = rk45_error_norm(state, &y_new, &y_err);
180
181    // Dormand-Prince 5(4) controls both accepted and rejected trials with a fifth-root scale.
182    let step_scale = if !error.is_finite() || !tol.is_finite() || tol <= 0.0 {
183        RK45_MIN_SCALE
184    } else if error == 0.0 {
185        RK45_MAX_SCALE
186    } else {
187        (RK45_SAFETY_FACTOR * (tol / error).powf(0.2)).clamp(RK45_MIN_SCALE, RK45_MAX_SCALE)
188    };
189    let dt_new = dt * step_scale;
190
191    (y_new, dt_new, error)
192}
193
194/// Retry an RK45 step from the same state until its embedded error estimate is acceptable.
195///
196/// `Err(n)` means no finite acceptable candidate was found in `n` trials. Rejected candidates
197/// never escape this function, so callers cannot accidentally advance state or time with one.
198fn adaptive_rk45_step(
199    state: &Vector6<f64>,
200    t: f64,
201    initial_dt: f64,
202    params: &TrajectoryParams,
203    inputs: &BallisticInputs,
204    control: Rk45Control,
205) -> Result<Rk45AcceptedStep, usize> {
206    let mut trial_dt = initial_dt;
207
208    for trials in 1..=control.max_trials {
209        let (new_state, suggested_dt, error) =
210            rk45_step(state, t, trial_dt, params, inputs, control.tolerance);
211        let candidate_is_finite = error.is_finite()
212            && suggested_dt.is_finite()
213            && new_state.iter().all(|value| value.is_finite());
214        let next_dt = suggested_dt.min(control.max_step).max(control.min_step);
215
216        if candidate_is_finite && (error <= control.tolerance || trial_dt <= control.min_step) {
217            return Ok(Rk45AcceptedStep {
218                state: new_state,
219                used_dt: trial_dt,
220                next_dt,
221                error,
222                trials,
223            });
224        }
225
226        if trial_dt <= control.min_step {
227            return Err(trials);
228        }
229        trial_dt = next_dt;
230    }
231
232    Err(control.max_trials)
233}
234
235/// Parameters for trajectory computation
236pub struct TrajectoryParams {
237    pub mass_kg: f64,
238    pub bc: f64,
239    pub drag_model: DragModel,
240    /// Downrange wind zones, normalized by `until_distance_m` when integration begins.
241    pub wind_segments: Vec<WindSegment>,
242    /// Dual-mode atmosphere tuple consumed by `compute_derivatives`:
243    /// **Standard** `(base_alt_m, base_temp_c, base_pressure_hPa, base_density_ratio)` — note
244    /// slot 3 is a density RATIO, NOT humidity, even though it rides in the `humidity` field;
245    /// or **Direct** `(air_density, speed_of_sound, 0.0, 0.0)` — slots 2 and 3 are zero
246    /// sentinels. A pressure of 0 that is not the direct-mode sentinel disables drag.
247    pub atmos_params: (f64, f64, f64, f64),
248    /// Earth rotation in level downrange/up/lateral axes. The derivative kernel projects it into
249    /// the inclined shot frame using `shooting_angle` before applying Coriolis acceleration.
250    pub omega_vector: Option<Vector3<f64>>,
251    pub enable_spin_drift: bool,
252    pub enable_magnus: bool,
253    pub enable_coriolis: bool,
254    pub target_distance_m: f64, // Target horizontal distance in meters
255    pub enable_wind_shear: bool,
256    pub wind_shear_model: String,
257    pub shooter_altitude_m: f64,
258    pub is_twist_right: bool, // True for right-hand twist, false for left-hand
259    pub shooting_angle: f64,  // uphill/downhill angle in radians
260    // MBA-717: real bullet geometry so spin-drift / Magnus / stability on this fast/MC
261    // path use the actual bullet instead of hardcoded .308 / 1.24in / 10-twist placeholders.
262    pub bullet_diameter: f64,                              // meters
263    pub bullet_length: f64, // meters (0.0 -> derivatives falls back to the 4.5-caliber heuristic)
264    pub twist_rate: f64,    // inches per turn
265    pub custom_drag_table: Option<crate::drag::DragTable>, // Custom Drag Model (CDM) data
266    pub bc_segments: Option<Vec<(f64, f64)>>, // Mach-based BC segments: (mach, bc)
267    pub use_bc_segments: bool, // Whether to use BC segment interpolation
268    /// MBA-954: altitude (m, relative to launch) below which integration stops. -1000.0 is the
269    /// historical default — effectively "no early ground impact" for normal flat-fire shots.
270    pub ground_threshold: f64,
271    /// MBA-1137: optional downrange-segmented atmosphere. When `Some`, `compute_derivatives`
272    /// swaps the standard-mode base T/P/H for the zone selected by downrange distance before the
273    /// altitude lapse. `None` (default) is byte-identical to pre-feature behavior.
274    pub atmo_sock: Option<crate::atmosphere::AtmoSock>,
275}
276
277/// Build the loop-invariant BallisticInputs for the derivatives function ONCE per integration,
278/// instead of rebuilding it (a "none".to_string() alloc plus bc_segments / custom_drag_table
279/// clones) on every derivative evaluation (4x per RK4 step, 7x per RK45 step). The launch-speed
280/// magnitude supplies the muzzle-set Magnus spin; every other field depends only on `params`, so
281/// the struct is constant for the whole integration.
282fn build_inputs(params: &TrajectoryParams, muzzle_velocity_mps: f64) -> BallisticInputs {
283    let mut inputs = BallisticInputs {
284        bc_value: params.bc,
285        bc_type: params.drag_model,
286        bullet_mass: params.mass_kg, // kg
287        muzzle_velocity: muzzle_velocity_mps,
288        bullet_diameter: params.bullet_diameter, // MBA-717: real geometry, not placeholders
289        bullet_length: params.bullet_length,
290        twist_rate: params.twist_rate,
291        is_twist_right: params.is_twist_right,
292        enable_advanced_effects: params.enable_spin_drift
293            || params.enable_magnus
294            || params.enable_coriolis,
295        enable_magnus: params.enable_magnus,
296        enable_coriolis: params.enable_coriolis,
297        altitude: params.atmos_params.0,
298        temperature: params.atmos_params.1,
299        pressure: params.atmos_params.2,
300        humidity: params.atmos_params.3,
301        tipoff_yaw: 0.0,
302        target_distance: 1000.0, // default
303        muzzle_angle: 0.0,
304        wind_speed: if !params.wind_segments.is_empty() {
305            params.wind_segments[0].speed_kmh * 0.2777778 // km/h -> m/s
306        } else {
307            0.0
308        },
309        wind_angle: if !params.wind_segments.is_empty() {
310            params.wind_segments[0].angle_deg.to_radians() // degrees -> radians
311        } else {
312            0.0
313        },
314        latitude: None,
315        shooting_angle: params.shooting_angle,
316        cant_angle: 0.0,
317        azimuth_angle: 0.0,
318        shot_azimuth: 0.0, // this fast path doesn't plumb latitude/bearing (no directional Coriolis here)
319        use_powder_sensitivity: false,
320        powder_temp_sensitivity: 0.0,
321        powder_temp: 59.0,
322        powder_temp_curve: None,
323        powder_curve_temp_c: None,
324        tipoff_decay_distance: 0.0,
325        ground_threshold: params.ground_threshold, // MBA-954: honor the configured ground plane
326        bc_segments: params.bc_segments.clone(),
327        caliber_inches: params.bullet_diameter / 0.0254, // MBA-717: from real diameter
328        weight_grains: params.mass_kg / 0.00006479891,
329        use_bc_segments: params.use_bc_segments,
330        bullet_id: None,
331        bc_segments_data: None,
332        use_enhanced_spin_drift: params.enable_spin_drift,
333        use_form_factor: false,
334        manufacturer: None,
335        bullet_model: None,
336        enable_wind_shear: false,
337        wind_shear_model: "none".to_string(),
338        use_cluster_bc: false,
339        bullet_cluster: None,
340        custom_drag_table: params.custom_drag_table.clone(),
341        bc_type_str: None,
342        enable_pitch_damping: false,
343        enable_precession_nutation: false,
344        // MBA-959/MBA-1183: aerodynamic jump stays OFF inside this low-level raw-state integrator.
345        // The high-level fast wrappers form Sg from their complete BallisticInputs and rotate the
346        // prebuilt initial velocity before entering their integration loops; enabling it again
347        // here would double-apply the launch perturbation. Direct low-level callers likewise own
348        // any desired launch-state rotation. (Real geometry is still carried for spin/Magnus.)
349        enable_aerodynamic_jump: false,
350        use_rk4: true,
351        use_adaptive_rk45: false,
352        enable_trajectory_sampling: false,
353        sample_interval: 10.0,
354        sight_height: 0.0,
355        muzzle_height: 0.0,
356        target_height: 0.0,
357    };
358
359    // MBA-955: pre-populate velocity-BC segments ONCE here, instead of get_bc_for_velocity
360    // rebuilding them (a model String + a segment Vec) on every derivative evaluation (4-7x per
361    // step). Gated to EXACTLY the case where the per-step path would estimate: use_bc_segments on,
362    // no explicit velocity segments, and no Mach-based bc_segments (those take a different,
363    // unchanged path). bc_used there == params.bc == inputs.bc_value, so the estimated segments are
364    // identical and the per-step fast-path lookup returns the same BC -> byte-identical output.
365    if inputs.use_bc_segments && inputs.bc_segments_data.is_none() && inputs.bc_segments.is_none() {
366        inputs.bc_segments_data =
367            crate::derivatives::estimate_bc_segments_for(&inputs, inputs.bc_value);
368    }
369    inputs
370}
371
372/// Convert state to Vector6 and call compute_derivatives
373fn compute_derivatives_vec(
374    state: &Vector6<f64>,
375    t: f64,
376    params: &TrajectoryParams,
377    inputs: &BallisticInputs,
378) -> Vector6<f64> {
379    let pos = Vector3::new(state[0], state[1], state[2]);
380    let vel = Vector3::new(state[3], state[4], state[5]);
381
382    // Calculate wind at current position with shear support
383    let wind_vector = if !params.wind_segments.is_empty() {
384        if params.enable_wind_shear && params.wind_shear_model != "none" {
385            crate::wind_shear::get_wind_at_position(
386                &pos,
387                &params.wind_segments,
388                params.enable_wind_shear,
389                &params.wind_shear_model,
390                params.shooter_altitude_m,
391            )
392        } else {
393            wind_vector_for_range(pos.x, &params.wind_segments)
394        }
395    } else {
396        Vector3::zeros()
397    };
398
399    // Call compute_derivatives - returns [f64; 6] directly. `inputs` is built once per
400    // integration by build_inputs() and threaded in, instead of rebuilt every call.
401    let deriv_result = compute_derivatives(
402        pos,
403        vel,
404        inputs,
405        wind_vector,
406        params.atmos_params,
407        params.bc,
408        params.omega_vector,
409        t,
410        params.atmo_sock.as_ref(),
411    );
412
413    Vector6::new(
414        deriv_result[0],
415        deriv_result[1],
416        deriv_result[2],
417        deriv_result[3],
418        deriv_result[4],
419        deriv_result[5],
420    )
421}
422
423/// Linearly localize a target crossing within an accepted forward integration step.
424///
425/// Callers provide a bracket with `start[0] <= target_x <= end[0]` and increasing downrange X.
426/// The same crossing fraction is applied to time and every phase-space component; X is then set
427/// exactly to the public target value to remove interpolation roundoff.
428fn interpolate_target_crossing(
429    start_time: f64,
430    start: &Vector6<f64>,
431    step_dt: f64,
432    end: &Vector6<f64>,
433    target_x: f64,
434) -> (f64, Vector6<f64>) {
435    debug_assert!(start[0] <= target_x && target_x <= end[0] && end[0] > start[0]);
436
437    let alpha = (target_x - start[0]) / (end[0] - start[0]);
438    let crossing_time = start_time + alpha * step_dt;
439    let mut crossing_state = start + alpha * (end - start);
440    crossing_state[0] = target_x;
441
442    (crossing_time, crossing_state)
443}
444
445/// Main trajectory integration function
446pub fn integrate_trajectory(
447    initial_state: [f64; 6],
448    t_span: (f64, f64),
449    mut params: TrajectoryParams,
450    method: &str,
451    tolerance: f64,
452    max_step: f64,
453) -> Vec<(f64, Vector6<f64>)> {
454    // Normalize once before build_inputs reads the first zone and before any RK stage performs a
455    // first-match lookup. Callers may supply zones in any order.
456    crate::wind::sort_wind_segments_by_distance(&mut params.wind_segments);
457
458    let mut state = Vector6::new(
459        initial_state[0],
460        initial_state[1],
461        initial_state[2],
462        initial_state[3],
463        initial_state[4],
464        initial_state[5],
465    );
466
467    let mut t = t_span.0;
468    let t_end = t_span.1;
469    let mut dt = (t_end - t) / 1000.0; // Initial step size
470
471    let mut trajectory = Vec::with_capacity(10000);
472    trajectory.push((t, state));
473    if state[0] >= params.target_distance_m {
474        return trajectory;
475    }
476
477    // Build the (loop-invariant) derivative inputs once for the whole integration, instead of
478    // rebuilding the struct on every derivative evaluation.
479    let muzzle_velocity_mps =
480        Vector3::new(initial_state[3], initial_state[4], initial_state[5]).norm();
481    let inputs = build_inputs(&params, muzzle_velocity_mps);
482
483    match method {
484        "RK4" => {
485            // Fixed step RK4 with target detection
486            dt = dt.min(max_step).min(0.001); // Use smaller steps for accuracy
487
488            while t < t_end {
489                if t + dt > t_end {
490                    dt = t_end - t;
491                }
492
493                let new_state = rk4_step(&state, t, dt, &params, &inputs);
494
495                // Check if we're about to pass the target (X is downrange, McCoy)
496                if state[0] < params.target_distance_m && new_state[0] >= params.target_distance_m {
497                    trajectory.push(interpolate_target_crossing(
498                        t,
499                        &state,
500                        dt,
501                        &new_state,
502                        params.target_distance_m,
503                    ));
504                    break; // Stop at target
505                }
506
507                state = new_state;
508                t += dt;
509                trajectory.push((t, state));
510
511                // Check if we've reached or passed the target
512                if state[0] >= params.target_distance_m {
513                    break;
514                }
515
516                // Check if bullet hit ground (MBA-954: honor the configured ground plane,
517                // not a hardcoded -1000.0)
518                if state[1] < params.ground_threshold {
519                    break;
520                }
521            }
522        }
523        "RK45" | _ => {
524            // Adaptive RK45 with better sampling
525            let mut last_save_x = 0.0; // X is downrange (McCoy)
526            let save_interval_m = params.target_distance_m / 50.0; // Save ~50 points minimum
527            let tolerance = if tolerance.is_finite() && tolerance > 0.0 {
528                tolerance
529            } else {
530                eprintln!(
531                    "WARNING: RK45 tolerance must be finite and positive; using {RK45_DEFAULT_TOLERANCE}"
532                );
533                RK45_DEFAULT_TOLERANCE
534            };
535
536            // OPTIMIZATION: Adjust max step size when wind shear is enabled
537            // This improves numerical stability at long ranges
538            let effective_max_step =
539                if params.enable_wind_shear && params.wind_shear_model != "none" {
540                    // Use smaller steps for wind shear, but not TOO small
541                    if params.target_distance_m > 800.0 {
542                        0.01 // Smaller steps for long range with shear (10ms)
543                    } else {
544                        0.02 // Normal steps for medium range with shear (20ms)
545                    }
546                } else {
547                    max_step // Use provided max_step when no wind shear
548                };
549            if !effective_max_step.is_finite() || effective_max_step <= 0.0 {
550                eprintln!("WARNING: RK45 max_step must be finite and positive");
551                return trajectory;
552            }
553            let min_step = RK45_MIN_STEP.min(effective_max_step);
554
555            // Set initial step size - ensure it's reasonable
556            dt = dt.min(effective_max_step).max(min_step);
557
558            // Safety check: maximum iterations to prevent infinite loops
559            let max_iterations = 100000; // Should be more than enough for any realistic trajectory
560            let mut iteration_count = 0;
561
562            while t < t_end && iteration_count < max_iterations {
563                // Limit time step for better resolution
564                if t + dt > t_end {
565                    dt = t_end - t;
566                }
567
568                let control = Rk45Control {
569                    tolerance,
570                    min_step,
571                    max_step: effective_max_step,
572                    max_trials: max_iterations - iteration_count,
573                };
574                let accepted = match adaptive_rk45_step(&state, t, dt, &params, &inputs, control) {
575                    Ok(accepted) => accepted,
576                    Err(trials) => {
577                        iteration_count += trials;
578                        if iteration_count < max_iterations {
579                            eprintln!("WARNING: RK45 minimum-step trial was non-finite");
580                        }
581                        break;
582                    }
583                };
584                iteration_count += accepted.trials;
585                debug_assert!(accepted.error <= tolerance || accepted.used_dt <= min_step);
586
587                // Target detection only examines an accepted candidate.
588                if state[0] < params.target_distance_m
589                    && accepted.state[0] >= params.target_distance_m
590                {
591                    trajectory.push(interpolate_target_crossing(
592                        t,
593                        &state,
594                        accepted.used_dt,
595                        &accepted.state,
596                        params.target_distance_m,
597                    ));
598                    break;
599                }
600
601                // Update state and time using the interval that actually passed acceptance.
602                state = accepted.state;
603                t += accepted.used_dt;
604
605                // Save trajectory point if we've moved enough distance
606                if state[0] - last_save_x >= save_interval_m || state[0] >= params.target_distance_m
607                {
608                    // X is downrange
609                    trajectory.push((t, state));
610                    last_save_x = state[0];
611                }
612
613                // Limit the proposal for the next trial; this does not change the time just used.
614                dt = accepted.next_dt;
615
616                // Stop if we've reached the target
617                if state[0] >= params.target_distance_m {
618                    break;
619                }
620
621                // Check if bullet hit ground (MBA-954: honor the configured ground plane,
622                // not a hardcoded -1000.0)
623                if state[1] < params.ground_threshold {
624                    break;
625                }
626            }
627
628            // Warn if we hit the iteration limit
629            if iteration_count >= max_iterations
630                && t < t_end
631                && state[0] < params.target_distance_m
632                && state[1] >= params.ground_threshold
633            {
634                eprintln!(
635                    "WARNING: Trajectory integration hit maximum iteration limit ({} iterations)",
636                    max_iterations
637                );
638                eprintln!("  Final time: {}, Target time: {}", t, t_end);
639                eprintln!(
640                    "  Final position: downrange(x)={}, Target: {}m",
641                    state[0], params.target_distance_m
642                );
643            }
644        }
645    }
646
647    trajectory
648}
649
650/// Python-exposed function for complete trajectory integration
651pub fn solve_trajectory_rust(
652    initial_state: [f64; 6],
653    t_span: (f64, f64),
654    mass_kg: f64,
655    bc: f64,
656    drag_model: DragModel,
657    wind_segments: Vec<WindSegment>,
658    atmos_params: (f64, f64, f64, f64),
659    omega_vector: Option<Vec<f64>>,
660    enable_spin_drift: bool,
661    enable_magnus: bool,
662    enable_coriolis: bool,
663    method: String,
664    tolerance: f64,
665    max_step: f64,
666    target_distance_m: f64,
667) -> Vec<HashMap<String, f64>> {
668    let omega_vec = omega_vector.map(|v| Vector3::new(v[0], v[1], v[2]));
669
670    let params = TrajectoryParams {
671        mass_kg,
672        bc,
673        drag_model,
674        wind_segments,
675        atmos_params,
676        omega_vector: omega_vec,
677        enable_spin_drift,
678        enable_magnus,
679        enable_coriolis,
680        target_distance_m,
681        enable_wind_shear: false, // Default for test function
682        wind_shear_model: "none".to_string(),
683        shooter_altitude_m: 0.0,
684        is_twist_right: true, // Default for test function
685        shooting_angle: 0.0,  // This legacy entry takes no inclined-fire arg; flat fire only
686        // This legacy entry takes no geometry args; keep the historical placeholders so its
687        // behavior is unchanged (callers needing real geometry use fast_integrate_with_segments).
688        bullet_diameter: 0.0078232,
689        bullet_length: 0.031496,
690        twist_rate: 10.0,
691        custom_drag_table: None, // No CDM for test function
692        bc_segments: None,       // No BC segments for legacy function
693        use_bc_segments: false,
694        ground_threshold: -1000.0, // MBA-954: preserve the historical default
695        atmo_sock: None,           // MBA-1137: legacy entry has no downrange atmosphere
696    };
697
698    let trajectory =
699        integrate_trajectory(initial_state, t_span, params, &method, tolerance, max_step);
700
701    // Convert to Python-friendly format
702    trajectory
703        .into_iter()
704        .map(|(t, state)| {
705            let mut point = HashMap::new();
706            point.insert("t".to_string(), t);
707            point.insert("x".to_string(), state[0]);
708            point.insert("y".to_string(), state[1]);
709            point.insert("z".to_string(), state[2]);
710            point.insert("vx".to_string(), state[3]);
711            point.insert("vy".to_string(), state[4]);
712            point.insert("vz".to_string(), state[5]);
713            point
714        })
715        .collect()
716}
717
718#[cfg(test)]
719mod tests {
720    use super::*;
721
722    fn create_test_params(target_distance_m: f64) -> TrajectoryParams {
723        TrajectoryParams {
724            mass_kg: 0.01134, // 175 grains in kg
725            bc: 0.442,
726            bullet_diameter: 0.0078232, // .308 in
727            bullet_length: 0.031496,    // 1.24 in
728            twist_rate: 10.0,
729            drag_model: DragModel::G7,
730            wind_segments: vec![],
731            atmos_params: (0.0, 15.0, 1013.25, 1.0),
732            omega_vector: None,
733            enable_spin_drift: false,
734            enable_magnus: false,
735            enable_coriolis: false,
736            target_distance_m,
737            enable_wind_shear: false,
738            wind_shear_model: "none".to_string(),
739            shooter_altitude_m: 0.0,
740            is_twist_right: true,
741            shooting_angle: 0.0,
742            custom_drag_table: None,
743            bc_segments: None,
744            use_bc_segments: false,
745            ground_threshold: -1000.0,
746            atmo_sock: None,
747        }
748    }
749
750    #[test]
751    fn derivative_inputs_preserve_initial_velocity_as_muzzle_speed() {
752        let params = create_test_params(1_000.0);
753        let launch_velocity = Vector3::new(700.0, 30.0, -20.0);
754        let inputs = build_inputs(&params, launch_velocity.norm());
755
756        assert_eq!(
757            inputs.muzzle_velocity.to_bits(),
758            launch_velocity.norm().to_bits()
759        );
760    }
761
762    #[test]
763    fn integrated_magnus_retains_nonzero_launch_spin() {
764        let initial_state = [0.0, 0.0, 0.0, 800.0, 0.0, 0.0];
765        let baseline = integrate_trajectory(
766            initial_state,
767            (0.0, 0.1),
768            create_test_params(1_000.0),
769            "RK4",
770            1e-6,
771            0.001,
772        );
773        let mut magnus_params = create_test_params(1_000.0);
774        magnus_params.enable_magnus = true;
775
776        let trajectory = integrate_trajectory(
777            initial_state,
778            (0.0, 0.1),
779            magnus_params,
780            "RK4",
781            1e-6,
782            0.001,
783        );
784        let baseline_y = baseline.last().expect("baseline trajectory is empty").1[1];
785        let magnus_y = trajectory.last().expect("trajectory is empty").1[1];
786        let vertical_delta = magnus_y - baseline_y;
787
788        assert!(
789            vertical_delta.is_finite() && vertical_delta < 0.0,
790            "right-twist Magnus should retain nonzero launch spin and point down, got \
791             delta_y={vertical_delta}"
792        );
793    }
794
795    #[test]
796    fn rk45_retries_rejected_wind_boundary_step() {
797        let initial_state = [0.0, 0.0, 0.0, 800.0, 0.0, 0.0];
798        let mut params = create_test_params(100.0);
799        params.wind_segments = vec![
800            WindSegment::new(0.0, 90.0, 4.0),
801            WindSegment::new(1_000.0, 90.0, 10_000.0),
802        ];
803
804        let state = Vector6::from_row_slice(&initial_state);
805        let launch_speed =
806            Vector3::new(initial_state[3], initial_state[4], initial_state[5]).norm();
807        let inputs = build_inputs(&params, launch_speed);
808        let initial_dt = 0.01;
809        let tolerance = 1e-6;
810        let (rejected_state, suggested_dt, error) =
811            rk45_step(&state, 0.0, initial_dt, &params, &inputs, tolerance);
812        assert!(
813            error > tolerance,
814            "wind-boundary trial must exceed tolerance, got {error}"
815        );
816        assert!(suggested_dt < initial_dt);
817
818        let accepted = adaptive_rk45_step(
819            &state,
820            0.0,
821            initial_dt,
822            &params,
823            &inputs,
824            Rk45Control {
825                tolerance,
826                min_step: RK45_MIN_STEP,
827                max_step: initial_dt,
828                max_trials: 100,
829            },
830        )
831        .expect("a smaller finite trial should satisfy the tolerance");
832
833        assert!(accepted.trials > 1, "oversized trial was not retried");
834        assert!(accepted.used_dt < initial_dt);
835        assert!(
836            accepted.error <= tolerance || accepted.used_dt <= RK45_MIN_STEP,
837            "accepted error {} exceeds tolerance at dt {}",
838            accepted.error,
839            accepted.used_dt
840        );
841
842        let (accepted_state, _, accepted_error) =
843            rk45_step(&state, 0.0, accepted.used_dt, &params, &inputs, tolerance);
844        assert_eq!(accepted.state, accepted_state);
845        assert_eq!(accepted.error, accepted_error);
846        assert_ne!(accepted.state, rejected_state);
847        assert!((RK45_MIN_STEP..=initial_dt).contains(&accepted.next_dt));
848    }
849
850    #[test]
851    fn integration_normalizes_wind_segments_by_distance() {
852        let initial_state = [0.0, 0.0, 0.0, 800.0, 0.0, 0.0];
853        let sorted_segments = vec![
854            WindSegment::new(40.0, 270.0, 300.0),
855            WindSegment::new(20.0, 90.0, 600.0),
856        ];
857
858        let mut sorted_params = create_test_params(100.0);
859        sorted_params.wind_segments = sorted_segments.clone();
860        let mut unsorted_params = create_test_params(100.0);
861        unsorted_params.wind_segments = sorted_segments.into_iter().rev().collect();
862
863        let sorted =
864            integrate_trajectory(initial_state, (0.0, 1.0), sorted_params, "RK4", 1e-6, 0.001);
865        let unsorted = integrate_trajectory(
866            initial_state,
867            (0.0, 1.0),
868            unsorted_params,
869            "RK4",
870            1e-6,
871            0.001,
872        );
873
874        assert_eq!(unsorted.len(), sorted.len());
875        for (index, ((sorted_t, sorted_state), (unsorted_t, unsorted_state))) in
876            sorted.iter().zip(&unsorted).enumerate()
877        {
878            assert_eq!(unsorted_t.to_bits(), sorted_t.to_bits());
879            for component in 0..6 {
880                assert_eq!(
881                    unsorted_state[component].to_bits(),
882                    sorted_state[component].to_bits(),
883                    "wind segment order changed state component {component} at point {index}"
884                );
885            }
886        }
887    }
888
889    #[test]
890    fn rk4_target_crossing_interpolates_complete_state_and_time() {
891        let initial_state = [0.0, 0.0, 0.0, 800.0, 5.0, 2.0];
892        let target_distance_m = 100.0;
893        let trajectory = integrate_trajectory(
894            initial_state,
895            (0.0, 1.0),
896            create_test_params(target_distance_m),
897            "RK4",
898            1e-6,
899            0.001,
900        );
901
902        let (previous_t, previous_state) = &trajectory[trajectory.len() - 2];
903        let (terminal_t, terminal_state) = trajectory.last().expect("trajectory is empty");
904        let reference_params = create_test_params(target_distance_m);
905        let inputs = build_inputs(&reference_params, Vector3::new(800.0, 5.0, 2.0).norm());
906        let full_step_dt = 0.001;
907        let bracket_end = rk4_step(
908            previous_state,
909            *previous_t,
910            full_step_dt,
911            &reference_params,
912            &inputs,
913        );
914        assert!(previous_state[0] < target_distance_m);
915        assert!(bracket_end[0] >= target_distance_m);
916
917        let alpha = (target_distance_m - previous_state[0]) / (bracket_end[0] - previous_state[0]);
918        let expected_t = previous_t + alpha * full_step_dt;
919        let mut expected_state = previous_state + alpha * (bracket_end - previous_state);
920        expected_state[0] = target_distance_m;
921
922        assert_eq!(terminal_t.to_bits(), expected_t.to_bits());
923        for component in 0..6 {
924            assert_eq!(
925                terminal_state[component].to_bits(),
926                expected_state[component].to_bits(),
927                "terminal component {component} was not interpolated at the target crossing"
928            );
929        }
930    }
931
932    #[test]
933    fn rk45_target_crossing_uses_the_accepted_state_and_time() {
934        let initial_state = [0.0, 0.0, 0.0, 800.0, 5.0, 2.0];
935        let initial = Vector6::from_row_slice(&initial_state);
936        let target_distance_m = 0.5;
937        let reference_params = create_test_params(target_distance_m);
938        let inputs = build_inputs(&reference_params, Vector3::new(800.0, 5.0, 2.0).norm());
939        let initial_dt = 0.001;
940        let accepted = adaptive_rk45_step(
941            &initial,
942            0.0,
943            initial_dt,
944            &reference_params,
945            &inputs,
946            Rk45Control {
947                tolerance: 1e-6,
948                min_step: RK45_MIN_STEP,
949                max_step: 0.01,
950                max_trials: 100_000,
951            },
952        )
953        .expect("first RK45 target bracket should be accepted");
954        assert!(accepted.state[0] >= target_distance_m);
955        let expected = interpolate_target_crossing(
956            0.0,
957            &initial,
958            accepted.used_dt,
959            &accepted.state,
960            target_distance_m,
961        );
962
963        let trajectory = integrate_trajectory(
964            initial_state,
965            (0.0, 1.0),
966            create_test_params(target_distance_m),
967            "RK45",
968            1e-6,
969            0.01,
970        );
971        let actual = trajectory.last().expect("trajectory is empty");
972
973        assert_eq!(actual.0.to_bits(), expected.0.to_bits());
974        for component in 0..6 {
975            assert_eq!(
976                actual.1[component].to_bits(),
977                expected.1[component].to_bits(),
978                "RK45 terminal component {component} was not interpolated from its accepted step"
979            );
980        }
981    }
982
983    #[test]
984    fn target_crossing_helper_interpolates_every_component() {
985        let start = Vector6::new(90.0, 10.0, -4.0, 700.0, -20.0, 5.0);
986        let end = Vector6::new(130.0, 6.0, 8.0, 660.0, -24.0, 9.0);
987        let (time, state) = interpolate_target_crossing(2.0, &start, 0.5, &end, 100.0);
988
989        assert_eq!(time.to_bits(), 2.125_f64.to_bits());
990        for (index, expected) in [100.0_f64, 9.0, -1.0, 690.0, -21.0, 6.0]
991            .into_iter()
992            .enumerate()
993        {
994            assert_eq!(state[index].to_bits(), expected.to_bits());
995        }
996    }
997
998    #[test]
999    fn already_at_or_past_target_returns_initial_state_without_advancing() {
1000        let initial = [150.0, 12.0, -3.0, 700.0, -4.0, 5.0];
1001
1002        for method in ["RK4", "RK45"] {
1003            for target in [150.0, 100.0] {
1004                let trajectory = integrate_trajectory(
1005                    initial,
1006                    (2.0, 3.0),
1007                    create_test_params(target),
1008                    method,
1009                    1e-6,
1010                    0.01,
1011                );
1012
1013                assert_eq!(trajectory.len(), 1, "{method} advanced a terminal state");
1014                let (time, state) = &trajectory[0];
1015                assert_eq!(time.to_bits(), 2.0_f64.to_bits());
1016                for index in 0..6 {
1017                    assert_eq!(state[index].to_bits(), initial[index].to_bits());
1018                }
1019            }
1020        }
1021    }
1022
1023    #[test]
1024    fn rk45_error_norm_scales_components_independently() {
1025        let state = Vector6::new(1.0e9, 0.0, 0.0, 800.0, 0.0, 0.0);
1026        let fifth_order = state;
1027        let mut fourth_order = state;
1028        fourth_order[4] = 1.0e-3;
1029
1030        let error = rk45_error_norm(&state, &fifth_order, &fourth_order);
1031        let expected = 1.0e-3 / 6.0_f64.sqrt();
1032
1033        assert!(
1034            (error - expected).abs() <= 1e-15,
1035            "large downrange position masked a velocity-component error: {error}"
1036        );
1037    }
1038
1039    #[test]
1040    fn test_mba954_ground_threshold_honored() {
1041        // MBA-954: integrate_trajectory must honor the configured ground plane, not a hardcoded
1042        // -1000.0. A descending bullet with a shallow ground_threshold must terminate earlier
1043        // (fewer points) than one with the historical deep default.
1044        let initial_state = [0.0, 0.0, 0.0, 300.0, -30.0, 0.0]; // descending (vy = -30 m/s)
1045
1046        let mut shallow = create_test_params(1_000_000.0); // huge target so range never terminates
1047        shallow.ground_threshold = -20.0; // stop ~20 m below launch
1048        let mut deep = create_test_params(1_000_000.0);
1049        deep.ground_threshold = -1000.0; // historical default
1050
1051        let t_shallow =
1052            integrate_trajectory(initial_state, (0.0, 60.0), shallow, "RK4", 1e-6, 0.001);
1053        let t_deep = integrate_trajectory(initial_state, (0.0, 60.0), deep, "RK4", 1e-6, 0.001);
1054
1055        assert!(
1056            t_shallow.len() < t_deep.len(),
1057            "shallow ground_threshold (-20) should terminate earlier than deep (-1000): \
1058             shallow={}, deep={}",
1059            t_shallow.len(),
1060            t_deep.len()
1061        );
1062    }
1063
1064    #[test]
1065    fn test_integrate_trajectory_basic() {
1066        // Initial state [x,y,z,vx,vy,vz] (McCoy: X=downrange, Z=lateral)
1067        // x=0 (downrange start), vx=821.52 (downrange velocity)
1068        let initial_state = [0.0, -0.038, 0.0, 821.52, 48.61, 0.0];
1069
1070        let params = TrajectoryParams {
1071            mass_kg: 0.01134, // 175 grains in kg
1072            bc: 0.442,
1073            bullet_diameter: 0.0078232, // .308 in
1074            bullet_length: 0.031496,    // 1.24 in
1075            twist_rate: 10.0,
1076            drag_model: DragModel::G7,
1077            wind_segments: vec![WindSegment::new(0.0, 90.0, 914.4)],
1078            atmos_params: (0.0, 15.0, 1013.25, 1.0),
1079            omega_vector: None,
1080            enable_spin_drift: false,
1081            enable_magnus: false,
1082            enable_coriolis: false,
1083            target_distance_m: 914.4, // 1000 yards in meters
1084            enable_wind_shear: false,
1085            wind_shear_model: "none".to_string(),
1086            shooter_altitude_m: 0.0,
1087            is_twist_right: true,
1088            shooting_angle: 0.0,
1089            custom_drag_table: None,
1090            bc_segments: None,
1091            use_bc_segments: false,
1092            ground_threshold: -1000.0,
1093            atmo_sock: None,
1094        };
1095
1096        println!("Running integrate_trajectory test...");
1097        println!("Initial state: {:?}", initial_state);
1098        println!("Target distance: {} m", params.target_distance_m);
1099
1100        let trajectory =
1101            integrate_trajectory(initial_state, (0.0, 10.0), params, "RK45", 1e-6, 0.01);
1102
1103        println!("Trajectory has {} points", trajectory.len());
1104
1105        // Should have more than just initial point
1106        assert!(
1107            trajectory.len() > 1,
1108            "Trajectory should have more than 1 point, but has {}",
1109            trajectory.len()
1110        );
1111
1112        // Check that we actually moved downrange
1113        if let Some((_, final_state)) = trajectory.last() {
1114            println!("Final state: downrange(x)={}", final_state[0]);
1115            assert!(
1116                final_state[0] > 0.0,
1117                "Final x should be positive (bullet moved downrange)"
1118            );
1119            assert!(
1120                final_state[0] >= 900.0,
1121                "Final x should be near target distance"
1122            );
1123            assert!(
1124                final_state[3] < 0.9 * initial_state[3],
1125                "standard-atmosphere drag should reduce downrange velocity"
1126            );
1127        }
1128    }
1129
1130    #[test]
1131    fn test_rk4_vs_rk45_consistency() {
1132        // Both methods should give similar results for the same trajectory
1133        let initial_state = [0.0, 0.0, 0.0, 800.0, 30.0, 0.0]; // McCoy: vx=downrange
1134        let target_distance = 500.0;
1135
1136        let params_rk4 = create_test_params(target_distance);
1137        let params_rk45 = create_test_params(target_distance);
1138
1139        let trajectory_rk4 =
1140            integrate_trajectory(initial_state, (0.0, 5.0), params_rk4, "RK4", 1e-6, 0.001);
1141        let trajectory_rk45 =
1142            integrate_trajectory(initial_state, (0.0, 5.0), params_rk45, "RK45", 1e-6, 0.01);
1143
1144        // Both should reach target
1145        assert!(!trajectory_rk4.is_empty());
1146        assert!(!trajectory_rk45.is_empty());
1147
1148        let (time_rk4, final_rk4) = trajectory_rk4.last().unwrap();
1149        let (time_rk45, final_rk45) = trajectory_rk45.last().unwrap();
1150
1151        // Compare quantities that are not forced equal by target-distance clamping.
1152        assert!(
1153            (time_rk4 - time_rk45).abs() < 1e-4,
1154            "RK4/RK45 time of flight diverged: {time_rk4} vs {time_rk45}"
1155        );
1156        assert!((final_rk4[1] - final_rk45[1]).abs() < 1e-3);
1157        assert!((final_rk4[3] - final_rk45[3]).abs() < 1e-2);
1158        assert!(final_rk45[3] < 0.9 * initial_state[3]);
1159    }
1160
1161    #[test]
1162    fn test_ground_impact_detection() {
1163        // Trajectory with steep downward angle should hit ground
1164        let initial_state = [0.0, 100.0, 0.0, 300.0, -50.0, 0.0]; // McCoy: vx=downrange // Steep descent
1165
1166        let mut params = create_test_params(10000.0); // Far target
1167        params.target_distance_m = 10000.0;
1168        let ground_threshold = 0.0;
1169        params.ground_threshold = ground_threshold;
1170
1171        let trajectory =
1172            integrate_trajectory(initial_state, (0.0, 20.0), params, "RK4", 1e-6, 0.01);
1173
1174        // Should stop before reaching target due to ground impact
1175        let (_, final_state) = trajectory.last().unwrap();
1176
1177        // y should have crossed the configured ground threshold.
1178        assert!(
1179            final_state[1] <= ground_threshold,
1180            "Should hit ground, but y={}",
1181            final_state[1]
1182        );
1183        assert!(
1184            final_state[0] < 10000.0,
1185            "Should not reach target, but z={}",
1186            final_state[0]
1187        );
1188    }
1189
1190    #[test]
1191    fn test_target_distance_reached() {
1192        let initial_state = [0.0, 0.0, 0.0, 800.0, 20.0, 0.0]; // McCoy: vx=downrange
1193        let target_distance = 300.0;
1194
1195        let params = create_test_params(target_distance);
1196
1197        let trajectory =
1198            integrate_trajectory(initial_state, (0.0, 5.0), params, "RK45", 1e-6, 0.01);
1199
1200        let (_, final_state) = trajectory.last().unwrap();
1201
1202        // Should stop at or very near target distance
1203        assert!(
1204            (final_state[0] - target_distance).abs() < 1.0,
1205            "Should reach target at {}m, but stopped at {}m",
1206            target_distance,
1207            final_state[0]
1208        );
1209    }
1210
1211    #[test]
1212    fn test_wind_affects_trajectory() {
1213        // Test that wind segments are properly stored and passed through
1214        // The actual wind effect depends on the derivatives computation which
1215        // uses the wind vector in the drag calculation
1216        let initial_state = [0.0, 0.0, 0.0, 800.0, 30.0, 0.0]; // McCoy: vx=downrange
1217        let target_distance = 500.0;
1218
1219        // No wind
1220        let params_no_wind = create_test_params(target_distance);
1221
1222        // Strong headwind (0 degrees = headwind)
1223        let mut params_headwind = create_test_params(target_distance);
1224        params_headwind.wind_segments = vec![WindSegment::new(72.0, 0.0, 500.0)]; // 72 km/h = 20 m/s headwind
1225
1226        let trajectory_no_wind = integrate_trajectory(
1227            initial_state,
1228            (0.0, 5.0),
1229            params_no_wind,
1230            "RK45",
1231            1e-6,
1232            0.01,
1233        );
1234        let trajectory_headwind = integrate_trajectory(
1235            initial_state,
1236            (0.0, 5.0),
1237            params_headwind,
1238            "RK45",
1239            1e-6,
1240            0.01,
1241        );
1242
1243        // Both trajectories should complete
1244        assert!(
1245            !trajectory_no_wind.is_empty(),
1246            "No-wind trajectory should complete"
1247        );
1248        assert!(
1249            !trajectory_headwind.is_empty(),
1250            "Headwind trajectory should complete"
1251        );
1252
1253        let (time_no_wind, final_no_wind) = trajectory_no_wind.last().unwrap();
1254        let (time_headwind, final_headwind) = trajectory_headwind.last().unwrap();
1255
1256        // Headwind should slow the bullet, resulting in longer flight time
1257        // or different drop at same distance
1258        let drop_no_wind = final_no_wind[1];
1259        let drop_headwind = final_headwind[1];
1260
1261        println!("No wind: time={}, drop={}", time_no_wind, drop_no_wind);
1262        println!("Headwind: time={}, drop={}", time_headwind, drop_headwind);
1263
1264        assert!(
1265            *time_headwind > *time_no_wind + 0.001,
1266            "headwind should increase time of flight: no-wind={time_no_wind}, headwind={time_headwind}"
1267        );
1268        assert!(
1269            final_headwind[3] < final_no_wind[3] - 1.0,
1270            "headwind should reduce terminal downrange velocity"
1271        );
1272
1273        // Both should reach approximately the target distance
1274        assert!(
1275            (final_no_wind[0] - target_distance).abs() < 10.0,
1276            "No-wind should reach target"
1277        );
1278        assert!(
1279            (final_headwind[0] - target_distance).abs() < 10.0,
1280            "Headwind should reach target"
1281        );
1282    }
1283
1284    #[test]
1285    fn test_solve_trajectory_rust_output_format() {
1286        let initial_state = [0.0, 0.0, 0.0, 800.0, 30.0, 0.0]; // McCoy: vx=downrange
1287
1288        let result = solve_trajectory_rust(
1289            initial_state,
1290            (0.0, 2.0),
1291            0.01134,       // mass_kg
1292            0.442,         // bc
1293            DragModel::G7, // drag_model
1294            vec![],        // wind_segments
1295            // Standard atmosphere: altitude m, temperature C, pressure hPa, density ratio.
1296            (0.0, 15.0, 1013.25, 1.0),
1297            None,               // omega_vector
1298            false,              // enable_spin_drift
1299            false,              // enable_magnus
1300            false,              // enable_coriolis
1301            "RK45".to_string(), // method
1302            1e-6,               // tolerance
1303            0.01,               // max_step
1304            500.0,              // target_distance_m
1305        );
1306
1307        // Should return Vec of HashMaps with expected keys
1308        assert!(!result.is_empty());
1309
1310        let first_point = &result[0];
1311        assert!(first_point.contains_key("t"));
1312        assert!(first_point.contains_key("x"));
1313        assert!(first_point.contains_key("y"));
1314        assert!(first_point.contains_key("z"));
1315        assert!(first_point.contains_key("vx"));
1316        assert!(first_point.contains_key("vy"));
1317        assert!(first_point.contains_key("vz"));
1318
1319        let final_point = result.last().unwrap();
1320        assert!(
1321            final_point["vx"] < 0.9 * initial_state[3],
1322            "standard-atmosphere wrapper fixture should exercise drag"
1323        );
1324    }
1325
1326    #[test]
1327    fn test_left_vs_right_twist() {
1328        let initial_state = [0.0, 0.0, 0.0, 800.0, 30.0, 0.0]; // McCoy: vx=downrange
1329        let target_distance = 500.0;
1330
1331        let mut params_right = create_test_params(target_distance);
1332        params_right.is_twist_right = true;
1333        params_right.enable_spin_drift = true;
1334
1335        let mut params_left = create_test_params(target_distance);
1336        params_left.is_twist_right = false;
1337        params_left.enable_spin_drift = true;
1338
1339        let trajectory_right =
1340            integrate_trajectory(initial_state, (0.0, 5.0), params_right, "RK45", 1e-6, 0.01);
1341        let trajectory_left =
1342            integrate_trajectory(initial_state, (0.0, 5.0), params_left, "RK45", 1e-6, 0.01);
1343
1344        // Both should complete
1345        assert!(!trajectory_right.is_empty());
1346        assert!(!trajectory_left.is_empty());
1347
1348        // Right and left twist should produce valid trajectories
1349        let (_, final_right) = trajectory_right.last().unwrap();
1350        let (_, final_left) = trajectory_left.last().unwrap();
1351
1352        // Both should reach approximately the same downrange distance
1353        assert!((final_right[2] - final_left[2]).abs() < 10.0);
1354    }
1355}