ballistics_engine/lib.rs
1//! # Ballistics Engine
2//!
3//! High-performance ballistics trajectory calculation engine with comprehensive physics modeling.
4//!
5//! ## Interactive Web Demo
6//!
7//! Try the ballistics engine directly in your browser at [https://ballistics.rs/](https://ballistics.rs/)
8//!
9//! ## Features
10//!
11//! - Professional-grade trajectory calculations with multiple drag models
12//! - Advanced physics including spin drift, Coriolis effect, and Magnus force
13//! - Monte Carlo simulations for uncertainty analysis
14//! - WebAssembly support for browser-based applications
15//! - FFI bindings for iOS and Android development
16//!
17//! ## Station air on every surface
18//!
19//! A station pressure must be finite and positive, a station altitude finite, and a
20//! temperature finite and above absolute zero. A density altitude must be finite and resolve
21//! to a station that can exist. [`RelativeHumidity`] applies the sensor band; [`StationAir`]
22//! checks the combined air. CLI flags (including the zero day), CSV columns, saved profiles,
23//! the browser terminal, C FFI, bridge cards and truing, solve-json and MCP share these rules.
24//! No surface adds a narrower weather range. A file format can: `profile.export_a7p` keeps
25//! the `.a7p` format's -100..100 °C and 300..1500 hPa bounds.
26//!
27//! [`atmosphere::pressure_altitude_m`] walks the same ICAO layers as [`air_at`] outside
28//! the troposphere band. [`atmosphere::nws_pressure_altitude_ft`] continues the NWS
29//! troposphere formula everywhere, and [`atmosphere::faa_rule_density_altitude_ft`] keeps
30//! that continuation so density-altitude entry remains its inverse. The bridge reports
31//! the layered pressure altitude and both FAA and density-matched altitudes wherever they land.
32//!
33//! [`AtmosphereError::refusal_in`] and [`AtmosphereError::temperature_refusal_from`] let a
34//! boundary name the originating flag, CSV column, profile field or request member in its
35//! own units, including a refusal discovered aloft. [`StationOrigin`] retains independent
36//! temperature and pressure sources; a QNH is quoted as sent with its reduced pressure.
37//! The JSON C bridge carries the request field path. Scalar and struct C APIs keep their
38//! existing NULL, NaN or status failure signals.
39
40// Re-export the main types and functions
41pub use atmosphere::{
42 air_at, resolve_station_conditions_with_presence, AirField, AirRefusal, AirSpelling,
43 AltitudeUnit, AtmoSegment, AtmoSock, AtmosphereError, AtmosphereErrorReason, KernelAtmosphere,
44 LocalAir, RelativeHumidity, StationAir, StationAtmospherePresence, StationOrigin,
45 StationPressureOrigin, StationReading, StationTemperatureOrigin, DEFAULT_HUMIDITY_PERCENT,
46 HUMIDITY_SENSOR_TOLERANCE_PERCENT,
47};
48pub use cli_api::{
49 calculate_zero_angle, calculate_zero_angle_with_conditions,
50 calculate_zero_angle_with_resolved_conditions, calculate_zero_angle_with_station_presence,
51 calculate_zero_range_from_angle_with_conditions,
52 calculate_zero_range_from_angle_with_resolved_conditions,
53 calculate_zero_range_from_angle_with_station_presence, estimate_bc_fit,
54 estimate_bc_fit_with_station_presence, estimate_bc_from_trajectory,
55 interpolate_powder_temp_curve, resolve_powder_adjusted_velocity, run_monte_carlo,
56 run_monte_carlo_adaptive_seeded, run_monte_carlo_adaptive_seeded_with_station_presence,
57 run_monte_carlo_with_direction_std_dev, run_monte_carlo_with_station_presence,
58 run_monte_carlo_with_wind, run_monte_carlo_with_wind_and_direction_std_dev,
59 run_monte_carlo_with_wind_and_direction_std_dev_seeded, AdaptiveMcReportV1,
60 AtmosphericConditions, BallisticInputs, BallisticsError, BcEstimate, BcFitMode,
61 BcReferenceStandard, DropsReference, McConvergence, McStopReason, MonteCarloParams,
62 MonteCarloResults, TrajectoryPoint, TrajectoryResult, TrajectorySolver, WindConditions,
63 ZeroCrossings, DEFAULT_HIT_RADIUS_M, MAX_TRAJECTORY_POINTS, MC_ADAPTIVE_ASSUMPTIONS_V1,
64 MC_ADAPTIVE_METHOD_V1, MC_ADAPTIVE_SCHEMA_VERSION_V1, TARGET_NOT_REACHED_SENTINEL_M,
65 ZERO_RANGE_FROM_ANGLE_MAX_RANGE_M,
66};
67pub use drag_model::DragModel;
68pub use mc_stats::{wilson_interval, ConfidenceLevel};
69pub use moving_target::{
70 calculate_lead, calculate_lead_with_station_presence, lead_from_tof, mover_ring,
71 LeadComponents, LeadError, LeadSolution,
72};
73pub use solve_json::{
74 decode_solve_request_v1, ResolvedSolveRequestV1, SolveErrorCodeV1, SolveErrorEnvelopeV1,
75 SolveRequestV1, SolveSuccessV1, MAX_SOLVE_JSON_SAMPLES_V1, SOLVE_JSON_SCHEMA_VERSION_V1,
76};
77pub use solve_v1::solve_v1;
78pub use trajectory_observation::{
79 TrajectoryObservation, TrajectoryObservationError, TrajectoryObservationFlag,
80 TrajectoryTermination,
81};
82pub use trajectory_sampling::MAX_TRAJECTORY_SAMPLES;
83
84// Module declarations
85pub mod cli_api;
86// MBA-1375: deterministic reference-family BC conversion and banded least-squares family
87// recommendation, shared by native and WASM front ends. Pure table math; no filesystem I/O.
88pub mod bc_conversion;
89mod drag_model;
90mod gravity;
91pub mod moving_target;
92// The C ABI. Gated behind the default-on `ffi` feature so a binary that links two versions of
93// this crate can disable it on one edge and avoid duplicate #[no_mangle] symbols.
94#[cfg(feature = "ffi")]
95pub mod ffi;
96pub mod solve_json;
97pub mod solve_v1;
98// 0.33.0 decision-support Task 2: reverse conversion from a resolved request back into a
99// solvable one (`impl From<&ResolvedSolveRequestV1> for SolveRequestV1`), the direction the
100// perturbation kernel needs to take a resolved request, change one input, and re-solve. No
101// public items of its own -- the trait impl is usable wherever solve_json's public types are.
102mod request_roundtrip;
103pub mod terminal_plot;
104// MBA-1343: multi-observation velocity/BC truing core, shared by the CLI and the WASM terminal.
105pub mod truing;
106// MBA-1346: observation-range experiment design for identifiable MV/BC truing.
107pub mod truing_plan;
108// MBA-1353: opt-in uncertainty-aware joint MV/BC truing.
109pub mod truing_uncertainty;
110// MBA-1357: Mach-keyed DSF (drop-scale-factor) truing table — a drop-only post-processing
111// correction applied to a solved TrajectoryResult. No feature gate: must compile for wasm32;
112// fs-free (profile persistence lives in main.rs).
113pub mod truing_dsf;
114// MBA-1392: back-solve the effective crosswind from an observed horizontal miss (wind-call
115// truing). Carries its own shared table/JSON/CSV formatter so the native CLI and the WASM
116// terminal render identical bytes. No feature gate: must compile for wasm32.
117pub mod truing_wind;
118// Task 6 (truing JSON bridge): the tall-target correction-factor arithmetic, extracted out
119// of the CLI's `Commands::TallTarget` arm so the CLI and a future bridge command share one
120// implementation. No feature gate: must compile for wasm32; fs-free (the CLI keeps its
121// println! formatting, only the arithmetic and validation moved here).
122pub mod truing_service;
123// MBA-1349: robust hold corridors across named segmented-wind scenarios. No feature gate:
124// must compile for wasm32 (the CLI surface is native-only this train, but the core and its
125// shared formatter are ready for the WASM follow-up); fs-free — file reading stays in
126// main.rs, this module parses TEXT.
127pub mod wind_scenarios;
128// MBA-1361: reticle schema, parametric generators, and the hold-point-in-reticle API,
129// shared by the CLI, the WASM terminal and the FFI. No feature gate: must compile for
130// wasm32; pure math + serde, no I/O (file reading stays in main.rs/wasm.rs).
131pub mod reticle;
132// MBA-1440: import Bero's "Ventum" reticle spec into `reticle::ReticleDescription` so a
133// reticle drawn in that tool can be hold-solved by `reticle::hold_point_in_reticle`. Pure
134// transform + serde, no I/O; must compile for wasm32. Deliberately NOT wired into the
135// CLI / solve-json / WASM / FFI surfaces yet (that exposure is held for review).
136pub mod reticle_import;
137// MBA-1545: named reticles by id — the per-vendor catalog `reticle`'s header defers
138// to, kept in its own module so that module's "no vendor reticle catalog" statement
139// stays true of the module it was made about. Provenance per entry is mandatory.
140pub mod reticle_catalog;
141// Cleanroom import of the third-party `.reticle` XML drawing format into
142// `reticle::ReticleDescription`, the sibling of `reticle_import` for a format that is a
143// picture rather than a mark list: its `<bdc>` entries are the holds, its `<elements>`
144// drawing is dropped (and counted, so the rule is visible). Pure transform, no I/O; must
145// compile for wasm32. Deliberately NOT wired into the CLI / solve-json / WASM / FFI
146// surfaces (that exposure is a separate decision).
147pub mod reticle_document_import;
148// MBA-1343 Phase B: WEZ (`monte-carlo --wez`) sweep core, shared by the CLI and the WASM terminal.
149pub mod wez;
150// MBA-1355: turret adjustment-unit conversions (SMOA/IPHY/clicks) and click-value parsing,
151// shared by the CLI and the WASM terminal. No feature gate: must compile for wasm32.
152pub mod adjustment;
153// MBA-1409: cleanroom `.drg` (Doppler drag-curve text file) parser, shared by the CLI and
154// the WASM terminal. No feature gate: must compile for wasm32; parses TEXT only (no
155// std::fs — file I/O stays in main.rs/wasm.rs).
156pub mod drag_file;
157// MBA-1372: SAAMI free-recoil momentum-balance calculator, shared by the CLI and the
158// WASM terminal. No feature gate: must compile for wasm32; pure math, no I/O.
159pub mod recoil;
160// MBA-1372: power-factor arithmetic and per-organization (USPSA/IDPA/SASS) rulebook
161// pass/fail thresholds, shared by the CLI and the WASM terminal. No feature gate: must
162// compile for wasm32; pure math + a data table, no I/O.
163pub mod power_factor;
164pub mod trajectory_observation;
165#[cfg(target_arch = "wasm32")]
166pub mod wasm;
167#[cfg(test)]
168mod wasm_tests;
169// The 0.50.0 humidity work's byte-identity pins for the pub(crate) gravity-aware entry points,
170// beside the public-API pins in tests/humidity_byte_identity.rs.
171#[cfg(test)]
172mod humidity_byte_identity_tests;
173// MBA-154: Make constants public for ballistics_rust wrapping
174pub mod atmosphere;
175// `atmosphere.density_altitude`: describe an atmosphere the way a solve resolves it.
176// Unconditional -- pure arithmetic over the solve-json schema, so it exists on every
177// target the bridge does, including wasm32, which has no PDF card.
178pub mod atmosphere_service;
179pub mod constants;
180pub mod drag;
181pub mod wind;
182// MBA-153: Make wind_shear public for ballistics_rust wrapping
183pub mod wind_shear;
184// MBA-154: Make derivatives public for ballistics_rust wrapping
185pub mod derivatives;
186pub mod trajectory_sampling;
187// MBA-154: Make fast_trajectory public for ballistics_rust wrapping
188pub mod fast_trajectory;
189// MBA-155: Add advanced integration methods (RK4, RK45)
190pub mod trajectory_integration;
191// MBA-149 Phase 5 Priority 2: Export enhanced spin_drift
192pub mod pitch_damping;
193pub mod spin_decay;
194pub mod spin_drift;
195pub mod spin_drift_advanced;
196// MBA-149 Phase 5 Priority 2: Export enhanced precession_nutation
197pub mod precession_nutation;
198// MBA-153: Make aerodynamic_jump public for ballistics_rust wrapping
199pub mod aerodynamic_jump;
200// MBA-149 Phase 5 Priority 2: Export enhanced angle_calculations
201pub mod angle_calculations;
202pub mod transonic_drag;
203// MBA-153: Make reynolds public for ballistics_rust wrapping
204pub mod reynolds;
205// MBA-149 Phase 5 Priority 2: Export enhanced form_factor
206pub mod form_factor;
207// MBA-153: Make monte_carlo public for ballistics_rust wrapping
208pub mod bc_estimation;
209pub mod cluster_bc;
210// MBA-1352 Task 2: Monte Carlo hit-statistics foundation -- Welford streaming moments and
211// fixed-n Wilson score intervals. The anytime-valid confidence sequence (Task 3) extends this
212// module. No feature gate: must compile for wasm32; pure std math, no randomness.
213pub mod mc_stats;
214pub mod monte_carlo;
215pub mod stability;
216pub mod stability_advanced;
217// 0.33.0 decision-support Phase 1: shared input taxonomy for perturbation kernel and
218// uncertainty propagation. No feature gate: must compile for wasm32 (pure data + serde).
219pub mod perturbation;
220// MBA-1345: explain why two fully resolved solve results differ, by symmetric counterfactual
221// swap of each input group (built on `perturbation`'s Tasks 5-8 kernel). No feature gate: must
222// compile for wasm32 (depends only on perturbation/solve_json/solve_v1, all unconditional).
223pub mod explain;
224// MBA-1347: erf/erfc/normal_cdf for hit-probability integration (mass of a bivariate
225// normal over a target). In-crate rather than a dependency: the crate ships to thirteen
226// platforms including big-endian MIPS and wasm32 and already hand-rolls its statistical
227// constants. No feature gate: must compile for wasm32; pure std float math, no I/O.
228pub mod special;
229// 0.33.0 decision-support Task 10, MBA-1347: propagate declared per-input uncertainty to
230// impact covariance via the perturbation kernel's central differences, and rank sources by
231// variance share into a measurement-priority report. Built on `perturbation` (Tasks 5-8) and
232// reuses `truing_uncertainty::Symmetric2` for the 2x2 covariance/eigenvalue arithmetic. No
233// feature gate: must compile for wasm32 (depends only on perturbation/solve_json/
234// truing_uncertainty, all unconditional).
235pub mod error_budget;
236// 0.33.0 decision-support Task 12, MBA-1350: one-variable tolerance envelopes -- how far a
237// single input may drift from its own current value before the impact leaves an explicit
238// target, by monotone bisection outward from the nominal (`perturbation::bisect_axis`, Task 7).
239// Reuses `error_budget::TargetGeometryV1` and its unavailable-axis classification verbatim. No
240// feature gate: must compile for wasm32 (depends only on perturbation/error_budget/solve_json,
241// all unconditional).
242pub mod tolerance;
243// 0.33.0 decision-support Task 3, MBA-1348: turret + reticle geometry model (click
244// detents/revolutions, zero stop, travel limits, current turret state, reticle hold
245// bounds) that a later dial/hold/hybrid engagement planner will read. Pure data +
246// validation; no feature gate: must compile for wasm32 (depends only on `adjustment`,
247// itself unconditional).
248pub mod optic;
249// 0.33.0 decision-support Task 8: `HoldCurve`, the drop-vs-range interpolation core shared
250// by `mark-to-range`, `bdc-match`, `optimal-zero` and `reticle hold --range`, promoted out of
251// the CLI binary (together with the sampled-trajectory helpers it solves through) so the
252// range-card work its own doc comment already nominates can reuse it as a library dependency.
253// No feature gate: must compile for wasm32 (pure math over already-resolved inputs; no fs, no
254// clap -- CLI argument resolution stays in `main.rs`).
255pub mod card_service;
256pub mod hold_curve;
257// 0.33.0 decision-support Task 9: `CardRow`, the shared display-ready row type behind the
258// come-ups/range-table/wind-card/compare CLI surfaces, replacing four function-local row
259// structs that each said the same thing a different way. Pure data; no feature gate: must
260// compile for wasm32 (no fs, no clap, no pdf -- those stay in main.rs). Task 10 rewrites the
261// PDF dope card on `&[CardRow]`; Task 11 grows an adaptive-card engine here.
262pub mod card;
263// 0.33.0 decision-support Task 10: the PDF dope card, promoted out of the `ballistics`
264// binary (it was `mod pdf_dope_card;`, private to `main.rs`) so it can consume
265// `card::CardRow` directly instead of its own `DopeCardRow { range_yd: u32, .. }` -- that
266// u32-yards field couldn't express the non-integer ranges Task 11's adaptive card engine
267// produces. Feature-gated (unlike `card`): pulls in `printpdf` (PDF generation) and `dirs`
268// (font-file lookup), neither wasm32-safe nor free -- `pdf` is on by default but the
269// wasm32 build always passes `--no-default-features`.
270#[cfg(feature = "pdf")]
271pub mod pdf_dope_card;
272
273// Online mode: HTTP client for Flask API (feature-gated)
274#[cfg(feature = "online")]
275pub mod api_client;
276
277#[cfg(feature = "online")]
278pub mod credentials;
279
280// BC5D table auto-download (feature-gated)
281#[cfg(feature = "online")]
282pub mod bc_table_download;
283
284// BC correction table for offline mode
285pub mod bc_table;
286
287// 5D BC correction tables (caliber-specific, ML-derived)
288pub mod bc_table_5d;
289
290// Saved-profile data model (ProfileData & friends), moved from main.rs so the bridge's
291// profile.validate/profile.normalize/profile.import_a7p commands and the CLI share one
292// serde wire shape. No feature gate: must compile for wasm32; fs-free (profile
293// persistence and unit conversion of loaded profiles stay in main.rs).
294pub mod profile;
295
296// Import of third-party ballistic profile files (.a7p), feature-gated
297#[cfg(feature = "profile-import")]
298pub mod profile_import;
299
300// MBA-1556: the outbound direction — ProfileData -> .a7p — with the list of every
301// ProfileData field the format cannot carry. Its own feature because writing a
302// third-party format is a separate capability from reading one; it implies
303// `profile-import`, whose MD5 envelope helper (`wrap_payload`) it shares so both
304// directions agree on the envelope by construction rather than by review.
305#[cfg(feature = "profile-export")]
306pub mod profile_export;
307
308// Versioned JSON command bridge for embedded (mobile/FFI) consumers
309#[cfg(feature = "bridge")]
310pub mod bridge;
311
312// Internal type alias for compatibility
313pub(crate) type InternalBallisticInputs = BallisticInputs;
314
315// BC segment data for velocity-dependent BC
316#[derive(Debug, Clone)]
317pub struct BCSegmentData {
318 pub velocity_min: f64,
319 pub velocity_max: f64,
320 pub bc_value: f64,
321}