1use crate::{
7 atmosphere::{calculate_air_density_cimp, get_local_atmosphere_humid, AtmoSock},
8 bc_estimation::velocity_segment_bc,
9 constants::{G_ACCEL_MPS2, MPS_TO_FPS, STANDARD_AIR_DENSITY},
10 drag::get_drag_coefficient,
11 wind::WindSock,
12 DragModel, InternalBallisticInputs as BallisticInputs,
13};
14use nalgebra::Vector3;
15
16#[derive(Debug, Clone)]
18pub struct FastSolution {
19 pub t: Vec<f64>,
21 pub y: Vec<Vec<f64>>,
23 pub t_events: [Vec<f64>; 3],
25 pub success: bool,
27}
28
29impl FastSolution {
30 pub fn sol(&self, t_query: &[f64]) -> Vec<Vec<f64>> {
32 let mut result = vec![vec![0.0; t_query.len()]; 6];
33
34 for (i, &tq) in t_query.iter().enumerate() {
35 let idx = match self
38 .t
39 .binary_search_by(|&t| t.partial_cmp(&tq).unwrap_or(std::cmp::Ordering::Greater))
40 {
41 Ok(idx) => idx,
42 Err(idx) => idx,
43 };
44
45 if idx == 0 {
46 for (result_component, source_component) in result.iter_mut().zip(&self.y) {
48 result_component[i] = source_component[0];
49 }
50 } else if idx >= self.t.len() {
51 for (result_component, source_component) in result.iter_mut().zip(&self.y) {
53 result_component[i] = source_component[self.t.len() - 1];
54 }
55 } else {
56 let t0 = self.t[idx - 1];
58 let t1 = self.t[idx];
59 let span = t1 - t0;
60
61 for (result_component, source_component) in result.iter_mut().zip(&self.y) {
62 let y0 = source_component[idx - 1];
63 let y1 = source_component[idx];
64 result_component[i] = if span.abs() < f64::EPSILON {
65 y1
66 } else {
67 let frac = (tq - t0) / span;
68 y0 + frac * (y1 - y0)
69 };
70 }
71 }
72 }
73
74 result
75 }
76
77 pub fn from_trajectory_data(
79 times: Vec<f64>,
80 states: Vec<[f64; 6]>,
81 t_events: [Vec<f64>; 3],
82 ) -> Self {
83 let n_points = times.len();
84 let mut y = vec![vec![0.0; n_points]; 6];
85
86 for (i, state) in states.iter().enumerate() {
87 for j in 0..6 {
88 y[j][i] = state[j];
89 }
90 }
91
92 FastSolution {
93 t: times,
94 y,
95 t_events,
96 success: true,
97 }
98 }
99
100 fn degenerate(initial_state: &[f64; 6]) -> Self {
104 let mut y = vec![Vec::new(); 6];
105 for (j, slot) in y.iter_mut().enumerate() {
106 slot.push(initial_state[j]);
107 }
108 FastSolution {
109 t: vec![0.0],
110 y,
111 t_events: [Vec::new(), Vec::new(), Vec::new()],
112 success: false,
113 }
114 }
115}
116
117fn direct_atmosphere_values(atmo_params: (f64, f64, f64, f64)) -> Option<(f64, f64)> {
118 let (a, b, c, d) = atmo_params;
119 (a.is_finite() && b.is_finite() && c == 0.0 && d == 0.0 && a > 0.0 && a < 2.0 && b > 200.0)
120 .then_some((a, b))
121}
122
123fn stability_atmosphere_params(atmo_params: (f64, f64, f64, f64)) -> (f64, f64, f64, f64) {
124 if let Some((air_density, _)) = direct_atmosphere_values(atmo_params) {
125 (0.0, 15.0, 1013.25 * air_density / STANDARD_AIR_DENSITY, 1.0)
129 } else {
130 atmo_params
131 }
132}
133
134const MAX_STANDARD_DENSITY_RATIO: f64 = 2.0;
135
136fn atmo_is_physical(atmo_params: (f64, f64, f64, f64)) -> bool {
149 let (a, b, c, d) = atmo_params;
150 if !(a.is_finite() && b.is_finite() && c.is_finite() && d.is_finite()) {
151 return false;
152 }
153 direct_atmosphere_values(atmo_params).is_some() || (c > 0.0 && d < MAX_STANDARD_DENSITY_RATIO)
158}
159
160#[derive(Debug, Clone, Copy)]
161enum FastAtmosphere {
162 Direct {
163 air_density: f64,
164 speed_of_sound: f64,
165 },
166 Standard {
167 base_density: f64,
168 },
169}
170
171pub struct FastIntegrationParams {
173 pub horiz: f64,
174 pub vert: f64,
175 pub initial_state: [f64; 6],
176 pub t_span: (f64, f64),
177 pub atmo_params: (f64, f64, f64, f64),
183 pub atmo_sock: Option<AtmoSock>,
188}
189
190pub fn aerodynamic_jump_launch_offset_rad(
198 inputs: &BallisticInputs,
199 atmo_params: (f64, f64, f64, f64),
200) -> f64 {
201 let crosswind_from_right_mps = inputs.wind_speed * inputs.wind_angle.sin();
202 aerodynamic_jump_launch_offset_for_crosswind_rad(inputs, atmo_params, crosswind_from_right_mps)
203}
204
205fn aerodynamic_jump_launch_offset_for_crosswind_rad(
206 inputs: &BallisticInputs,
207 atmo_params: (f64, f64, f64, f64),
208 crosswind_from_right_mps: f64,
209) -> f64 {
210 if !inputs.enable_aerodynamic_jump {
211 return 0.0;
212 }
213 let diameter = inputs.bullet_diameter;
214 if !(inputs.twist_rate.is_finite()
215 && inputs.twist_rate != 0.0
216 && diameter.is_finite()
217 && diameter > 0.0
218 && inputs.bullet_length.is_finite()
219 && inputs.bullet_length > 0.0
220 && inputs.muzzle_velocity.is_finite())
221 {
222 return 0.0;
223 }
224 let stability_atmo = stability_atmosphere_params(atmo_params);
225 let sg = crate::stability::compute_stability_coefficient(inputs, stability_atmo);
226 if !(sg.is_finite() && sg > 0.0) {
227 return 0.0;
228 }
229 let length_cal = inputs.bullet_length / diameter;
230 const MS_TO_MPH: f64 = 2.236_936_292_054_4;
231 let crosswind_from_right_mph = crosswind_from_right_mps * MS_TO_MPH;
232 let vertical_moa = crate::aerodynamic_jump::litz_crosswind_jump_moa(
233 sg,
234 length_cal,
235 crosswind_from_right_mph,
236 inputs.is_twist_right,
237 );
238 if !vertical_moa.is_finite() {
239 return 0.0;
240 }
241 const MOA_PER_RAD: f64 = 3437.7467707849;
242 vertical_moa / MOA_PER_RAD
243}
244
245fn rotate_launch_velocity(state: &mut [f64; 6], theta_rad: f64) {
248 let (vx, vy, vz) = (state[3], state[4], state[5]);
249 let speed = (vx * vx + vy * vy + vz * vz).sqrt();
250 if speed <= 0.0 {
251 return;
252 }
253 let h = (vx * vx + vz * vz).sqrt(); let new_elev = vy.atan2(h) + theta_rad;
255 state[4] = speed * new_elev.sin();
256 let new_h = speed * new_elev.cos();
257 let scale = if h > 1e-12 { new_h / h } else { 0.0 };
258 state[3] = vx * scale;
259 state[5] = vz * scale;
260}
261
262fn launch_state_with_aerodynamic_jump(
263 inputs: &BallisticInputs,
264 atmo_params: (f64, f64, f64, f64),
265 segmented_crosswind_from_right_mps: Option<f64>,
266 mut initial_state: [f64; 6],
267) -> [f64; 6] {
268 let offset = match segmented_crosswind_from_right_mps {
269 Some(crosswind) => {
270 aerodynamic_jump_launch_offset_for_crosswind_rad(inputs, atmo_params, crosswind)
271 }
272 None => aerodynamic_jump_launch_offset_rad(inputs, atmo_params),
273 };
274 if offset != 0.0 {
275 rotate_launch_velocity(&mut initial_state, offset);
276 }
277 initial_state
278}
279
280pub fn fast_integrate(
282 inputs: &BallisticInputs,
283 wind_sock: &WindSock,
284 params: FastIntegrationParams,
285) -> FastSolution {
286 if wind_sock.validate_segments().is_err() || !atmo_is_physical(params.atmo_params) {
288 return FastSolution::degenerate(¶ms.initial_state);
289 }
290 let mut effective_inputs = inputs.clone();
291 effective_inputs.normalize_for_solve();
296 if params.atmo_params.2 > 0.0 {
297 effective_inputs.altitude = params.atmo_params.0;
298 effective_inputs.temperature = params.atmo_params.1;
299 effective_inputs.pressure = params.atmo_params.2;
300 effective_inputs.humidity = params.atmo_params.3;
301 }
302 let inputs = &effective_inputs;
303 let _mass_kg = inputs.bullet_mass; let bc = inputs.bc_value;
306 let drag_model = &inputs.bc_type;
307
308 let has_bc_segments =
310 inputs.bc_segments.is_some() && !inputs.bc_segments.as_ref().unwrap().is_empty();
311 let has_bc_segments_data =
312 inputs.bc_segments_data.is_some() && !inputs.bc_segments_data.as_ref().unwrap().is_empty();
313
314 let dt = if params.horiz > 200.0 {
316 0.001
317 } else if params.horiz > 100.0 {
318 0.0005
319 } else {
320 0.0001
321 };
322
323 let segmented_crosswind_from_right_mps = if inputs.enable_aerodynamic_jump {
326 wind_sock.muzzle_crosswind_from_right_mps()
327 } else {
328 None
329 };
330 let initial_state = launch_state_with_aerodynamic_jump(
331 inputs,
332 params.atmo_params,
333 segmented_crosswind_from_right_mps,
334 params.initial_state,
335 );
336 let vx = initial_state[3]; let n_steps = ((params.t_span.1 / dt) as usize) + 1;
350 let est_steps = if vx > 1e-6 && params.horiz > 0.0 {
351 (((4.0 * params.horiz / vx) / dt) as usize) + 1
352 } else {
353 n_steps
354 };
355 let cap = est_steps.min(n_steps);
356 let mut times = Vec::with_capacity(cap);
357 let mut states = Vec::with_capacity(cap);
358
359 times.push(0.0);
361 states.push(initial_state);
362
363 let atmosphere =
368 if let Some((air_density, speed_of_sound)) = direct_atmosphere_values(params.atmo_params) {
369 FastAtmosphere::Direct {
370 air_density,
371 speed_of_sound,
372 }
373 } else {
374 let base_density = if params.atmo_params.3 > 0.0 {
375 params.atmo_params.3 * 1.225
376 } else {
377 1.225
378 };
379 FastAtmosphere::Standard { base_density }
380 };
381
382 let atmo_sock = params.atmo_sock.as_ref();
384
385 let drag_model_str: &str = match drag_model {
393 DragModel::G1 => "G1",
394 DragModel::G2 => "G2",
395 DragModel::G5 => "G5",
396 DragModel::G6 => "G6",
397 DragModel::G7 => "G7",
398 DragModel::G8 => "G8",
399 DragModel::GI => "GI",
400 DragModel::GS => "GS",
401 DragModel::RA4 => "RA4",
402 };
403
404 let caliber_in = if inputs.caliber_inches > 0.0 {
406 inputs.caliber_inches
407 } else {
408 inputs.bullet_diameter / 0.0254
409 };
410 let weight_gr = if inputs.weight_grains > 0.0 {
411 inputs.weight_grains
412 } else {
413 inputs.bullet_mass / crate::constants::GRAINS_TO_KG
414 };
415
416 let projectile_shape = crate::transonic_drag::resolve_projectile_shape(
419 inputs.bullet_model.as_deref(),
420 caliber_in,
421 weight_gr,
422 drag_model_str,
423 );
424
425 let omega_vector = match inputs.latitude {
431 Some(latitude) if inputs.enable_coriolis => {
432 let omega_earth = 7.2921159e-5_f64; let lat = latitude.to_radians();
434 let az = inputs.shot_azimuth; Some(Vector3::new(
436 omega_earth * lat.cos() * az.cos(), omega_earth * lat.sin(), -omega_earth * lat.cos() * az.sin(), ))
440 }
441 _ => None,
442 };
443 let wind_shear_model = if inputs.enable_wind_shear {
445 let model = crate::wind_shear::boundary_layer_model_from_name(&inputs.wind_shear_model);
446 (model != crate::wind_shear::WindShearModel::None).then_some(model)
447 } else {
448 None
449 };
450
451 let mut hit_target = false;
453 let mut hit_ground = false;
454 let mut max_ord_time = None;
455 let mut max_ord_y = 0.0;
456 let ground_threshold = inputs.ground_threshold;
457
458 for i in 0..n_steps - 1 {
460 let t = i as f64 * dt;
461 let state = states[i];
462
463 let pos = Vector3::new(state[0], state[1], state[2]);
464 let _vel = Vector3::new(state[3], state[4], state[5]);
465
466 if pos.x >= params.horiz {
468 hit_target = true;
469 break;
470 }
471
472 if pos.y <= ground_threshold {
473 hit_ground = true;
474 break;
475 }
476
477 if pos.y > max_ord_y {
479 max_ord_y = pos.y;
480 max_ord_time = Some(t);
481 }
482
483 let k1 = compute_derivatives(
485 &state,
486 inputs,
487 wind_sock,
488 atmosphere,
489 drag_model,
490 projectile_shape,
491 bc,
492 has_bc_segments,
493 has_bc_segments_data,
494 omega_vector,
495 wind_shear_model,
496 atmo_sock,
497 );
498
499 let mut state2 = state;
500 for j in 0..6 {
501 state2[j] = state[j] + 0.5 * dt * k1[j];
502 }
503 let k2 = compute_derivatives(
504 &state2,
505 inputs,
506 wind_sock,
507 atmosphere,
508 drag_model,
509 projectile_shape,
510 bc,
511 has_bc_segments,
512 has_bc_segments_data,
513 omega_vector,
514 wind_shear_model,
515 atmo_sock,
516 );
517
518 let mut state3 = state;
519 for j in 0..6 {
520 state3[j] = state[j] + 0.5 * dt * k2[j];
521 }
522 let k3 = compute_derivatives(
523 &state3,
524 inputs,
525 wind_sock,
526 atmosphere,
527 drag_model,
528 projectile_shape,
529 bc,
530 has_bc_segments,
531 has_bc_segments_data,
532 omega_vector,
533 wind_shear_model,
534 atmo_sock,
535 );
536
537 let mut state4 = state;
538 for j in 0..6 {
539 state4[j] = state[j] + dt * k3[j];
540 }
541 let k4 = compute_derivatives(
542 &state4,
543 inputs,
544 wind_sock,
545 atmosphere,
546 drag_model,
547 projectile_shape,
548 bc,
549 has_bc_segments,
550 has_bc_segments_data,
551 omega_vector,
552 wind_shear_model,
553 atmo_sock,
554 );
555
556 let mut new_state = state;
558 for j in 0..6 {
559 new_state[j] = state[j] + dt * (k1[j] + 2.0 * k2[j] + 2.0 * k3[j] + k4[j]) / 6.0;
560 }
561
562 if state[0] < params.horiz && new_state[0] >= params.horiz {
563 let alpha = (params.horiz - state[0]) / (new_state[0] - state[0]);
566 let mut target_state = state;
567 for j in 0..6 {
568 target_state[j] = state[j] + alpha * (new_state[j] - state[j]);
569 }
570 target_state[0] = params.horiz;
571 times.push(t + alpha * dt);
572 states.push(target_state);
573 hit_target = true;
574 break;
575 }
576
577 times.push(t + dt);
578 states.push(new_state);
579 }
580
581 let t_events = [
583 if hit_target {
584 vec![*times.last().unwrap()]
585 } else {
586 vec![]
587 },
588 if let Some(t) = max_ord_time {
589 vec![t]
590 } else {
591 vec![]
592 },
593 if hit_ground {
594 vec![*times.last().unwrap()]
595 } else {
596 vec![]
597 },
598 ];
599
600 if inputs.use_enhanced_spin_drift {
609 let (sd_temp_c, sd_press_hpa) = if params.atmo_params.2 > 0.0 {
613 (params.atmo_params.1, params.atmo_params.2)
614 } else {
615 (15.0, 1013.25)
616 };
617 let sg = crate::spin_drift::effective_sg_from_inputs(inputs, sd_temp_c, sd_press_hpa);
618 for (t, state) in times.iter().zip(states.iter_mut()) {
619 if *t > 0.0 {
620 state[2] += crate::spin_drift::litz_drift_meters(sg, *t, inputs.is_twist_right);
621 }
622 }
623 }
624
625 FastSolution::from_trajectory_data(times, states, t_events)
626}
627
628fn fast_magnus_acceleration(
629 inputs: &BallisticInputs,
630 air_velocity: Vector3<f64>,
631 air_density: f64,
632 mach: f64,
633 gravity_acceleration: Vector3<f64>,
634) -> Vector3<f64> {
635 if !inputs.enable_magnus
636 || inputs.use_enhanced_spin_drift
637 || inputs.bullet_diameter <= 0.0
638 || inputs.twist_rate <= 0.0
639 || inputs.bullet_mass <= 0.0
640 {
641 return Vector3::zeros();
642 }
643
644 let speed_air = air_velocity.norm();
645 let diameter_m = inputs.bullet_diameter;
646 let (spin_rate_rad_s, spin_param) = crate::spin_drift::calculate_magnus_spin_state(
647 inputs.muzzle_velocity,
648 speed_air,
649 inputs.twist_rate,
650 diameter_m,
651 );
652 let d_in = if inputs.caliber_inches > 0.0 {
653 inputs.caliber_inches
654 } else {
655 diameter_m / 0.0254
656 };
657 let m_gr = if inputs.weight_grains > 0.0 {
658 inputs.weight_grains
659 } else {
660 inputs.bullet_mass / crate::constants::GRAINS_TO_KG
661 };
662 let l_in = if inputs.bullet_length > 0.0 {
663 inputs.bullet_length / 0.0254
664 } else {
665 let estimated = crate::stability::estimate_bullet_length_m(diameter_m, inputs.bullet_mass);
666 if estimated > 0.0 {
667 estimated / 0.0254
668 } else {
669 4.5 * d_in.max(1e-9)
670 }
671 };
672 let sg = crate::spin_drift::calculate_dynamic_stability(
673 m_gr,
674 speed_air,
675 spin_rate_rad_s,
676 d_in,
677 l_in,
678 air_density,
679 );
680 let (yaw_rad, _) = crate::spin_drift::calculate_yaw_of_repose(
681 sg,
682 speed_air,
683 spin_rate_rad_s,
684 0.0,
685 0.0,
686 air_density,
687 d_in,
688 l_in,
689 m_gr,
690 mach,
691 "match",
692 false,
693 );
694 let area = std::f64::consts::PI * (diameter_m / 2.0).powi(2);
695 let c_np = crate::derivatives::calculate_magnus_moment_coefficient(mach);
696 let force = 0.5 * air_density * speed_air.powi(2) * area * c_np * spin_param * yaw_rad.sin();
697 if force <= 1e-12 {
698 return Vector3::zeros();
699 }
700
701 crate::derivatives::yaw_of_repose_magnus_direction(
702 air_velocity,
703 gravity_acceleration,
704 inputs.is_twist_right,
705 )
706 .map_or_else(Vector3::zeros, |direction| {
707 (force / inputs.bullet_mass) * direction
708 })
709}
710
711fn interpolated_vertical_apex(
712 previous_time: f64,
713 previous: &[f64; 6],
714 current_time: f64,
715 current: &[f64; 6],
716) -> Option<(f64, [f64; 6])> {
717 let dt = current_time - previous_time;
718 let previous_vy = previous[4];
719 let current_vy = current[4];
720 if !dt.is_finite()
721 || dt <= 0.0
722 || !previous_vy.is_finite()
723 || !current_vy.is_finite()
724 || previous_vy <= 0.0
725 || current_vy > 0.0
726 {
727 return None;
728 }
729
730 let denominator = previous_vy - current_vy;
731 if !denominator.is_finite() || denominator <= 0.0 {
732 return None;
733 }
734 let alpha = previous_vy / denominator;
735 if !alpha.is_finite() || !(0.0..1.0).contains(&alpha) {
738 return None;
739 }
740
741 let mut apex = [0.0; 6];
742 for component in 0..6 {
743 apex[component] = previous[component] + alpha * (current[component] - previous[component]);
744 }
745
746 let alpha2 = alpha * alpha;
749 let alpha3 = alpha2 * alpha;
750 let h00 = 2.0 * alpha3 - 3.0 * alpha2 + 1.0;
751 let h10 = alpha3 - 2.0 * alpha2 + alpha;
752 let h01 = -2.0 * alpha3 + 3.0 * alpha2;
753 let h11 = alpha3 - alpha2;
754 for axis in 0..3 {
755 apex[axis] = h00 * previous[axis]
756 + h10 * dt * previous[axis + 3]
757 + h01 * current[axis]
758 + h11 * dt * current[axis + 3];
759 }
760 apex[4] = 0.0;
761
762 apex.iter()
763 .all(|component| component.is_finite())
764 .then_some((previous_time + alpha * dt, apex))
765}
766
767#[allow(clippy::too_many_arguments)]
769fn compute_derivatives(
770 state: &[f64; 6],
771 inputs: &BallisticInputs,
772 wind_sock: &WindSock,
773 atmosphere: FastAtmosphere,
774 drag_model: &DragModel,
775 projectile_shape: crate::transonic_drag::ProjectileShape,
776 bc: f64,
777 has_bc_segments: bool,
778 has_bc_segments_data: bool,
779 omega: Option<Vector3<f64>>,
780 wind_shear_model: Option<crate::wind_shear::WindShearModel>,
781 atmo_sock: Option<&AtmoSock>,
783) -> [f64; 6] {
784 let pos = Vector3::new(state[0], state[1], state[2]);
785 let vel = Vector3::new(state[3], state[4], state[5]);
786
787 let level_wind = wind_sock.vector_for_range_stateless(pos.x);
790 let level_wind = if let Some(model) = wind_shear_model {
791 let height_rel_launch =
792 crate::atmosphere::shot_frame_altitude(0.0, pos.x, pos.y, inputs.shooting_angle);
793 crate::wind_shear::apply_boundary_layer_shear(level_wind, height_rel_launch, model)
794 } else {
795 level_wind
796 };
797 let wind_vector =
798 crate::derivatives::level_vector_to_shot_frame(level_wind, inputs.shooting_angle);
799
800 let vel_adjusted = vel - wind_vector;
802 let v_mag = vel_adjusted.norm();
803
804 let theta = inputs.shooting_angle;
807 let accel_gravity = Vector3::new(
808 -G_ACCEL_MPS2 * theta.sin(),
809 -G_ACCEL_MPS2 * theta.cos(),
810 0.0,
811 );
812
813 let mut accel = if v_mag < 1e-6 {
815 accel_gravity
816 } else {
817 let v_fps = v_mag * MPS_TO_FPS;
819
820 let (local_density, speed_of_sound) = match atmosphere {
842 FastAtmosphere::Direct {
843 air_density,
844 speed_of_sound,
845 } => (air_density, speed_of_sound),
846 FastAtmosphere::Standard { base_density } => {
847 let altitude = crate::atmosphere::shot_frame_altitude(
848 inputs.altitude,
849 pos.x,
850 pos.y,
851 inputs.shooting_angle,
852 );
853 let (base_temp_c, base_press_hpa, base_ratio) = match atmo_sock {
854 Some(sock) => {
855 let (zt, zp, zh) = sock.atmo_for_range(pos.x);
856 (zt, zp, calculate_air_density_cimp(zt, zp, zh) / 1.225)
857 }
858 None => (inputs.temperature, inputs.pressure, base_density / 1.225),
859 };
860 get_local_atmosphere_humid(
861 altitude,
862 inputs.altitude, base_temp_c,
864 base_press_hpa,
865 base_ratio,
866 0.0, )
868 }
869 };
870 let mach = v_mag / speed_of_sound;
871
872 let bc_current = match (
874 inputs.bc_segments_data.as_ref(),
875 inputs.bc_segments.as_ref(),
876 ) {
877 (Some(segments_data), _) if inputs.use_bc_segments && has_bc_segments_data => {
878 velocity_segment_bc(v_fps, segments_data, bc)
879 }
880 (_, Some(segments)) if has_bc_segments => {
881 crate::derivatives::interpolated_bc(mach, segments, Some(inputs))
882 }
883 _ => bc,
884 };
885 let bc_current = bc_current.max(1e-6);
888
889 let (drag_factor, retard_denom) = if let Some(ref table) = inputs.custom_drag_table {
900 (
901 table.interpolate(mach) * inputs.cd_scale,
906 inputs.custom_drag_denominator(bc_current),
907 )
908 } else {
909 let base_cd = get_drag_coefficient(mach, drag_model);
910 let cd =
911 crate::transonic_drag::transonic_correction(mach, base_cd, projectile_shape, false);
912 (cd, bc_current)
913 };
914
915 let cd_to_retard = crate::constants::CD_TO_RETARD;
917 let standard_factor = drag_factor * cd_to_retard;
918 let density_scale = local_density / 1.225;
921
922 let a_drag_ft_s2 = (v_fps * v_fps) * standard_factor * density_scale / retard_denom;
924
925 let a_drag_m_s2 = a_drag_ft_s2 * 0.3048; let accel_drag = -a_drag_m_s2 * (vel_adjusted / v_mag);
928
929 let accel_magnus =
932 fast_magnus_acceleration(inputs, vel_adjusted, local_density, mach, accel_gravity);
933
934 accel_drag + accel_gravity + accel_magnus
936 };
937
938 if let Some(omega) = omega {
941 let omega = crate::derivatives::level_vector_to_shot_frame(omega, inputs.shooting_angle);
942 accel += -2.0 * omega.cross(&vel);
943 }
944
945 [vel.x, vel.y, vel.z, accel.x, accel.y, accel.z]
947}
948
949pub fn fast_integrate_with_segments(
957 inputs: &BallisticInputs,
958 wind_segments: Vec<crate::wind::WindSegment>,
959 params: FastIntegrationParams,
960) -> FastSolution {
961 use crate::trajectory_integration::{integrate_trajectory, TrajectoryParams};
963
964 if crate::wind::validate_wind_segments(&wind_segments).is_err()
966 || !atmo_is_physical(params.atmo_params)
967 {
968 return FastSolution::degenerate(¶ms.initial_state);
969 }
970
971 let mut normalized_inputs = inputs.clone();
977 normalized_inputs.normalize_for_solve();
978 let inputs = &normalized_inputs;
979
980 let segmented_crosswind_from_right_mps =
983 if inputs.enable_aerodynamic_jump && !wind_segments.is_empty() {
984 WindSock::new(wind_segments.clone()).muzzle_crosswind_from_right_mps()
985 } else {
986 None
987 };
988 let initial_state = launch_state_with_aerodynamic_jump(
989 inputs,
990 params.atmo_params,
991 segmented_crosswind_from_right_mps,
992 params.initial_state,
993 );
994
995 let mass_kg = inputs.bullet_mass; let bc = inputs.bc_value;
998 let drag_model = inputs.bc_type;
999
1000 let omega_vector = if inputs.enable_coriolis && inputs.latitude.is_some() {
1004 let omega_earth = 7.2921159e-5; let lat_rad = inputs.latitude.unwrap_or(0.0).to_radians();
1010 let azimuth = inputs.shot_azimuth; Some(Vector3::new(
1012 omega_earth * lat_rad.cos() * azimuth.cos(), omega_earth * lat_rad.sin(), -omega_earth * lat_rad.cos() * azimuth.sin(), ))
1016 } else {
1017 None
1018 };
1019
1020 let traj_params = TrajectoryParams {
1022 mass_kg,
1023 bc,
1024 drag_model,
1025 wind_segments,
1026 atmos_params: params.atmo_params,
1027 omega_vector,
1028 enable_spin_drift: inputs.use_enhanced_spin_drift,
1029 enable_magnus: inputs.enable_magnus,
1030 enable_coriolis: inputs.enable_coriolis,
1031 target_distance_m: params.horiz,
1032 enable_wind_shear: inputs.enable_wind_shear,
1033 wind_shear_model: inputs.wind_shear_model.clone(),
1034 shooter_altitude_m: inputs.altitude,
1035 is_twist_right: inputs.is_twist_right,
1036 shooting_angle: inputs.shooting_angle,
1037 bullet_diameter: inputs.bullet_diameter,
1039 bullet_length: inputs.bullet_length,
1040 twist_rate: inputs.twist_rate,
1041 cd_scale: inputs.cd_scale,
1042 custom_drag_table: inputs.custom_drag_table.clone(),
1043 bc_segments: inputs.bc_segments.clone(),
1044 use_bc_segments: inputs.use_bc_segments,
1045 bc_segments_data: inputs.bc_segments_data.clone(),
1048 ground_threshold: -1000.0,
1052 atmo_sock: params.atmo_sock,
1054 };
1055
1056 let trajectory = integrate_trajectory(
1058 initial_state,
1059 params.t_span,
1060 traj_params,
1061 "RK45", 1e-6, 0.01, );
1065
1066 let n_points = trajectory.len();
1068 let mut times = Vec::with_capacity(n_points + 1);
1069 let mut states = Vec::with_capacity(n_points + 1);
1070
1071 let mut target_hit_time: Option<f64> = None;
1072 let mut ground_hit_time: Option<f64> = None;
1073 let mut max_ord_time = None;
1074 let mut max_ord_y = 0.0;
1075
1076 for (t, state_vec) in trajectory {
1077 let state = [
1079 state_vec[0],
1080 state_vec[1],
1081 state_vec[2],
1082 state_vec[3],
1083 state_vec[4],
1084 state_vec[5],
1085 ];
1086
1087 if let Some((&previous_time, &previous_state)) = times.last().zip(states.last()) {
1095 if let Some((apex_time, apex_state)) =
1096 interpolated_vertical_apex(previous_time, &previous_state, t, &state)
1097 {
1098 if apex_state[1] > max_ord_y {
1099 max_ord_y = apex_state[1];
1100 max_ord_time = Some(apex_time);
1101 }
1102 times.push(apex_time);
1103 states.push(apex_state);
1104 }
1105 }
1106
1107 if target_hit_time.is_none() && state[0] >= params.horiz {
1109 target_hit_time = Some(t);
1110 }
1111
1112 if ground_hit_time.is_none() && state[1] <= inputs.ground_threshold {
1114 ground_hit_time = Some(t);
1115 }
1116
1117 if state[1] > max_ord_y {
1119 max_ord_y = state[1];
1120 max_ord_time = Some(t);
1121 }
1122
1123 times.push(t);
1124 states.push(state);
1125 }
1126
1127 let t_events = [
1129 if let Some(t) = target_hit_time {
1130 vec![t]
1131 } else {
1132 vec![]
1133 },
1134 if let Some(t) = max_ord_time {
1135 vec![t]
1136 } else {
1137 vec![]
1138 },
1139 if let Some(t) = ground_hit_time {
1140 vec![t]
1141 } else {
1142 vec![]
1143 },
1144 ];
1145
1146 if inputs.use_enhanced_spin_drift {
1151 let (sd_temp_c, sd_press_hpa) = if params.atmo_params.2 > 0.0 {
1155 (params.atmo_params.1, params.atmo_params.2)
1156 } else {
1157 (15.0, 1013.25)
1158 };
1159 let sg = crate::spin_drift::effective_sg_from_inputs(inputs, sd_temp_c, sd_press_hpa);
1160 for (t, state) in times.iter().zip(states.iter_mut()) {
1161 if *t > 0.0 {
1162 state[2] += crate::spin_drift::litz_drift_meters(sg, *t, inputs.is_twist_right);
1163 }
1164 }
1165 }
1166
1167 FastSolution::from_trajectory_data(times, states, t_events)
1168}
1169
1170#[cfg(test)]
1171mod tests {
1172 use super::*;
1173 use crate::BCSegmentData;
1174
1175 fn expected_shot_frame_vector(level: Vector3<f64>, angle: f64) -> Vector3<f64> {
1176 let (sin_angle, cos_angle) = angle.sin_cos();
1177 Vector3::new(
1178 level.x * cos_angle + level.y * sin_angle,
1179 -level.x * sin_angle + level.y * cos_angle,
1180 level.z,
1181 )
1182 }
1183
1184 #[test]
1185 fn measured_bc_fast_drag_ignores_name_based_form_factor_flag() {
1186 let derivatives_with_flag = |use_form_factor| {
1187 let inputs = BallisticInputs {
1188 bc_value: 0.462,
1189 bc_type: DragModel::G1,
1190 bullet_model: Some("168gr SMK Match".to_string()),
1191 use_form_factor,
1192 temperature: 15.0,
1193 pressure: 1013.25,
1194 ..BallisticInputs::default()
1195 };
1196
1197 compute_derivatives(
1198 &[0.0, 0.0, 0.0, 600.0, 0.0, 0.0],
1199 &inputs,
1200 &WindSock::new(vec![]),
1201 FastAtmosphere::Standard {
1202 base_density: 1.225,
1203 },
1204 &inputs.bc_type,
1205 crate::transonic_drag::ProjectileShape::Spitzer,
1206 inputs.bc_value,
1207 false,
1208 false,
1209 None,
1210 None,
1211 None,
1212 )
1213 };
1214
1215 let baseline = derivatives_with_flag(false);
1216 let flagged = derivatives_with_flag(true);
1217
1218 for component in 3..6 {
1219 assert_eq!(
1220 flagged[component].to_bits(),
1221 baseline[component].to_bits(),
1222 "published BC already encodes form factor: component {component}, baseline={} flagged={}",
1223 baseline[component],
1224 flagged[component]
1225 );
1226 }
1227 }
1228
1229 #[test]
1230 fn velocity_bc_data_requires_opt_in_in_plain_fast_kernel() {
1231 let acceleration = |inputs: &BallisticInputs| {
1232 let has_mach_segments = inputs
1233 .bc_segments
1234 .as_ref()
1235 .is_some_and(|segments| !segments.is_empty());
1236 let has_velocity_segments = inputs
1237 .bc_segments_data
1238 .as_ref()
1239 .is_some_and(|segments| !segments.is_empty());
1240 compute_derivatives(
1241 &[0.0, 0.0, 0.0, 600.0, 0.0, 0.0],
1242 inputs,
1243 &WindSock::new(vec![]),
1244 FastAtmosphere::Standard {
1245 base_density: 1.225,
1246 },
1247 &inputs.bc_type,
1248 crate::transonic_drag::ProjectileShape::Spitzer,
1249 inputs.bc_value,
1250 has_mach_segments,
1251 has_velocity_segments,
1252 None,
1253 None,
1254 None,
1255 )
1256 };
1257
1258 let scalar_inputs = BallisticInputs {
1259 bc_value: 0.5,
1260 bc_type: DragModel::G7,
1261 temperature: 15.0,
1262 pressure: 1013.25,
1263 ..BallisticInputs::default()
1264 };
1265 let mut disabled_inputs = scalar_inputs.clone();
1266 disabled_inputs.bc_segments_data = Some(vec![BCSegmentData {
1267 velocity_min: 0.0,
1268 velocity_max: 4_000.0,
1269 bc_value: 0.46,
1270 }]);
1271 disabled_inputs.use_bc_segments = false;
1272 let mut enabled_inputs = disabled_inputs.clone();
1273 enabled_inputs.use_bc_segments = true;
1274 let mut mach_only_inputs = scalar_inputs.clone();
1275 mach_only_inputs.bc_segments = Some(vec![(0.0, 0.4), (3.0, 0.4)]);
1276 let mut disabled_with_both = mach_only_inputs.clone();
1277 disabled_with_both.bc_segments_data = disabled_inputs.bc_segments_data.clone();
1278
1279 let scalar = acceleration(&scalar_inputs);
1280 let disabled = acceleration(&disabled_inputs);
1281 let enabled = acceleration(&enabled_inputs);
1282 let mach_only = acceleration(&mach_only_inputs);
1283 let disabled_with_both = acceleration(&disabled_with_both);
1284
1285 assert_eq!(
1286 disabled[3].to_bits(),
1287 scalar[3].to_bits(),
1288 "a populated velocity table must not change drag while use_bc_segments is false"
1289 );
1290 assert!(
1291 enabled[3] < disabled[3] - 1.0,
1292 "enabling the lower BC table must increase drag: disabled ax={} enabled ax={}",
1293 disabled[3],
1294 enabled[3]
1295 );
1296 assert_eq!(
1297 disabled_with_both[3].to_bits(),
1298 mach_only[3].to_bits(),
1299 "disabling velocity data must fall through to an explicit Mach table"
1300 );
1301 }
1302
1303 #[test]
1304 fn inclined_positions_at_same_world_altitude_have_same_fast_acceleration() {
1305 let angle = std::f64::consts::FRAC_PI_6;
1306 let inputs = BallisticInputs {
1307 altitude: 100.0,
1308 temperature: 15.0,
1309 pressure: 1013.25,
1310 shooting_angle: angle,
1311 ..BallisticInputs::default()
1312 };
1313 let wind_sock = WindSock::new(vec![]);
1314 let atmosphere = FastAtmosphere::Standard {
1315 base_density: 1.225,
1316 };
1317 let state_along_slant = [1_000.0, 0.0, 0.0, 600.0, 0.0, 0.0];
1318 let state_across_slant = [0.0, 500.0 / angle.cos(), 0.0, 600.0, 0.0, 0.0];
1319
1320 let a = compute_derivatives(
1321 &state_along_slant,
1322 &inputs,
1323 &wind_sock,
1324 atmosphere,
1325 &inputs.bc_type,
1326 crate::transonic_drag::ProjectileShape::Spitzer,
1327 inputs.bc_value,
1328 false,
1329 false,
1330 None,
1331 None,
1332 None,
1333 );
1334 let b = compute_derivatives(
1335 &state_across_slant,
1336 &inputs,
1337 &wind_sock,
1338 atmosphere,
1339 &inputs.bc_type,
1340 crate::transonic_drag::ProjectileShape::Spitzer,
1341 inputs.bc_value,
1342 false,
1343 false,
1344 None,
1345 None,
1346 None,
1347 );
1348
1349 for component in 3..6 {
1350 assert!(
1351 (a[component] - b[component]).abs() < 1e-10,
1352 "fast derivative component {component} differs at equal world altitude: {} vs {}",
1353 a[component],
1354 b[component]
1355 );
1356 }
1357 }
1358
1359 #[test]
1360 fn inclined_headwind_is_rotated_into_solver_frame() {
1361 let angle = std::f64::consts::FRAC_PI_6;
1362 let inputs = BallisticInputs {
1363 shooting_angle: angle,
1364 ..BallisticInputs::default()
1365 };
1366 let speed_mps = 360.0 * (1000.0 / 3600.0);
1367 let level_headwind = Vector3::new(-speed_mps, 0.0, 0.0);
1368 let velocity = expected_shot_frame_vector(level_headwind, angle);
1369 let state = [0.0, 0.0, 0.0, velocity.x, velocity.y, velocity.z];
1370 let actual = compute_derivatives(
1371 &state,
1372 &inputs,
1373 &WindSock::new(vec![crate::wind::WindSegment::new(360.0, 0.0, 1000.0)]),
1374 FastAtmosphere::Direct {
1375 air_density: 1.225,
1376 speed_of_sound: 340.0,
1377 },
1378 &inputs.bc_type,
1379 crate::transonic_drag::ProjectileShape::Spitzer,
1380 inputs.bc_value,
1381 false,
1382 false,
1383 None,
1384 None,
1385 None,
1386 );
1387 let expected = Vector3::new(
1388 -G_ACCEL_MPS2 * angle.sin(),
1389 -G_ACCEL_MPS2 * angle.cos(),
1390 0.0,
1391 );
1392
1393 assert!(
1394 (Vector3::new(actual[3], actual[4], actual[5]) - expected).norm() < 1e-12,
1395 "co-moving horizontal wind must leave only shot-frame gravity: {actual:?}"
1396 );
1397 }
1398
1399 #[test]
1400 fn plain_fast_kernel_applies_power_law_wind_shear() {
1401 let state = [500.0, 100.0, 0.0, 700.0, 0.0, 0.0];
1402 let run = |enable_wind_shear: bool, model: &str, wind_speed_kmh: f64| {
1403 let inputs = BallisticInputs {
1404 bc_value: 0.5,
1405 bc_type: DragModel::G7,
1406 enable_wind_shear,
1407 wind_shear_model: model.to_string(),
1408 ..BallisticInputs::default()
1409 };
1410 let wind_shear_model = enable_wind_shear
1411 .then(|| crate::wind_shear::boundary_layer_model_from_name(model))
1412 .filter(|model| *model != crate::wind_shear::WindShearModel::None);
1413 compute_derivatives(
1414 &state,
1415 &inputs,
1416 &WindSock::new(vec![crate::wind::WindSegment::new(
1417 wind_speed_kmh,
1418 90.0,
1419 2_000.0,
1420 )]),
1421 FastAtmosphere::Direct {
1422 air_density: 1.225,
1423 speed_of_sound: 340.0,
1424 },
1425 &inputs.bc_type,
1426 crate::transonic_drag::ProjectileShape::Spitzer,
1427 inputs.bc_value,
1428 false,
1429 false,
1430 None,
1431 wind_shear_model,
1432 None,
1433 )
1434 };
1435
1436 let uniform = run(false, "power_law", 36.0);
1437 let model_none = run(true, "none", 36.0);
1438 assert_eq!(model_none, uniform, "model=none must preserve uniform wind");
1439
1440 let sheared = run(true, "power_law", 36.0);
1441 assert!(
1442 sheared[5] < uniform[5],
1443 "stronger aloft crosswind must increase leftward acceleration: uniform={}, shear={}",
1444 uniform[5],
1445 sheared[5]
1446 );
1447
1448 let ratio = crate::wind_shear::boundary_layer_speed_ratio(
1449 state[1],
1450 crate::wind_shear::WindShearModel::PowerLaw,
1451 );
1452 let equivalent_uniform = run(false, "none", 36.0 * ratio);
1453 for component in 3..6 {
1454 assert!(
1455 (sheared[component] - equivalent_uniform[component]).abs() < 1e-12,
1456 "shear component {component} must equal base wind scaled by {ratio}: shear={}, expected={}",
1457 sheared[component],
1458 equivalent_uniform[component]
1459 );
1460 }
1461 }
1462
1463 #[test]
1464 fn plain_fast_path_wind_shear_changes_high_arc_drift() {
1465 let run = |enable_wind_shear: bool, model: &str| {
1466 let inputs = BallisticInputs {
1467 muzzle_velocity: 800.0,
1468 bc_value: 0.5,
1469 bc_type: DragModel::G7,
1470 bullet_mass: 168.0 * crate::constants::GRAINS_TO_KG,
1471 bullet_diameter: 0.308 * 0.0254,
1472 enable_wind_shear,
1473 wind_shear_model: model.to_string(),
1474 ground_threshold: -100.0,
1475 ..BallisticInputs::default()
1476 };
1477 let elevation = 0.12_f64;
1478 let solution = fast_integrate(
1479 &inputs,
1480 &WindSock::new(vec![crate::wind::WindSegment::new(36.0, 90.0, 2_000.0)]),
1481 FastIntegrationParams {
1482 horiz: 1_000.0,
1483 vert: 0.0,
1484 initial_state: [
1485 0.0,
1486 0.0,
1487 0.0,
1488 inputs.muzzle_velocity * elevation.cos(),
1489 inputs.muzzle_velocity * elevation.sin(),
1490 0.0,
1491 ],
1492 t_span: (0.0, 5.0),
1493 atmo_params: (0.0, 15.0, 1013.25, 1.0),
1494 atmo_sock: None,
1495 },
1496 );
1497 let last = solution.t.len() - 1;
1498 assert_eq!(solution.y[0][last].to_bits(), 1_000.0_f64.to_bits());
1499 solution.y[2][last]
1500 };
1501
1502 let uniform = run(false, "power_law");
1503 let model_none = run(true, "none");
1504 assert_eq!(model_none.to_bits(), uniform.to_bits());
1505 let sheared = run(true, "power_law");
1506 assert!(
1507 sheared.abs() > uniform.abs() + 0.01,
1508 "aloft shear must increase drift magnitude: uniform={uniform}, shear={sheared}"
1509 );
1510 }
1511
1512 #[test]
1513 fn inclined_coriolis_is_rotated_into_solver_frame() {
1514 let angle = std::f64::consts::FRAC_PI_6;
1515 let inputs = BallisticInputs {
1516 shooting_angle: angle,
1517 ..BallisticInputs::default()
1518 };
1519 let velocity = Vector3::new(600.0, 20.0, 5.0);
1520 let state = [0.0, 0.0, 0.0, velocity.x, velocity.y, velocity.z];
1521 let level_omega = Vector3::new(3.0e-5, 6.0e-5, -2.0e-5);
1522 let run = |omega| {
1523 compute_derivatives(
1524 &state,
1525 &inputs,
1526 &WindSock::new(vec![]),
1527 FastAtmosphere::Direct {
1528 air_density: 1.225,
1529 speed_of_sound: 340.0,
1530 },
1531 &inputs.bc_type,
1532 crate::transonic_drag::ProjectileShape::Spitzer,
1533 inputs.bc_value,
1534 false,
1535 false,
1536 omega,
1537 None,
1538 None,
1539 )
1540 };
1541 let baseline = run(None);
1542 let with_coriolis = run(Some(level_omega));
1543 let actual = Vector3::new(
1544 with_coriolis[3] - baseline[3],
1545 with_coriolis[4] - baseline[4],
1546 with_coriolis[5] - baseline[5],
1547 );
1548 let expected = -2.0 * expected_shot_frame_vector(level_omega, angle).cross(&velocity);
1549
1550 assert!(
1551 (actual - expected).norm() < 1e-12,
1552 "inclined Coriolis mismatch: actual={actual:?}, expected={expected:?}"
1553 );
1554 }
1555
1556 #[test]
1557 fn test_fast_solution_interpolation() {
1558 let times = vec![0.0, 1.0, 2.0];
1559 let states = vec![
1560 [0.0, 0.0, 0.0, 100.0, 50.0, 0.0],
1561 [100.0, 45.0, 0.0, 99.0, 40.0, 0.0],
1562 [198.0, 80.0, 0.0, 98.0, 30.0, 0.0],
1563 ];
1564
1565 let solution = FastSolution::from_trajectory_data(times, states, [vec![], vec![], vec![]]);
1566
1567 let result = solution.sol(&[1.5]);
1569
1570 assert!((result[0][0] - 149.0).abs() < 1e-10); assert!((result[1][0] - 62.5).abs() < 1e-10); assert!((result[3][0] - 98.5).abs() < 1e-10); }
1574
1575 #[test]
1576 fn test_bc_from_velocity_segments() {
1577 let segments = vec![
1578 BCSegmentData {
1579 velocity_min: 0.0,
1580 velocity_max: 1000.0,
1581 bc_value: 0.5,
1582 },
1583 BCSegmentData {
1584 velocity_min: 1000.0,
1585 velocity_max: 2000.0,
1586 bc_value: 0.52,
1587 },
1588 BCSegmentData {
1589 velocity_min: 2000.0,
1590 velocity_max: 3000.0,
1591 bc_value: 0.55,
1592 },
1593 ];
1594
1595 assert_eq!(velocity_segment_bc(500.0, &segments, 0.5), 0.5);
1600 assert_eq!(velocity_segment_bc(1500.0, &segments, 0.5), 0.52);
1601 assert_eq!(velocity_segment_bc(2500.0, &segments, 0.5), 0.55);
1602
1603 assert_eq!(velocity_segment_bc(-100.0, &segments, 0.5), 0.5); assert_eq!(velocity_segment_bc(3500.0, &segments, 0.5), 0.55); }
1607
1608 #[test]
1609 fn test_fast_solution_interpolation_edge_cases() {
1610 let times = vec![0.0, 1.0, 2.0, 3.0];
1611 let states = vec![
1612 [0.0, 0.0, 0.0, 800.0, 50.0, 0.0],
1613 [800.0, 40.0, 100.0, 750.0, 30.0, 0.0],
1614 [1550.0, 60.0, 200.0, 700.0, 10.0, 0.0],
1615 [2250.0, 50.0, 300.0, 650.0, -10.0, 0.0],
1616 ];
1617
1618 let solution = FastSolution::from_trajectory_data(times, states, [vec![], vec![], vec![]]);
1619
1620 let result_before = solution.sol(&[-0.5]);
1622 assert!((result_before[0][0] - 0.0).abs() < 1e-10); let result_after = solution.sol(&[5.0]);
1626 assert!((result_after[0][0] - 2250.0).abs() < 1e-10); let result_exact = solution.sol(&[1.0]);
1630 assert!((result_exact[0][0] - 800.0).abs() < 1e-10);
1631
1632 let result_multi = solution.sol(&[0.5, 1.5, 2.5]);
1634 assert_eq!(result_multi[0].len(), 3);
1635 }
1636
1637 #[test]
1638 fn test_fast_solution_from_trajectory_data() {
1639 let times = vec![0.0, 0.5, 1.0];
1640 let states = vec![
1641 [0.0, 1.0, 2.0, 3.0, 4.0, 5.0],
1642 [10.0, 11.0, 12.0, 13.0, 14.0, 15.0],
1643 [20.0, 21.0, 22.0, 23.0, 24.0, 25.0],
1644 ];
1645 let t_events = [vec![1.0], vec![0.5], vec![]];
1646
1647 let solution = FastSolution::from_trajectory_data(times.clone(), states, t_events);
1648
1649 assert_eq!(solution.t, times);
1651 assert_eq!(solution.y.len(), 6); assert_eq!(solution.y[0].len(), 3); assert!(solution.success);
1654
1655 assert_eq!(solution.y[0][0], 0.0); assert_eq!(solution.y[1][0], 1.0); assert_eq!(solution.y[0][2], 20.0); }
1660
1661 #[test]
1662 fn test_bc_segments_boundary_conditions() {
1663 let single_segment = vec![BCSegmentData {
1667 velocity_min: 1000.0,
1668 velocity_max: 2000.0,
1669 bc_value: 0.5,
1670 }];
1671
1672 assert_eq!(velocity_segment_bc(500.0, &single_segment, 0.5), 0.5); assert_eq!(velocity_segment_bc(1500.0, &single_segment, 0.5), 0.5); assert_eq!(velocity_segment_bc(2500.0, &single_segment, 0.5), 0.5); let segments = vec![
1680 BCSegmentData {
1681 velocity_min: 0.0,
1682 velocity_max: 999.0, bc_value: 0.45,
1684 },
1685 BCSegmentData {
1686 velocity_min: 1000.0,
1687 velocity_max: 2000.0,
1688 bc_value: 0.50,
1689 },
1690 ];
1691
1692 assert_eq!(velocity_segment_bc(1000.0, &segments, 0.7), 0.6); assert_eq!(velocity_segment_bc(0.0, &segments, 0.7), 0.45); assert_eq!(
1707 velocity_segment_bc(998.999, &segments, 0.7),
1708 0.5735000320000354
1709 ); assert_eq!(velocity_segment_bc(999.0, &segments, 0.7), 0.575); }
1714
1715 #[test]
1716 fn velocity_segment_gaps_and_clamps_do_not_depend_on_order() {
1717 let fallback_bc = 0.73;
1718 let ascending_with_gap = vec![
1719 BCSegmentData {
1720 velocity_min: 0.0,
1721 velocity_max: 999.0,
1722 bc_value: 0.6,
1723 },
1724 BCSegmentData {
1725 velocity_min: 1000.0,
1726 velocity_max: 2000.0,
1727 bc_value: 0.8,
1728 },
1729 ];
1730 assert_eq!(
1734 velocity_segment_bc(999.5, &ascending_with_gap, fallback_bc),
1735 fallback_bc,
1736 "coverage gaps must use the projectile's base BC"
1737 );
1738
1739 let mut descending = ascending_with_gap.clone();
1740 descending.reverse();
1741 assert_eq!(
1744 velocity_segment_bc(-100.0, &descending, fallback_bc),
1745 0.6,
1746 "below coverage must clamp to the lowest-velocity band"
1747 );
1748 assert_eq!(
1749 velocity_segment_bc(2500.0, &descending, fallback_bc),
1750 0.8,
1751 "above coverage must clamp to the highest-velocity band"
1752 );
1753 }
1754
1755 #[test]
1756 fn test_bc_segments_empty_fallback() {
1757 let empty_segments: Vec<BCSegmentData> = vec![];
1758
1759 let result = velocity_segment_bc(1500.0, &empty_segments, 0.73);
1763 assert_eq!(result, 0.73); }
1765
1766 #[test]
1767 fn test_fast_integration_params() {
1768 let params = FastIntegrationParams {
1770 horiz: 1000.0,
1771 vert: 0.0,
1772 initial_state: [0.0, 0.0, 0.0, 800.0, 50.0, 0.0], t_span: (0.0, 5.0),
1774 atmo_params: (0.0, 15.0, 1013.25, 1.0),
1775 atmo_sock: None,
1776 };
1777
1778 assert_eq!(params.horiz, 1000.0);
1779 assert_eq!(params.t_span.0, 0.0);
1780 assert_eq!(params.t_span.1, 5.0);
1781 assert_eq!(params.initial_state[3], 800.0); }
1783
1784 #[test]
1785 fn test_fast_solution_event_arrays() {
1786 let times = vec![0.0, 1.0, 2.0];
1787 let states = vec![
1788 [0.0, 0.0, 0.0, 800.0, 50.0, 0.0],
1789 [800.0, 40.0, 500.0, 750.0, 30.0, 0.0],
1790 [1500.0, 20.0, 1000.0, 700.0, 10.0, 0.0],
1791 ];
1792
1793 let t_events = [
1795 vec![2.0], vec![0.5], vec![], ];
1799
1800 let solution = FastSolution::from_trajectory_data(times, states, t_events);
1801
1802 assert_eq!(solution.t_events[0], vec![2.0]); assert_eq!(solution.t_events[1], vec![0.5]); assert!(solution.t_events[2].is_empty()); }
1806
1807 #[test]
1808 fn segmented_fast_path_interpolates_max_ordinate_between_saved_points() {
1809 let expected_apex_time = 5.105_f64;
1810 let downrange_velocity = 100.0_f64;
1811 let vertical_velocity = G_ACCEL_MPS2 * expected_apex_time;
1812 let inputs = BallisticInputs {
1813 muzzle_velocity: downrange_velocity.hypot(vertical_velocity),
1814 bc_value: 0.5,
1815 bc_type: DragModel::G7,
1816 use_enhanced_spin_drift: false,
1817 ..BallisticInputs::default()
1818 };
1819 let solution = fast_integrate_with_segments(
1820 &inputs,
1821 vec![],
1822 FastIntegrationParams {
1823 horiz: 1_000.0,
1824 vert: 0.0,
1825 initial_state: [0.0, 0.0, 0.0, downrange_velocity, vertical_velocity, 0.0],
1826 t_span: (0.0, 12.0),
1827 atmo_params: (1e-12, 340.0, 0.0, 0.0),
1830 atmo_sock: None,
1831 },
1832 );
1833
1834 assert!(solution.success);
1835 assert_eq!(solution.t_events[1].len(), 1);
1836 let reported_time = solution.t_events[1][0];
1837 assert!(
1838 (reported_time - expected_apex_time).abs() < 0.006,
1839 "max-ordinate time must be interpolated between coarse saves: reported={reported_time} expected={expected_apex_time}"
1840 );
1841 let event_index = solution
1842 .t
1843 .iter()
1844 .position(|time| time.to_bits() == reported_time.to_bits())
1845 .expect("the interpolated apex must be retained in the solution");
1846 assert_eq!(solution.y[4][event_index].to_bits(), 0.0_f64.to_bits());
1847
1848 let expected_height = vertical_velocity * expected_apex_time
1849 - 0.5 * G_ACCEL_MPS2 * expected_apex_time.powi(2);
1850 let event_state = solution.sol(&[reported_time]);
1851 assert!(
1852 (event_state[1][0] - expected_height).abs() < 2e-4,
1853 "max-ordinate state must preserve the interpolated apex height: reported={} expected={expected_height}",
1854 event_state[1][0]
1855 );
1856 }
1857
1858 #[test]
1859 fn plain_fast_path_interpolates_the_target_crossing() {
1860 let target = 500.123456789;
1861 let initial_state = [0.0, 0.0, 0.25, 800.0, 12.0, -2.5];
1862 let inputs = BallisticInputs {
1863 muzzle_velocity: 800.0,
1864 bc_value: 0.5,
1865 bc_type: DragModel::G7,
1866 ground_threshold: -100.0,
1867 use_enhanced_spin_drift: false,
1868 ..BallisticInputs::default()
1869 };
1870 let run = |horiz| {
1871 fast_integrate(
1872 &inputs,
1873 &WindSock::new(vec![]),
1874 FastIntegrationParams {
1875 horiz,
1876 vert: 0.0,
1877 initial_state,
1878 t_span: (0.0, 2.0),
1879 atmo_params: (0.0, 15.0, 1013.25, 1.0),
1880 atmo_sock: None,
1881 },
1882 )
1883 };
1884
1885 let reference = run(target + 2.0);
1887 let left = reference.y[0]
1888 .windows(2)
1889 .position(|x| x[0] < target && x[1] > target)
1890 .expect("reference trajectory must bracket target");
1891 let right = left + 1;
1892 let alpha =
1893 (target - reference.y[0][left]) / (reference.y[0][right] - reference.y[0][left]);
1894
1895 let solution = run(target);
1896 let last = solution.t.len() - 1;
1897 assert_eq!(solution.y[0][last].to_bits(), target.to_bits());
1898 let expected_time = reference.t[left] + alpha * (reference.t[right] - reference.t[left]);
1899 assert!((solution.t[last] - expected_time).abs() < 1e-12);
1900 assert_eq!(solution.t_events[0], vec![solution.t[last]]);
1901
1902 for component in 0..6 {
1903 assert_eq!(solution.y[component].len(), solution.t.len());
1904 let expected = reference.y[component][left]
1905 + alpha * (reference.y[component][right] - reference.y[component][left]);
1906 assert!(
1907 (solution.y[component][last] - expected).abs() < 1e-9,
1908 "component {component} is not at the crossing: actual={}, expected={expected}",
1909 solution.y[component][last]
1910 );
1911 }
1912 }
1913
1914 #[test]
1915 fn fast_path_coriolis_uses_shot_direction() {
1916 use std::f64::consts::FRAC_PI_2;
1921 fn final_xy(shot_az: f64) -> (f64, f64) {
1923 let inputs = BallisticInputs {
1924 muzzle_velocity: 800.0,
1925 bc_value: 0.5,
1926 bc_type: DragModel::G7,
1927 enable_advanced_effects: true, enable_coriolis: true,
1929 latitude: Some(45.0),
1930 shot_azimuth: shot_az,
1931 ..BallisticInputs::default()
1932 };
1933 let v = 800.0_f64;
1934 let elev = 0.02_f64;
1935 let params = FastIntegrationParams {
1936 horiz: 1000.0,
1937 vert: 0.0,
1938 initial_state: [0.0, 0.0, 0.0, v * elev.cos(), v * elev.sin(), 0.0],
1939 t_span: (0.0, 5.0),
1940 atmo_params: (0.0, 15.0, 1013.25, 1.0),
1941 atmo_sock: None,
1942 };
1943 let sol = fast_integrate_with_segments(&inputs, vec![], params);
1944 let n = sol.y[0].len();
1945 (sol.y[0][n - 1], sol.y[1][n - 1])
1946 }
1947 let (ex, ey) = final_xy(FRAC_PI_2); let (wx, wy) = final_xy(3.0 * FRAC_PI_2); assert!(
1952 (ex - wx).abs() < 0.5,
1953 "east/west downrange should be ~equal (ex={ex:.4}, wx={wx:.4})"
1954 );
1955 assert!(
1958 ey > wy,
1959 "fast-path east ({ey:.6}) must be higher than west ({wy:.6}) (Eotvos)"
1960 );
1961 assert!(
1962 (ey - wy) > 1e-5,
1963 "fast-path E-W vertical separation ({:.8} m) should be non-zero (the pre-fix bug was exact equality)",
1964 ey - wy
1965 );
1966 }
1967
1968 #[test]
1969 fn fast_path_coriolis_independent_of_advanced_effects() {
1970 use std::f64::consts::FRAC_PI_2;
1973 fn final_y(coriolis: bool, shot_az: f64) -> f64 {
1974 let inputs = BallisticInputs {
1975 muzzle_velocity: 800.0,
1976 bc_value: 0.5,
1977 bc_type: DragModel::G7,
1978 enable_coriolis: coriolis,
1979 enable_advanced_effects: false, latitude: Some(45.0),
1981 shot_azimuth: shot_az,
1982 ..BallisticInputs::default()
1983 };
1984 let v = 800.0_f64;
1985 let elev = 0.02_f64;
1986 let params = FastIntegrationParams {
1987 horiz: 1000.0,
1988 vert: 0.0,
1989 initial_state: [0.0, 0.0, 0.0, v * elev.cos(), v * elev.sin(), 0.0],
1990 t_span: (0.0, 5.0),
1991 atmo_params: (0.0, 15.0, 1013.25, 1.0),
1992 atmo_sock: None,
1993 };
1994 let sol = fast_integrate_with_segments(&inputs, vec![], params);
1995 let n = sol.y[0].len();
1996 sol.y[1][n - 1]
1997 }
1998 let e = final_y(true, FRAC_PI_2);
2000 let w = final_y(true, 3.0 * FRAC_PI_2);
2001 assert!(
2002 e > w && (e - w) > 1e-5,
2003 "Coriolis-only (no advanced effects) must still be directional: E={e} W={w}"
2004 );
2005 let e2 = final_y(false, FRAC_PI_2);
2007 let w2 = final_y(false, 3.0 * FRAC_PI_2);
2008 assert!(
2009 (e2 - w2).abs() < 1e-9,
2010 "with enable_coriolis=false, east/west must be identical: E={e2} W={w2}"
2011 );
2012 }
2013
2014 #[test]
2015 fn fast_path_rejects_degenerate_atmosphere() {
2016 let inputs = BallisticInputs {
2017 muzzle_velocity: 800.0,
2018 bc_value: 0.5,
2019 bc_type: DragModel::G7,
2020 ..BallisticInputs::default()
2021 };
2022 let v = 800.0_f64;
2023 let e = 0.02_f64;
2024 let mk = |atmo: (f64, f64, f64, f64)| FastIntegrationParams {
2025 horiz: 500.0,
2026 vert: 0.0,
2027 initial_state: [0.0, 0.0, 0.0, v * e.cos(), v * e.sin(), 0.0],
2028 t_span: (0.0, 5.0),
2029 atmo_params: atmo,
2030 atmo_sock: None,
2031 };
2032 let zero_p = fast_integrate_with_segments(&inputs, vec![], mk((0.0, 15.0, 0.0, 1.0)));
2034 assert!(
2035 !zero_p.success,
2036 "pressure=0 atmosphere must yield success=false"
2037 );
2038 let nan_p = fast_integrate_with_segments(&inputs, vec![], mk((0.0, 15.0, f64::NAN, 1.0)));
2040 assert!(!nan_p.success, "NaN pressure must yield success=false");
2041 let segmented_too_dense =
2043 fast_integrate_with_segments(&inputs, vec![], mk((0.0, 15.0, 1013.25, 50.0)));
2044 let plain_too_dense = fast_integrate(
2045 &inputs,
2046 &WindSock::new(vec![]),
2047 mk((0.0, 15.0, 1013.25, 50.0)),
2048 );
2049 assert!(
2050 !segmented_too_dense.success && !plain_too_dense.success,
2051 "ratio=50 atmosphere must fail in both wrappers: segmented={}, plain={}",
2052 segmented_too_dense.success,
2053 plain_too_dense.success
2054 );
2055 let good = fast_integrate_with_segments(&inputs, vec![], mk((0.0, 15.0, 1013.25, 1.0)));
2057 assert!(good.success, "realistic atmosphere must yield success=true");
2058 let direct = fast_integrate_with_segments(&inputs, vec![], mk((1.225, 340.0, 0.0, 0.0)));
2061 assert!(
2062 direct.success,
2063 "direct-atmosphere mode (pressure=0 sentinel) must yield success=true"
2064 );
2065 }
2066
2067 #[test]
2068 fn fast_paths_reject_invalid_wind_segments() {
2069 let inputs = BallisticInputs {
2070 muzzle_velocity: 800.0,
2071 bc_value: 0.5,
2072 bc_type: DragModel::G7,
2073 ..BallisticInputs::default()
2074 };
2075 let mk = || FastIntegrationParams {
2076 horiz: 100.0,
2077 vert: 0.0,
2078 initial_state: [0.0, 0.0, 0.0, 800.0, 0.0, 0.0],
2079 t_span: (0.0, 5.0),
2080 atmo_params: (0.0, 15.0, 1013.25, 1.0),
2081 atmo_sock: None,
2082 };
2083 let invalid = crate::wind::WindSegment::new(10.0, 90.0, f64::NAN);
2084
2085 let plain = fast_integrate(&inputs, &WindSock::new(vec![invalid]), mk());
2086 let segmented = fast_integrate_with_segments(&inputs, vec![invalid], mk());
2087
2088 assert!(
2089 !plain.success && !segmented.success,
2090 "invalid segmented wind must fail in both fast wrappers: plain={}, segmented={}",
2091 plain.success,
2092 segmented.success
2093 );
2094 }
2095
2096 #[test]
2097 fn plain_fast_path_honors_direct_atmosphere_values() {
2098 fn final_speed(muzzle_velocity: f64, atmo_params: (f64, f64, f64, f64)) -> f64 {
2099 let inputs = BallisticInputs {
2100 muzzle_velocity,
2101 bc_value: 0.5,
2102 bc_type: DragModel::G7,
2103 ground_threshold: -100.0,
2104 ..BallisticInputs::default()
2105 };
2106
2107 let wind_sock = WindSock::new(vec![]);
2108 let solution = fast_integrate(
2109 &inputs,
2110 &wind_sock,
2111 FastIntegrationParams {
2112 horiz: 10_000.0,
2113 vert: 0.0,
2114 initial_state: [0.0, 0.0, 0.0, muzzle_velocity, 0.0, 0.0],
2115 t_span: (0.0, 0.2),
2116 atmo_params,
2117 atmo_sock: None,
2118 },
2119 );
2120 assert!(solution.success);
2121
2122 let last = solution.y[0].len() - 1;
2123 (solution.y[3][last].powi(2)
2124 + solution.y[4][last].powi(2)
2125 + solution.y[5][last].powi(2))
2126 .sqrt()
2127 }
2128
2129 let thin_air = final_speed(800.0, (0.905, 340.0, 0.0, 0.0));
2130 let dense_air = final_speed(800.0, (1.225, 340.0, 0.0, 0.0));
2131 assert!(
2132 thin_air > dense_air,
2133 "lower supplied density must retain more velocity: thin={thin_air}, dense={dense_air}"
2134 );
2135
2136 let low_sound_speed = final_speed(340.0, (1.0, 300.0, 0.0, 0.0));
2137 let high_sound_speed = final_speed(340.0, (1.0, 400.0, 0.0, 0.0));
2138 assert!(
2139 (low_sound_speed - high_sound_speed).abs() > 1e-6,
2140 "supplied sound speed must affect Mach-dependent drag"
2141 );
2142 }
2143
2144 #[test]
2145 fn segmented_fast_path_nonpositive_density_ratio_uses_standard_fallback() {
2146 fn terminal_velocity(base_ratio: f64) -> f64 {
2147 let inputs = BallisticInputs {
2148 muzzle_velocity: 800.0,
2149 bc_value: 0.5,
2150 bc_type: DragModel::G7,
2151 ground_threshold: -100.0,
2152 ..BallisticInputs::default()
2153 };
2154
2155 let solution = fast_integrate_with_segments(
2156 &inputs,
2157 vec![],
2158 FastIntegrationParams {
2159 horiz: 500.0,
2160 vert: 0.0,
2161 initial_state: [0.0, 0.0, 0.0, 800.0, 0.0, 0.0],
2162 t_span: (0.0, 5.0),
2163 atmo_params: (0.0, 15.0, 1013.25, base_ratio),
2164 atmo_sock: None,
2165 },
2166 );
2167 assert!(solution.success);
2168
2169 let last = solution.y[3].len() - 1;
2170 solution.y[3][last]
2171 }
2172
2173 let explicit_sea_level = terminal_velocity(1.0);
2174 for base_ratio in [0.0, -1.0] {
2175 let missing_ratio = terminal_velocity(base_ratio);
2176 assert!(
2177 missing_ratio < 800.0,
2178 "missing density ratio must not create a vacuum trajectory: {missing_ratio}"
2179 );
2180 assert!((missing_ratio - explicit_sea_level).abs() < 1e-9);
2181 }
2182 }
2183
2184 #[test]
2185 fn fast_path_carries_real_bullet_geometry() {
2186 let run = |diameter: f64, twist: f64| {
2194 let inputs = BallisticInputs {
2195 muzzle_velocity: 800.0,
2196 bc_value: 0.5,
2197 bc_type: DragModel::G7,
2198 bullet_diameter: diameter,
2199 bullet_length: 0.0318,
2200 twist_rate: twist,
2201 enable_advanced_effects: true,
2202 enable_magnus: true,
2203 ..BallisticInputs::default()
2204 };
2205 let v = 800.0_f64;
2206 let elev = 0.02_f64;
2207 let params = FastIntegrationParams {
2208 horiz: 1000.0,
2209 vert: 0.0,
2210 initial_state: [0.0, 0.0, 0.0, v * elev.cos(), v * elev.sin(), 0.0],
2211 t_span: (0.0, 5.0),
2212 atmo_params: (0.0, 15.0, 1013.25, 1.0),
2213 atmo_sock: None,
2214 };
2215 fast_integrate_with_segments(&inputs, vec![], params)
2216 };
2217 assert!(run(0.00569, 7.0).success, ".224 geometry must solve");
2220 assert!(run(0.00858, 10.0).success, ".338 geometry must solve");
2221 }
2222
2223 #[test]
2224 fn segmented_fast_spin_flags_do_not_depend_on_advanced_umbrella() {
2225 fn endpoint(
2226 enable_advanced_effects: bool,
2227 enable_magnus: bool,
2228 use_enhanced_spin_drift: bool,
2229 ) -> Vector3<f64> {
2230 let inputs = BallisticInputs {
2231 muzzle_velocity: 823.0,
2232 bullet_mass: 168.0 * crate::constants::GRAINS_TO_KG,
2233 bullet_diameter: 0.308 * 0.0254,
2234 bullet_length: 1.215 * 0.0254,
2235 caliber_inches: 0.308,
2236 weight_grains: 168.0,
2237 bc_value: 0.475,
2238 bc_type: DragModel::G1,
2239 twist_rate: 12.0,
2240 is_twist_right: true,
2241 enable_advanced_effects,
2242 enable_magnus,
2243 use_enhanced_spin_drift,
2244 ..BallisticInputs::default()
2245 };
2246 let elevation = 0.02_f64;
2247 let solution = fast_integrate_with_segments(
2248 &inputs,
2249 vec![],
2250 FastIntegrationParams {
2251 horiz: 1_000.0,
2252 vert: 0.0,
2253 initial_state: [
2254 0.0,
2255 0.0,
2256 0.0,
2257 inputs.muzzle_velocity * elevation.cos(),
2258 inputs.muzzle_velocity * elevation.sin(),
2259 0.0,
2260 ],
2261 t_span: (0.0, 5.0),
2262 atmo_params: (0.0, 15.0, 1013.25, 1.0),
2263 atmo_sock: None,
2264 },
2265 );
2266 assert!(solution.success);
2267 let last = solution.t.len() - 1;
2268 Vector3::new(
2269 solution.y[0][last],
2270 solution.y[1][last],
2271 solution.y[2][last],
2272 )
2273 }
2274
2275 let baseline = endpoint(false, false, false);
2276 let magnus_without_umbrella = endpoint(false, true, false);
2277 let magnus_with_umbrella = endpoint(true, true, false);
2278 assert!(
2279 (magnus_without_umbrella - baseline).norm() > 1e-5,
2280 "test shot must produce a measurable Magnus displacement"
2281 );
2282 assert!(
2283 (magnus_with_umbrella - magnus_without_umbrella).norm() < 1e-12,
2284 "the legacy umbrella must not suppress explicitly enabled Magnus: without={magnus_without_umbrella:?} with={magnus_with_umbrella:?}"
2285 );
2286
2287 let litz_only = endpoint(false, false, true);
2288 let litz_without_umbrella = endpoint(false, true, true);
2289 let litz_with_umbrella = endpoint(true, true, true);
2290 assert!(
2291 (litz_without_umbrella - litz_only).norm() < 1e-12,
2292 "Litz mode must suppress explicitly enabled Magnus: litz={litz_only:?} both={litz_without_umbrella:?}"
2293 );
2294 assert!(
2295 (litz_with_umbrella - litz_without_umbrella).norm() < 1e-12,
2296 "the legacy umbrella must not change Magnus suppression in Litz mode: without={litz_without_umbrella:?} with={litz_with_umbrella:?}"
2297 );
2298 }
2299
2300 fn deck_test_inputs(cd_scale: f64) -> BallisticInputs {
2302 BallisticInputs {
2303 bullet_mass: 0.0106,
2304 bullet_diameter: 0.00782,
2305 muzzle_velocity: 850.0,
2306 custom_drag_table: Some(crate::drag::DragTable::new(
2307 vec![0.5, 1.0, 2.0, 3.0],
2308 vec![0.23, 0.40, 0.30, 0.26],
2309 )),
2310 cd_scale,
2311 temperature: 15.0,
2312 pressure: 1013.25,
2313 ..BallisticInputs::default()
2314 }
2315 }
2316
2317 fn deck_accel_x(cd_scale: f64) -> f64 {
2318 let inputs = deck_test_inputs(cd_scale);
2319 compute_derivatives(
2320 &[0.0, 0.0, 0.0, 700.0, 0.0, 0.0],
2321 &inputs,
2322 &WindSock::new(vec![]),
2323 FastAtmosphere::Standard {
2324 base_density: 1.225,
2325 },
2326 &inputs.bc_type,
2327 crate::transonic_drag::ProjectileShape::Spitzer,
2328 inputs.bc_value,
2329 false,
2330 false,
2331 None,
2332 None,
2333 None,
2334 )[3]
2335 }
2336
2337 #[test]
2338 fn cd_scale_default_is_one_and_absent_matches_explicit() {
2339 assert_eq!(BallisticInputs::default().cd_scale, 1.0);
2340
2341 let omitted_inputs = BallisticInputs {
2342 bullet_mass: 0.0106,
2343 bullet_diameter: 0.00782,
2344 muzzle_velocity: 850.0,
2345 custom_drag_table: Some(crate::drag::DragTable::new(
2346 vec![0.5, 1.0, 2.0, 3.0],
2347 vec![0.23, 0.40, 0.30, 0.26],
2348 )),
2349 temperature: 15.0,
2350 pressure: 1013.25,
2351 ..BallisticInputs::default()
2352 };
2353 assert_eq!(omitted_inputs.cd_scale, 1.0);
2354
2355 let a_omitted = compute_derivatives(
2356 &[0.0, 0.0, 0.0, 700.0, 0.0, 0.0],
2357 &omitted_inputs,
2358 &WindSock::new(vec![]),
2359 FastAtmosphere::Standard {
2360 base_density: 1.225,
2361 },
2362 &omitted_inputs.bc_type,
2363 crate::transonic_drag::ProjectileShape::Spitzer,
2364 omitted_inputs.bc_value,
2365 false,
2366 false,
2367 None,
2368 None,
2369 None,
2370 )[3];
2371 let a_explicit = deck_accel_x(1.0);
2372 assert_eq!(
2373 a_omitted.to_bits(),
2374 a_explicit.to_bits(),
2375 "omitted cd_scale (Default) must be bit-identical to an explicit 1.0"
2376 );
2377 }
2378
2379 #[test]
2382 fn cd_scale_direction_on_fast_trajectory_kernel() {
2383 let baseline = deck_accel_x(1.0);
2384 let scaled_up = deck_accel_x(1.10);
2385 let scaled_down = deck_accel_x(0.90);
2386
2387 assert!(
2388 scaled_up < baseline,
2389 "cd_scale=1.10 must increase drag deceleration (more negative ax): \
2390 base={baseline} up={scaled_up}"
2391 );
2392 assert!(
2393 scaled_down > baseline,
2394 "cd_scale=0.90 must decrease drag deceleration (less negative ax): \
2395 base={baseline} down={scaled_down}"
2396 );
2397 }
2398
2399 #[test]
2401 fn cd_scale_is_inert_without_a_custom_drag_table() {
2402 let make = |cd_scale: f64| BallisticInputs {
2403 bc_value: 0.5,
2404 bc_type: DragModel::G1,
2405 temperature: 15.0,
2406 pressure: 1013.25,
2407 cd_scale,
2408 ..BallisticInputs::default()
2409 };
2410 let accel = |cd_scale: f64| {
2411 let inputs = make(cd_scale);
2412 compute_derivatives(
2413 &[0.0, 0.0, 0.0, 700.0, 0.0, 0.0],
2414 &inputs,
2415 &WindSock::new(vec![]),
2416 FastAtmosphere::Standard {
2417 base_density: 1.225,
2418 },
2419 &inputs.bc_type,
2420 crate::transonic_drag::ProjectileShape::Spitzer,
2421 inputs.bc_value,
2422 false,
2423 false,
2424 None,
2425 None,
2426 None,
2427 )[3]
2428 };
2429 assert_eq!(
2430 accel(1.0).to_bits(),
2431 accel(1.5).to_bits(),
2432 "cd_scale must not affect the G-model/BC drag path"
2433 );
2434 }
2435
2436 fn segmented_speed_at_1_5_s(inputs: &BallisticInputs) -> f64 {
2438 let v = inputs.muzzle_velocity;
2439 let elev = 0.012_f64;
2440 let solution = fast_integrate_with_segments(
2441 inputs,
2442 vec![],
2443 FastIntegrationParams {
2444 horiz: 1000.0,
2445 vert: 0.0,
2446 initial_state: [0.0, 0.0, 0.0, v * elev.cos(), v * elev.sin(), 0.0],
2447 t_span: (0.0, 5.0),
2448 atmo_params: (0.0, 15.0, 1013.25, 1.0),
2449 atmo_sock: None,
2450 },
2451 );
2452 assert!(solution.success);
2453 let s = solution.sol(&[1.5]);
2454 (s[3][0].powi(2) + s[4][0].powi(2) + s[5][0].powi(2)).sqrt()
2455 }
2456
2457 fn mba1602_308_inputs() -> BallisticInputs {
2458 BallisticInputs {
2459 muzzle_velocity: 792.48,
2460 bullet_mass: 0.01134,
2461 bullet_diameter: 0.0078232,
2462 bullet_length: 0.031496,
2463 bc_value: 0.505,
2464 bc_type: DragModel::G1,
2465 ..BallisticInputs::default()
2466 }
2467 }
2468
2469 #[test]
2470 fn segmented_fast_path_flies_caller_velocity_bc_ladder() {
2471 let base = mba1602_308_inputs();
2476 let mut ladder = base.clone();
2477 ladder.use_bc_segments = true;
2478 ladder.bc_segments_data = Some(vec![BCSegmentData {
2479 velocity_min: 0.0,
2480 velocity_max: 5000.0,
2481 bc_value: 0.300,
2482 }]);
2483 let scalar = BallisticInputs {
2484 bc_value: 0.300,
2485 ..base.clone()
2486 };
2487 let mut estimated = base.clone();
2488 estimated.use_bc_segments = true;
2489
2490 let flown = segmented_speed_at_1_5_s(&ladder);
2491 let expected = segmented_speed_at_1_5_s(&scalar);
2492 let auto = segmented_speed_at_1_5_s(&estimated);
2493 assert!(
2494 (flown - expected).abs() < 1e-9,
2495 "a one-band 0.300 ladder must fly as scalar BC 0.300: ladder={flown} scalar={expected}"
2496 );
2497 assert!(
2498 (flown - auto).abs() > 10.0,
2499 "the caller's ladder must not be replaced by the auto-estimate: ladder={flown} estimate={auto}"
2500 );
2501 }
2502
2503 #[test]
2504 fn segmented_fast_path_converts_army_standard_metro_caller_ladder() {
2505 let base = mba1602_308_inputs();
2508 let mut ladder = base.clone();
2509 ladder.bc_reference_standard = crate::cli_api::BcReferenceStandard::ArmyStandardMetro;
2510 ladder.use_bc_segments = true;
2511 ladder.bc_segments_data = Some(vec![BCSegmentData {
2512 velocity_min: 0.0,
2513 velocity_max: 5000.0,
2514 bc_value: 0.300,
2515 }]);
2516 let scalar = BallisticInputs {
2517 bc_value: 0.300,
2518 bc_reference_standard: crate::cli_api::BcReferenceStandard::ArmyStandardMetro,
2519 ..base
2520 };
2521 let flown = segmented_speed_at_1_5_s(&ladder);
2522 let expected = segmented_speed_at_1_5_s(&scalar);
2523 assert!(
2524 (flown - expected).abs() < 1e-9,
2525 "an ASM ladder must be converted like an ASM scalar: ladder={flown} scalar={expected}"
2526 );
2527 }
2528
2529 #[test]
2530 fn segmented_fast_path_empty_ladder_matches_absent_ladder() {
2531 let mut absent = mba1602_308_inputs();
2534 absent.use_bc_segments = true;
2535 let mut empty = absent.clone();
2536 empty.bc_segments_data = Some(Vec::new());
2537 assert_eq!(
2538 segmented_speed_at_1_5_s(&empty).to_bits(),
2539 segmented_speed_at_1_5_s(&absent).to_bits(),
2540 "Some(empty) must behave exactly like None"
2541 );
2542 }
2543}