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
17fn wind_vector_for_range(range_m: f64, wind_segments: &[WindSegment]) -> Vector3<f64> {
18    if range_m.is_nan() {
19        return Vector3::zeros();
20    }
21    for seg in wind_segments {
22        if range_m < seg.2 {
23            let wind_speed_mps = seg.0 * 0.2777778; // km/h to m/s
24            let wind_angle_rad = seg.1.to_radians();
25            return Vector3::new(
26                -wind_speed_mps * wind_angle_rad.cos(),
27                0.0,
28                -wind_speed_mps * wind_angle_rad.sin(),
29            );
30        }
31    }
32    Vector3::zeros()
33}
34
35/// RK4 integration step
36fn rk4_step(
37    state: &Vector6<f64>,
38    t: f64,
39    dt: f64,
40    params: &TrajectoryParams,
41    inputs: &BallisticInputs,
42) -> Vector6<f64> {
43    // RK4 integration
44    let k1 = compute_derivatives_vec(state, t, params, inputs);
45    let k2 = compute_derivatives_vec(&(state + dt * 0.5 * k1), t + dt * 0.5, params, inputs);
46    let k3 = compute_derivatives_vec(&(state + dt * 0.5 * k2), t + dt * 0.5, params, inputs);
47    let k4 = compute_derivatives_vec(&(state + dt * k3), t + dt, params, inputs);
48
49    state + (dt / 6.0) * (k1 + 2.0 * k2 + 2.0 * k3 + k4)
50}
51
52/// Adaptive RK45 integration step (Dormand-Prince method)
53fn rk45_step(
54    state: &Vector6<f64>,
55    t: f64,
56    dt: f64,
57    params: &TrajectoryParams,
58    inputs: &BallisticInputs,
59    tol: f64,
60) -> (Vector6<f64>, f64, f64) {
61    // Dormand-Prince coefficients (same as scipy.integrate.solve_ivp RK45)
62    const A21: f64 = 1.0 / 5.0;
63    const A31: f64 = 3.0 / 40.0;
64    const A32: f64 = 9.0 / 40.0;
65    const A41: f64 = 44.0 / 45.0;
66    const A42: f64 = -56.0 / 15.0;
67    const A43: f64 = 32.0 / 9.0;
68    const A51: f64 = 19372.0 / 6561.0;
69    const A52: f64 = -25360.0 / 2187.0;
70    const A53: f64 = 64448.0 / 6561.0;
71    const A54: f64 = -212.0 / 729.0;
72    const A61: f64 = 9017.0 / 3168.0;
73    const A62: f64 = -355.0 / 33.0;
74    const A63: f64 = 46732.0 / 5247.0;
75    const A64: f64 = 49.0 / 176.0;
76    const A65: f64 = -5103.0 / 18656.0;
77    const A71: f64 = 35.0 / 384.0;
78    const A73: f64 = 500.0 / 1113.0;
79    const A74: f64 = 125.0 / 192.0;
80    const A75: f64 = -2187.0 / 6784.0;
81    const A76: f64 = 11.0 / 84.0;
82
83    // 5th order coefficients
84    const B1: f64 = 35.0 / 384.0;
85    const B3: f64 = 500.0 / 1113.0;
86    const B4: f64 = 125.0 / 192.0;
87    const B5: f64 = -2187.0 / 6784.0;
88    const B6: f64 = 11.0 / 84.0;
89
90    // 4th order coefficients (for error estimation)
91    const B1_ERR: f64 = 5179.0 / 57600.0;
92    const B3_ERR: f64 = 7571.0 / 16695.0;
93    const B4_ERR: f64 = 393.0 / 640.0;
94    const B5_ERR: f64 = -92097.0 / 339200.0;
95    const B6_ERR: f64 = 187.0 / 2100.0;
96    const B7_ERR: f64 = 1.0 / 40.0;
97
98    // Compute stages
99    let k1 = compute_derivatives_vec(state, t, params, inputs);
100    let k2 = compute_derivatives_vec(&(state + dt * A21 * k1), t + dt * 0.2, params, inputs);
101    let k3 = compute_derivatives_vec(
102        &(state + dt * (A31 * k1 + A32 * k2)),
103        t + dt * 0.3,
104        params,
105        inputs,
106    );
107    let k4 = compute_derivatives_vec(
108        &(state + dt * (A41 * k1 + A42 * k2 + A43 * k3)),
109        t + dt * 0.8,
110        params,
111        inputs,
112    );
113    let k5 = compute_derivatives_vec(
114        &(state + dt * (A51 * k1 + A52 * k2 + A53 * k3 + A54 * k4)),
115        t + dt * 8.0 / 9.0,
116        params,
117        inputs,
118    );
119    let k6 = compute_derivatives_vec(
120        &(state + dt * (A61 * k1 + A62 * k2 + A63 * k3 + A64 * k4 + A65 * k5)),
121        t + dt,
122        params,
123        inputs,
124    );
125    let k7 = compute_derivatives_vec(
126        &(state + dt * (A71 * k1 + A73 * k3 + A74 * k4 + A75 * k5 + A76 * k6)),
127        t + dt,
128        params,
129        inputs,
130    );
131
132    // 5th order solution
133    let y_new = state + dt * (B1 * k1 + B3 * k3 + B4 * k4 + B5 * k5 + B6 * k6);
134
135    // 4th order solution for error estimate
136    let y_err = state
137        + dt * (B1_ERR * k1 + B3_ERR * k3 + B4_ERR * k4 + B5_ERR * k5 + B6_ERR * k6 + B7_ERR * k7);
138
139    // Error estimate
140    let error = (y_new - y_err).norm() / (1.0 + state.norm());
141
142    // Adaptive step size
143    let safety = 0.9;
144    let dt_new = if error < tol {
145        dt * safety * (tol / error).powf(0.2).min(2.0)
146    } else {
147        dt * safety * (tol / error).powf(0.25).max(0.1)
148    };
149
150    (y_new, dt_new, error)
151}
152
153/// Parameters for trajectory computation
154pub struct TrajectoryParams {
155    pub mass_kg: f64,
156    pub bc: f64,
157    pub drag_model: DragModel,
158    pub wind_segments: Vec<WindSegment>,
159    /// Dual-mode atmosphere tuple consumed by `compute_derivatives`:
160    /// **Standard** `(base_alt_m, base_temp_c, base_pressure_hPa, base_density_ratio)` — note
161    /// slot 3 is a density RATIO, NOT humidity, even though it rides in the `humidity` field;
162    /// or **Direct** `(air_density, speed_of_sound, 0.0, 0.0)` — slots 2 and 3 are zero
163    /// sentinels. A pressure of 0 that is not the direct-mode sentinel disables drag.
164    pub atmos_params: (f64, f64, f64, f64),
165    pub omega_vector: Option<Vector3<f64>>,
166    pub enable_spin_drift: bool,
167    pub enable_magnus: bool,
168    pub enable_coriolis: bool,
169    pub target_distance_m: f64, // Target horizontal distance in meters
170    pub enable_wind_shear: bool,
171    pub wind_shear_model: String,
172    pub shooter_altitude_m: f64,
173    pub is_twist_right: bool, // True for right-hand twist, false for left-hand
174    pub shooting_angle: f64,  // uphill/downhill angle in radians
175    // MBA-717: real bullet geometry so spin-drift / Magnus / stability on this fast/MC
176    // path use the actual bullet instead of hardcoded .308 / 1.24in / 10-twist placeholders.
177    pub bullet_diameter: f64,                              // meters
178    pub bullet_length: f64, // meters (0.0 -> derivatives falls back to the 4.5-caliber heuristic)
179    pub twist_rate: f64,    // inches per turn
180    pub custom_drag_table: Option<crate::drag::DragTable>, // Custom Drag Model (CDM) data
181    pub bc_segments: Option<Vec<(f64, f64)>>, // Mach-based BC segments: (mach, bc)
182    pub use_bc_segments: bool, // Whether to use BC segment interpolation
183    /// MBA-954: altitude (m, relative to launch) below which integration stops. -1000.0 is the
184    /// historical default — effectively "no early ground impact" for normal flat-fire shots.
185    pub ground_threshold: f64,
186}
187
188/// Build the loop-invariant BallisticInputs for the derivatives function ONCE per integration,
189/// instead of rebuilding it (a "none".to_string() alloc plus bc_segments / custom_drag_table
190/// clones) on every derivative evaluation (4x per RK4 step, 7x per RK45 step). muzzle_velocity is
191/// set to 0.0 because compute_derivatives never reads it on this path; every other field depends
192/// only on `params`, so the struct is constant for the whole integration.
193fn build_inputs(params: &TrajectoryParams) -> BallisticInputs {
194    let mut inputs = BallisticInputs {
195        bc_value: params.bc,
196        bc_type: params.drag_model,
197        bullet_mass: params.mass_kg,             // kg
198        muzzle_velocity: 0.0,                    // unread by compute_derivatives on this path
199        bullet_diameter: params.bullet_diameter, // MBA-717: real geometry, not placeholders
200        bullet_length: params.bullet_length,
201        twist_rate: params.twist_rate,
202        is_twist_right: params.is_twist_right,
203        enable_advanced_effects: params.enable_spin_drift
204            || params.enable_magnus
205            || params.enable_coriolis,
206        enable_magnus: params.enable_magnus,
207        enable_coriolis: params.enable_coriolis,
208        altitude: params.atmos_params.0,
209        temperature: params.atmos_params.1,
210        pressure: params.atmos_params.2,
211        humidity: params.atmos_params.3,
212        tipoff_yaw: 0.0,
213        target_distance: 1000.0, // default
214        muzzle_angle: 0.0,
215        wind_speed: if !params.wind_segments.is_empty() {
216            params.wind_segments[0].0 * 0.2777778 // km/h -> m/s
217        } else {
218            0.0
219        },
220        wind_angle: if !params.wind_segments.is_empty() {
221            params.wind_segments[0].1.to_radians() // degrees -> radians
222        } else {
223            0.0
224        },
225        latitude: None,
226        shooting_angle: params.shooting_angle,
227        azimuth_angle: 0.0,
228        shot_azimuth: 0.0, // this fast path doesn't plumb latitude/bearing (no directional Coriolis here)
229        use_powder_sensitivity: false,
230        powder_temp_sensitivity: 0.0,
231        powder_temp: 59.0,
232        tipoff_decay_distance: 0.0,
233        ground_threshold: params.ground_threshold, // MBA-954: honor the configured ground plane
234        bc_segments: params.bc_segments.clone(),
235        caliber_inches: params.bullet_diameter / 0.0254, // MBA-717: from real diameter
236        weight_grains: params.mass_kg / 0.00006479891,
237        use_bc_segments: params.use_bc_segments,
238        bullet_id: None,
239        bc_segments_data: None,
240        use_enhanced_spin_drift: params.enable_spin_drift,
241        use_form_factor: false,
242        manufacturer: None,
243        bullet_model: None,
244        enable_wind_shear: false,
245        wind_shear_model: "none".to_string(),
246        use_cluster_bc: false,
247        bullet_cluster: None,
248        custom_drag_table: params.custom_drag_table.clone(),
249        bc_type_str: None,
250        enable_pitch_damping: false,
251        enable_precession_nutation: false,
252        // MBA-959: aerodynamic jump is intentionally OFF on this path. integrate_trajectory
253        // is a low-level state integrator: it advances a raw initial_state (no muzzle angle to
254        // perturb) and an unread muzzle_velocity, so a meaningful Litz Sg can't be formed here
255        // (Sg would be ~0 and the AJ guard would suppress it regardless). AJ belongs on the
256        // BallisticInputs + TrajectorySolver path, which bindings use and already honors the flag.
257        // (Bullet geometry IS now carried through TrajectoryParams — MBA-717 — so spin-drift /
258        // Magnus on this path use the real diameter/length/twist.)
259        enable_aerodynamic_jump: false,
260        use_rk4: true,
261        use_adaptive_rk45: false,
262        enable_trajectory_sampling: false,
263        sample_interval: 10.0,
264        sight_height: 0.0,
265        muzzle_height: 0.0,
266        target_height: 0.0,
267    };
268
269    // MBA-955: pre-populate velocity-BC segments ONCE here, instead of get_bc_for_velocity
270    // rebuilding them (a model String + a segment Vec) on every derivative evaluation (4-7x per
271    // step). Gated to EXACTLY the case where the per-step path would estimate: use_bc_segments on,
272    // no explicit velocity segments, and no Mach-based bc_segments (those take a different,
273    // unchanged path). bc_used there == params.bc == inputs.bc_value, so the estimated segments are
274    // identical and the per-step fast-path lookup returns the same BC -> byte-identical output.
275    if inputs.use_bc_segments && inputs.bc_segments_data.is_none() && inputs.bc_segments.is_none() {
276        inputs.bc_segments_data =
277            crate::derivatives::estimate_bc_segments_for(&inputs, inputs.bc_value);
278    }
279    inputs
280}
281
282/// Convert state to Vector6 and call compute_derivatives
283fn compute_derivatives_vec(
284    state: &Vector6<f64>,
285    t: f64,
286    params: &TrajectoryParams,
287    inputs: &BallisticInputs,
288) -> Vector6<f64> {
289    let pos = Vector3::new(state[0], state[1], state[2]);
290    let vel = Vector3::new(state[3], state[4], state[5]);
291
292    // Calculate wind at current position with shear support
293    let wind_vector = if !params.wind_segments.is_empty() {
294        if params.enable_wind_shear && params.wind_shear_model != "none" {
295            crate::wind_shear::get_wind_at_position(
296                &pos,
297                &params.wind_segments,
298                params.enable_wind_shear,
299                &params.wind_shear_model,
300                params.shooter_altitude_m,
301            )
302        } else {
303            wind_vector_for_range(pos.x, &params.wind_segments)
304        }
305    } else {
306        Vector3::zeros()
307    };
308
309    // Call compute_derivatives - returns [f64; 6] directly. `inputs` is built once per
310    // integration by build_inputs() and threaded in, instead of rebuilt every call.
311    let deriv_result = compute_derivatives(
312        pos,
313        vel,
314        inputs,
315        wind_vector,
316        params.atmos_params,
317        params.bc,
318        params.omega_vector,
319        t,
320    );
321
322    Vector6::new(
323        deriv_result[0],
324        deriv_result[1],
325        deriv_result[2],
326        deriv_result[3],
327        deriv_result[4],
328        deriv_result[5],
329    )
330}
331
332/// Main trajectory integration function
333pub fn integrate_trajectory(
334    initial_state: [f64; 6],
335    t_span: (f64, f64),
336    params: TrajectoryParams,
337    method: &str,
338    tolerance: f64,
339    max_step: f64,
340) -> Vec<(f64, Vector6<f64>)> {
341    let mut state = Vector6::new(
342        initial_state[0],
343        initial_state[1],
344        initial_state[2],
345        initial_state[3],
346        initial_state[4],
347        initial_state[5],
348    );
349
350    let mut t = t_span.0;
351    let t_end = t_span.1;
352    let mut dt = (t_end - t) / 1000.0; // Initial step size
353
354    let mut trajectory = Vec::with_capacity(10000);
355    trajectory.push((t, state));
356
357    // Build the (loop-invariant) derivative inputs once for the whole integration, instead of
358    // rebuilding the struct on every derivative evaluation.
359    let inputs = build_inputs(&params);
360
361    match method {
362        "RK4" => {
363            // Fixed step RK4 with target detection
364            dt = dt.min(max_step).min(0.001); // Use smaller steps for accuracy
365
366            while t < t_end {
367                if t + dt > t_end {
368                    dt = t_end - t;
369                }
370
371                let new_state = rk4_step(&state, t, dt, &params, &inputs);
372
373                // Check if we're about to pass the target (X is downrange, McCoy)
374                if state[0] < params.target_distance_m && new_state[0] >= params.target_distance_m {
375                    // Interpolate to find exact target crossing
376                    let alpha = (params.target_distance_m - state[0]) / (new_state[0] - state[0]);
377                    let dt_to_target = dt * alpha;
378
379                    // Take a smaller step to reach target exactly
380                    let final_state = rk4_step(&state, t, dt_to_target, &params, &inputs);
381
382                    // Ensure we don't overshoot
383                    let mut corrected_state = final_state;
384                    if corrected_state[0] > params.target_distance_m {
385                        corrected_state[0] = params.target_distance_m;
386                    }
387
388                    trajectory.push((t + dt_to_target, corrected_state));
389                    break; // Stop at target
390                }
391
392                state = new_state;
393                t += dt;
394                trajectory.push((t, state));
395
396                // Check if we've reached or passed the target
397                if state[0] >= params.target_distance_m {
398                    // X is downrange (McCoy)
399                    // Add final point exactly at target
400                    let mut final_state = state;
401                    final_state[0] = params.target_distance_m; // X is downrange
402                    trajectory.push((t, final_state));
403                    break;
404                }
405
406                // Check if bullet hit ground (MBA-954: honor the configured ground plane,
407                // not a hardcoded -1000.0)
408                if state[1] < params.ground_threshold {
409                    break;
410                }
411            }
412        }
413        "RK45" | _ => {
414            // Adaptive RK45 with better sampling
415            let mut last_save_x = 0.0; // X is downrange (McCoy)
416            let save_interval_m = params.target_distance_m / 50.0; // Save ~50 points minimum
417
418            // OPTIMIZATION: Adjust max step size when wind shear is enabled
419            // This improves numerical stability at long ranges
420            let effective_max_step =
421                if params.enable_wind_shear && params.wind_shear_model != "none" {
422                    // Use smaller steps for wind shear, but not TOO small
423                    if params.target_distance_m > 800.0 {
424                        0.01 // Smaller steps for long range with shear (10ms)
425                    } else {
426                        0.02 // Normal steps for medium range with shear (20ms)
427                    }
428                } else {
429                    max_step // Use provided max_step when no wind shear
430                };
431
432            // Set initial step size - ensure it's reasonable
433            dt = dt.min(effective_max_step).max(0.0001); // At least 0.1ms to avoid infinite loops
434
435            // Safety check: maximum iterations to prevent infinite loops
436            let max_iterations = 100000; // Should be more than enough for any realistic trajectory
437            let mut iteration_count = 0;
438
439            while t < t_end && iteration_count < max_iterations {
440                iteration_count += 1;
441
442                // Limit time step for better resolution
443                if t + dt > t_end {
444                    dt = t_end - t;
445                }
446
447                let (new_state, dt_new, _error) =
448                    rk45_step(&state, t, dt, &params, &inputs, tolerance);
449
450                // Check if we're about to pass the target (X is downrange, McCoy)
451                if state[0] < params.target_distance_m && new_state[0] >= params.target_distance_m {
452                    // Interpolate to find exact target crossing
453                    let alpha = (params.target_distance_m - state[0]) / (new_state[0] - state[0]);
454                    let dt_to_target = dt * alpha;
455
456                    // Take a smaller step to reach target exactly
457                    let (final_state, _, _) =
458                        rk45_step(&state, t, dt_to_target, &params, &inputs, tolerance);
459
460                    // Make sure we don't overshoot
461                    let mut corrected_state = final_state;
462                    if corrected_state[0] > params.target_distance_m {
463                        corrected_state[0] = params.target_distance_m;
464                    }
465
466                    trajectory.push((t + dt_to_target, corrected_state));
467                    break; // Stop at target - no more points after this
468                }
469
470                // Update state
471                state = new_state;
472                t += dt;
473
474                // Save trajectory point if we've moved enough distance
475                if state[0] - last_save_x >= save_interval_m || state[0] >= params.target_distance_m
476                {
477                    // X is downrange
478                    trajectory.push((t, state));
479                    last_save_x = state[0];
480                }
481
482                // Limit dt for next step - ensure we get enough resolution
483                dt = dt_new.min(effective_max_step).max(0.0001); // Use effective max step, min 0.1ms
484
485                // Stop if we've reached the target
486                if state[0] >= params.target_distance_m {
487                    // X is downrange (McCoy)
488                    // Add final point at target distance
489                    let mut final_state = state;
490                    final_state[0] = params.target_distance_m; // X is downrange
491                    trajectory.push((t, final_state));
492                    break;
493                }
494
495                // Check if bullet hit ground (MBA-954: honor the configured ground plane,
496                // not a hardcoded -1000.0)
497                if state[1] < params.ground_threshold {
498                    break;
499                }
500            }
501
502            // Warn if we hit the iteration limit
503            if iteration_count >= max_iterations {
504                eprintln!(
505                    "WARNING: Trajectory integration hit maximum iteration limit ({} iterations)",
506                    max_iterations
507                );
508                eprintln!("  Final time: {}, Target time: {}", t, t_end);
509                eprintln!(
510                    "  Final position: downrange(x)={}, Target: {}m",
511                    state[0], params.target_distance_m
512                );
513            }
514        }
515    }
516
517    trajectory
518}
519
520/// Python-exposed function for complete trajectory integration
521pub fn solve_trajectory_rust(
522    initial_state: [f64; 6],
523    t_span: (f64, f64),
524    mass_kg: f64,
525    bc: f64,
526    drag_model: DragModel,
527    wind_segments: Vec<WindSegment>,
528    atmos_params: (f64, f64, f64, f64),
529    omega_vector: Option<Vec<f64>>,
530    enable_spin_drift: bool,
531    enable_magnus: bool,
532    enable_coriolis: bool,
533    method: String,
534    tolerance: f64,
535    max_step: f64,
536    target_distance_m: f64,
537) -> Vec<HashMap<String, f64>> {
538    let omega_vec = omega_vector.map(|v| Vector3::new(v[0], v[1], v[2]));
539
540    let params = TrajectoryParams {
541        mass_kg,
542        bc,
543        drag_model,
544        wind_segments,
545        atmos_params,
546        omega_vector: omega_vec,
547        enable_spin_drift,
548        enable_magnus,
549        enable_coriolis,
550        target_distance_m,
551        enable_wind_shear: false, // Default for test function
552        wind_shear_model: "none".to_string(),
553        shooter_altitude_m: 0.0,
554        is_twist_right: true, // Default for test function
555        shooting_angle: 0.0,  // This legacy entry takes no inclined-fire arg; flat fire only
556        // This legacy entry takes no geometry args; keep the historical placeholders so its
557        // behavior is unchanged (callers needing real geometry use fast_integrate_with_segments).
558        bullet_diameter: 0.0078232,
559        bullet_length: 0.031496,
560        twist_rate: 10.0,
561        custom_drag_table: None, // No CDM for test function
562        bc_segments: None,       // No BC segments for legacy function
563        use_bc_segments: false,
564        ground_threshold: -1000.0, // MBA-954: preserve the historical default
565    };
566
567    let trajectory =
568        integrate_trajectory(initial_state, t_span, params, &method, tolerance, max_step);
569
570    // Convert to Python-friendly format
571    trajectory
572        .into_iter()
573        .map(|(t, state)| {
574            let mut point = HashMap::new();
575            point.insert("t".to_string(), t);
576            point.insert("x".to_string(), state[0]);
577            point.insert("y".to_string(), state[1]);
578            point.insert("z".to_string(), state[2]);
579            point.insert("vx".to_string(), state[3]);
580            point.insert("vy".to_string(), state[4]);
581            point.insert("vz".to_string(), state[5]);
582            point
583        })
584        .collect()
585}
586
587#[cfg(test)]
588mod tests {
589    use super::*;
590
591    fn create_test_params(target_distance_m: f64) -> TrajectoryParams {
592        TrajectoryParams {
593            mass_kg: 0.01134, // 175 grains in kg
594            bc: 0.442,
595            bullet_diameter: 0.0078232, // .308 in
596            bullet_length: 0.031496,    // 1.24 in
597            twist_rate: 10.0,
598            drag_model: DragModel::G7,
599            wind_segments: vec![],
600            atmos_params: (0.0, 59.0, 29.92, 0.0),
601            omega_vector: None,
602            enable_spin_drift: false,
603            enable_magnus: false,
604            enable_coriolis: false,
605            target_distance_m,
606            enable_wind_shear: false,
607            wind_shear_model: "none".to_string(),
608            shooter_altitude_m: 0.0,
609            is_twist_right: true,
610            shooting_angle: 0.0,
611            custom_drag_table: None,
612            bc_segments: None,
613            use_bc_segments: false,
614            ground_threshold: -1000.0,
615        }
616    }
617
618    #[test]
619    fn test_mba954_ground_threshold_honored() {
620        // MBA-954: integrate_trajectory must honor the configured ground plane, not a hardcoded
621        // -1000.0. A descending bullet with a shallow ground_threshold must terminate earlier
622        // (fewer points) than one with the historical deep default.
623        let initial_state = [0.0, 0.0, 0.0, 300.0, -30.0, 0.0]; // descending (vy = -30 m/s)
624
625        let mut shallow = create_test_params(1_000_000.0); // huge target so range never terminates
626        shallow.ground_threshold = -20.0; // stop ~20 m below launch
627        let mut deep = create_test_params(1_000_000.0);
628        deep.ground_threshold = -1000.0; // historical default
629
630        let t_shallow =
631            integrate_trajectory(initial_state, (0.0, 60.0), shallow, "RK4", 1e-6, 0.001);
632        let t_deep = integrate_trajectory(initial_state, (0.0, 60.0), deep, "RK4", 1e-6, 0.001);
633
634        assert!(
635            t_shallow.len() < t_deep.len(),
636            "shallow ground_threshold (-20) should terminate earlier than deep (-1000): \
637             shallow={}, deep={}",
638            t_shallow.len(),
639            t_deep.len()
640        );
641    }
642
643    #[test]
644    fn test_integrate_trajectory_basic() {
645        // Initial state [x,y,z,vx,vy,vz] (McCoy: X=downrange, Z=lateral)
646        // x=0 (downrange start), vx=821.52 (downrange velocity)
647        let initial_state = [0.0, -0.038, 0.0, 821.52, 48.61, 0.0];
648
649        let params = TrajectoryParams {
650            mass_kg: 0.01134, // 175 grains in kg
651            bc: 0.442,
652            bullet_diameter: 0.0078232, // .308 in
653            bullet_length: 0.031496,    // 1.24 in
654            twist_rate: 10.0,
655            drag_model: DragModel::G7,
656            wind_segments: vec![(0.0, 90.0, 914.4)],
657            atmos_params: (0.0, 59.0, 29.92, 0.0),
658            omega_vector: None,
659            enable_spin_drift: false,
660            enable_magnus: false,
661            enable_coriolis: false,
662            target_distance_m: 914.4, // 1000 yards in meters
663            enable_wind_shear: false,
664            wind_shear_model: "none".to_string(),
665            shooter_altitude_m: 0.0,
666            is_twist_right: true,
667            shooting_angle: 0.0,
668            custom_drag_table: None,
669            bc_segments: None,
670            use_bc_segments: false,
671            ground_threshold: -1000.0,
672        };
673
674        println!("Running integrate_trajectory test...");
675        println!("Initial state: {:?}", initial_state);
676        println!("Target distance: {} m", params.target_distance_m);
677
678        let trajectory =
679            integrate_trajectory(initial_state, (0.0, 10.0), params, "RK45", 1e-6, 0.01);
680
681        println!("Trajectory has {} points", trajectory.len());
682
683        // Should have more than just initial point
684        assert!(
685            trajectory.len() > 1,
686            "Trajectory should have more than 1 point, but has {}",
687            trajectory.len()
688        );
689
690        // Check that we actually moved downrange
691        if let Some((_, final_state)) = trajectory.last() {
692            println!("Final state: downrange(x)={}", final_state[0]);
693            assert!(
694                final_state[0] > 0.0,
695                "Final x should be positive (bullet moved downrange)"
696            );
697            assert!(
698                final_state[0] >= 900.0,
699                "Final x should be near target distance"
700            );
701        }
702    }
703
704    #[test]
705    fn test_rk4_vs_rk45_consistency() {
706        // Both methods should give similar results for the same trajectory
707        let initial_state = [0.0, 0.0, 0.0, 800.0, 30.0, 0.0]; // McCoy: vx=downrange
708        let target_distance = 500.0;
709
710        let params_rk4 = create_test_params(target_distance);
711        let params_rk45 = create_test_params(target_distance);
712
713        let trajectory_rk4 =
714            integrate_trajectory(initial_state, (0.0, 5.0), params_rk4, "RK4", 1e-6, 0.001);
715        let trajectory_rk45 =
716            integrate_trajectory(initial_state, (0.0, 5.0), params_rk45, "RK45", 1e-6, 0.01);
717
718        // Both should reach target
719        assert!(!trajectory_rk4.is_empty());
720        assert!(!trajectory_rk45.is_empty());
721
722        let (_, final_rk4) = trajectory_rk4.last().unwrap();
723        let (_, final_rk45) = trajectory_rk45.last().unwrap();
724
725        // Final downrange positions should be within 1% of each other
726        let rk4_z = final_rk4[0];
727        let rk45_z = final_rk45[0];
728        let diff_percent = ((rk4_z - rk45_z) / rk45_z).abs() * 100.0;
729
730        assert!(
731            diff_percent < 1.0,
732            "RK4 and RK45 final positions differ by {}%: RK4={}, RK45={}",
733            diff_percent,
734            rk4_z,
735            rk45_z
736        );
737    }
738
739    #[test]
740    fn test_ground_impact_detection() {
741        // Trajectory with steep downward angle should hit ground
742        let initial_state = [0.0, 100.0, 0.0, 300.0, -50.0, 0.0]; // McCoy: vx=downrange // Steep descent
743
744        let mut params = create_test_params(10000.0); // Far target
745        params.target_distance_m = 10000.0;
746
747        let trajectory =
748            integrate_trajectory(initial_state, (0.0, 20.0), params, "RK45", 1e-6, 0.01);
749
750        // Should stop before reaching target due to ground impact
751        let (_, final_state) = trajectory.last().unwrap();
752
753        // y should be near ground threshold (-1000m)
754        assert!(
755            final_state[1] <= -900.0,
756            "Should hit ground, but y={}",
757            final_state[1]
758        );
759        assert!(
760            final_state[0] < 10000.0,
761            "Should not reach target, but z={}",
762            final_state[0]
763        );
764    }
765
766    #[test]
767    fn test_target_distance_reached() {
768        let initial_state = [0.0, 0.0, 0.0, 800.0, 20.0, 0.0]; // McCoy: vx=downrange
769        let target_distance = 300.0;
770
771        let params = create_test_params(target_distance);
772
773        let trajectory =
774            integrate_trajectory(initial_state, (0.0, 5.0), params, "RK45", 1e-6, 0.01);
775
776        let (_, final_state) = trajectory.last().unwrap();
777
778        // Should stop at or very near target distance
779        assert!(
780            (final_state[0] - target_distance).abs() < 1.0,
781            "Should reach target at {}m, but stopped at {}m",
782            target_distance,
783            final_state[0]
784        );
785    }
786
787    #[test]
788    fn test_wind_affects_trajectory() {
789        // Test that wind segments are properly stored and passed through
790        // The actual wind effect depends on the derivatives computation which
791        // uses the wind vector in the drag calculation
792        let initial_state = [0.0, 0.0, 0.0, 800.0, 30.0, 0.0]; // McCoy: vx=downrange
793        let target_distance = 500.0;
794
795        // No wind
796        let params_no_wind = create_test_params(target_distance);
797
798        // Strong headwind (0 degrees = headwind)
799        let mut params_headwind = create_test_params(target_distance);
800        params_headwind.wind_segments = vec![(72.0, 0.0, 500.0)]; // 72 km/h = 20 m/s headwind
801
802        let trajectory_no_wind = integrate_trajectory(
803            initial_state,
804            (0.0, 5.0),
805            params_no_wind,
806            "RK45",
807            1e-6,
808            0.01,
809        );
810        let trajectory_headwind = integrate_trajectory(
811            initial_state,
812            (0.0, 5.0),
813            params_headwind,
814            "RK45",
815            1e-6,
816            0.01,
817        );
818
819        // Both trajectories should complete
820        assert!(
821            !trajectory_no_wind.is_empty(),
822            "No-wind trajectory should complete"
823        );
824        assert!(
825            !trajectory_headwind.is_empty(),
826            "Headwind trajectory should complete"
827        );
828
829        let (time_no_wind, final_no_wind) = trajectory_no_wind.last().unwrap();
830        let (time_headwind, final_headwind) = trajectory_headwind.last().unwrap();
831
832        // Headwind should slow the bullet, resulting in longer flight time
833        // or different drop at same distance
834        let drop_no_wind = final_no_wind[1];
835        let drop_headwind = final_headwind[1];
836
837        // With headwind, bullet should drop more (more negative y) due to slower velocity
838        // The effect might be small, so we check that both trajectories are valid
839        println!("No wind: time={}, drop={}", time_no_wind, drop_no_wind);
840        println!("Headwind: time={}, drop={}", time_headwind, drop_headwind);
841
842        // Both should reach approximately the target distance
843        assert!(
844            (final_no_wind[0] - target_distance).abs() < 10.0,
845            "No-wind should reach target"
846        );
847        assert!(
848            (final_headwind[0] - target_distance).abs() < 10.0,
849            "Headwind should reach target"
850        );
851    }
852
853    #[test]
854    fn test_solve_trajectory_rust_output_format() {
855        let initial_state = [0.0, 0.0, 0.0, 800.0, 30.0, 0.0]; // McCoy: vx=downrange
856
857        let result = solve_trajectory_rust(
858            initial_state,
859            (0.0, 2.0),
860            0.01134,                 // mass_kg
861            0.442,                   // bc
862            DragModel::G7,           // drag_model
863            vec![],                  // wind_segments
864            (0.0, 59.0, 29.92, 0.0), // atmos_params
865            None,                    // omega_vector
866            false,                   // enable_spin_drift
867            false,                   // enable_magnus
868            false,                   // enable_coriolis
869            "RK45".to_string(),      // method
870            1e-6,                    // tolerance
871            0.01,                    // max_step
872            500.0,                   // target_distance_m
873        );
874
875        // Should return Vec of HashMaps with expected keys
876        assert!(!result.is_empty());
877
878        let first_point = &result[0];
879        assert!(first_point.contains_key("t"));
880        assert!(first_point.contains_key("x"));
881        assert!(first_point.contains_key("y"));
882        assert!(first_point.contains_key("z"));
883        assert!(first_point.contains_key("vx"));
884        assert!(first_point.contains_key("vy"));
885        assert!(first_point.contains_key("vz"));
886    }
887
888    #[test]
889    fn test_left_vs_right_twist() {
890        let initial_state = [0.0, 0.0, 0.0, 800.0, 30.0, 0.0]; // McCoy: vx=downrange
891        let target_distance = 500.0;
892
893        let mut params_right = create_test_params(target_distance);
894        params_right.is_twist_right = true;
895        params_right.enable_spin_drift = true;
896
897        let mut params_left = create_test_params(target_distance);
898        params_left.is_twist_right = false;
899        params_left.enable_spin_drift = true;
900
901        let trajectory_right =
902            integrate_trajectory(initial_state, (0.0, 5.0), params_right, "RK45", 1e-6, 0.01);
903        let trajectory_left =
904            integrate_trajectory(initial_state, (0.0, 5.0), params_left, "RK45", 1e-6, 0.01);
905
906        // Both should complete
907        assert!(!trajectory_right.is_empty());
908        assert!(!trajectory_left.is_empty());
909
910        // Right and left twist should produce valid trajectories
911        let (_, final_right) = trajectory_right.last().unwrap();
912        let (_, final_left) = trajectory_left.last().unwrap();
913
914        // Both should reach approximately the same downrange distance
915        assert!((final_right[2] - final_left[2]).abs() < 10.0);
916    }
917}