1use crate::{
4 calculate_zero_angle_with_conditions, run_monte_carlo_with_direction_std_dev,
5 AtmosphericConditions, BallisticInputs, DragModel, MonteCarloParams, TrajectorySolver,
6 WindConditions,
7};
8use std::os::raw::{c_char, c_double, c_int};
9use std::ptr;
10
11pub const MIN_FFI_STEP_SIZE_MS: c_double = 0.1;
16
17pub const MAX_FFI_DRAG_TABLE_LEN: c_int = 4096;
25
26#[repr(C)]
29pub struct FFIBallisticInputs {
30 pub muzzle_velocity: c_double, pub muzzle_angle: c_double, pub bc_value: c_double, pub bullet_mass: c_double, pub bullet_diameter: c_double, pub bc_type: c_int, pub sight_height: c_double, pub target_distance: c_double, pub temperature: c_double, pub twist_rate: c_double, pub is_twist_right: c_int, pub shooting_angle: c_double, pub altitude: c_double, pub latitude: c_double, pub azimuth_angle: c_double, pub use_rk4: c_int, pub use_adaptive_rk45: c_int, pub enable_wind_shear: c_int, pub enable_trajectory_sampling: c_int, pub sample_interval: c_double, pub enable_pitch_damping: c_int, pub enable_precession_nutation: c_int, pub enable_spin_drift: c_int, pub enable_magnus: c_int, pub enable_coriolis: c_int, pub shot_azimuth: c_double,
59 pub cant_angle: c_double,
63 pub zero_poi_vertical: c_double,
68 pub zero_poi_horizontal: c_double,
72 pub sight_offset_lateral: c_double,
81 }
87
88#[repr(C)]
89pub struct FFIWindConditions {
90 pub speed: c_double, pub direction: c_double,
99 pub vertical_speed: c_double,
102}
103
104#[repr(C)]
105pub struct FFIAtmosphericConditions {
106 pub temperature: c_double, pub pressure: c_double, pub humidity: c_double, pub altitude: c_double, }
111
112#[repr(C)]
113pub struct FFITrajectorySample {
114 pub distance: c_double, pub time: c_double, pub velocity_mps: c_double, pub energy_joules: c_double, pub drop_meters: c_double, pub windage_meters: c_double, pub mach: c_double, pub spin_rate_rps: c_double, }
123
124#[repr(C)]
151pub struct FFITrajectoryPoint {
152 pub time: c_double,
153 pub position_x: c_double,
155 pub position_y: c_double,
158 pub position_z: c_double,
161 pub velocity_magnitude: c_double,
162 pub kinetic_energy: c_double,
163}
164
165#[repr(C)]
166pub struct FFITrajectoryResult {
167 pub max_range: c_double,
168 pub max_height: c_double,
169 pub time_of_flight: c_double,
170 pub impact_velocity: c_double,
171 pub impact_energy: c_double,
172 pub points: *mut FFITrajectoryPoint,
173 pub point_count: c_int,
174 pub sampled_points: *mut FFITrajectorySample,
175 pub sampled_point_count: c_int,
176 pub min_pitch_damping: c_double, pub transonic_mach: c_double, pub final_pitch_angle: c_double, pub final_yaw_angle: c_double, pub max_yaw_angle: c_double, pub max_precession_angle: c_double, }
183
184#[repr(C)]
186pub struct FFIMonteCarloParams {
187 pub num_simulations: c_int,
188 pub velocity_std_dev: c_double,
189 pub angle_std_dev: c_double,
190 pub bc_std_dev: c_double,
191 pub wind_speed_std_dev: c_double,
192 pub target_distance: c_double, pub base_wind_speed: c_double, pub base_wind_direction: c_double, pub azimuth_std_dev: c_double, }
197
198#[repr(C)]
235pub struct FFIMonteCarloResults {
236 pub ranges: *mut c_double,
237 pub impact_velocities: *mut c_double,
238 pub impact_positions_x: *mut c_double,
241 pub impact_positions_y: *mut c_double,
246 pub impact_positions_z: *mut c_double,
249 pub num_results: c_int,
250 pub mean_range: c_double,
251 pub std_dev_range: c_double,
252 pub mean_impact_velocity: c_double,
253 pub std_dev_impact_velocity: c_double,
254 pub hit_probability: c_double, }
256
257#[allow(clippy::field_reassign_with_default)] fn convert_inputs(inputs: &FFIBallisticInputs) -> BallisticInputs {
260 let mut ballistic_inputs = BallisticInputs::default();
261
262 ballistic_inputs.muzzle_velocity = inputs.muzzle_velocity;
263 ballistic_inputs.muzzle_angle = inputs.muzzle_angle;
264 ballistic_inputs.azimuth_angle = inputs.azimuth_angle;
265 ballistic_inputs.shot_azimuth = inputs.shot_azimuth;
266 ballistic_inputs.cant_angle = inputs.cant_angle;
267 ballistic_inputs.zero_poi_vertical_m = inputs.zero_poi_vertical;
268 ballistic_inputs.zero_poi_horizontal_m = inputs.zero_poi_horizontal;
269 ballistic_inputs.sight_offset_lateral_m = inputs.sight_offset_lateral;
270 ballistic_inputs.use_rk4 = inputs.use_rk4 != 0;
271 ballistic_inputs.use_adaptive_rk45 = inputs.use_adaptive_rk45 != 0;
272 ballistic_inputs.bc_value = inputs.bc_value;
273 ballistic_inputs.bullet_mass = inputs.bullet_mass;
274 ballistic_inputs.bullet_diameter = inputs.bullet_diameter;
275 ballistic_inputs.bc_type = match inputs.bc_type {
276 1 => DragModel::G7,
277 2 => DragModel::G2,
278 3 => DragModel::G5,
279 4 => DragModel::G6,
280 5 => DragModel::G8,
281 6 => DragModel::GI,
282 7 => DragModel::GS,
283 8 => DragModel::RA4,
286 _ => DragModel::G1,
287 };
288 ballistic_inputs.sight_height = inputs.sight_height;
289 ballistic_inputs.target_distance = inputs.target_distance;
290 ballistic_inputs.temperature = inputs.temperature;
291 ballistic_inputs.twist_rate = inputs.twist_rate;
292 ballistic_inputs.is_twist_right = inputs.is_twist_right != 0;
293 ballistic_inputs.shooting_angle = inputs.shooting_angle;
294 ballistic_inputs.altitude = inputs.altitude;
295
296 if !inputs.latitude.is_nan() {
297 ballistic_inputs.latitude = Some(inputs.latitude);
298 }
299
300 ballistic_inputs.caliber_inches = inputs.bullet_diameter / 0.0254;
302 ballistic_inputs.weight_grains = inputs.bullet_mass / crate::constants::GRAINS_TO_KG;
303 ballistic_inputs.bullet_length = {
306 let est = crate::stability::estimate_bullet_length_m(
307 ballistic_inputs.bullet_diameter,
308 ballistic_inputs.bullet_mass,
309 );
310 if est > 0.0 {
311 est
312 } else {
313 ballistic_inputs.bullet_diameter * 4.5
314 }
315 };
316
317 ballistic_inputs.enable_wind_shear = inputs.enable_wind_shear != 0;
319 ballistic_inputs.enable_trajectory_sampling = inputs.enable_trajectory_sampling != 0;
320 ballistic_inputs.sample_interval = inputs.sample_interval;
321 ballistic_inputs.enable_pitch_damping = inputs.enable_pitch_damping != 0;
322 ballistic_inputs.enable_precession_nutation = inputs.enable_precession_nutation != 0;
323 ballistic_inputs.use_enhanced_spin_drift = inputs.enable_spin_drift != 0;
324 ballistic_inputs.enable_advanced_effects =
325 inputs.enable_magnus != 0 || inputs.enable_coriolis != 0;
326 ballistic_inputs.enable_magnus = inputs.enable_magnus != 0;
328 ballistic_inputs.enable_coriolis = inputs.enable_coriolis != 0;
329
330 ballistic_inputs
331}
332
333unsafe fn drag_table_from_raw(
347 mach: *const c_double,
348 cd: *const c_double,
349 len: c_int,
350) -> Result<crate::drag::DragTable, ()> {
351 if mach.is_null() || cd.is_null() || !(2..=MAX_FFI_DRAG_TABLE_LEN).contains(&len) {
352 return Err(());
353 }
354 let len = len as usize;
355 let mach = unsafe { std::slice::from_raw_parts(mach, len) }.to_vec();
356 let cd = unsafe { std::slice::from_raw_parts(cd, len) }.to_vec();
357 crate::drag::DragTable::try_new(mach, cd).map_err(|_| ())
358}
359
360unsafe fn calculate_trajectory_impl(
366 inputs: *const FFIBallisticInputs,
367 wind: *const FFIWindConditions,
368 atmosphere: *const FFIAtmosphericConditions,
369 max_range: c_double,
370 step_size: c_double,
371 custom_drag_table: Option<crate::drag::DragTable>,
372 cd_scale: c_double,
373) -> *mut FFITrajectoryResult {
374 if inputs.is_null() {
375 return ptr::null_mut();
376 }
377 if !step_size.is_finite() || step_size < MIN_FFI_STEP_SIZE_MS {
378 return ptr::null_mut();
379 }
380
381 let inputs = unsafe { &*inputs };
382 let mut ballistic_inputs = convert_inputs(inputs);
383 ballistic_inputs.custom_drag_table = custom_drag_table;
384 ballistic_inputs.cd_scale = cd_scale;
385 let twist_rate_in = ballistic_inputs.twist_rate;
386
387 let wind_conditions = if wind.is_null() {
388 WindConditions::default()
389 } else {
390 let wind = unsafe { &*wind };
391 WindConditions {
392 speed: wind.speed,
393 direction: wind.direction,
394 vertical_speed: wind.vertical_speed,
395 }
396 };
397
398 let atmospheric_conditions = if atmosphere.is_null() {
399 AtmosphericConditions::default()
400 } else {
401 let atmo = unsafe { &*atmosphere };
402 AtmosphericConditions {
403 temperature: atmo.temperature,
404 pressure: atmo.pressure,
405 humidity: atmo.humidity,
406 altitude: atmo.altitude,
407 }
408 };
409
410 let (sample_temp_c, sample_pressure_hpa) = crate::atmosphere::resolve_station_conditions(
412 atmospheric_conditions.temperature,
413 atmospheric_conditions.pressure,
414 atmospheric_conditions.altitude,
415 );
416 let (_, sample_speed_of_sound) = crate::atmosphere::calculate_atmosphere(
417 atmospheric_conditions.altitude,
418 Some(sample_temp_c),
419 Some(sample_pressure_hpa),
420 atmospheric_conditions.humidity,
421 );
422
423 let mut solver =
424 TrajectorySolver::new(ballistic_inputs, wind_conditions, atmospheric_conditions);
425
426 solver.set_max_range(max_range);
428 solver.set_time_step(step_size / 1000.0); match solver.solve() {
431 Ok(result) => {
432 let point_count = result.points.len();
434 let points = if point_count > 0 {
435 let mut ffi_points = Vec::with_capacity(point_count);
436 for point in result.points.iter() {
437 ffi_points.push(FFITrajectoryPoint {
438 time: point.time,
439 position_x: point.position[0],
440 position_y: point.position[1],
441 position_z: point.position[2],
442 velocity_magnitude: point.velocity_magnitude,
443 kinetic_energy: point.kinetic_energy,
444 });
445 }
446 let points_ptr = ffi_points.as_mut_ptr();
447 std::mem::forget(ffi_points); points_ptr
449 } else {
450 ptr::null_mut()
451 };
452
453 let (sampled_points, sampled_point_count) =
455 if let Some(ref samples) = result.sampled_points {
456 let mut ffi_samples = Vec::with_capacity(samples.len());
457 for sample in samples {
458 ffi_samples.push(FFITrajectorySample {
459 distance: sample.distance_m,
460 time: sample.time_s,
461 velocity_mps: sample.velocity_mps,
462 energy_joules: sample.energy_j,
463 drop_meters: sample.drop_m,
464 windage_meters: sample.wind_drift_m,
465 mach: if sample_speed_of_sound > 0.0 {
466 sample.velocity_mps / sample_speed_of_sound
467 } else {
468 0.0
469 },
470 spin_rate_rps: if twist_rate_in > 0.0 {
471 sample.velocity_mps / (twist_rate_in * 0.0254)
472 } else {
473 0.0
474 },
475 });
476 }
477 let count = ffi_samples.len() as c_int;
478 let samples_ptr = ffi_samples.as_mut_ptr();
479 std::mem::forget(ffi_samples);
480 (samples_ptr, count)
481 } else {
482 (ptr::null_mut(), 0)
483 };
484
485 let (final_pitch, final_yaw, max_yaw, max_prec) =
487 if let Some(ref angular) = result.angular_state {
488 (
489 angular.pitch_angle,
490 angular.yaw_angle,
491 result.max_yaw_angle.unwrap_or(f64::NAN),
492 result.max_precession_angle.unwrap_or(f64::NAN),
493 )
494 } else {
495 (f64::NAN, f64::NAN, f64::NAN, f64::NAN)
496 };
497
498 let ffi_result = Box::new(FFITrajectoryResult {
500 max_range: result.max_range,
501 max_height: result.max_height,
502 time_of_flight: result.time_of_flight,
503 impact_velocity: result.impact_velocity,
504 impact_energy: result.impact_energy,
505 points,
506 point_count: point_count as c_int,
507 sampled_points,
508 sampled_point_count,
509 min_pitch_damping: result.min_pitch_damping.unwrap_or(f64::NAN),
510 transonic_mach: result.transonic_mach.unwrap_or(f64::NAN),
511 final_pitch_angle: final_pitch,
512 final_yaw_angle: final_yaw,
513 max_yaw_angle: max_yaw,
514 max_precession_angle: max_prec,
515 });
516
517 Box::into_raw(ffi_result)
518 }
519 Err(_) => ptr::null_mut(),
520 }
521}
522
523#[no_mangle]
542pub unsafe extern "C" fn ballistics_calculate_trajectory(
543 inputs: *const FFIBallisticInputs,
544 wind: *const FFIWindConditions,
545 atmosphere: *const FFIAtmosphericConditions,
546 max_range: c_double,
547 step_size: c_double,
548) -> *mut FFITrajectoryResult {
549 unsafe { calculate_trajectory_impl(inputs, wind, atmosphere, max_range, step_size, None, 1.0) }
550}
551
552#[no_mangle]
573pub unsafe extern "C" fn ballistics_calculate_trajectory_with_drag_table(
574 inputs: *const FFIBallisticInputs,
575 wind: *const FFIWindConditions,
576 atmosphere: *const FFIAtmosphericConditions,
577 max_range: c_double,
578 step_size: c_double,
579 drag_mach: *const c_double,
580 drag_cd: *const c_double,
581 drag_table_len: c_int,
582) -> *mut FFITrajectoryResult {
583 let table = match unsafe { drag_table_from_raw(drag_mach, drag_cd, drag_table_len) } {
584 Ok(t) => t,
585 Err(()) => return ptr::null_mut(),
586 };
587 unsafe {
588 calculate_trajectory_impl(
589 inputs, wind, atmosphere, max_range, step_size, Some(table), 1.0,
590 )
591 }
592}
593
594#[no_mangle]
611pub unsafe extern "C" fn ballistics_calculate_trajectory_with_drag_table_scaled(
612 inputs: *const FFIBallisticInputs,
613 wind: *const FFIWindConditions,
614 atmosphere: *const FFIAtmosphericConditions,
615 max_range: c_double,
616 step_size: c_double,
617 drag_mach: *const c_double,
618 drag_cd: *const c_double,
619 drag_table_len: c_int,
620 cd_scale: c_double,
621) -> *mut FFITrajectoryResult {
622 if !cd_scale.is_finite() || cd_scale <= 0.0 {
623 return ptr::null_mut();
624 }
625 let table = match unsafe { drag_table_from_raw(drag_mach, drag_cd, drag_table_len) } {
626 Ok(t) => t,
627 Err(()) => return ptr::null_mut(),
628 };
629 unsafe {
630 calculate_trajectory_impl(
631 inputs, wind, atmosphere, max_range, step_size, Some(table), cd_scale,
632 )
633 }
634}
635
636#[no_mangle]
645pub unsafe extern "C" fn ballistics_free_trajectory_result(result: *mut FFITrajectoryResult) {
646 if !result.is_null() {
647 unsafe {
648 let result = Box::from_raw(result);
649 if !result.points.is_null() && result.point_count > 0 {
650 let points = Vec::from_raw_parts(
651 result.points,
652 result.point_count as usize,
653 result.point_count as usize,
654 );
655 drop(points);
656 }
657 if !result.sampled_points.is_null() && result.sampled_point_count > 0 {
658 let samples = Vec::from_raw_parts(
659 result.sampled_points,
660 result.sampled_point_count as usize,
661 result.sampled_point_count as usize,
662 );
663 drop(samples);
664 }
665 drop(result);
666 }
667 }
668}
669
670unsafe fn calculate_zero_angle_impl(
677 inputs: *const FFIBallisticInputs,
678 wind: *const FFIWindConditions,
679 atmosphere: *const FFIAtmosphericConditions,
680 zero_distance: c_double,
681 custom_drag_table: Option<crate::drag::DragTable>,
682 cd_scale: c_double,
683) -> c_double {
684 if inputs.is_null() {
685 return f64::NAN;
686 }
687
688 let inputs = unsafe { &*inputs };
689 let mut ballistic_inputs = convert_inputs(inputs);
690 ballistic_inputs.custom_drag_table = custom_drag_table;
691 ballistic_inputs.cd_scale = cd_scale;
692
693 let wind_conditions = if wind.is_null() {
694 WindConditions::default()
695 } else {
696 let wind = unsafe { &*wind };
697 WindConditions {
698 speed: wind.speed,
699 direction: wind.direction,
700 vertical_speed: wind.vertical_speed,
701 }
702 };
703
704 let atmospheric_conditions = if atmosphere.is_null() {
705 AtmosphericConditions::default()
706 } else {
707 let atmo = unsafe { &*atmosphere };
708 AtmosphericConditions {
709 temperature: atmo.temperature,
710 pressure: atmo.pressure,
711 humidity: atmo.humidity,
712 altitude: atmo.altitude,
713 }
714 };
715
716 let target_height = ballistic_inputs.sight_height;
719
720 calculate_zero_angle_with_conditions(
721 ballistic_inputs,
722 zero_distance,
723 target_height,
724 wind_conditions,
725 atmospheric_conditions,
726 )
727 .unwrap_or(f64::NAN)
728}
729
730#[no_mangle]
740pub unsafe extern "C" fn ballistics_calculate_zero_angle(
741 inputs: *const FFIBallisticInputs,
742 wind: *const FFIWindConditions,
743 atmosphere: *const FFIAtmosphericConditions,
744 zero_distance: c_double,
745) -> c_double {
746 unsafe { calculate_zero_angle_impl(inputs, wind, atmosphere, zero_distance, None, 1.0) }
747}
748
749#[no_mangle]
771pub unsafe extern "C" fn ballistics_calculate_zero_angle_with_drag_table(
772 inputs: *const FFIBallisticInputs,
773 wind: *const FFIWindConditions,
774 atmosphere: *const FFIAtmosphericConditions,
775 zero_distance: c_double,
776 drag_mach: *const c_double,
777 drag_cd: *const c_double,
778 drag_table_len: c_int,
779) -> c_double {
780 let table = match unsafe { drag_table_from_raw(drag_mach, drag_cd, drag_table_len) } {
781 Ok(t) => t,
782 Err(()) => return f64::NAN,
783 };
784 unsafe {
785 calculate_zero_angle_impl(inputs, wind, atmosphere, zero_distance, Some(table), 1.0)
786 }
787}
788
789#[no_mangle]
807pub unsafe extern "C" fn ballistics_calculate_zero_angle_with_drag_table_scaled(
808 inputs: *const FFIBallisticInputs,
809 wind: *const FFIWindConditions,
810 atmosphere: *const FFIAtmosphericConditions,
811 zero_distance: c_double,
812 drag_mach: *const c_double,
813 drag_cd: *const c_double,
814 drag_table_len: c_int,
815 cd_scale: c_double,
816) -> c_double {
817 if !cd_scale.is_finite() || cd_scale <= 0.0 {
818 return f64::NAN;
819 }
820 let table = match unsafe { drag_table_from_raw(drag_mach, drag_cd, drag_table_len) } {
821 Ok(t) => t,
822 Err(()) => return f64::NAN,
823 };
824 unsafe {
825 calculate_zero_angle_impl(
826 inputs,
827 wind,
828 atmosphere,
829 zero_distance,
830 Some(table),
831 cd_scale,
832 )
833 }
834}
835
836#[no_mangle]
838#[allow(clippy::field_reassign_with_default)] pub extern "C" fn ballistics_quick_trajectory(
840 muzzle_velocity: c_double,
841 bc: c_double,
842 sight_height: c_double,
843 zero_distance: c_double,
844 target_distance: c_double,
845) -> c_double {
846 let mut inputs = BallisticInputs::default();
850 inputs.muzzle_velocity = muzzle_velocity;
851 inputs.bc_value = bc;
852 inputs.sight_height = sight_height;
853 inputs.target_distance = target_distance;
854
855 let wind = WindConditions::default();
856 let atmo = AtmosphericConditions::default();
857
858 let zero_angle = match calculate_zero_angle_with_conditions(
860 inputs.clone(),
861 zero_distance,
862 sight_height,
863 wind.clone(),
864 atmo.clone(),
865 ) {
866 Ok(angle) => angle,
867 Err(_) => return f64::NAN,
868 };
869
870 inputs.muzzle_angle = zero_angle;
872
873 let mut solver = TrajectorySolver::new(inputs, wind, atmo);
874 solver.set_max_range(target_distance * 1.1);
875
876 match solver.solve() {
877 Ok(result) => {
878 for point in result.points {
880 if point.position[0] >= target_distance {
881 return sight_height - point.position[1];
882 }
883 }
884 f64::NAN
885 }
886 Err(_) => f64::NAN,
887 }
888}
889
890#[no_mangle]
902pub unsafe extern "C" fn ballistics_monte_carlo(
903 inputs: *const FFIBallisticInputs,
904 atmosphere: *const FFIAtmosphericConditions,
905 params: *const FFIMonteCarloParams,
906) -> *mut FFIMonteCarloResults {
907 unsafe { ballistics_monte_carlo_impl(inputs, atmosphere, params, 0.0) }
908}
909
910#[no_mangle]
920pub unsafe extern "C" fn ballistics_monte_carlo_with_direction_std_dev(
921 inputs: *const FFIBallisticInputs,
922 atmosphere: *const FFIAtmosphericConditions,
923 params: *const FFIMonteCarloParams,
924 wind_direction_std_dev: c_double,
925) -> *mut FFIMonteCarloResults {
926 unsafe { ballistics_monte_carlo_impl(inputs, atmosphere, params, wind_direction_std_dev) }
927}
928
929unsafe fn ballistics_monte_carlo_impl(
930 inputs: *const FFIBallisticInputs,
931 atmosphere: *const FFIAtmosphericConditions,
932 params: *const FFIMonteCarloParams,
933 wind_direction_std_dev: f64,
934) -> *mut FFIMonteCarloResults {
935 if inputs.is_null() || params.is_null() {
936 return ptr::null_mut();
937 }
938
939 let inputs = unsafe { &*inputs };
940 let params = unsafe { &*params };
941
942 const MAX_SIMULATIONS: c_int = 1_000_000;
948 if params.num_simulations <= 0 || params.num_simulations > MAX_SIMULATIONS {
949 return ptr::null_mut();
950 }
951
952 let mut ballistic_inputs = convert_inputs(inputs);
954 ballistic_inputs.muzzle_height = 1.5;
955 ballistic_inputs.ground_threshold = 0.0;
956 if !atmosphere.is_null() {
957 let atmo = unsafe { &*atmosphere };
958 ballistic_inputs.temperature = atmo.temperature;
959 ballistic_inputs.pressure = atmo.pressure;
960 ballistic_inputs.humidity = (atmo.humidity / 100.0).clamp(0.0, 1.0);
961 ballistic_inputs.altitude = atmo.altitude;
962 }
963
964 let mc_params = MonteCarloParams {
966 num_simulations: params.num_simulations as usize,
967 velocity_std_dev: params.velocity_std_dev,
968 angle_std_dev: params.angle_std_dev,
969 bc_std_dev: params.bc_std_dev,
970 wind_speed_std_dev: params.wind_speed_std_dev,
971 target_distance: if params.target_distance.is_nan() {
972 None
973 } else {
974 Some(params.target_distance)
975 },
976 base_wind_speed: params.base_wind_speed,
977 base_wind_direction: params.base_wind_direction,
978 azimuth_std_dev: params.azimuth_std_dev,
979 };
980
981 match run_monte_carlo_with_direction_std_dev(
983 ballistic_inputs,
984 mc_params,
985 wind_direction_std_dev,
986 ) {
987 Ok(results) => {
988 let num_results = results.ranges.len() as c_int;
989
990 let mean_range: f64 = results.ranges.iter().sum::<f64>() / num_results as f64;
992 let variance_range: f64 = results
993 .ranges
994 .iter()
995 .map(|r| (r - mean_range).powi(2))
996 .sum::<f64>()
997 / num_results as f64;
998 let std_dev_range = variance_range.sqrt();
999
1000 let mean_velocity: f64 =
1001 results.impact_velocities.iter().sum::<f64>() / num_results as f64;
1002 let variance_velocity: f64 = results
1003 .impact_velocities
1004 .iter()
1005 .map(|v| (v - mean_velocity).powi(2))
1006 .sum::<f64>()
1007 / num_results as f64;
1008 let std_dev_velocity = variance_velocity.sqrt();
1009
1010 let hit_probability = if params.target_distance.is_nan() {
1016 0.0
1017 } else {
1018 results.hit_probability(crate::DEFAULT_HIT_RADIUS_M)
1019 };
1020
1021 let ranges_ptr = unsafe {
1023 let ptr = std::alloc::alloc(
1024 std::alloc::Layout::array::<c_double>(num_results as usize).unwrap(),
1025 ) as *mut c_double;
1026 for (i, &range) in results.ranges.iter().enumerate() {
1027 *ptr.add(i) = range;
1028 }
1029 ptr
1030 };
1031
1032 let velocities_ptr = unsafe {
1033 let ptr = std::alloc::alloc(
1034 std::alloc::Layout::array::<c_double>(num_results as usize).unwrap(),
1035 ) as *mut c_double;
1036 for (i, &vel) in results.impact_velocities.iter().enumerate() {
1037 *ptr.add(i) = vel;
1038 }
1039 ptr
1040 };
1041
1042 let pos_x_ptr = unsafe {
1043 let ptr = std::alloc::alloc(
1044 std::alloc::Layout::array::<c_double>(num_results as usize).unwrap(),
1045 ) as *mut c_double;
1046 for (i, pos) in results.impact_positions.iter().enumerate() {
1047 *ptr.add(i) = pos.x;
1048 }
1049 ptr
1050 };
1051
1052 let pos_y_ptr = unsafe {
1053 let ptr = std::alloc::alloc(
1054 std::alloc::Layout::array::<c_double>(num_results as usize).unwrap(),
1055 ) as *mut c_double;
1056 for (i, pos) in results.impact_positions.iter().enumerate() {
1057 *ptr.add(i) = pos.y;
1058 }
1059 ptr
1060 };
1061
1062 let pos_z_ptr = unsafe {
1063 let ptr = std::alloc::alloc(
1064 std::alloc::Layout::array::<c_double>(num_results as usize).unwrap(),
1065 ) as *mut c_double;
1066 for (i, pos) in results.impact_positions.iter().enumerate() {
1067 *ptr.add(i) = pos.z;
1068 }
1069 ptr
1070 };
1071
1072 let result = Box::new(FFIMonteCarloResults {
1074 ranges: ranges_ptr,
1075 impact_velocities: velocities_ptr,
1076 impact_positions_x: pos_x_ptr,
1077 impact_positions_y: pos_y_ptr,
1078 impact_positions_z: pos_z_ptr,
1079 num_results,
1080 mean_range,
1081 std_dev_range,
1082 mean_impact_velocity: mean_velocity,
1083 std_dev_impact_velocity: std_dev_velocity,
1084 hit_probability,
1085 });
1086
1087 Box::into_raw(result)
1088 }
1089 Err(_) => ptr::null_mut(),
1090 }
1091}
1092
1093#[no_mangle]
1102pub unsafe extern "C" fn ballistics_free_monte_carlo_results(results: *mut FFIMonteCarloResults) {
1103 if results.is_null() {
1104 return;
1105 }
1106
1107 unsafe {
1108 let results = Box::from_raw(results);
1109 let num = results.num_results as usize;
1110
1111 if !results.ranges.is_null() {
1113 std::alloc::dealloc(
1114 results.ranges as *mut u8,
1115 std::alloc::Layout::array::<c_double>(num).unwrap(),
1116 );
1117 }
1118
1119 if !results.impact_velocities.is_null() {
1120 std::alloc::dealloc(
1121 results.impact_velocities as *mut u8,
1122 std::alloc::Layout::array::<c_double>(num).unwrap(),
1123 );
1124 }
1125
1126 if !results.impact_positions_x.is_null() {
1127 std::alloc::dealloc(
1128 results.impact_positions_x as *mut u8,
1129 std::alloc::Layout::array::<c_double>(num).unwrap(),
1130 );
1131 }
1132
1133 if !results.impact_positions_y.is_null() {
1134 std::alloc::dealloc(
1135 results.impact_positions_y as *mut u8,
1136 std::alloc::Layout::array::<c_double>(num).unwrap(),
1137 );
1138 }
1139
1140 if !results.impact_positions_z.is_null() {
1141 std::alloc::dealloc(
1142 results.impact_positions_z as *mut u8,
1143 std::alloc::Layout::array::<c_double>(num).unwrap(),
1144 );
1145 }
1146
1147 }
1149}
1150
1151pub const FFI_BC_REFERENCE_ICAO: c_int = 0;
1157pub const FFI_BC_REFERENCE_ARMY_STANDARD_METRO: c_int = 1;
1158
1159#[no_mangle]
1178pub extern "C" fn ballistics_bc_for_reference_standard(
1179 bc: c_double,
1180 reference_standard: c_int,
1181) -> c_double {
1182 if reference_standard == FFI_BC_REFERENCE_ARMY_STANDARD_METRO {
1183 bc * crate::constants::ASM_TO_ICAO_BC
1184 } else {
1185 bc
1186 }
1187}
1188
1189#[no_mangle]
1207pub extern "C" fn ballistics_reduce_qnh_pressure(
1208 qnh_hpa: c_double,
1209 altitude_m: c_double,
1210) -> c_double {
1211 if !qnh_hpa.is_finite() || !altitude_m.is_finite() {
1212 return qnh_hpa;
1213 }
1214 crate::atmosphere::reduce_qnh_to_station_pressure(qnh_hpa, altitude_m)
1215}
1216
1217pub const FFI_NO_EXPLICIT_TEMPERATURE: c_double = f64::NAN;
1222
1223#[no_mangle]
1243pub extern "C" fn ballistics_density_altitude_temperature_c(
1244 density_altitude_m: c_double,
1245 explicit_temperature_c: c_double,
1246) -> c_double {
1247 if !density_altitude_m.is_finite() {
1248 return f64::NAN;
1249 }
1250 let explicit = (!explicit_temperature_c.is_nan()).then_some(explicit_temperature_c);
1251 crate::atmosphere::resolve_atmosphere_for_density_altitude(density_altitude_m, explicit).1
1252}
1253
1254#[no_mangle]
1257pub extern "C" fn ballistics_density_altitude_pressure_hpa(
1258 density_altitude_m: c_double,
1259 explicit_temperature_c: c_double,
1260) -> c_double {
1261 if !density_altitude_m.is_finite() {
1262 return f64::NAN;
1263 }
1264 let explicit = (!explicit_temperature_c.is_nan()).then_some(explicit_temperature_c);
1265 crate::atmosphere::resolve_atmosphere_for_density_altitude(density_altitude_m, explicit).2
1266}
1267
1268#[no_mangle]
1273pub extern "C" fn ballistics_density_altitude_altitude_m(
1274 density_altitude_m: c_double,
1275 explicit_temperature_c: c_double,
1276) -> c_double {
1277 if !density_altitude_m.is_finite() {
1278 return f64::NAN;
1279 }
1280 let explicit = (!explicit_temperature_c.is_nan()).then_some(explicit_temperature_c);
1281 crate::atmosphere::resolve_atmosphere_for_density_altitude(density_altitude_m, explicit).0
1282}
1283
1284pub const MAX_FFI_RETICLE_MARKS: c_int = crate::reticle::MAX_RETICLE_MARKS as c_int;
1292
1293pub const FFI_RETICLE_FIRST_FOCAL_PLANE: c_int = 0;
1296pub const FFI_RETICLE_SECOND_FOCAL_PLANE: c_int = 1;
1299
1300pub const FFI_RETICLE_OK: c_int = 0;
1302pub const FFI_RETICLE_ERR_INVALID_ARGUMENT: c_int = -1;
1304pub const FFI_RETICLE_ERR_MAGNIFICATION: c_int = -2;
1306pub const FFI_RETICLE_ERR_REFERENCE_MAGNIFICATION: c_int = -3;
1308pub const FFI_RETICLE_ERR_NON_FINITE: c_int = -4;
1310
1311#[repr(C)]
1318pub struct FFIReticleHold {
1319 pub down_mil: c_double,
1321 pub right_mil: c_double,
1323 pub nearest_mark: c_int,
1326 pub nearest_mark_distance_mil: c_double,
1329 pub off_reticle: c_int,
1332 pub mark_scale: c_double,
1335}
1336
1337#[no_mangle]
1356pub unsafe extern "C" fn ballistics_hold_point_in_reticle(
1357 drop_mil: c_double,
1358 wind_mil: c_double,
1359 magnification: c_double,
1360 marks: *const c_double,
1361 marks_len: c_int,
1362 focal_plane: c_int,
1363 reference_magnification: c_double,
1364 out: *mut FFIReticleHold,
1365) -> c_int {
1366 use crate::reticle::{
1367 hold_point_in_reticle, FocalPlane, MarkKind, ReticleDescription, ReticleError, ReticleMark,
1368 };
1369
1370 if marks.is_null() || out.is_null() || !(1..=MAX_FFI_RETICLE_MARKS).contains(&marks_len) {
1371 return FFI_RETICLE_ERR_INVALID_ARGUMENT;
1372 }
1373 let count = marks_len as usize;
1374 let flat = unsafe { std::slice::from_raw_parts(marks, count * 2) };
1376
1377 let description = ReticleDescription {
1378 name: String::new(),
1379 focal_plane: if focal_plane == FFI_RETICLE_SECOND_FOCAL_PLANE {
1380 FocalPlane::Second
1381 } else {
1382 FocalPlane::First
1383 },
1384 reference_magnification,
1385 marks: flat
1386 .chunks_exact(2)
1387 .map(|pair| ReticleMark::new(pair[0], pair[1], MarkKind::Dot))
1388 .collect(),
1389 };
1390
1391 let hold = match hold_point_in_reticle(drop_mil, wind_mil, magnification, &description) {
1392 Ok(hold) => hold,
1393 Err(ReticleError::NonPositiveMagnification { .. }) => return FFI_RETICLE_ERR_MAGNIFICATION,
1394 Err(ReticleError::NonPositiveReferenceMagnification { .. }) => {
1395 return FFI_RETICLE_ERR_REFERENCE_MAGNIFICATION
1396 }
1397 Err(ReticleError::NonFiniteMark { .. }) | Err(ReticleError::NonFiniteHold { .. }) => {
1398 return FFI_RETICLE_ERR_NON_FINITE
1399 }
1400 Err(_) => return FFI_RETICLE_ERR_INVALID_ARGUMENT,
1401 };
1402
1403 unsafe {
1404 *out = FFIReticleHold {
1405 down_mil: hold.down_mil,
1406 right_mil: hold.right_mil,
1407 nearest_mark: hold.nearest_mark.map_or(-1, |index| index as c_int),
1408 nearest_mark_distance_mil: hold.nearest_mark_distance_mil,
1409 off_reticle: c_int::from(hold.off_reticle),
1410 mark_scale: hold.mark_scale,
1411 };
1412 }
1413 FFI_RETICLE_OK
1414}
1415
1416#[no_mangle]
1418pub extern "C" fn ballistics_get_version() -> *const c_char {
1419 concat!(env!("CARGO_PKG_VERSION"), "\0").as_ptr() as *const c_char
1423}
1424
1425#[cfg(test)]
1426mod tests {
1427 use super::*;
1428
1429 fn valid_trajectory_inputs() -> FFIBallisticInputs {
1430 FFIBallisticInputs {
1431 muzzle_velocity: 800.0,
1432 muzzle_angle: 0.0,
1433 bc_value: 0.5,
1434 bullet_mass: 0.01,
1435 bullet_diameter: 0.00762,
1436 bc_type: 0,
1437 sight_height: 0.05,
1438 target_distance: 1.0,
1439 temperature: 15.0,
1440 twist_rate: 12.0,
1441 is_twist_right: 1,
1442 shooting_angle: 0.0,
1443 altitude: 0.0,
1444 latitude: f64::NAN,
1445 azimuth_angle: 0.0,
1446 use_rk4: 1,
1447 use_adaptive_rk45: 0,
1448 enable_wind_shear: 0,
1449 enable_trajectory_sampling: 0,
1450 sample_interval: 10.0,
1451 enable_pitch_damping: 0,
1452 enable_precession_nutation: 0,
1453 enable_spin_drift: 0,
1454 enable_magnus: 0,
1455 enable_coriolis: 0,
1456 shot_azimuth: 0.0,
1457 cant_angle: 0.0,
1458 zero_poi_vertical: 0.0,
1459 zero_poi_horizontal: 0.0,
1460 sight_offset_lateral: 0.0,
1461 }
1462 }
1463
1464 #[allow(dead_code)]
1465 #[repr(C)]
1466 struct LegacyFFIMonteCarloParams {
1467 num_simulations: c_int,
1468 velocity_std_dev: c_double,
1469 angle_std_dev: c_double,
1470 bc_std_dev: c_double,
1471 wind_speed_std_dev: c_double,
1472 target_distance: c_double,
1473 base_wind_speed: c_double,
1474 base_wind_direction: c_double,
1475 azimuth_std_dev: c_double,
1476 }
1477
1478 #[test]
1479 fn monte_carlo_params_legacy_abi_size_is_unchanged() {
1480 assert_eq!(
1481 std::mem::size_of::<FFIMonteCarloParams>(),
1482 std::mem::size_of::<LegacyFFIMonteCarloParams>()
1483 );
1484 assert_eq!(
1485 std::mem::align_of::<FFIMonteCarloParams>(),
1486 std::mem::align_of::<LegacyFFIMonteCarloParams>()
1487 );
1488 }
1489
1490 #[test]
1493 fn reticle_addition_does_not_disturb_existing_layouts() {
1494 assert_eq!(
1495 std::mem::size_of::<FFIMonteCarloParams>(),
1496 std::mem::size_of::<LegacyFFIMonteCarloParams>()
1497 );
1498 assert_eq!(std::mem::align_of::<FFIReticleHold>(), 8);
1500 }
1501
1502 fn zeroed_hold() -> FFIReticleHold {
1503 FFIReticleHold {
1504 down_mil: 0.0,
1505 right_mil: 0.0,
1506 nearest_mark: -99,
1507 nearest_mark_distance_mil: -1.0,
1508 off_reticle: -1,
1509 mark_scale: -1.0,
1510 }
1511 }
1512
1513 #[test]
1514 fn ffi_hold_point_matches_the_rust_api_on_both_focal_planes() {
1515 let marks: [c_double; 8] = [0.0, 0.0, 2.0, 0.0, 4.0, 0.0, 2.0, 1.0];
1517 let mut out = zeroed_hold();
1518
1519 let code = unsafe {
1521 ballistics_hold_point_in_reticle(
1522 4.0,
1523 0.0,
1524 6.0,
1525 marks.as_ptr(),
1526 4,
1527 FFI_RETICLE_FIRST_FOCAL_PLANE,
1528 0.0,
1529 &mut out,
1530 )
1531 };
1532 assert_eq!(code, FFI_RETICLE_OK);
1533 assert_eq!(out.down_mil, 4.0);
1534 assert_eq!(out.nearest_mark, 2);
1535 assert_eq!(out.nearest_mark_distance_mil, 0.0);
1536 assert_eq!(out.mark_scale, 1.0);
1537 assert_eq!(out.off_reticle, 0);
1538
1539 let mut out = zeroed_hold();
1541 let code = unsafe {
1542 ballistics_hold_point_in_reticle(
1543 4.0,
1544 0.0,
1545 5.0,
1546 marks.as_ptr(),
1547 4,
1548 FFI_RETICLE_SECOND_FOCAL_PLANE,
1549 10.0,
1550 &mut out,
1551 )
1552 };
1553 assert_eq!(code, FFI_RETICLE_OK);
1554 assert_eq!(out.nearest_mark, 1);
1555 assert_eq!(out.nearest_mark_distance_mil, 0.0);
1556 assert_eq!(out.mark_scale, 2.0);
1557 }
1558
1559 #[test]
1562 fn ffi_hold_point_bounds_check_marks_len_before_reading() {
1563 let marks: [c_double; 4] = [0.0, 0.0, 2.0, 0.0];
1564 let mut out = zeroed_hold();
1565 let call = |len: c_int, ptr: *const c_double, out: &mut FFIReticleHold| unsafe {
1566 ballistics_hold_point_in_reticle(
1567 1.0,
1568 0.0,
1569 10.0,
1570 ptr,
1571 len,
1572 FFI_RETICLE_FIRST_FOCAL_PLANE,
1573 0.0,
1574 out,
1575 )
1576 };
1577
1578 assert_eq!(call(0, marks.as_ptr(), &mut out), FFI_RETICLE_ERR_INVALID_ARGUMENT);
1579 assert_eq!(call(-1, marks.as_ptr(), &mut out), FFI_RETICLE_ERR_INVALID_ARGUMENT);
1580 assert_eq!(
1581 call(MAX_FFI_RETICLE_MARKS + 1, marks.as_ptr(), &mut out),
1582 FFI_RETICLE_ERR_INVALID_ARGUMENT
1583 );
1584 assert_eq!(call(c_int::MAX, marks.as_ptr(), &mut out), FFI_RETICLE_ERR_INVALID_ARGUMENT);
1585 assert_eq!(call(2, std::ptr::null(), &mut out), FFI_RETICLE_ERR_INVALID_ARGUMENT);
1586 assert_eq!(out.nearest_mark, -99);
1588
1589 assert_eq!(
1591 unsafe {
1592 ballistics_hold_point_in_reticle(
1593 1.0,
1594 0.0,
1595 10.0,
1596 marks.as_ptr(),
1597 2,
1598 FFI_RETICLE_FIRST_FOCAL_PLANE,
1599 0.0,
1600 std::ptr::null_mut(),
1601 )
1602 },
1603 FFI_RETICLE_ERR_INVALID_ARGUMENT
1604 );
1605 }
1606
1607 #[test]
1608 fn ffi_hold_point_maps_each_error_class_to_its_own_code() {
1609 let marks: [c_double; 4] = [0.0, 0.0, 2.0, 0.0];
1610 let bad_marks: [c_double; 4] = [0.0, 0.0, f64::NAN, 0.0];
1611 let mut out = zeroed_hold();
1612 let call = |drop: c_double, mag: c_double, plane: c_int, ref_mag: c_double,
1613 m: &[c_double], out: &mut FFIReticleHold| unsafe {
1614 ballistics_hold_point_in_reticle(
1615 drop,
1616 0.0,
1617 mag,
1618 m.as_ptr(),
1619 (m.len() / 2) as c_int,
1620 plane,
1621 ref_mag,
1622 out,
1623 )
1624 };
1625
1626 assert_eq!(
1627 call(1.0, 0.0, FFI_RETICLE_FIRST_FOCAL_PLANE, 0.0, &marks, &mut out),
1628 FFI_RETICLE_ERR_MAGNIFICATION
1629 );
1630 assert_eq!(
1631 call(1.0, 10.0, FFI_RETICLE_SECOND_FOCAL_PLANE, 0.0, &marks, &mut out),
1632 FFI_RETICLE_ERR_REFERENCE_MAGNIFICATION
1633 );
1634 assert_eq!(
1635 call(f64::NAN, 10.0, FFI_RETICLE_FIRST_FOCAL_PLANE, 0.0, &marks, &mut out),
1636 FFI_RETICLE_ERR_NON_FINITE
1637 );
1638 assert_eq!(
1639 call(1.0, 10.0, FFI_RETICLE_FIRST_FOCAL_PLANE, 0.0, &bad_marks, &mut out),
1640 FFI_RETICLE_ERR_NON_FINITE
1641 );
1642 assert_eq!(out.nearest_mark, -99, "out stays untouched on every error");
1643 }
1644
1645 #[test]
1650 fn bc_type_8_maps_to_ra4() {
1651 let mut inputs = valid_trajectory_inputs();
1652 inputs.bc_type = 8;
1653 assert_eq!(convert_inputs(&inputs).bc_type, DragModel::RA4);
1654
1655 let expected = [
1657 (0, DragModel::G1),
1658 (1, DragModel::G7),
1659 (2, DragModel::G2),
1660 (3, DragModel::G5),
1661 (4, DragModel::G6),
1662 (5, DragModel::G8),
1663 (6, DragModel::GI),
1664 (7, DragModel::GS),
1665 ];
1666 for (code, model) in expected {
1667 let mut inputs = valid_trajectory_inputs();
1668 inputs.bc_type = code;
1669 assert_eq!(convert_inputs(&inputs).bc_type, model, "code {code}");
1670 }
1671
1672 for code in [9, 42, -1] {
1674 let mut inputs = valid_trajectory_inputs();
1675 inputs.bc_type = code;
1676 assert_eq!(convert_inputs(&inputs).bc_type, DragModel::G1, "code {code}");
1677 }
1678 }
1679
1680 #[test]
1681 fn null_pointer_contracts_return_sentinels_and_free_safely() {
1682 unsafe {
1683 assert!(ballistics_calculate_trajectory(
1684 std::ptr::null(),
1685 std::ptr::null(),
1686 std::ptr::null(),
1687 1_000.0,
1688 1.0,
1689 )
1690 .is_null());
1691 assert!(ballistics_calculate_zero_angle(
1692 std::ptr::null(),
1693 std::ptr::null(),
1694 std::ptr::null(),
1695 100.0,
1696 )
1697 .is_nan());
1698 assert!(ballistics_calculate_trajectory_with_drag_table(
1699 std::ptr::null(),
1700 std::ptr::null(),
1701 std::ptr::null(),
1702 1_000.0,
1703 1.0,
1704 DECK_MACH.as_ptr(),
1705 DECK_CD_LOW.as_ptr(),
1706 DECK_MACH.len() as c_int,
1707 )
1708 .is_null());
1709 assert!(ballistics_calculate_zero_angle_with_drag_table(
1710 std::ptr::null(),
1711 std::ptr::null(),
1712 std::ptr::null(),
1713 100.0,
1714 DECK_MACH.as_ptr(),
1715 DECK_CD_LOW.as_ptr(),
1716 DECK_MACH.len() as c_int,
1717 )
1718 .is_nan());
1719 assert!(
1720 ballistics_monte_carlo(std::ptr::null(), std::ptr::null(), std::ptr::null(),)
1721 .is_null()
1722 );
1723 assert!(ballistics_monte_carlo_with_direction_std_dev(
1724 std::ptr::null(),
1725 std::ptr::null(),
1726 std::ptr::null(),
1727 0.1,
1728 )
1729 .is_null());
1730
1731 ballistics_free_trajectory_result(std::ptr::null_mut());
1732 ballistics_free_monte_carlo_results(std::ptr::null_mut());
1733 }
1734 }
1735
1736 #[test]
1737 fn mba1283_ffi_enforces_step_floor_for_every_solver_mode() {
1738 for (mode, use_rk4, use_adaptive_rk45) in [("Euler", 0, 0), ("RK4", 1, 0), ("RK45", 1, 1)] {
1739 for step_size in [
1740 f64::NAN,
1741 f64::INFINITY,
1742 f64::NEG_INFINITY,
1743 -1.0,
1744 -0.0,
1745 0.0,
1746 0.001,
1747 MIN_FFI_STEP_SIZE_MS - 0.001,
1748 ] {
1749 let mut inputs = valid_trajectory_inputs();
1750 inputs.use_rk4 = use_rk4;
1751 inputs.use_adaptive_rk45 = use_adaptive_rk45;
1752 let result = unsafe {
1753 ballistics_calculate_trajectory(
1754 &inputs,
1755 std::ptr::null(),
1756 std::ptr::null(),
1757 0.01,
1758 step_size,
1759 )
1760 };
1761 assert!(
1762 result.is_null(),
1763 "{mode} step_size={step_size:?} bypassed the FFI floor"
1764 );
1765 }
1766
1767 let mut inputs = valid_trajectory_inputs();
1768 inputs.use_rk4 = use_rk4;
1769 inputs.use_adaptive_rk45 = use_adaptive_rk45;
1770 let result = unsafe {
1771 ballistics_calculate_trajectory(
1772 &inputs,
1773 std::ptr::null(),
1774 std::ptr::null(),
1775 0.01,
1776 MIN_FFI_STEP_SIZE_MS,
1777 )
1778 };
1779 assert!(
1780 !result.is_null(),
1781 "the documented minimum step must remain usable in {mode}"
1782 );
1783 unsafe {
1784 assert!((*result).point_count >= 0);
1785 assert!((*result).point_count as usize <= crate::MAX_TRAJECTORY_POINTS);
1786 ballistics_free_trajectory_result(result);
1787 }
1788 }
1789 }
1790
1791 const DECK_MACH: [f64; 4] = [0.5, 1.0, 2.0, 3.0];
1793 const DECK_CD_LOW: [f64; 4] = [0.05, 0.08, 0.06, 0.05];
1795
1796 #[test]
1797 fn trajectory_with_drag_table_applies_the_deck() {
1798 let inputs = valid_trajectory_inputs();
1799 unsafe {
1800 let plain = ballistics_calculate_trajectory(
1801 &inputs,
1802 std::ptr::null(),
1803 std::ptr::null(),
1804 300.0,
1805 1.0,
1806 );
1807 let decked = ballistics_calculate_trajectory_with_drag_table(
1808 &inputs,
1809 std::ptr::null(),
1810 std::ptr::null(),
1811 300.0,
1812 1.0,
1813 DECK_MACH.as_ptr(),
1814 DECK_CD_LOW.as_ptr(),
1815 DECK_MACH.len() as c_int,
1816 );
1817 assert!(!plain.is_null() && !decked.is_null());
1818 assert!(
1820 (*decked).impact_velocity > (*plain).impact_velocity + 1.0,
1821 "deck did not change the solve: plain={} decked={}",
1822 (*plain).impact_velocity,
1823 (*decked).impact_velocity
1824 );
1825 ballistics_free_trajectory_result(plain);
1826 ballistics_free_trajectory_result(decked);
1827 }
1828 }
1829
1830 #[test]
1831 fn trajectory_with_drag_table_rejects_invalid_decks() {
1832 let inputs = valid_trajectory_inputs();
1833 let descending = [3.0, 2.0, 1.0, 0.5];
1834 let negative_cd = [0.05, -0.08, 0.06, 0.05];
1835 unsafe {
1836 assert!(ballistics_calculate_trajectory_with_drag_table(
1838 &inputs,
1839 std::ptr::null(),
1840 std::ptr::null(),
1841 300.0,
1842 1.0,
1843 std::ptr::null(),
1844 DECK_CD_LOW.as_ptr(),
1845 4,
1846 )
1847 .is_null());
1848 assert!(ballistics_calculate_trajectory_with_drag_table(
1849 &inputs,
1850 std::ptr::null(),
1851 std::ptr::null(),
1852 300.0,
1853 1.0,
1854 DECK_MACH.as_ptr(),
1855 std::ptr::null(),
1856 4,
1857 )
1858 .is_null());
1859 assert!(ballistics_calculate_trajectory_with_drag_table(
1861 &inputs,
1862 std::ptr::null(),
1863 std::ptr::null(),
1864 300.0,
1865 1.0,
1866 DECK_MACH.as_ptr(),
1867 DECK_CD_LOW.as_ptr(),
1868 1,
1869 )
1870 .is_null());
1871 assert!(ballistics_calculate_trajectory_with_drag_table(
1873 &inputs,
1874 std::ptr::null(),
1875 std::ptr::null(),
1876 300.0,
1877 1.0,
1878 descending.as_ptr(),
1879 DECK_CD_LOW.as_ptr(),
1880 4,
1881 )
1882 .is_null());
1883 assert!(ballistics_calculate_trajectory_with_drag_table(
1885 &inputs,
1886 std::ptr::null(),
1887 std::ptr::null(),
1888 300.0,
1889 1.0,
1890 DECK_MACH.as_ptr(),
1891 negative_cd.as_ptr(),
1892 4,
1893 )
1894 .is_null());
1895 assert!(ballistics_calculate_trajectory_with_drag_table(
1897 std::ptr::null(),
1898 std::ptr::null(),
1899 std::ptr::null(),
1900 300.0,
1901 1.0,
1902 DECK_MACH.as_ptr(),
1903 DECK_CD_LOW.as_ptr(),
1904 4,
1905 )
1906 .is_null());
1907 }
1908 }
1909
1910 #[test]
1911 fn zero_angle_with_drag_table_applies_the_deck() {
1912 let inputs = valid_trajectory_inputs();
1914 unsafe {
1915 let plain =
1916 ballistics_calculate_zero_angle(&inputs, std::ptr::null(), std::ptr::null(), 100.0);
1917 let decked = ballistics_calculate_zero_angle_with_drag_table(
1918 &inputs,
1919 std::ptr::null(),
1920 std::ptr::null(),
1921 100.0,
1922 DECK_MACH.as_ptr(),
1923 DECK_CD_LOW.as_ptr(),
1924 DECK_MACH.len() as c_int,
1925 );
1926 assert!(plain.is_finite() && decked.is_finite());
1927 assert!(
1930 (plain - decked).abs() > 1e-6,
1931 "deck did not change the zero: plain={plain} decked={decked}"
1932 );
1933 }
1934 }
1935
1936 #[test]
1937 fn zero_angle_with_drag_table_rejects_invalid_decks() {
1938 let inputs = valid_trajectory_inputs();
1939 let descending = [3.0, 2.0, 1.0, 0.5];
1940 unsafe {
1941 assert!(ballistics_calculate_zero_angle_with_drag_table(
1942 &inputs,
1943 std::ptr::null(),
1944 std::ptr::null(),
1945 100.0,
1946 std::ptr::null(),
1947 DECK_CD_LOW.as_ptr(),
1948 4,
1949 )
1950 .is_nan());
1951 assert!(ballistics_calculate_zero_angle_with_drag_table(
1952 &inputs,
1953 std::ptr::null(),
1954 std::ptr::null(),
1955 100.0,
1956 DECK_MACH.as_ptr(),
1957 DECK_CD_LOW.as_ptr(),
1958 0,
1959 )
1960 .is_nan());
1961 assert!(ballistics_calculate_zero_angle_with_drag_table(
1962 &inputs,
1963 std::ptr::null(),
1964 std::ptr::null(),
1965 100.0,
1966 descending.as_ptr(),
1967 DECK_CD_LOW.as_ptr(),
1968 4,
1969 )
1970 .is_nan());
1971 assert!(ballistics_calculate_zero_angle_with_drag_table(
1973 std::ptr::null(),
1974 std::ptr::null(),
1975 std::ptr::null(),
1976 100.0,
1977 DECK_MACH.as_ptr(),
1978 DECK_CD_LOW.as_ptr(),
1979 4,
1980 )
1981 .is_nan());
1982 }
1983 }
1984
1985 #[test]
1986 fn zero_then_fly_with_same_deck_is_consistent() {
1987 let mut inputs = valid_trajectory_inputs();
1991 unsafe {
1992 let angle = ballistics_calculate_zero_angle_with_drag_table(
1993 &inputs,
1994 std::ptr::null(),
1995 std::ptr::null(),
1996 100.0,
1997 DECK_MACH.as_ptr(),
1998 DECK_CD_LOW.as_ptr(),
1999 DECK_MACH.len() as c_int,
2000 );
2001 assert!(angle.is_finite());
2002 inputs.muzzle_angle = angle;
2003 let result = ballistics_calculate_trajectory_with_drag_table(
2004 &inputs,
2005 std::ptr::null(),
2006 std::ptr::null(),
2007 150.0,
2008 1.0,
2009 DECK_MACH.as_ptr(),
2010 DECK_CD_LOW.as_ptr(),
2011 DECK_MACH.len() as c_int,
2012 );
2013 assert!(!result.is_null());
2014 let zero_distance = 100.0;
2018 let pts = std::slice::from_raw_parts((*result).points, (*result).point_count as usize);
2019 let bracket = pts
2020 .windows(2)
2021 .find(|w| w[0].position_x <= zero_distance && w[1].position_x >= zero_distance)
2022 .expect("trajectory brackets the zero distance");
2023 let (lo, hi) = (&bracket[0], &bracket[1]);
2024 let y_at_zero = if hi.position_x > lo.position_x {
2025 let t = (zero_distance - lo.position_x) / (hi.position_x - lo.position_x);
2026 lo.position_y + t * (hi.position_y - lo.position_y)
2027 } else {
2028 lo.position_y
2029 };
2030 assert!(
2031 (y_at_zero - inputs.sight_height).abs() < 0.002,
2032 "zeroed flight missed the line of sight at 100 m: y={} (sight_height={})",
2033 y_at_zero,
2034 inputs.sight_height
2035 );
2036 ballistics_free_trajectory_result(result);
2037 }
2038 }
2039
2040 #[test]
2041 fn drag_table_len_above_cap_is_rejected() {
2042 let n = (MAX_FFI_DRAG_TABLE_LEN + 1) as usize;
2045 let mach: Vec<f64> = (0..n).map(|i| 0.01 + i as f64 * 0.001).collect();
2046 let cd: Vec<f64> = vec![0.3; n];
2047 let inputs = valid_trajectory_inputs();
2048 unsafe {
2049 let r = ballistics_calculate_trajectory_with_drag_table(
2050 &inputs,
2051 std::ptr::null(),
2052 std::ptr::null(),
2053 300.0,
2054 1.0,
2055 mach.as_ptr(),
2056 cd.as_ptr(),
2057 n as c_int,
2058 );
2059 assert!(r.is_null(), "len {n} must be rejected by the cap");
2060 }
2061 }
2062
2063 #[test]
2064 fn drag_table_len_at_cap_is_accepted() {
2065 let n = MAX_FFI_DRAG_TABLE_LEN as usize;
2066 let mach: Vec<f64> = (0..n).map(|i| 0.01 + i as f64 * 0.001).collect();
2067 let cd: Vec<f64> = vec![0.3; n];
2068 let inputs = valid_trajectory_inputs();
2069 unsafe {
2070 let r = ballistics_calculate_trajectory_with_drag_table(
2071 &inputs,
2072 std::ptr::null(),
2073 std::ptr::null(),
2074 300.0,
2075 1.0,
2076 mach.as_ptr(),
2077 cd.as_ptr(),
2078 n as c_int,
2079 );
2080 assert!(!r.is_null(), "len == cap must be accepted");
2081 ballistics_free_trajectory_result(r);
2082 }
2083 }
2084
2085 #[test]
2086 fn ffi_cant_angle_deflects_laterally() {
2087 let mut level = valid_trajectory_inputs();
2088 level.muzzle_angle = 0.003;
2089 let mut canted = valid_trajectory_inputs();
2090 canted.muzzle_angle = 0.003;
2091 canted.cant_angle = 10f64.to_radians();
2092 unsafe {
2093 let a = ballistics_calculate_trajectory(&level, std::ptr::null(), std::ptr::null(), 400.0, 1.0);
2094 let b = ballistics_calculate_trajectory(&canted, std::ptr::null(), std::ptr::null(), 400.0, 1.0);
2095 assert!(!a.is_null() && !b.is_null());
2096 let za = std::slice::from_raw_parts((*a).points, (*a).point_count as usize).last().unwrap().position_z;
2097 let zb = std::slice::from_raw_parts((*b).points, (*b).point_count as usize).last().unwrap().position_z;
2098 assert!(zb > za + 0.005, "FFI cant must deflect right: level={za} canted={zb}");
2099 ballistics_free_trajectory_result(a);
2100 ballistics_free_trajectory_result(b);
2101 }
2102 }
2103
2104 #[test]
2105 fn ffi_vertical_wind_raises_trajectory() {
2106 let inputs = valid_trajectory_inputs();
2107 let no_wind = FFIWindConditions {
2108 speed: 0.0,
2109 direction: 0.0,
2110 vertical_speed: 0.0,
2111 };
2112 let updraft = FFIWindConditions {
2113 speed: 0.0,
2114 direction: 0.0,
2115 vertical_speed: 5.0,
2116 };
2117 unsafe {
2118 let a = ballistics_calculate_trajectory(&inputs, &no_wind, std::ptr::null(), 400.0, 1.0);
2119 let b = ballistics_calculate_trajectory(&inputs, &updraft, std::ptr::null(), 400.0, 1.0);
2120 assert!(!a.is_null() && !b.is_null());
2121 let ya = std::slice::from_raw_parts((*a).points, (*a).point_count as usize).last().unwrap().position_y;
2122 let yb = std::slice::from_raw_parts((*b).points, (*b).point_count as usize).last().unwrap().position_y;
2123 assert!(yb > ya + 0.01, "FFI updraft must raise the trajectory: no_wind={ya} updraft={yb}");
2124 ballistics_free_trajectory_result(a);
2125 ballistics_free_trajectory_result(b);
2126 }
2127 }
2128
2129 #[test]
2132 fn trajectory_scaled_at_one_matches_unscaled_export() {
2133 let inputs = valid_trajectory_inputs();
2134 unsafe {
2135 let unscaled = ballistics_calculate_trajectory_with_drag_table(
2136 &inputs,
2137 std::ptr::null(),
2138 std::ptr::null(),
2139 300.0,
2140 1.0,
2141 DECK_MACH.as_ptr(),
2142 DECK_CD_LOW.as_ptr(),
2143 DECK_MACH.len() as c_int,
2144 );
2145 let scaled = ballistics_calculate_trajectory_with_drag_table_scaled(
2146 &inputs,
2147 std::ptr::null(),
2148 std::ptr::null(),
2149 300.0,
2150 1.0,
2151 DECK_MACH.as_ptr(),
2152 DECK_CD_LOW.as_ptr(),
2153 DECK_MACH.len() as c_int,
2154 1.0,
2155 );
2156 assert!(!unscaled.is_null() && !scaled.is_null());
2157 assert_eq!(
2158 (*unscaled).impact_velocity.to_bits(),
2159 (*scaled).impact_velocity.to_bits(),
2160 "cd_scale=1.0 must be byte-identical to the unscaled export: unscaled={} scaled={}",
2161 (*unscaled).impact_velocity,
2162 (*scaled).impact_velocity
2163 );
2164 ballistics_free_trajectory_result(unscaled);
2165 ballistics_free_trajectory_result(scaled);
2166 }
2167 }
2168
2169 #[test]
2170 fn trajectory_scaled_at_1_10_lowers_impact_velocity() {
2171 let inputs = valid_trajectory_inputs();
2172 unsafe {
2173 let baseline = ballistics_calculate_trajectory_with_drag_table_scaled(
2174 &inputs,
2175 std::ptr::null(),
2176 std::ptr::null(),
2177 300.0,
2178 1.0,
2179 DECK_MACH.as_ptr(),
2180 DECK_CD_LOW.as_ptr(),
2181 DECK_MACH.len() as c_int,
2182 1.0,
2183 );
2184 let scaled_up = ballistics_calculate_trajectory_with_drag_table_scaled(
2185 &inputs,
2186 std::ptr::null(),
2187 std::ptr::null(),
2188 300.0,
2189 1.0,
2190 DECK_MACH.as_ptr(),
2191 DECK_CD_LOW.as_ptr(),
2192 DECK_MACH.len() as c_int,
2193 1.10,
2194 );
2195 assert!(!baseline.is_null() && !scaled_up.is_null());
2196 assert!(
2197 (*scaled_up).impact_velocity < (*baseline).impact_velocity,
2198 "cd_scale=1.10 must increase drag -> lower impact velocity: base={} scaled={}",
2199 (*baseline).impact_velocity,
2200 (*scaled_up).impact_velocity
2201 );
2202 ballistics_free_trajectory_result(baseline);
2203 ballistics_free_trajectory_result(scaled_up);
2204 }
2205 }
2206
2207 #[test]
2208 fn trajectory_scaled_rejects_invalid_cd_scale() {
2209 let inputs = valid_trajectory_inputs();
2210 unsafe {
2211 for bad in [0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
2212 let r = ballistics_calculate_trajectory_with_drag_table_scaled(
2213 &inputs,
2214 std::ptr::null(),
2215 std::ptr::null(),
2216 300.0,
2217 1.0,
2218 DECK_MACH.as_ptr(),
2219 DECK_CD_LOW.as_ptr(),
2220 DECK_MACH.len() as c_int,
2221 bad,
2222 );
2223 assert!(r.is_null(), "cd_scale={bad} must be rejected (null sentinel)");
2224 }
2225 }
2226 }
2227
2228 #[test]
2229 fn zero_angle_scaled_at_one_matches_unscaled_export() {
2230 let inputs = valid_trajectory_inputs();
2231 unsafe {
2232 let unscaled = ballistics_calculate_zero_angle_with_drag_table(
2233 &inputs,
2234 std::ptr::null(),
2235 std::ptr::null(),
2236 100.0,
2237 DECK_MACH.as_ptr(),
2238 DECK_CD_LOW.as_ptr(),
2239 DECK_MACH.len() as c_int,
2240 );
2241 let scaled = ballistics_calculate_zero_angle_with_drag_table_scaled(
2242 &inputs,
2243 std::ptr::null(),
2244 std::ptr::null(),
2245 100.0,
2246 DECK_MACH.as_ptr(),
2247 DECK_CD_LOW.as_ptr(),
2248 DECK_MACH.len() as c_int,
2249 1.0,
2250 );
2251 assert!(unscaled.is_finite() && scaled.is_finite());
2252 assert_eq!(
2253 unscaled.to_bits(),
2254 scaled.to_bits(),
2255 "cd_scale=1.0 must be byte-identical to the unscaled export: unscaled={unscaled} scaled={scaled}"
2256 );
2257 }
2258 }
2259
2260 #[test]
2261 fn zero_angle_scaled_at_1_10_differs_from_baseline() {
2262 let inputs = valid_trajectory_inputs();
2263 unsafe {
2264 let baseline = ballistics_calculate_zero_angle_with_drag_table_scaled(
2265 &inputs,
2266 std::ptr::null(),
2267 std::ptr::null(),
2268 100.0,
2269 DECK_MACH.as_ptr(),
2270 DECK_CD_LOW.as_ptr(),
2271 DECK_MACH.len() as c_int,
2272 1.0,
2273 );
2274 let scaled_up = ballistics_calculate_zero_angle_with_drag_table_scaled(
2275 &inputs,
2276 std::ptr::null(),
2277 std::ptr::null(),
2278 100.0,
2279 DECK_MACH.as_ptr(),
2280 DECK_CD_LOW.as_ptr(),
2281 DECK_MACH.len() as c_int,
2282 1.10,
2283 );
2284 assert!(baseline.is_finite() && scaled_up.is_finite());
2285 assert!(
2287 scaled_up > baseline,
2288 "cd_scale=1.10 must need a larger zero angle: base={baseline} scaled={scaled_up}"
2289 );
2290 }
2291 }
2292
2293 #[test]
2294 fn zero_angle_scaled_rejects_invalid_cd_scale() {
2295 let inputs = valid_trajectory_inputs();
2296 unsafe {
2297 for bad in [0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
2298 let angle = ballistics_calculate_zero_angle_with_drag_table_scaled(
2299 &inputs,
2300 std::ptr::null(),
2301 std::ptr::null(),
2302 100.0,
2303 DECK_MACH.as_ptr(),
2304 DECK_CD_LOW.as_ptr(),
2305 DECK_MACH.len() as c_int,
2306 bad,
2307 );
2308 assert!(angle.is_nan(), "cd_scale={bad} must be rejected (NaN sentinel)");
2309 }
2310 }
2311 }
2312
2313 #[test]
2317 fn legacy_drag_table_exports_unaffected_by_cd_scale_plumbing() {
2318 let inputs = valid_trajectory_inputs();
2319 unsafe {
2320 let a = ballistics_calculate_trajectory_with_drag_table(
2321 &inputs,
2322 std::ptr::null(),
2323 std::ptr::null(),
2324 300.0,
2325 1.0,
2326 DECK_MACH.as_ptr(),
2327 DECK_CD_LOW.as_ptr(),
2328 DECK_MACH.len() as c_int,
2329 );
2330 let b = ballistics_calculate_trajectory_with_drag_table(
2331 &inputs,
2332 std::ptr::null(),
2333 std::ptr::null(),
2334 300.0,
2335 1.0,
2336 DECK_MACH.as_ptr(),
2337 DECK_CD_LOW.as_ptr(),
2338 DECK_MACH.len() as c_int,
2339 );
2340 assert!(!a.is_null() && !b.is_null());
2341 assert_eq!((*a).impact_velocity.to_bits(), (*b).impact_velocity.to_bits());
2342 ballistics_free_trajectory_result(a);
2343 ballistics_free_trajectory_result(b);
2344
2345 let za = ballistics_calculate_zero_angle_with_drag_table(
2346 &inputs,
2347 std::ptr::null(),
2348 std::ptr::null(),
2349 100.0,
2350 DECK_MACH.as_ptr(),
2351 DECK_CD_LOW.as_ptr(),
2352 DECK_MACH.len() as c_int,
2353 );
2354 let zb = ballistics_calculate_zero_angle_with_drag_table(
2355 &inputs,
2356 std::ptr::null(),
2357 std::ptr::null(),
2358 100.0,
2359 DECK_MACH.as_ptr(),
2360 DECK_CD_LOW.as_ptr(),
2361 DECK_MACH.len() as c_int,
2362 );
2363 assert!(za.is_finite() && zb.is_finite());
2364 assert_eq!(za.to_bits(), zb.to_bits());
2365 }
2366 }
2367
2368 #[test]
2371 fn bc_for_reference_standard_icao_is_a_byte_identical_no_op() {
2372 let bc = 0.475;
2373 assert_eq!(
2374 ballistics_bc_for_reference_standard(bc, FFI_BC_REFERENCE_ICAO).to_bits(),
2375 bc.to_bits()
2376 );
2377 }
2378
2379 #[test]
2380 fn bc_for_reference_standard_unrecognized_value_falls_back_to_icao() {
2381 let bc = 0.475;
2384 assert_eq!(
2385 ballistics_bc_for_reference_standard(bc, 99).to_bits(),
2386 bc.to_bits()
2387 );
2388 }
2389
2390 #[test]
2391 fn bc_for_reference_standard_army_standard_metro_applies_the_documented_ratio() {
2392 let bc = 0.475;
2393 let converted =
2394 ballistics_bc_for_reference_standard(bc, FFI_BC_REFERENCE_ARMY_STANDARD_METRO);
2395 assert_eq!(converted, bc * crate::constants::ASM_TO_ICAO_BC);
2396 assert!(converted < bc);
2398 }
2399
2400 #[test]
2403 fn reduce_qnh_pressure_matches_the_library_function_and_lowers_pressure() {
2404 let reduced = ballistics_reduce_qnh_pressure(1030.0, 1500.0);
2405 assert_eq!(
2406 reduced,
2407 crate::atmosphere::reduce_qnh_to_station_pressure(1030.0, 1500.0)
2408 );
2409 assert!(reduced < 1030.0);
2410 }
2411
2412 #[test]
2413 fn reduce_qnh_pressure_passes_through_non_finite_inputs() {
2414 assert!(ballistics_reduce_qnh_pressure(f64::NAN, 1500.0).is_nan());
2415 assert_eq!(ballistics_reduce_qnh_pressure(1030.0, f64::INFINITY), 1030.0);
2416 }
2417
2418 #[test]
2426 fn ffi_trajectory_uses_the_reduced_pressure_not_the_raw_qnh() {
2427 let inputs = valid_trajectory_inputs();
2428 let altitude_m = 1500.0;
2429 let qnh_hpa = 1030.0;
2430 let reduced = ballistics_reduce_qnh_pressure(qnh_hpa, altitude_m);
2431 assert!(reduced < qnh_hpa);
2432
2433 let atmo_reduced = FFIAtmosphericConditions {
2434 temperature: 15.0,
2435 pressure: reduced,
2436 humidity: 50.0,
2437 altitude: altitude_m,
2438 };
2439 let atmo_raw_qnh = FFIAtmosphericConditions {
2440 temperature: 15.0,
2441 pressure: qnh_hpa,
2442 humidity: 50.0,
2443 altitude: altitude_m,
2444 };
2445
2446 unsafe {
2447 let a = ballistics_calculate_trajectory(
2448 &inputs,
2449 std::ptr::null(),
2450 &atmo_reduced,
2451 400.0,
2452 1.0,
2453 );
2454 let b = ballistics_calculate_trajectory(
2455 &inputs,
2456 std::ptr::null(),
2457 &atmo_raw_qnh,
2458 400.0,
2459 1.0,
2460 );
2461 assert!(!a.is_null() && !b.is_null());
2462 let drop_a = std::slice::from_raw_parts((*a).points, (*a).point_count as usize)
2463 .last()
2464 .unwrap()
2465 .position_y;
2466 let drop_b = std::slice::from_raw_parts((*b).points, (*b).point_count as usize)
2467 .last()
2468 .unwrap()
2469 .position_y;
2470 assert!(
2471 (drop_a - drop_b).abs() > 1e-6,
2472 "reduced vs. raw-QNH pressure must produce materially different trajectories: \
2473 {drop_a} vs {drop_b}"
2474 );
2475 ballistics_free_trajectory_result(a);
2476 ballistics_free_trajectory_result(b);
2477 }
2478 }
2479
2480 #[test]
2484 fn ffi_monte_carlo_uses_the_reduced_pressure_not_the_raw_qnh() {
2485 let inputs = valid_trajectory_inputs();
2486 let altitude_m = 1500.0;
2487 let qnh_hpa = 1030.0;
2488 let reduced = ballistics_reduce_qnh_pressure(qnh_hpa, altitude_m);
2489
2490 let atmo_reduced = FFIAtmosphericConditions {
2491 temperature: 15.0,
2492 pressure: reduced,
2493 humidity: 50.0,
2494 altitude: altitude_m,
2495 };
2496 let atmo_raw_qnh = FFIAtmosphericConditions {
2497 temperature: 15.0,
2498 pressure: qnh_hpa,
2499 humidity: 50.0,
2500 altitude: altitude_m,
2501 };
2502 let params = FFIMonteCarloParams {
2503 num_simulations: 200,
2504 velocity_std_dev: 1.0,
2505 angle_std_dev: 0.0,
2506 bc_std_dev: 0.0,
2507 wind_speed_std_dev: 0.0,
2508 target_distance: f64::NAN,
2509 base_wind_speed: 0.0,
2510 base_wind_direction: 0.0,
2511 azimuth_std_dev: 0.0,
2512 };
2513
2514 unsafe {
2515 let a = ballistics_monte_carlo(&inputs, &atmo_reduced, ¶ms);
2516 let b = ballistics_monte_carlo(&inputs, &atmo_raw_qnh, ¶ms);
2517 assert!(!a.is_null() && !b.is_null());
2518 assert!(
2519 ((*a).mean_range - (*b).mean_range).abs() > 0.5,
2520 "reduced vs. raw-QNH pressure must change MC mean range materially: \
2521 {} vs {}",
2522 (*a).mean_range,
2523 (*b).mean_range
2524 );
2525 ballistics_free_monte_carlo_results(a);
2526 ballistics_free_monte_carlo_results(b);
2527 }
2528 }
2529
2530 #[test]
2533 fn density_altitude_ffi_exports_match_the_library_function() {
2534 let da_m = 1000.0 * 0.3048;
2535 let expected = crate::atmosphere::resolve_atmosphere_for_density_altitude(da_m, None);
2536 assert_eq!(
2537 ballistics_density_altitude_altitude_m(da_m, FFI_NO_EXPLICIT_TEMPERATURE),
2538 expected.0
2539 );
2540 assert_eq!(
2541 ballistics_density_altitude_temperature_c(da_m, FFI_NO_EXPLICIT_TEMPERATURE),
2542 expected.1
2543 );
2544 assert_eq!(
2545 ballistics_density_altitude_pressure_hpa(da_m, FFI_NO_EXPLICIT_TEMPERATURE),
2546 expected.2
2547 );
2548
2549 assert!((ballistics_density_altitude_altitude_m(da_m, FFI_NO_EXPLICIT_TEMPERATURE) - da_m).abs() < 1e-6);
2551 }
2552
2553 #[test]
2554 fn density_altitude_ffi_explicit_temperature_is_honored_exactly() {
2555 let da_m = 500.0;
2556 let explicit_temp_c = 30.0;
2557 let expected =
2558 crate::atmosphere::resolve_atmosphere_for_density_altitude(da_m, Some(explicit_temp_c));
2559 assert_eq!(
2560 ballistics_density_altitude_temperature_c(da_m, explicit_temp_c),
2561 explicit_temp_c
2562 );
2563 assert_eq!(
2564 ballistics_density_altitude_temperature_c(da_m, explicit_temp_c),
2565 expected.1
2566 );
2567 assert_eq!(
2568 ballistics_density_altitude_pressure_hpa(da_m, explicit_temp_c),
2569 expected.2
2570 );
2571 assert_eq!(
2572 ballistics_density_altitude_altitude_m(da_m, explicit_temp_c),
2573 expected.0
2574 );
2575 }
2576
2577 #[test]
2578 fn density_altitude_ffi_non_finite_input_returns_nan() {
2579 assert!(
2580 ballistics_density_altitude_temperature_c(f64::INFINITY, FFI_NO_EXPLICIT_TEMPERATURE)
2581 .is_nan()
2582 );
2583 assert!(
2584 ballistics_density_altitude_pressure_hpa(f64::NAN, FFI_NO_EXPLICIT_TEMPERATURE).is_nan()
2585 );
2586 assert!(
2587 ballistics_density_altitude_altitude_m(f64::NEG_INFINITY, FFI_NO_EXPLICIT_TEMPERATURE)
2588 .is_nan()
2589 );
2590 }
2591
2592 #[test]
2597 fn ffi_trajectory_uses_the_density_altitude_derived_station_values() {
2598 let inputs = valid_trajectory_inputs();
2599 let da_m = 3000.0 * 0.3048; let altitude_m =
2601 ballistics_density_altitude_altitude_m(da_m, FFI_NO_EXPLICIT_TEMPERATURE);
2602 let temperature_c =
2603 ballistics_density_altitude_temperature_c(da_m, FFI_NO_EXPLICIT_TEMPERATURE);
2604 let pressure_hpa =
2605 ballistics_density_altitude_pressure_hpa(da_m, FFI_NO_EXPLICIT_TEMPERATURE);
2606
2607 let atmo_da = FFIAtmosphericConditions {
2608 temperature: temperature_c,
2609 pressure: pressure_hpa,
2610 humidity: 50.0,
2611 altitude: altitude_m,
2612 };
2613 let atmo_sea_level = FFIAtmosphericConditions {
2614 temperature: 15.0,
2615 pressure: 1013.25,
2616 humidity: 50.0,
2617 altitude: 0.0,
2618 };
2619
2620 unsafe {
2621 let a = ballistics_calculate_trajectory(
2622 &inputs,
2623 std::ptr::null(),
2624 &atmo_da,
2625 400.0,
2626 1.0,
2627 );
2628 let b = ballistics_calculate_trajectory(
2629 &inputs,
2630 std::ptr::null(),
2631 &atmo_sea_level,
2632 400.0,
2633 1.0,
2634 );
2635 assert!(!a.is_null() && !b.is_null());
2636 let drop_a = std::slice::from_raw_parts((*a).points, (*a).point_count as usize)
2637 .last()
2638 .unwrap()
2639 .position_y;
2640 let drop_b = std::slice::from_raw_parts((*b).points, (*b).point_count as usize)
2641 .last()
2642 .unwrap()
2643 .position_y;
2644 assert!(
2645 (drop_a - drop_b).abs() > 1e-6,
2646 "density-altitude-derived vs sea-level atmosphere must produce materially \
2647 different trajectories: {drop_a} vs {drop_b}"
2648 );
2649 ballistics_free_trajectory_result(a);
2650 ballistics_free_trajectory_result(b);
2651 }
2652 }
2653}