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        powder_temp_curve: None,
233        powder_curve_temp_c: None,
234        tipoff_decay_distance: 0.0,
235        ground_threshold: params.ground_threshold, // MBA-954: honor the configured ground plane
236        bc_segments: params.bc_segments.clone(),
237        caliber_inches: params.bullet_diameter / 0.0254, // MBA-717: from real diameter
238        weight_grains: params.mass_kg / 0.00006479891,
239        use_bc_segments: params.use_bc_segments,
240        bullet_id: None,
241        bc_segments_data: None,
242        use_enhanced_spin_drift: params.enable_spin_drift,
243        use_form_factor: false,
244        manufacturer: None,
245        bullet_model: None,
246        enable_wind_shear: false,
247        wind_shear_model: "none".to_string(),
248        use_cluster_bc: false,
249        bullet_cluster: None,
250        custom_drag_table: params.custom_drag_table.clone(),
251        bc_type_str: None,
252        enable_pitch_damping: false,
253        enable_precession_nutation: false,
254        // MBA-959: aerodynamic jump is intentionally OFF on this path. integrate_trajectory
255        // is a low-level state integrator: it advances a raw initial_state (no muzzle angle to
256        // perturb) and an unread muzzle_velocity, so a meaningful Litz Sg can't be formed here
257        // (Sg would be ~0 and the AJ guard would suppress it regardless). AJ belongs on the
258        // BallisticInputs + TrajectorySolver path, which bindings use and already honors the flag.
259        // (Bullet geometry IS now carried through TrajectoryParams — MBA-717 — so spin-drift /
260        // Magnus on this path use the real diameter/length/twist.)
261        enable_aerodynamic_jump: false,
262        use_rk4: true,
263        use_adaptive_rk45: false,
264        enable_trajectory_sampling: false,
265        sample_interval: 10.0,
266        sight_height: 0.0,
267        muzzle_height: 0.0,
268        target_height: 0.0,
269    };
270
271    // MBA-955: pre-populate velocity-BC segments ONCE here, instead of get_bc_for_velocity
272    // rebuilding them (a model String + a segment Vec) on every derivative evaluation (4-7x per
273    // step). Gated to EXACTLY the case where the per-step path would estimate: use_bc_segments on,
274    // no explicit velocity segments, and no Mach-based bc_segments (those take a different,
275    // unchanged path). bc_used there == params.bc == inputs.bc_value, so the estimated segments are
276    // identical and the per-step fast-path lookup returns the same BC -> byte-identical output.
277    if inputs.use_bc_segments && inputs.bc_segments_data.is_none() && inputs.bc_segments.is_none() {
278        inputs.bc_segments_data =
279            crate::derivatives::estimate_bc_segments_for(&inputs, inputs.bc_value);
280    }
281    inputs
282}
283
284/// Convert state to Vector6 and call compute_derivatives
285fn compute_derivatives_vec(
286    state: &Vector6<f64>,
287    t: f64,
288    params: &TrajectoryParams,
289    inputs: &BallisticInputs,
290) -> Vector6<f64> {
291    let pos = Vector3::new(state[0], state[1], state[2]);
292    let vel = Vector3::new(state[3], state[4], state[5]);
293
294    // Calculate wind at current position with shear support
295    let wind_vector = if !params.wind_segments.is_empty() {
296        if params.enable_wind_shear && params.wind_shear_model != "none" {
297            crate::wind_shear::get_wind_at_position(
298                &pos,
299                &params.wind_segments,
300                params.enable_wind_shear,
301                &params.wind_shear_model,
302                params.shooter_altitude_m,
303            )
304        } else {
305            wind_vector_for_range(pos.x, &params.wind_segments)
306        }
307    } else {
308        Vector3::zeros()
309    };
310
311    // Call compute_derivatives - returns [f64; 6] directly. `inputs` is built once per
312    // integration by build_inputs() and threaded in, instead of rebuilt every call.
313    let deriv_result = compute_derivatives(
314        pos,
315        vel,
316        inputs,
317        wind_vector,
318        params.atmos_params,
319        params.bc,
320        params.omega_vector,
321        t,
322    );
323
324    Vector6::new(
325        deriv_result[0],
326        deriv_result[1],
327        deriv_result[2],
328        deriv_result[3],
329        deriv_result[4],
330        deriv_result[5],
331    )
332}
333
334/// Main trajectory integration function
335pub fn integrate_trajectory(
336    initial_state: [f64; 6],
337    t_span: (f64, f64),
338    params: TrajectoryParams,
339    method: &str,
340    tolerance: f64,
341    max_step: f64,
342) -> Vec<(f64, Vector6<f64>)> {
343    let mut state = Vector6::new(
344        initial_state[0],
345        initial_state[1],
346        initial_state[2],
347        initial_state[3],
348        initial_state[4],
349        initial_state[5],
350    );
351
352    let mut t = t_span.0;
353    let t_end = t_span.1;
354    let mut dt = (t_end - t) / 1000.0; // Initial step size
355
356    let mut trajectory = Vec::with_capacity(10000);
357    trajectory.push((t, state));
358
359    // Build the (loop-invariant) derivative inputs once for the whole integration, instead of
360    // rebuilding the struct on every derivative evaluation.
361    let inputs = build_inputs(&params);
362
363    match method {
364        "RK4" => {
365            // Fixed step RK4 with target detection
366            dt = dt.min(max_step).min(0.001); // Use smaller steps for accuracy
367
368            while t < t_end {
369                if t + dt > t_end {
370                    dt = t_end - t;
371                }
372
373                let new_state = rk4_step(&state, t, dt, &params, &inputs);
374
375                // Check if we're about to pass the target (X is downrange, McCoy)
376                if state[0] < params.target_distance_m && new_state[0] >= params.target_distance_m {
377                    // Interpolate to find exact target crossing
378                    let alpha = (params.target_distance_m - state[0]) / (new_state[0] - state[0]);
379                    let dt_to_target = dt * alpha;
380
381                    // Take a smaller step to reach target exactly
382                    let final_state = rk4_step(&state, t, dt_to_target, &params, &inputs);
383
384                    // Ensure we don't overshoot
385                    let mut corrected_state = final_state;
386                    if corrected_state[0] > params.target_distance_m {
387                        corrected_state[0] = params.target_distance_m;
388                    }
389
390                    trajectory.push((t + dt_to_target, corrected_state));
391                    break; // Stop at target
392                }
393
394                state = new_state;
395                t += dt;
396                trajectory.push((t, state));
397
398                // Check if we've reached or passed the target
399                if state[0] >= params.target_distance_m {
400                    // X is downrange (McCoy)
401                    // Add final point exactly at target
402                    let mut final_state = state;
403                    final_state[0] = params.target_distance_m; // X is downrange
404                    trajectory.push((t, final_state));
405                    break;
406                }
407
408                // Check if bullet hit ground (MBA-954: honor the configured ground plane,
409                // not a hardcoded -1000.0)
410                if state[1] < params.ground_threshold {
411                    break;
412                }
413            }
414        }
415        "RK45" | _ => {
416            // Adaptive RK45 with better sampling
417            let mut last_save_x = 0.0; // X is downrange (McCoy)
418            let save_interval_m = params.target_distance_m / 50.0; // Save ~50 points minimum
419
420            // OPTIMIZATION: Adjust max step size when wind shear is enabled
421            // This improves numerical stability at long ranges
422            let effective_max_step =
423                if params.enable_wind_shear && params.wind_shear_model != "none" {
424                    // Use smaller steps for wind shear, but not TOO small
425                    if params.target_distance_m > 800.0 {
426                        0.01 // Smaller steps for long range with shear (10ms)
427                    } else {
428                        0.02 // Normal steps for medium range with shear (20ms)
429                    }
430                } else {
431                    max_step // Use provided max_step when no wind shear
432                };
433
434            // Set initial step size - ensure it's reasonable
435            dt = dt.min(effective_max_step).max(0.0001); // At least 0.1ms to avoid infinite loops
436
437            // Safety check: maximum iterations to prevent infinite loops
438            let max_iterations = 100000; // Should be more than enough for any realistic trajectory
439            let mut iteration_count = 0;
440
441            while t < t_end && iteration_count < max_iterations {
442                iteration_count += 1;
443
444                // Limit time step for better resolution
445                if t + dt > t_end {
446                    dt = t_end - t;
447                }
448
449                let (new_state, dt_new, _error) =
450                    rk45_step(&state, t, dt, &params, &inputs, tolerance);
451
452                // Check if we're about to pass the target (X is downrange, McCoy)
453                if state[0] < params.target_distance_m && new_state[0] >= params.target_distance_m {
454                    // Interpolate to find exact target crossing
455                    let alpha = (params.target_distance_m - state[0]) / (new_state[0] - state[0]);
456                    let dt_to_target = dt * alpha;
457
458                    // Take a smaller step to reach target exactly
459                    let (final_state, _, _) =
460                        rk45_step(&state, t, dt_to_target, &params, &inputs, tolerance);
461
462                    // Make sure we don't overshoot
463                    let mut corrected_state = final_state;
464                    if corrected_state[0] > params.target_distance_m {
465                        corrected_state[0] = params.target_distance_m;
466                    }
467
468                    trajectory.push((t + dt_to_target, corrected_state));
469                    break; // Stop at target - no more points after this
470                }
471
472                // Update state
473                state = new_state;
474                t += dt;
475
476                // Save trajectory point if we've moved enough distance
477                if state[0] - last_save_x >= save_interval_m || state[0] >= params.target_distance_m
478                {
479                    // X is downrange
480                    trajectory.push((t, state));
481                    last_save_x = state[0];
482                }
483
484                // Limit dt for next step - ensure we get enough resolution
485                dt = dt_new.min(effective_max_step).max(0.0001); // Use effective max step, min 0.1ms
486
487                // Stop if we've reached the target
488                if state[0] >= params.target_distance_m {
489                    // X is downrange (McCoy)
490                    // Add final point at target distance
491                    let mut final_state = state;
492                    final_state[0] = params.target_distance_m; // X is downrange
493                    trajectory.push((t, final_state));
494                    break;
495                }
496
497                // Check if bullet hit ground (MBA-954: honor the configured ground plane,
498                // not a hardcoded -1000.0)
499                if state[1] < params.ground_threshold {
500                    break;
501                }
502            }
503
504            // Warn if we hit the iteration limit
505            if iteration_count >= max_iterations {
506                eprintln!(
507                    "WARNING: Trajectory integration hit maximum iteration limit ({} iterations)",
508                    max_iterations
509                );
510                eprintln!("  Final time: {}, Target time: {}", t, t_end);
511                eprintln!(
512                    "  Final position: downrange(x)={}, Target: {}m",
513                    state[0], params.target_distance_m
514                );
515            }
516        }
517    }
518
519    trajectory
520}
521
522/// Python-exposed function for complete trajectory integration
523pub fn solve_trajectory_rust(
524    initial_state: [f64; 6],
525    t_span: (f64, f64),
526    mass_kg: f64,
527    bc: f64,
528    drag_model: DragModel,
529    wind_segments: Vec<WindSegment>,
530    atmos_params: (f64, f64, f64, f64),
531    omega_vector: Option<Vec<f64>>,
532    enable_spin_drift: bool,
533    enable_magnus: bool,
534    enable_coriolis: bool,
535    method: String,
536    tolerance: f64,
537    max_step: f64,
538    target_distance_m: f64,
539) -> Vec<HashMap<String, f64>> {
540    let omega_vec = omega_vector.map(|v| Vector3::new(v[0], v[1], v[2]));
541
542    let params = TrajectoryParams {
543        mass_kg,
544        bc,
545        drag_model,
546        wind_segments,
547        atmos_params,
548        omega_vector: omega_vec,
549        enable_spin_drift,
550        enable_magnus,
551        enable_coriolis,
552        target_distance_m,
553        enable_wind_shear: false, // Default for test function
554        wind_shear_model: "none".to_string(),
555        shooter_altitude_m: 0.0,
556        is_twist_right: true, // Default for test function
557        shooting_angle: 0.0,  // This legacy entry takes no inclined-fire arg; flat fire only
558        // This legacy entry takes no geometry args; keep the historical placeholders so its
559        // behavior is unchanged (callers needing real geometry use fast_integrate_with_segments).
560        bullet_diameter: 0.0078232,
561        bullet_length: 0.031496,
562        twist_rate: 10.0,
563        custom_drag_table: None, // No CDM for test function
564        bc_segments: None,       // No BC segments for legacy function
565        use_bc_segments: false,
566        ground_threshold: -1000.0, // MBA-954: preserve the historical default
567    };
568
569    let trajectory =
570        integrate_trajectory(initial_state, t_span, params, &method, tolerance, max_step);
571
572    // Convert to Python-friendly format
573    trajectory
574        .into_iter()
575        .map(|(t, state)| {
576            let mut point = HashMap::new();
577            point.insert("t".to_string(), t);
578            point.insert("x".to_string(), state[0]);
579            point.insert("y".to_string(), state[1]);
580            point.insert("z".to_string(), state[2]);
581            point.insert("vx".to_string(), state[3]);
582            point.insert("vy".to_string(), state[4]);
583            point.insert("vz".to_string(), state[5]);
584            point
585        })
586        .collect()
587}
588
589#[cfg(test)]
590mod tests {
591    use super::*;
592
593    fn create_test_params(target_distance_m: f64) -> TrajectoryParams {
594        TrajectoryParams {
595            mass_kg: 0.01134, // 175 grains in kg
596            bc: 0.442,
597            bullet_diameter: 0.0078232, // .308 in
598            bullet_length: 0.031496,    // 1.24 in
599            twist_rate: 10.0,
600            drag_model: DragModel::G7,
601            wind_segments: vec![],
602            atmos_params: (0.0, 59.0, 29.92, 0.0),
603            omega_vector: None,
604            enable_spin_drift: false,
605            enable_magnus: false,
606            enable_coriolis: false,
607            target_distance_m,
608            enable_wind_shear: false,
609            wind_shear_model: "none".to_string(),
610            shooter_altitude_m: 0.0,
611            is_twist_right: true,
612            shooting_angle: 0.0,
613            custom_drag_table: None,
614            bc_segments: None,
615            use_bc_segments: false,
616            ground_threshold: -1000.0,
617        }
618    }
619
620    #[test]
621    fn test_mba954_ground_threshold_honored() {
622        // MBA-954: integrate_trajectory must honor the configured ground plane, not a hardcoded
623        // -1000.0. A descending bullet with a shallow ground_threshold must terminate earlier
624        // (fewer points) than one with the historical deep default.
625        let initial_state = [0.0, 0.0, 0.0, 300.0, -30.0, 0.0]; // descending (vy = -30 m/s)
626
627        let mut shallow = create_test_params(1_000_000.0); // huge target so range never terminates
628        shallow.ground_threshold = -20.0; // stop ~20 m below launch
629        let mut deep = create_test_params(1_000_000.0);
630        deep.ground_threshold = -1000.0; // historical default
631
632        let t_shallow =
633            integrate_trajectory(initial_state, (0.0, 60.0), shallow, "RK4", 1e-6, 0.001);
634        let t_deep = integrate_trajectory(initial_state, (0.0, 60.0), deep, "RK4", 1e-6, 0.001);
635
636        assert!(
637            t_shallow.len() < t_deep.len(),
638            "shallow ground_threshold (-20) should terminate earlier than deep (-1000): \
639             shallow={}, deep={}",
640            t_shallow.len(),
641            t_deep.len()
642        );
643    }
644
645    #[test]
646    fn test_integrate_trajectory_basic() {
647        // Initial state [x,y,z,vx,vy,vz] (McCoy: X=downrange, Z=lateral)
648        // x=0 (downrange start), vx=821.52 (downrange velocity)
649        let initial_state = [0.0, -0.038, 0.0, 821.52, 48.61, 0.0];
650
651        let params = TrajectoryParams {
652            mass_kg: 0.01134, // 175 grains in kg
653            bc: 0.442,
654            bullet_diameter: 0.0078232, // .308 in
655            bullet_length: 0.031496,    // 1.24 in
656            twist_rate: 10.0,
657            drag_model: DragModel::G7,
658            wind_segments: vec![(0.0, 90.0, 914.4)],
659            atmos_params: (0.0, 59.0, 29.92, 0.0),
660            omega_vector: None,
661            enable_spin_drift: false,
662            enable_magnus: false,
663            enable_coriolis: false,
664            target_distance_m: 914.4, // 1000 yards in meters
665            enable_wind_shear: false,
666            wind_shear_model: "none".to_string(),
667            shooter_altitude_m: 0.0,
668            is_twist_right: true,
669            shooting_angle: 0.0,
670            custom_drag_table: None,
671            bc_segments: None,
672            use_bc_segments: false,
673            ground_threshold: -1000.0,
674        };
675
676        println!("Running integrate_trajectory test...");
677        println!("Initial state: {:?}", initial_state);
678        println!("Target distance: {} m", params.target_distance_m);
679
680        let trajectory =
681            integrate_trajectory(initial_state, (0.0, 10.0), params, "RK45", 1e-6, 0.01);
682
683        println!("Trajectory has {} points", trajectory.len());
684
685        // Should have more than just initial point
686        assert!(
687            trajectory.len() > 1,
688            "Trajectory should have more than 1 point, but has {}",
689            trajectory.len()
690        );
691
692        // Check that we actually moved downrange
693        if let Some((_, final_state)) = trajectory.last() {
694            println!("Final state: downrange(x)={}", final_state[0]);
695            assert!(
696                final_state[0] > 0.0,
697                "Final x should be positive (bullet moved downrange)"
698            );
699            assert!(
700                final_state[0] >= 900.0,
701                "Final x should be near target distance"
702            );
703        }
704    }
705
706    #[test]
707    fn test_rk4_vs_rk45_consistency() {
708        // Both methods should give similar results for the same trajectory
709        let initial_state = [0.0, 0.0, 0.0, 800.0, 30.0, 0.0]; // McCoy: vx=downrange
710        let target_distance = 500.0;
711
712        let params_rk4 = create_test_params(target_distance);
713        let params_rk45 = create_test_params(target_distance);
714
715        let trajectory_rk4 =
716            integrate_trajectory(initial_state, (0.0, 5.0), params_rk4, "RK4", 1e-6, 0.001);
717        let trajectory_rk45 =
718            integrate_trajectory(initial_state, (0.0, 5.0), params_rk45, "RK45", 1e-6, 0.01);
719
720        // Both should reach target
721        assert!(!trajectory_rk4.is_empty());
722        assert!(!trajectory_rk45.is_empty());
723
724        let (_, final_rk4) = trajectory_rk4.last().unwrap();
725        let (_, final_rk45) = trajectory_rk45.last().unwrap();
726
727        // Final downrange positions should be within 1% of each other
728        let rk4_z = final_rk4[0];
729        let rk45_z = final_rk45[0];
730        let diff_percent = ((rk4_z - rk45_z) / rk45_z).abs() * 100.0;
731
732        assert!(
733            diff_percent < 1.0,
734            "RK4 and RK45 final positions differ by {}%: RK4={}, RK45={}",
735            diff_percent,
736            rk4_z,
737            rk45_z
738        );
739    }
740
741    #[test]
742    fn test_ground_impact_detection() {
743        // Trajectory with steep downward angle should hit ground
744        let initial_state = [0.0, 100.0, 0.0, 300.0, -50.0, 0.0]; // McCoy: vx=downrange // Steep descent
745
746        let mut params = create_test_params(10000.0); // Far target
747        params.target_distance_m = 10000.0;
748
749        let trajectory =
750            integrate_trajectory(initial_state, (0.0, 20.0), params, "RK45", 1e-6, 0.01);
751
752        // Should stop before reaching target due to ground impact
753        let (_, final_state) = trajectory.last().unwrap();
754
755        // y should be near ground threshold (-1000m)
756        assert!(
757            final_state[1] <= -900.0,
758            "Should hit ground, but y={}",
759            final_state[1]
760        );
761        assert!(
762            final_state[0] < 10000.0,
763            "Should not reach target, but z={}",
764            final_state[0]
765        );
766    }
767
768    #[test]
769    fn test_target_distance_reached() {
770        let initial_state = [0.0, 0.0, 0.0, 800.0, 20.0, 0.0]; // McCoy: vx=downrange
771        let target_distance = 300.0;
772
773        let params = create_test_params(target_distance);
774
775        let trajectory =
776            integrate_trajectory(initial_state, (0.0, 5.0), params, "RK45", 1e-6, 0.01);
777
778        let (_, final_state) = trajectory.last().unwrap();
779
780        // Should stop at or very near target distance
781        assert!(
782            (final_state[0] - target_distance).abs() < 1.0,
783            "Should reach target at {}m, but stopped at {}m",
784            target_distance,
785            final_state[0]
786        );
787    }
788
789    #[test]
790    fn test_wind_affects_trajectory() {
791        // Test that wind segments are properly stored and passed through
792        // The actual wind effect depends on the derivatives computation which
793        // uses the wind vector in the drag calculation
794        let initial_state = [0.0, 0.0, 0.0, 800.0, 30.0, 0.0]; // McCoy: vx=downrange
795        let target_distance = 500.0;
796
797        // No wind
798        let params_no_wind = create_test_params(target_distance);
799
800        // Strong headwind (0 degrees = headwind)
801        let mut params_headwind = create_test_params(target_distance);
802        params_headwind.wind_segments = vec![(72.0, 0.0, 500.0)]; // 72 km/h = 20 m/s headwind
803
804        let trajectory_no_wind = integrate_trajectory(
805            initial_state,
806            (0.0, 5.0),
807            params_no_wind,
808            "RK45",
809            1e-6,
810            0.01,
811        );
812        let trajectory_headwind = integrate_trajectory(
813            initial_state,
814            (0.0, 5.0),
815            params_headwind,
816            "RK45",
817            1e-6,
818            0.01,
819        );
820
821        // Both trajectories should complete
822        assert!(
823            !trajectory_no_wind.is_empty(),
824            "No-wind trajectory should complete"
825        );
826        assert!(
827            !trajectory_headwind.is_empty(),
828            "Headwind trajectory should complete"
829        );
830
831        let (time_no_wind, final_no_wind) = trajectory_no_wind.last().unwrap();
832        let (time_headwind, final_headwind) = trajectory_headwind.last().unwrap();
833
834        // Headwind should slow the bullet, resulting in longer flight time
835        // or different drop at same distance
836        let drop_no_wind = final_no_wind[1];
837        let drop_headwind = final_headwind[1];
838
839        // With headwind, bullet should drop more (more negative y) due to slower velocity
840        // The effect might be small, so we check that both trajectories are valid
841        println!("No wind: time={}, drop={}", time_no_wind, drop_no_wind);
842        println!("Headwind: time={}, drop={}", time_headwind, drop_headwind);
843
844        // Both should reach approximately the target distance
845        assert!(
846            (final_no_wind[0] - target_distance).abs() < 10.0,
847            "No-wind should reach target"
848        );
849        assert!(
850            (final_headwind[0] - target_distance).abs() < 10.0,
851            "Headwind should reach target"
852        );
853    }
854
855    #[test]
856    fn test_solve_trajectory_rust_output_format() {
857        let initial_state = [0.0, 0.0, 0.0, 800.0, 30.0, 0.0]; // McCoy: vx=downrange
858
859        let result = solve_trajectory_rust(
860            initial_state,
861            (0.0, 2.0),
862            0.01134,                 // mass_kg
863            0.442,                   // bc
864            DragModel::G7,           // drag_model
865            vec![],                  // wind_segments
866            (0.0, 59.0, 29.92, 0.0), // atmos_params
867            None,                    // omega_vector
868            false,                   // enable_spin_drift
869            false,                   // enable_magnus
870            false,                   // enable_coriolis
871            "RK45".to_string(),      // method
872            1e-6,                    // tolerance
873            0.01,                    // max_step
874            500.0,                   // target_distance_m
875        );
876
877        // Should return Vec of HashMaps with expected keys
878        assert!(!result.is_empty());
879
880        let first_point = &result[0];
881        assert!(first_point.contains_key("t"));
882        assert!(first_point.contains_key("x"));
883        assert!(first_point.contains_key("y"));
884        assert!(first_point.contains_key("z"));
885        assert!(first_point.contains_key("vx"));
886        assert!(first_point.contains_key("vy"));
887        assert!(first_point.contains_key("vz"));
888    }
889
890    #[test]
891    fn test_left_vs_right_twist() {
892        let initial_state = [0.0, 0.0, 0.0, 800.0, 30.0, 0.0]; // McCoy: vx=downrange
893        let target_distance = 500.0;
894
895        let mut params_right = create_test_params(target_distance);
896        params_right.is_twist_right = true;
897        params_right.enable_spin_drift = true;
898
899        let mut params_left = create_test_params(target_distance);
900        params_left.is_twist_right = false;
901        params_left.enable_spin_drift = true;
902
903        let trajectory_right =
904            integrate_trajectory(initial_state, (0.0, 5.0), params_right, "RK45", 1e-6, 0.01);
905        let trajectory_left =
906            integrate_trajectory(initial_state, (0.0, 5.0), params_left, "RK45", 1e-6, 0.01);
907
908        // Both should complete
909        assert!(!trajectory_right.is_empty());
910        assert!(!trajectory_left.is_empty());
911
912        // Right and left twist should produce valid trajectories
913        let (_, final_right) = trajectory_right.last().unwrap();
914        let (_, final_left) = trajectory_left.last().unwrap();
915
916        // Both should reach approximately the same downrange distance
917        assert!((final_right[2] - final_left[2]).abs() < 10.0);
918    }
919}