Skip to main content

ballistics_engine/
stability.rs

1use crate::InternalBallisticInputs as BallisticInputs;
2
3/// Calculate the gyroscopic stability coefficient (SG) for the bullet.
4///
5/// This function uses the Miller stability formula. An SG value greater than 1.5
6/// is generally considered to indicate adequate stability.
7///
8/// # Arguments
9/// * `inputs` - Ballistic input parameters
10/// * `atmo_params` - Atmospheric parameters (altitude, temp_c, pressure_hpa, density_ratio)
11///
12/// # Returns
13/// * Stability coefficient (dimensionless)
14pub fn compute_stability_coefficient(
15    inputs: &BallisticInputs,
16    atmo_params: (f64, f64, f64, f64),
17) -> f64 {
18    // Check for required parameters
19    if inputs.twist_rate == 0.0 || inputs.bullet_length == 0.0 || inputs.bullet_diameter == 0.0 {
20        return 0.0;
21    }
22
23    // Pre-calculated constants for efficiency
24    const MILLER_CONST: f64 = 30.0;
25    const VEL_REF_FPS: f64 = 2800.0;
26    const TEMP_REF_K: f64 = 288.15; // 15°C
27    const PRESS_REF_HPA: f64 = 1013.25;
28
29    // Calculate intermediate values
30    // Convert twist rate from inches to meters for consistency
31    let twist_rate_m = inputs.twist_rate.abs() * 0.0254; // inches to meters
32    let twist_calibers = twist_rate_m / inputs.bullet_diameter;
33    let length_calibers = inputs.bullet_length / inputs.bullet_diameter;
34
35    // Convert units for Miller formula
36    let mass_grains = inputs.bullet_mass / 0.00006479891; // kg to grains
37    let diameter_inches = inputs.bullet_diameter / 0.0254; // meters to inches
38    let velocity_fps = inputs.muzzle_velocity * 3.28084; // m/s to fps
39
40    // Miller stability formula components
41    let mass_term = MILLER_CONST * mass_grains;
42    let geom_term = twist_calibers.powi(2)
43        * diameter_inches.powi(3)
44        * length_calibers
45        * (1.0 + length_calibers.powi(2));
46
47    if geom_term == 0.0 {
48        return 0.0;
49    }
50
51    // Extract atmospheric parameters
52    let (_, temp_c, current_press_hpa, _) = atmo_params;
53    let temp_k = temp_c + 273.15;
54
55    // Atmospheric density correction factor
56    // Ratio of reference density to current density
57    let density_correction = (temp_k / TEMP_REF_K) * (PRESS_REF_HPA / current_press_hpa);
58
59    // Velocity correction factor
60    let velocity_correction = (velocity_fps / VEL_REF_FPS).powf(1.0 / 3.0);
61
62    // Final stability calculation
63
64    (mass_term / geom_term) * velocity_correction * density_correction
65}
66
67/// Effective density (kg/m^3) used by the mass-based bullet-length estimate.
68///
69/// A jacketed lead-core bullet is not a solid cylinder of lead (11340 kg/m^3): the ogive/boat-tail
70/// taper and the copper jacket lower the *effective* density that relates total mass to a simple
71/// `length * frontal-area` cylinder. 7600 kg/m^3 was fit so common lead-core match bullets land at
72/// their real length / caliber ratio (see reference-bullet unit tests below). MBA-1135.
73pub const BULLET_LENGTH_RHO_EFF_KG_M3: f64 = 7600.0;
74
75/// Lower / upper bound on the estimated length-to-diameter ratio (calibers). Keeps degenerate
76/// mass/diameter combinations inside the range of real small-arms projectiles.
77const MIN_LENGTH_CALIBERS: f64 = 2.5;
78const MAX_LENGTH_CALIBERS: f64 = 6.5;
79
80/// Gyroscopic-stability target used to synthesize a default twist when the shooter does not
81/// supply one (MBA-1135).
82///
83/// Chosen = **2.0** (see [`default_twist_inches`] docs for the reference-bullet comparison that
84/// motivated 2.0 over 1.5). A synthesized default should slightly *over*-stabilize rather than
85/// under-stabilize, and 2.0 reproduces the real factory twists of the twist-sensitive high-BC
86/// match bullets (.308/175 gr -> ~1:11", 6.5mm/140 gr -> ~1:8") most faithfully.
87pub const DEFAULT_TWIST_SG_TARGET: f64 = 2.0;
88
89const GRAINS_PER_KG: f64 = 1.0 / 0.00006479891;
90const METERS_PER_INCH: f64 = 0.0254;
91const MPS_TO_FPS: f64 = 3.28084;
92const MILLER_VEL_REF_FPS: f64 = 2800.0;
93
94/// Estimate a bullet's length (meters) from its diameter and mass using a constant-effective-density
95/// cylinder model (MBA-1135).
96///
97/// Replaces the historical mass-blind `diameter * 4.5` fallback: two bullets of the same caliber but
98/// very different weights get very different lengths, which is what the Miller stability formula and
99/// the enhanced spin-drift / Magnus models actually need.
100///
101/// Model: `L = mass / (rho_eff * (pi/4) * d^2)` with `rho_eff = 7600 kg/m^3`, then the length/diameter
102/// ratio is clamped to `[2.5, 6.5]` calibers so pathological inputs stay physical.
103///
104/// Returns `0.0` for non-physical inputs (`mass_kg <= 0` or `diameter_m <= 0`); callers that need a
105/// non-zero length should fall back to their historical literal in that case.
106pub fn estimate_bullet_length_m(diameter_m: f64, mass_kg: f64) -> f64 {
107    if mass_kg <= 0.0 || diameter_m <= 0.0 || !mass_kg.is_finite() || !diameter_m.is_finite() {
108        return 0.0;
109    }
110
111    let frontal_area = std::f64::consts::FRAC_PI_4 * diameter_m * diameter_m;
112    let raw_length = mass_kg / (BULLET_LENGTH_RHO_EFF_KG_M3 * frontal_area);
113
114    // Clamp the length-to-diameter ratio (calibers) into a physically sensible band.
115    let length_calibers = (raw_length / diameter_m).clamp(MIN_LENGTH_CALIBERS, MAX_LENGTH_CALIBERS);
116    length_calibers * diameter_m
117}
118
119/// Synthesize a default barrel twist (inches per turn) for a bullet whose twist the shooter did not
120/// supply, by inverting the Miller stability formula for the twist that yields
121/// [`DEFAULT_TWIST_SG_TARGET`] (MBA-1135).
122///
123/// This replaces the mass-blind fixed `1:12"` fallback: heavier / longer bullets correctly demand a
124/// faster twist. The bullet length is taken from [`estimate_bullet_length_m`] (so the whole default
125/// is caliber + weight aware), the velocity term is `(v_fps / 2800)^(1/3)` at the supplied muzzle
126/// velocity, and the density correction is `1.0` (sea-level ICAO standard).
127///
128/// Inverting `Sg = 30 m_gr * vel_corr / (t_cal^2 * d_in^3 * L_cal * (1 + L_cal^2))`:
129///
130/// `t_cal = sqrt( 30 m_gr * vel_corr / (Sg_target * d_in^3 * L_cal * (1 + L_cal^2)) )`,
131/// `twist_in = t_cal * d_in`.
132///
133/// `Sg_target` was selected by comparing 1.5 vs 2.0 against common factory twists
134/// (velocities: .308/175 gr @ 2600 fps, .223/55 gr @ 3240 fps, .224/77 gr @ 2750 fps,
135/// 6.5mm/140 gr @ 2700 fps):
136///
137/// | bullet          | factory | Sg=1.5 | Sg=2.0 |
138/// |-----------------|---------|--------|--------|
139/// | .308 / 175 gr   | 1:10-12"| 1:12.9"| 1:11.2"|
140/// | .223 / 55 gr    | ~1:12"  | 1:11.7"| 1:10.1"|
141/// | .224 / 77 gr    | ~1:8"   | 1:8.4" | 1:7.2" |
142/// | 6.5mm / 140 gr  | ~1:8"   | 1:8.9" | 1:7.7" |
143///
144/// 2.0 wins: Sg=1.5 gives 1:12.9" for the 175 gr match bullet (no real .308 barrel is that slow and
145/// it under-stabilizes 175 gr), whereas 2.0's 1:11.2" / 1:8" are exactly the standard twists for the
146/// twist-sensitive high-BC bullets, and slight over-stabilization is the safe direction for a default.
147///
148/// Guards degenerate inputs (`diameter_m`, `mass_kg`, or `muzzle_velocity_mps` <= 0) by returning the
149/// historical `12.0` (1:12") fallback. Always returns a positive inches-per-turn value.
150pub fn default_twist_inches(diameter_m: f64, mass_kg: f64, muzzle_velocity_mps: f64) -> f64 {
151    const FALLBACK_TWIST_IN: f64 = 12.0;
152
153    if diameter_m <= 0.0
154        || mass_kg <= 0.0
155        || muzzle_velocity_mps <= 0.0
156        || !diameter_m.is_finite()
157        || !mass_kg.is_finite()
158        || !muzzle_velocity_mps.is_finite()
159    {
160        return FALLBACK_TWIST_IN;
161    }
162
163    let length_m = estimate_bullet_length_m(diameter_m, mass_kg);
164    if length_m <= 0.0 {
165        return FALLBACK_TWIST_IN;
166    }
167
168    let d_in = diameter_m / METERS_PER_INCH;
169    let m_gr = mass_kg * GRAINS_PER_KG;
170    let l_cal = length_m / diameter_m;
171    let v_fps = muzzle_velocity_mps * MPS_TO_FPS;
172    let velocity_correction = (v_fps / MILLER_VEL_REF_FPS).powf(1.0 / 3.0);
173
174    let geom = d_in.powi(3) * l_cal * (1.0 + l_cal * l_cal);
175    let denom = DEFAULT_TWIST_SG_TARGET * geom;
176    if denom <= 0.0 {
177        return FALLBACK_TWIST_IN;
178    }
179
180    let t_cal_sq = 30.0 * m_gr * velocity_correction / denom;
181    if !t_cal_sq.is_finite() || t_cal_sq <= 0.0 {
182        return FALLBACK_TWIST_IN;
183    }
184
185    let twist_in = t_cal_sq.sqrt() * d_in;
186    if twist_in.is_finite() && twist_in > 0.0 {
187        twist_in
188    } else {
189        FALLBACK_TWIST_IN
190    }
191}
192
193/// Calculate spin drift in meters using Litz approximation.
194///
195/// # Arguments
196/// * `time_s` - Time of flight in seconds
197/// * `stability` - Stability coefficient
198/// * `twist_rate` - Twist rate in inches (calibers per turn)
199/// * `is_twist_right` - True for right-hand twist, false for left-hand
200///
201/// # Returns
202/// * Spin drift in meters
203pub fn compute_spin_drift(
204    time_s: f64,
205    stability: f64,
206    twist_rate: f64,
207    is_twist_right: bool,
208) -> f64 {
209    compute_spin_drift_with_decay(time_s, stability, twist_rate, is_twist_right, None)
210}
211
212/// Calculate spin drift with optional spin decay modeling
213pub fn compute_spin_drift_with_decay(
214    time_s: f64,
215    stability: f64,
216    twist_rate: f64,
217    is_twist_right: bool,
218    decay_factor: Option<f64>, // Optional spin decay factor (0-1)
219) -> f64 {
220    if stability == 0.0 || time_s <= 0.0 || twist_rate == 0.0 {
221        return 0.0;
222    }
223
224    let sign = if is_twist_right { 1.0 } else { -1.0 };
225
226    // Litz empirical spin drift: inches = 1.25 * (SG + 1.2) * TOF^1.83.
227    // Keep this summary/API path consistent with cli_api::apply_spin_drift.
228    let scaling_factor = 1.25;
229    let base_drift = sign * scaling_factor * (stability + 1.2) * time_s.powf(1.83);
230
231    // Apply spin decay if provided
232    let effective_drift = if let Some(decay) = decay_factor {
233        base_drift * decay.max(0.0).min(1.0)
234    } else {
235        base_drift
236    };
237
238    // Convert inches to meters
239    effective_drift * 0.0254
240}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245
246    fn create_test_inputs() -> BallisticInputs {
247        BallisticInputs {
248            muzzle_velocity: 823.0, // 2700 fps in m/s
249            bc_value: 0.5,
250            bullet_mass: 0.0109,      // 168 grains in kg
251            bullet_diameter: 0.00782, // 0.308 inches in meters
252            bullet_length: 0.033,     // in meters (1.3 inches)
253            twist_rate: 10.0,
254            ..Default::default()
255        }
256    }
257
258    #[test]
259    fn test_compute_stability_coefficient() {
260        let inputs = create_test_inputs();
261        let atmo_params = (0.0, 15.0, 1013.25, 1.0); // Standard conditions
262
263        let stability = compute_stability_coefficient(&inputs, atmo_params);
264
265        // Debug output
266        println!("Computed stability: {}", stability);
267
268        // Should be a reasonable stability value
269        assert!(stability > 0.0);
270        assert!(stability < 10.0); // Sanity check
271
272        // Test with typical values should give stability around 1.5-2.5
273        assert!(stability > 1.0);
274        assert!(stability < 3.0);
275    }
276
277    #[test]
278    fn test_compute_stability_coefficient_zero_cases() {
279        let mut inputs = create_test_inputs();
280        let atmo_params = (0.0, 15.0, 1013.25, 1.0);
281
282        // Test with zero twist rate
283        inputs.twist_rate = 0.0;
284        assert_eq!(compute_stability_coefficient(&inputs, atmo_params), 0.0);
285
286        // Test with zero bullet length
287        inputs = create_test_inputs();
288        inputs.bullet_length = 0.0;
289        assert_eq!(compute_stability_coefficient(&inputs, atmo_params), 0.0);
290
291        // Test with zero bullet diameter
292        inputs = create_test_inputs();
293        inputs.bullet_diameter = 0.0;
294        assert_eq!(compute_stability_coefficient(&inputs, atmo_params), 0.0);
295    }
296
297    #[test]
298    fn test_compute_stability_coefficient_atmospheric_effects() {
299        let inputs = create_test_inputs();
300
301        // Standard conditions
302        let standard_atmo = (0.0, 15.0, 1013.25, 1.0);
303        let standard_stability = compute_stability_coefficient(&inputs, standard_atmo);
304
305        // High altitude (lower pressure, lower temperature)
306        let high_alt_atmo = (3000.0, 5.0, 900.0, 1.0);
307        let high_alt_stability = compute_stability_coefficient(&inputs, high_alt_atmo);
308
309        // High altitude should have higher stability due to lower air density
310        assert!(high_alt_stability > standard_stability);
311
312        // Hot conditions (higher temperature)
313        let hot_atmo = (0.0, 35.0, 1013.25, 1.0);
314        let hot_stability = compute_stability_coefficient(&inputs, hot_atmo);
315
316        // Hot conditions should have higher stability due to lower air density
317        assert!(hot_stability > standard_stability);
318    }
319
320    #[test]
321    fn test_compute_spin_drift() {
322        let time_s = 1.5;
323        let stability = 2.0;
324        let twist_rate = 10.0;
325
326        // Test right-hand twist
327        let drift_right = compute_spin_drift(time_s, stability, twist_rate, true);
328        assert!(drift_right > 0.0); // Should drift to the right (positive)
329
330        // Test left-hand twist
331        let drift_left = compute_spin_drift(time_s, stability, twist_rate, false);
332        assert!(drift_left < 0.0); // Should drift to the left (negative)
333        assert!((drift_left + drift_right).abs() < 1e-10); // Should be equal magnitude
334
335        // Litz spin drift remains a small correction for this flight time.
336        assert!(drift_right.abs() < 0.25); // Less than 25cm for 1.5s flight
337    }
338
339    #[test]
340    fn test_compute_spin_drift_zero_cases() {
341        // Test with zero stability
342        assert_eq!(compute_spin_drift(1.5, 0.0, 10.0, true), 0.0);
343
344        // Test with zero time
345        assert_eq!(compute_spin_drift(0.0, 2.0, 10.0, true), 0.0);
346
347        // Test with negative time
348        assert_eq!(compute_spin_drift(-1.0, 2.0, 10.0, true), 0.0);
349
350        // Test with zero twist rate
351        assert_eq!(compute_spin_drift(1.5, 2.0, 0.0, true), 0.0);
352    }
353
354    // --- MBA-1135: mass-based length + Miller-inverse twist defaults ---
355
356    const GR_TO_KG: f64 = 0.00006479891;
357    const IN_TO_M: f64 = 0.0254;
358
359    fn len_in(diameter_in: f64, mass_gr: f64) -> f64 {
360        estimate_bullet_length_m(diameter_in * IN_TO_M, mass_gr * GR_TO_KG) / IN_TO_M
361    }
362
363    fn twist_in(diameter_in: f64, mass_gr: f64, v_fps: f64) -> f64 {
364        default_twist_inches(diameter_in * IN_TO_M, mass_gr * GR_TO_KG, v_fps * 0.3048)
365    }
366
367    #[test]
368    fn test_estimate_bullet_length_reference_bullets() {
369        // (diameter_in, mass_gr, expected_in, tolerance_in)
370        let cases = [
371            (0.308, 175.0, 1.24, 0.06), // .308 175 gr match  -> L/d ~4.0
372            (0.224, 77.0, 0.99, 0.06),  // .224 77 gr         -> long for caliber
373            (0.338, 300.0, 1.74, 0.06), // .338 300 gr
374            (0.224, 55.0, 0.72, 0.05),  // .224 55 gr varmint -> L/d ~3.2
375            (0.510, 750.0, 1.90, 0.08), // .510 750 gr
376        ];
377        for (d, m, expected, tol) in cases {
378            let got = len_in(d, m);
379            assert!(
380                (got - expected).abs() < tol,
381                ".{d}/{m}gr length: expected ~{expected}\", got {got:.4}\" (L/d {:.2})",
382                got / d
383            );
384        }
385    }
386
387    #[test]
388    fn test_estimate_bullet_length_degenerate_inputs() {
389        assert_eq!(estimate_bullet_length_m(0.00782, 0.0), 0.0);
390        assert_eq!(estimate_bullet_length_m(0.00782, -1.0), 0.0);
391        assert_eq!(estimate_bullet_length_m(0.0, 0.011), 0.0);
392        assert_eq!(estimate_bullet_length_m(-0.1, 0.011), 0.0);
393        assert_eq!(estimate_bullet_length_m(f64::NAN, 0.011), 0.0);
394    }
395
396    #[test]
397    fn test_estimate_bullet_length_clamps_ld_ratio() {
398        // Absurdly heavy for a tiny caliber -> clamp at 6.5 calibers.
399        let d = 0.172 * IN_TO_M;
400        let long = estimate_bullet_length_m(d, 0.05); // way too heavy
401        assert!((long / d - 6.5).abs() < 1e-9, "expected clamp at 6.5 cal, got {}", long / d);
402        // Absurdly light -> clamp at 2.5 calibers.
403        let short = estimate_bullet_length_m(0.510 * IN_TO_M, 0.001);
404        assert!(
405            (short / (0.510 * IN_TO_M) - 2.5).abs() < 1e-9,
406            "expected clamp at 2.5 cal, got {}",
407            short / (0.510 * IN_TO_M)
408        );
409    }
410
411    #[test]
412    fn test_default_twist_reference_bullets() {
413        // With DEFAULT_TWIST_SG_TARGET = 2.0, these should land near common factory twists.
414        // (diameter_in, mass_gr, v_fps, expected_twist_in, tolerance_in)
415        let cases = [
416            (0.308, 175.0, 2600.0, 11.2, 1.2), // .308 175 gr -> ~1:10-12"
417            (0.224, 55.0, 3240.0, 10.1, 1.5),  // .223 55 gr  -> ~1:10-12"
418            (0.224, 77.0, 2750.0, 7.2, 1.2),   // .224 77 gr  -> ~1:7-8"
419            (0.264, 140.0, 2700.0, 7.7, 1.2),  // 6.5mm 140 gr -> ~1:8"
420        ];
421        for (d, m, v, expected, tol) in cases {
422            let got = twist_in(d, m, v);
423            assert!(got > 0.0, ".{d}/{m}gr twist must be positive, got {got}");
424            assert!(
425                (got - expected).abs() < tol,
426                ".{d}/{m}gr twist: expected ~1:{expected}\", got 1:{got:.2}\"",
427            );
428        }
429    }
430
431    #[test]
432    fn test_default_twist_yields_target_sg() {
433        // By construction, at sea-level standard the synthesized twist should reproduce
434        // DEFAULT_TWIST_SG_TARGET when the same estimated length is used for the Sg check.
435        let d_m = 0.308 * IN_TO_M;
436        let m_kg = 175.0 * GR_TO_KG;
437        let v_mps = 2600.0 * 0.3048;
438        let twist = default_twist_inches(d_m, m_kg, v_mps);
439        let inputs = BallisticInputs {
440            muzzle_velocity: v_mps,
441            bullet_mass: m_kg,
442            bullet_diameter: d_m,
443            bullet_length: estimate_bullet_length_m(d_m, m_kg),
444            twist_rate: twist,
445            ..Default::default()
446        };
447        let sg = compute_stability_coefficient(&inputs, (0.0, 15.0, 1013.25, 1.0));
448        assert!(
449            (sg - DEFAULT_TWIST_SG_TARGET).abs() < 0.02,
450            "expected Sg ~{DEFAULT_TWIST_SG_TARGET}, got {sg}"
451        );
452    }
453
454    #[test]
455    fn test_default_twist_degenerate_inputs_fall_back() {
456        assert_eq!(default_twist_inches(0.0, 0.011, 800.0), 12.0);
457        assert_eq!(default_twist_inches(0.00782, 0.0, 800.0), 12.0);
458        assert_eq!(default_twist_inches(0.00782, 0.011, 0.0), 12.0);
459        assert_eq!(default_twist_inches(f64::NAN, 0.011, 800.0), 12.0);
460    }
461
462    #[test]
463    fn test_heavier_bullet_needs_faster_twist() {
464        // Same caliber + velocity: the heavier (longer) bullet must get a faster (smaller) twist.
465        let light = twist_in(0.224, 55.0, 2900.0);
466        let heavy = twist_in(0.224, 77.0, 2900.0);
467        assert!(heavy < light, "77gr twist {heavy} should be faster than 55gr {light}");
468    }
469
470    #[test]
471    fn test_print_reference_estimates() {
472        // Diagnostic dump for the MBA-1135 report: `cargo test print_reference_estimates -- --nocapture`.
473        println!("\n=== MBA-1135 estimate_bullet_length_m ===");
474        for (d, m) in [
475            (0.308, 175.0),
476            (0.224, 77.0),
477            (0.338, 300.0),
478            (0.224, 55.0),
479            (0.510, 750.0),
480            (0.264, 140.0),
481        ] {
482            let l = len_in(d, m);
483            println!(".{d}/{m}gr -> {l:.4}\" (L/d {:.3})", l / d);
484        }
485        println!("\n=== MBA-1135 default_twist_inches (SG=1.5 vs 2.0) ===");
486        for (d, m, v) in [
487            (0.308, 175.0, 2600.0),
488            (0.224, 55.0, 3240.0),
489            (0.224, 77.0, 2750.0),
490            (0.264, 140.0, 2700.0),
491        ] {
492            // Reconstruct both targets by scaling: t_cal ~ 1/sqrt(Sg) so twist(1.5)=twist(2.0)*sqrt(2.0/1.5).
493            let t20 = twist_in(d, m, v);
494            let t15 = t20 * (DEFAULT_TWIST_SG_TARGET / 1.5_f64).sqrt();
495            println!(".{d}/{m}gr @ {v}fps -> SG1.5: 1:{t15:.2}\"  SG2.0: 1:{t20:.2}\"");
496        }
497        println!();
498    }
499
500    #[test]
501    fn test_compute_spin_drift_scaling() {
502        let stability = 2.0;
503        let twist_rate = 10.0;
504
505        // Test time scaling
506        let drift_1s = compute_spin_drift(1.0, stability, twist_rate, true);
507        let drift_2s = compute_spin_drift(2.0, stability, twist_rate, true);
508
509        // Drift should increase with time (non-linearly due to 1.83 exponent)
510        assert!(drift_2s > drift_1s);
511
512        // Test stability scaling
513        let drift_low_stability = compute_spin_drift(1.5, 1.0, twist_rate, true);
514        let drift_high_stability = compute_spin_drift(1.5, 3.0, twist_rate, true);
515
516        // Higher stability should produce more drift
517        assert!(drift_high_stability > drift_low_stability);
518    }
519}