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