ballistics-engine 0.32.0 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,1040 +1,131 @@
1
- # Ballistics Engine
1
+ # ballistics-engine (WASM)
2
2
 
3
- A high-performance ballistics trajectory calculation engine with comprehensive physics modeling, automatic zeroing, and statistical analysis capabilities.
3
+ WebAssembly build of [`ballistics-engine`](https://github.com/ajokela/ballistics-engine), a
4
+ high-performance ballistics trajectory engine (RK4 integration, wind/Coriolis/spin-drift/Magnus
5
+ effects, custom drag tables, Monte Carlo, and more). This package exposes the same CLI-style
6
+ command surface as the native Rust binary, plus a small object-oriented `Calculator` class, to
7
+ JavaScript/TypeScript.
4
8
 
5
- **Project Website:** [https://ballistics.rs/](https://ballistics.rs/)
9
+ Built with `wasm-pack` and `--no-default-features` — the native crate's default `pdf`/`online`
10
+ features pull in dependencies that don't compile for `wasm32-unknown-unknown`, so the PDF dope-card
11
+ export and the online BC-estimation API are not available from WASM.
6
12
 
7
- ## Features
13
+ > This package is built from `pkg/` (the `wasm-pack --target bundler` output) via
14
+ > `scripts/build-npm.sh` in the source repo. The same script also produces a `pkg-web/` build
15
+ > (`--target web`) for use without a bundler — see "Browser without a bundler" below.
8
16
 
9
- - **Full 3D Trajectory Integration** - Six-state ballistic modeling with adaptive RK45 and fixed-step RK4 integration methods
10
- - **Advanced Drag Models** - Full standard-projectile family (G1, G2, G5, G6, G7, G8, GI, GS, and the British RA4 reference function), each backed by its own real Mach-indexed table with automatic transonic corrections, plus user-supplied custom Cd(Mach) drag tables (`--drag-table`, used as-is with endpoint hold outside their measured domain, no transonic correction applied — see [CLI_USAGE.md](CLI_USAGE.md#custom-drag-tables); `bc_value` is ignored while a custom table is active), with an optional `--cd-scale <FACTOR>` whole-curve truing multiplier (Hornady AFF / AB CDF style; `1.0` = neutral, typical range 0.90-1.10; requires `--drag-table` — see [CLI_USAGE.md](CLI_USAGE.md#whole-curve-drag-scale---cd-scale)). `true-velocity`/`plan-truing`'s forward model is deliberately G1/G7 only. GL is out of scope — its only public source is velocity-domain data, which doesn't fit this engine's Mach-indexed table format.
11
- - **Automatic Zeroing** - Calculate sight adjustments and apply zero angles automatically; `trajectory` echoes the solved bore angle (degrees, additive across table/JSON/CSV) whenever auto-zero ran, and `zero --from-angle <DEGREES>` solves the zero RANGE(S) a previously solved/stored bore angle produces — a bore angle generally implies two zeros (the classic 25/300-yard relationship), so both are reported rather than one being silently picked — so the angle can be captured once and reused later, independent of the day it was solved — see [CLI_USAGE.md](CLI_USAGE.md#solving-range-from-a-stored-angle---from-angle)
12
- - **Canted-Rifle Modeling** - Model a rifle zeroed level but fired canted (`--cant <DEGREES>`, alias `--cant-angle`, on `trajectory`/`monte-carlo`); clockwise cant shifts point of impact right and low downrange for a rifle with an upward zero correction — see [CLI_USAGE.md](CLI_USAGE.md#canted-shooting)
13
- - **Deliberate Zero POI Offset** - Record that the rifle is deliberately zeroed off — e.g. 0.1 in high / 0.2 in left at the zero range (Kestrel ZH/ZO semantics) — and shift the whole solution by the equivalent angular bias (`--zero-poi-up`/`--zero-poi-right`, inches imperial / cm metric, on `trajectory` and every zero-solving subcommand; solve-json `shot.zero_poi_up_m`/`zero_poi_right_m`; saved-profile fields; `.a7p` zero click counts convertible via `profile import --zero-click`) — see [CLI_USAGE.md](CLI_USAGE.md#sight-geometry-and-zero-state)
14
- - **Lateral Sight Offset** - Model offset-mounted optics (`--sight-offset`, inches imperial / mm metric, positive = sight right of bore): the bullet starts that far left of the sight line and the windage zero converges it onto the sight line at the zero range — physical mount geometry, distinct from and additive with the zero POI offset (solve-json `rifle.sight_offset_lateral_m`; saved-profile field; also on `monte-carlo`/WEZ mirroring `--cant`) — see [CLI_USAGE.md](CLI_USAGE.md#sight-geometry-and-zero-state)
15
- - **Multiple Named Zeroes / Per-Load Offsets in Profiles** - Store alternate zero conditions on a saved profile (Lapua Sight-In POI / ATrag zero-zone class): each named set carries an optional zero distance plus constant per-load dial corrections in mils (`profile zero-set add|remove|list`; `--zero-set NAME` on `trajectory`/`come-ups`/`wind-card`/`range-table`/`dsf`/`plan-truing`; corrections are added to total-correction dial outputs before the tracking-CF division; profile-CSV `V_OFFSET_MIL`/`H_OFFSET_MIL` columns and `.a7p --zero-click` import feed sets automatically; unknown names fail loudly listing the available sets) — see [CLI_USAGE.md](CLI_USAGE.md#named-zero-sets-and-per-load-offsets-profile-zero-set---zero-set)
16
- - **Drops Reference: LOS vs Target Plane** - Reference sampled drops to the line of sight (default, unchanged) or to the vertical target plane on steep inclined shots (`trajectory --drops-reference target`: drop ÷ cos(shooting angle), JBM's "target plane" checkbox; sampled table/CSV column relabeled `Drop (target)`/`drop_target_in`; solve-json `shot.drops_reference`) — see [CLI_USAGE.md](CLI_USAGE.md#drops-reference-los-vs-target-plane---drops-reference--mba-1403)
17
- - **Scope Tracking Correction Factors** - Compensate turrets that don't track their nominal click value: derive `CF = actual/dialed` from a tall-target test (`tall-target` subcommand, pure arithmetic), then `--elevation-cf`/`--windage-cf` (or validated saved-profile fields) DIVIDE every dial-unit output once at the shared conversion boundary — come-ups, range/compare/wind cards, mover lead/Ring, PDF dope card, zero MOA/mrad — never raw inches (an under-tracking scope, CF < 1, needs more dial); `true-velocity` multiplies dialed observations by the CF (scope-dial to true angular) so scope error is not baked into trued MV/BC — see [CLI_USAGE.md](CLI_USAGE.md#scope-tracking-correction-factors---elevation-cf---windage-cf-tall-target--mba-1358)
18
- - **Equivalent Horizontal Range (BDC shoot-to)** - Inclined zeroed shots print the flat range whose angular correction against the same zero matches the inclined solution (SIG AMR / Leica EHR / Gunwerks style, angular-match inversion over one flat re-solve — not the rifleman's-rule cosine), so fixed BDC turrets/reticles can dial as if flat (`trajectory` summary line; solve-json `summary.equivalent_horizontal_range_m`; public `TrajectorySolver::equivalent_horizontal_range`) — see [CLI_USAGE.md](CLI_USAGE.md#equivalent-horizontal-range-bdc-shoot-to--mba-1395)
19
- - **Reticle Hold Points** - Place a firing solution where you actually read it: a point in your own reticle, FFP/SFP aware with second-focal-plane subtensions rescaled for the magnification in use (`reticle hold`, native + browser terminal + a new appended C ABI export; `reticle generate mil-grid|tree|bdc` builds descriptions in one shared serde schema that saved profiles, `--reticle-json` and solve-json's optional `reticle` block all speak). Horus/TREMOR grid layouts, wind-dot calibration and any vendor catalog are deliberately excluded — see [CLI_USAGE.md](CLI_USAGE.md#reticle-hold-points-reticle--mba-1361)
20
- - **Reticle/BDC Inverse Solvers** - Three read-only solvers over an existing load, sharing one drop-vs-range root find: `mark-to-range` maps each reticle subtension to the range where it lands (Nightforce / Nikon Spot On / Swarovski / TRACT), reporting marks the load cannot reach rather than dropping them; `bdc-match` fits the magnification that makes an SFP BDC reticle match the load (Zeiss Rapid-Z; closed-form least squares, with a residual warning when nothing fits); `optimal-zero` min-max searches the one zero that minimizes the largest hold a whole target list needs and reports whether a dead-center hold keeps each inside its vital zone (GeoBallistics HDZ). CLI-only this train — see [CLI_USAGE.md](CLI_USAGE.md#reticlebdc-inverse-solvers--mba-1362)
21
- - **Robust Hold Corridors** - Solve a bounded set of NAMED segmented-wind scenarios at once (`hold-corridor --scenarios set.json --ranges 200,400,600 [--target rect:WxH|circle:D]`) and get, at every range, each scenario's hold, the min/max corridor they span, the minimax (Chebyshev-center) hold, the worst-case miss from it, and whether one hold keeps every scenario inside the target — with a versioned `RobustHoldReportV1` JSON form. Caps (≤8 scenarios, ≤64 ranges) and malformed segments are structured errors raised *before* any solving, and reordering scenarios cannot change the answer. No probabilities are assigned anywhere: the corridor is the span of the hypotheses you supplied, not a confidence interval — see [CLI_USAGE.md](CLI_USAGE.md#robust-hold-corridors-hold-corridor--mba-1349)
22
- - **Moving-Target Lead** - Wind-aware hold tables for targets moving at a constant speed/angle, with iterative intercept-range correction for non-perpendicular motion (`lead` subcommand; public `ballistics_engine::calculate_lead` API) — see [CLI_USAGE.md](CLI_USAGE.md#moving-target-lead)
23
- - **Mover Ring** - Field-tested alternative for engaging movers: a per-point ring radius (`target_speed × time-of-flight`) falls out of an already-solved trajectory with no second command or re-entered ballistic data (`trajectory --target-speed`, additive across table/JSON/CSV output); `lead` also gained `trajectory`'s powder-temperature flags for muzzle-velocity parity between the two — see [CLI_USAGE.md](CLI_USAGE.md#mover-ring---target-speed)
24
- - **Side-by-Side Load Comparison** - Compare 2-8 loads at identical conditions with per-load independent zeroing (`compare --load "NAME:DRAG:BC:MASS:VELOCITY[:DIAMETER]"`, mixable with saved profiles); JSON/CSV output carries per-row deltas against the first load — see [CLI_USAGE.md](CLI_USAGE.md#load-comparison-compare)
25
- - **Powder Temperature Command** - Resolve the temperature-adjusted muzzle velocity standalone, without a trajectory solve (`powder` subcommand): linear fps-per-degree model or a measured temperature→velocity curve, optional `--sweep` velocity ladder and muzzle energy; shares the solvers' exact resolution code (public `resolve_powder_adjusted_velocity` API) — see [CLI_USAGE.md](CLI_USAGE.md#powder-temperature-velocity-powder)
26
- - **Unit Conversion** - Seamless switching between Imperial (default) and Metric units
27
- - **BC Segmentation** - Velocity-dependent ballistic coefficient modeling with automatic estimation
28
- - **Atmospheric Modeling** - Temperature, pressure, humidity, and altitude effects with ICAO standard atmosphere; also accepts a single **density altitude** reading (`trajectory --density-altitude`, feet imperial / meters metric) as a direct alternative to entering altitude/pressure/temperature separately — back-solves an ISA-equivalent atmosphere (preserving Mach/lapse-rate/segmented-atmosphere behavior, not a density-only shortcut) and supersedes `--altitude`/`--pressure`/`--pressure-type` entirely, with an explicit `--temperature` still honored for correct powder-temperature sensitivity — see [CLI_USAGE.md](CLI_USAGE.md#density-altitude-as-a-direct-input---density-altitude)
29
- - **Clock-Position Wind Entry** - Enter wind direction as the dominant field convention: marked clock positions (`--wind-direction 3oc`, `10h30`, or `10:30`; 12 o'clock = headwind, minutes count 0.5°) alongside plain degrees on every wind-direction flag and the WASM terminal; inside `--wind-segment` the colon-free forms apply (`10:3oc:400`) while `10:30:400` keeps its numeric SPEED:ANGLE:DIST meaning; bare numbers stay degrees everywhere — see [CLI_USAGE.md](CLI_USAGE.md#wind-direction-entry-degrees-clock-positions--mba-1367)
30
- - **Earth-Fixed Compass Wind Bearings** - Store wind as absolute compass bearings and let the solver re-reference them against the shot azimuth (`--wind-ref compass` + `--shot-direction` on `trajectory`/`monte-carlo`; covers the single direction, location-CSV WIND_DIR, and every `--wind-segment` angle; Monte Carlo converts before dispersion sampling; solve-json `wind.wind_reference`; WASM builder `setWindReference`/`setShotDirection`; wind FROM north on a shot due north = pure headwind, pinned) — see [CLI_USAGE.md](CLI_USAGE.md#earth-fixed-compass-bearings---wind-ref-compass--mba-1368)
31
- - **Wind Effects** - 3D wind calculations with altitude-dependent wind shear modeling, **downrange-segmented wind** (`--wind-segment SPEED:ANGLE:DIST[:VERTICAL]`, repeatable — model wind that varies along the path, e.g. muzzle plus downrange sensor readings), and **vertical wind** (`--wind-vertical <SPEED>` on `trajectory`/`monte-carlo`, or the segment's optional 4th field; positive = updraft, raises point of impact) — see [CLI_USAGE.md](CLI_USAGE.md#vertical-wind)
32
- - **Oblique Wind-Drift Cards** - Wind dope cards at any wind-FROM angle, not just full-value 90° crosswind (`wind-card --wind-angle <DEG>` or `--wind-angles <CSV>` for one card per angle); each cell is a real trajectory solve, default (no flags) unchanged from the classic full-value 90° card — see [CLI_USAGE.md](CLI_USAGE.md#wind-card)
33
- - **Monte Carlo Simulations** - Statistical analysis with parameter uncertainties
34
- - **BC Estimation** - Estimate ballistic coefficients from trajectory data
35
- - **Advanced Physics**:
36
- - **Spin Effects**: Magnus effect and empirical Litz spin drift
37
- - **Earth Effects**: Coriolis effect with latitude-dependent calculations
38
- - **Angular Motion**: Gyroscopic precession and nutation physics
39
- - **Transonic Analysis**: Pitch damping coefficients and stability warnings
40
- - **Trajectory Sampling**: Regular interval data collection for analysis
41
- - **Form Factor Corrections**: Bullet-specific drag adjustments
42
- - **Multiple Output Formats** - JSON, CSV, formatted tables, and printable PDF dope cards
43
- - **Terminal Chart** - Inline drop, drift, velocity, and energy vs. range charts right in the terminal (`trajectory --plot`, Unicode braille-dot canvas by default, `--plot ascii` fallback); pure Rust, zero new dependencies, no ANSI colors — see [CLI_USAGE.md](CLI_USAGE.md#terminal-chart---plot)
44
- - **Profile import**: `ballistics profile import file.a7p` — imports ArcherBC2 `.a7p` profiles (rifle, bullet, atmosphere, zero) with a full mapping report; `--dry-run` previews without saving
45
- - **Online Reverse Solvers** - Optional `login` + `recommend-powder`/`recommend-twist`/`recommend-col`/`calibrate-bc` subcommands query the hosted service for load, twist, cartridge-overall-length, and BC suggestions using a CLI access token saved from your ballisticsinsight.com account (`BALLISTICS_API_TOKEN` env var, or `~/.ballistics/credentials.toml`); all local subcommands work offline with no token — see [CLI_USAGE.md](CLI_USAGE.md#online-reverse-solvers)
46
-
47
- ## Installation
48
-
49
- ### From crates.io
50
-
51
- ```bash
52
- cargo install ballistics-engine
53
- ```
54
-
55
- ### From Source
56
-
57
- ```bash
58
- git clone https://github.com/ajokela/ballistics-engine.git
59
- cd ballistics-engine
60
- cargo build --release
61
- ```
62
-
63
- The binary will be at: `target/release/ballistics`
64
-
65
- ### Feature Flags
66
-
67
- | Feature | Default | Description |
68
- |---------|---------|-------------|
69
- | `online` | ✅ Yes | HTTP client for API integration (`--online` flag) |
70
-
71
- To build without network capabilities:
72
- ```bash
73
- cargo build --release --no-default-features
74
- ```
75
-
76
- ## Quick Start
77
-
78
- ### Basic Trajectory (Imperial Units - Default)
79
-
80
- ```bash
81
- # .308 Winchester, 168gr bullet at 2700 fps
82
- ./ballistics trajectory -v 2700 -b 0.475 -m 168 -d 0.308 --max-range 1000
83
-
84
- # With automatic zeroing at 200 yards
85
- ./ballistics trajectory -v 2700 -b 0.475 -m 168 -d 0.308 --auto-zero 200 --max-range 500
86
- ```
87
-
88
- ### Metric Units
89
-
90
- ```bash
91
- # Same bullet in metric units
92
- ./ballistics trajectory --units metric -v 823 -b 0.475 -m 10.9 -d 7.82 --max-range 1000
93
- ```
94
-
95
- ## Unit Systems
96
-
97
- The engine supports two unit systems, selectable with the `--units` flag:
98
-
99
- ### Imperial (Default)
100
- - **Velocity**: feet per second (fps)
101
- - **Mass**: grains
102
- - **Distance**: yards
103
- - **Diameter**: inches
104
- - **Temperature**: Fahrenheit
105
- - **Pressure**: inHg
106
- - **Wind**: mph
107
-
108
- ### Metric
109
- - **Velocity**: meters per second (m/s)
110
- - **Mass**: grams
111
- - **Distance**: meters
112
- - **Diameter**: millimeters
113
- - **Temperature**: Celsius
114
- - **Pressure**: hPa (millibars)
115
- - **Wind**: m/s
116
-
117
- ## Commands
118
-
119
- ### Trajectory Calculation
120
-
121
- Calculate ballistic trajectory with environmental conditions:
122
-
123
- ```bash
124
- # Imperial units (default)
125
- ./ballistics trajectory \
126
- -v 2700 # Velocity (fps)
127
- -b 0.475 # Ballistic coefficient
128
- -m 168 # Mass (grains)
129
- -d 0.308 # Diameter (inches)
130
- --drag-model g7 # G7 drag model
131
- --angle 0 # Launch angle (degrees)
132
- --max-range 1000 # Maximum range (yards)
133
- --wind-speed 10 # Wind speed (mph)
134
- --wind-direction 90 # Wind from right (degrees)
135
- --temperature 59 # Temperature (Fahrenheit)
136
- --pressure 29.92 # Pressure (inHg)
137
- --humidity 50 # Relative humidity (%)
138
- --altitude 0 # Altitude (feet)
139
- --full # Show all trajectory points
140
- ```
141
-
142
- #### Auto-Zero Feature
143
-
144
- Automatically calculate and apply the zero angle for a specific distance:
145
-
146
- ```bash
147
- # Zero at 200 yards and show trajectory to 500 yards
148
- ./ballistics trajectory \
149
- -v 2700 -b 0.475 -m 168 -d 0.308 \
150
- --auto-zero 200 \ # Automatically zero at 200 yards
151
- --max-range 500 \
152
- --full
153
-
154
- # Custom sight height for auto-zero
155
- ./ballistics trajectory \
156
- -v 2700 -b 0.475 -m 168 -d 0.308 \
157
- --auto-zero 100 \
158
- --sight-height 0.055 # 2.2 inches in yards
159
- ```
160
-
161
- #### Zero-Day Conditions (zero shift)
162
-
163
- A rifle's zero is a fixed barrel angle set on the day you sighted in. If you later shoot
164
- in different weather — or with a different muzzle velocity (e.g. a cold vs. warm powder
165
- temperature) — the point of impact shifts. By default `--auto-zero` solves the zero angle
166
- using the same conditions you pass for the shot, which assumes you zeroed in today's
167
- conditions. The `--zero-*` flags let you decouple the two: the zero **angle** is solved
168
- under the conditions the rifle was actually zeroed in, while the trajectory itself runs
169
- under the current shot-day conditions.
170
-
171
- ```bash
172
- # Zeroed on a cold morning (28 F) at 2600 fps; shooting this afternoon at 85 F / 2700 fps.
173
- # The zero angle is solved for the cold/slow load, then the warm/fast trajectory is
174
- # computed against it — so the dope correctly shows the point of impact drifting high.
175
- ./ballistics trajectory \
176
- -v 2700 -b 0.19 -m 77 -d 0.224 --drag-model g7 \
177
- --temperature 85 --pressure 29.92 \
178
- --auto-zero 100 --max-range 1000 --full \
179
- --zero-velocity 2600 \
180
- --zero-temperature 28
181
- ```
182
-
183
- Available overrides (each independently optional; any omitted flag falls back to the
184
- shot-day value, so leaving them all off reproduces the previous behavior exactly):
185
-
186
- | Flag | Meaning | Units (imperial / metric) |
187
- |------|---------|---------------------------|
188
- | `--zero-velocity` | Muzzle velocity on the zeroing day | fps / m·s⁻¹ |
189
- | `--zero-temperature` | Air temperature on the zeroing day | °F / °C |
190
- | `--zero-pressure` | Barometric pressure on the zeroing day | inHg / hPa |
191
- | `--zero-humidity` | Relative humidity on the zeroing day | percent |
192
- | `--zero-altitude` | Altitude on the zeroing day | feet / meters |
193
-
194
- #### Powder Temperature
195
-
196
- Propellant temperature changes muzzle velocity. Two models are available:
197
-
198
- **Linear** — a constant sensitivity (fps or m/s per degree) applied relative to the
199
- temperature the load was chronographed at:
200
-
201
- ```bash
202
- ./ballistics trajectory -v 2700 -b 0.19 -m 77 -d 0.224 --drag-model g7 \
203
- --temperature 85 --use-powder-sensitivity \
204
- --powder-temp-sensitivity 1.2 --powder-temp 70 # +1.2 fps per F above 70 F
205
- ```
206
-
207
- **Measured curve (non-linear)** — real powders aren't perfectly linear (temperature-
208
- stable powders flatten; others steepen when hot). If you've chronographed the load at
209
- several temperatures, pass the points directly and the muzzle velocity is interpolated
210
- at the powder temperature (clamped at the endpoints — no extrapolation). This
211
- **overrides** `--powder-temp-sensitivity` when supplied:
212
-
213
- ```bash
214
- ./ballistics trajectory -v 2700 -b 0.19 -m 77 -d 0.224 --drag-model g7 \
215
- --temperature 85 \
216
- --powder-temp-curve "40:2620,70:2700,100:2760" # TEMP:VELOCITY points
217
- ```
218
-
219
- **Powder temperature vs air temperature.** The curve maps *powder* temperature to
220
- velocity, while `--temperature` drives air *density*. These are decoupled: the curve is
221
- looked up at `--powder-temp` when given, otherwise at `--temperature` (powder assumed at
222
- air temperature). So a load left in a hot chamber or a cold pocket:
223
-
224
- ```bash
225
- # 85 F air (density), but the powder is at 60 F (velocity from the curve at 60 F)
226
- ./ballistics trajectory ... --temperature 85 --powder-temp 60 \
227
- --powder-temp-curve "40:2620,70:2700,100:2760"
228
- ```
229
-
230
- Both powder models compose with `--auto-zero`, symmetrically. For the linear model,
231
- `--zero-temperature` resolves zero-day velocity relative to the reference `--powder-temp`.
232
- For a curve, `--zero-powder-temp` overrides the powder lookup; otherwise an explicit
233
- `--zero-temperature` is used, or the shot-day `--powder-temp` is inherited when no zero-day
234
- temperature was supplied. Zero-day atmosphere flags still drive air density independently.
235
- An explicit `--zero-velocity` takes precedence over either powder model.
236
-
237
- #### Bore Height and Ground Impact
238
-
239
- Control bore height above ground and ground impact detection:
240
-
241
- ```bash
242
- # Set bore height for prone shooting position (2 feet)
243
- ./ballistics trajectory \
244
- -v 2700 -b 0.475 -m 168 -d 0.308 \
245
- --auto-zero 100 \
246
- --bore-height 2 # 2 feet (imperial) or meters (metric)
247
-
248
- # Disable ground impact detection for full trajectory to max range
249
- ./ballistics trajectory \
250
- -v 2700 -b 0.475 -m 168 -d 0.308 \
251
- --auto-zero 100 \
252
- --max-range 1000 \
253
- --ignore-ground-impact
254
- ```
255
-
256
- Bore height defaults: 5 feet (imperial) / 1.5 meters (metric) - standing position.
257
-
258
- #### Advanced BC Modeling
259
-
260
- Enable velocity-dependent BC modeling for more accurate long-range predictions:
261
-
262
- ```bash
263
- # Enable BC segmentation (velocity-based BC changes)
264
- ./ballistics trajectory \
265
- -v 2700 -b 0.475 -m 168 -d 0.308 \
266
- --use-bc-segments \
267
- --auto-zero 600 \
268
- --max-range 1000
269
- ```
270
-
271
- #### Advanced Physics - Magnus and Spin Drift
272
-
273
- Enable advanced gyroscopic and aerodynamic effects:
274
-
275
- ```bash
276
- # Magnus effect and spin drift calculation
277
- ./ballistics trajectory \
278
- -v 2700 -b 0.475 -m 168 -d 0.308 \
279
- --twist-rate 10 # 1:10" barrel twist
280
- --twist-right # Right-hand twist
281
- --enable-magnus # Enable Magnus effect
282
- --enable-spin-drift # Enable empirical Litz spin drift
283
- --wind-speed 10 \
284
- --wind-direction 90 \
285
- --max-range 1000
286
-
287
- # Coriolis effect for extreme long range
288
- ./ballistics trajectory \
289
- -v 3000 -b 0.750 -m 250 -d 0.338 \
290
- --enable-coriolis \
291
- --latitude 45 # Shooting latitude
292
- --shooting-angle 90 # Azimuth (0=N, 90=E)
293
- --max-range 2000
294
- ```
295
-
296
- ### Zero Calculation
297
-
298
- Calculate the sight adjustment needed to zero at a specific distance:
299
-
300
- ```bash
301
- # Calculate zero for 200 yards
302
- ./ballistics zero \
303
- -v 2700 -b 0.475 -m 168 -d 0.308 \
304
- --target-distance 200
305
-
306
- # With custom sight height (default is 0.05 yards / 1.8 inches)
307
- ./ballistics zero \
308
- -v 2700 -b 0.475 -m 168 -d 0.308 \
309
- --target-distance 300 \
310
- --sight-height 0.055 # 2.2 inches
311
-
312
- # Metric example
313
- ./ballistics zero --units metric \
314
- -v 823 -b 0.475 -m 10.9 -d 7.82 \
315
- --target-distance 200 # 200 meters
316
- ```
317
-
318
- Output includes:
319
- - Zero angle in degrees
320
- - Adjustment in MOA (Minutes of Angle)
321
- - Adjustment in mrad (milliradians)
322
- - Maximum ordinate (highest point of trajectory)
323
-
324
- ### Monte Carlo Simulation
325
-
326
- Run statistical analysis with parameter variations:
327
-
328
- ```bash
329
- ./ballistics monte-carlo \
330
- -v 2700 # Base velocity (fps)
331
- -b 0.475 # Base BC
332
- -m 168 # Mass (grains)
333
- -d 0.308 # Diameter (inches)
334
- -n 1000 # Number of simulations
335
- --velocity-std 10 # Velocity std dev (fps)
336
- --angle-std 0.5 # Angle std dev (degrees)
337
- --bc-std 0.01 # BC std dev
338
- --wind-std 2 # Wind speed std dev (mph)
339
- --wind-direction-std 5 # Wind direction std dev (degrees)
340
- --target-distance 300 # Target distance for hit probability
341
- ```
342
-
343
- ### BC Estimation
344
-
345
- Estimate ballistic coefficient from observed trajectory data:
17
+ ## Install
346
18
 
347
19
  ```bash
348
- ./ballistics estimate-bc \
349
- -v 2700 -m 168 -d 0.308 \
350
- --distance1 100 --drop1 0.0 # First data point
351
- --distance2 200 --drop2 0.023 # Second data point
20
+ npm install @SCOPE/ballistics-engine
352
21
  ```
353
22
 
354
- ### True Velocity (Velocity Truing)
23
+ `@SCOPE` is a placeholder — see the source repo's `README.md` ("WASM / npm Package" section) for
24
+ the real published name once one exists.
355
25
 
356
- Calculate the effective muzzle velocity that produces a measured drop at a known range. This helps "true" your ballistic system by identifying discrepancies between chronograph readings and real-world performance.
26
+ ## Quick start (bundler: webpack, Vite, Rollup, Parcel)
357
27
 
358
- ```bash
359
- # Basic offline calculation
360
- ./ballistics true-velocity \
361
- --measured-drop 5.1 --range 600 \
362
- --bc 0.27 --drag-model g7 \
363
- --mass 140 --diameter 0.264 \
364
- --offline
365
-
366
- # With chronograph comparison
367
- ./ballistics true-velocity \
368
- --measured-drop 5.1 --range 600 \
369
- --bc 0.27 --drag-model g7 \
370
- --mass 140 --diameter 0.264 \
371
- --chrono-velocity 2822 \
372
- --offline
373
-
374
- # Chronograph measured downrange, not at the muzzle (MBA-1377): most
375
- # chronographs read 10-15 ft (or 25 m) downrange, so --chrono-distance
376
- # back-solves the true muzzle velocity from the raw reading
377
- ./ballistics true-velocity \
378
- --measured-drop 5.1 --range 600 \
379
- --bc 0.27 --drag-model g7 \
380
- --mass 140 --diameter 0.264 \
381
- --chrono-velocity 2822 --chrono-distance 15 \
382
- --offline
383
-
384
- # With BC5D tables for improved accuracy
385
- ./ballistics true-velocity \
386
- --measured-drop 5.1 --range 600 \
387
- --bc 0.27 --drag-model g7 \
388
- --mass 140 --diameter 0.264 \
389
- --bc-table-auto --offline
390
-
391
- # Joint MV + BC calibration from multiple observed impacts
392
- ./ballistics true-velocity \
393
- --range 300 --measured-drop 1.30 \
394
- --observed 600:4.40 --observed 900:9.00 \
395
- --bc 0.45 --drag-model g1 \
396
- --mass 168 --diameter 0.308
397
- ```
398
-
399
- Use case: A shooter measures 5.1 MIL of drop at 600 yards. Their chronograph showed 2822 fps. The command calculates the effective velocity is actually ~2740 fps, suggesting a -82 fps adjustment for accurate ballistic predictions.
400
-
401
- **Downrange chronograph correction (MBA-1377).** Most chronographs (and radar units) read some distance downrange rather than at the muzzle — 10-15 ft is typical for optical screens, 25 m for Lapua/JBM's reference distance — so the raw reading is a few fps low. `--chrono-distance` back-solves the true muzzle velocity from that reading via secant iteration on the same forward drag model (BC/`--drag-model`/atmosphere) the rest of the command uses; zero or absent is an exact no-op. It's a pure display-side correction (`--chrono-velocity` never feeds the drop-based solve either way) and validates its input to a sane 1-98 ft / 0.3-30 m band (100 ft is out of range) rather than silently extrapolating a bad distance into a bad velocity.
28
+ This package's `main` entry imports its `.wasm` file as a native ES module, which is how
29
+ `wasm-pack --target bundler` output is meant to be consumed. It works out of the box with Vite and
30
+ Rollup (`@rollup/plugin-wasm`), and with webpack once `experiments.asyncWebAssembly` (or
31
+ `experiments.syncWebAssembly`) is enabled — check your bundler's WASM docs if the import fails.
402
32
 
403
- **Joint velocity + BC truing.** With two or more `--observed RANGE:DROP` impacts spanning supersonic to transonic ranges, `true-velocity` fits *both* muzzle velocity and ballistic coefficient against the real trajectory solver. When the observation set is too short/closely-spaced to separate the two, it refuses the joint fit, trues velocity only, and says so — no false-precision BC. See [CLI_USAGE.md](CLI_USAGE.md#joint-mv--bc-calibration-multiple-observed-impacts) for details.
33
+ ```js
34
+ import { WasmBallistics } from '@SCOPE/ballistics-engine';
404
35
 
405
- **Plan the observations before shooting (MBA-1346).** `plan-truing` evaluates a
406
- discrete set of ranges with the same forward model and finite-difference Jacobian
407
- used by the fitter, then chooses an exact-size, minimum-separation-compliant design.
408
- It reports information gain, singular values, conditioning, rejected/unreachable
409
- candidates, and an explicit MV-only recommendation when the available facility
410
- cannot identify BC:
36
+ const calc = new WasmBallistics();
411
37
 
412
- ```bash
413
- ./ballistics plan-truing \
414
- -v 2700 -b 0.475 --drag-model g1 -m 168 -d 0.308 \
415
- --candidate-ranges 200,300,400,500,600,700,800,900 \
416
- --observation-count 3 --minimum-separation 100 \
417
- --measurement-resolution 0.03 --drop-unit mil
418
- ```
419
-
420
- `--measurement-resolution` is the assumed independent **one-standard-deviation**
421
- impact-reading error, not a tolerance or extreme bound. A saved scalar G1/G7
422
- profile may replace the explicit load flags (`--profile NAME`); velocity-banded BC
423
- profiles and custom drag curves are rejected because they do not have one scalar BC
424
- parameter to identify.
425
-
426
- **Quantify what the observations actually learned (MBA-1353).** Add
427
- `--observation-sigma` to opt into a weighted joint MV/BC MAP fit and local Gaussian
428
- uncertainty report. A third `--observed RANGE:DROP:SIGMA` field overrides the default
429
- for one reading. Optional priors are always visible and explicit; predictive output
430
- separates uncertainty in the modeled drop from the wider interval for a future
431
- reading:
432
-
433
- ```bash
434
- ./ballistics true-velocity \
435
- --range 500 --measured-drop 3.18 \
436
- --observed 600:4.35:0.03 --observed 900:8.89:0.02 \
437
- --observation-sigma 0.03 \
438
- --bc 0.45 --drag-model g1 --mass 168 --diameter 0.308 \
439
- --predict-range 1000 --prediction-sigma 0.03 --output json
38
+ // The command surface mirrors the native CLI (see CLI_USAGE.md in the source repo for the full
39
+ // flag reference): .308 Winchester, 168gr @ 2700 fps, zeroed at 200 yd, table out to 500 yd.
40
+ const table = calc.runCommand(
41
+ 'trajectory -v 2700 -b 0.475 -m 168 -d 0.308 --max-range 500 --auto-zero 200',
42
+ );
43
+ console.log(table);
440
44
  ```
441
45
 
442
- The report includes MV/BC 95% intervals, covariance and correlation, chi-square,
443
- effective degrees of freedom, prior-domination/weak-identification warnings, and
444
- propagated drop bands. Declared sigmas are treated as absolute known errors, so the
445
- covariance is not rescaled by residual RMS. With no uncertainty flags, the existing
446
- point estimate and output schema are unchanged.
46
+ ### Custom drag tables (`loadDragTable`)
447
47
 
448
- ### Wind-Call Truing (`true-wind`)
48
+ Supply a measured or manufacturer-published Mach:Cd drag curve (Hornady CDM data, a Lapua/Doppler
49
+ deck, or your own) instead of a G1/G7 model + BC. Once loaded it's applied automatically to every
50
+ `trajectory`, `zero`, `lead`, and `monte-carlo` run — no extra flag needed.
449
51
 
450
- `true-velocity` trues the vertical axis; `true-wind` (MBA-1392) trues the other one.
451
- Give it where your groups actually landed left/right of the aim point and it back-solves
452
- the crosswind that reproduces that miss through the real forward model, plus a wind-call
453
- correction factor against the wind you *called*:
52
+ ```js
53
+ const csv = 'mach,cd\n0.5,0.220\n0.8,0.230\n1.0,0.520\n1.2,0.480\n1.5,0.400\n2.0,0.330\n2.5,0.300\n';
54
+ calc.loadDragTable(new TextEncoder().encode(csv));
55
+ calc.hasDragTable(); // true
454
56
 
455
- ```bash
456
- ./ballistics true-wind \
457
- --miss 500:14.0 --miss 700:29.5 \
458
- -v 2700 -b 0.475 -m 168 -d 0.308 --drag-model g7 \
459
- --twist-rate 11 --called-wind 9
57
+ calc.runCommand('trajectory -v 2700 -b 0.475 -m 168 -d 0.308 --max-range 500');
460
58
  ```
461
59
 
462
- A horizontal miss is not purely wind, so the command separates it: `--twist-rate` is
463
- **required** and gyroscopic spin drift is always modelled and subtracted (a 1:11" .308
464
- drifts ~3.5 in right at 700 yd read as wind, that alone is several mph of error), and
465
- `--latitude` with `--shot-direction` adds Coriolis. Anything the model had no data for
466
- stays absorbed in the solved wind and is named in the report, so a contaminated number is
467
- never presented as pure wind. Signs are documented in one block: `--miss` positive =
468
- impact **right** of aim, solved wind positive = wind **from the shooter's left**
469
- (9 o'clock) pushing impacts right. `--miss` values are linear inches off the target, not
470
- dial readings, so scope tracking correction factors deliberately do not apply.
471
- See [CLI_USAGE.md](CLI_USAGE.md#wind-call-truing-true-wind--mba-1392).
60
+ `loadDragTable` takes raw bytes because WASM has no filesystem access fetch the CSV yourself
61
+ (`fetch()` in the browser, `fs.readFileSync` in Node) and pass the bytes in. The CSV format is
62
+ documented in the source repo's `CLI_USAGE.md` ("Custom Drag Tables"); a matching
63
+ `loadBc5dTable(bytes)` / `hasBc5dTable()` pair exists for BC5D correction tables.
472
64
 
473
- ### DSF (Drop-Scale-Factor) Truing
65
+ ## Browser without a bundler
474
66
 
475
- Second stage of the Applied Ballistics-style two-stage truing workflow (MBA-1357).
476
- Once `true-velocity` has fixed the supersonic (Mach > 1.2) muzzle velocity/BC, the
477
- drop discrepancies that grow through the transonic region and into subsonic flight are
478
- no longer fixable by a single MV correction — the residual is a slowly-varying function
479
- of Mach. `dsf` records observed-drop/predicted-drop ratios at specific Mach <= 1.2
480
- ranges and keys them, one saved profile at a time, to a Mach-indexed table:
67
+ For a plain `<script type="module">` page (no build step), use the `pkg-web/` build instead
68
+ produced by the same `scripts/build-npm.sh`, and the same build already deployed at
69
+ [ballistics.sh](https://ballistics.sh). It ships an explicit async `init()` you call once before
70
+ constructing `WasmBallistics`:
481
71
 
482
- ```bash
483
- # Stage 1: true the muzzle velocity from a supersonic-range drop reading (as above).
484
- ./ballistics true-velocity \
485
- --measured-drop 3.2 --range 500 \
486
- --bc 0.475 --mass 168 --diameter 0.308 \
487
- --offline
72
+ ```html
73
+ <script type="module">
74
+ import init, { WasmBallistics } from './ballistics_engine.js';
488
75
 
489
- # Stage 2: record a subsonic/transonic drop observation on the trued, saved profile.
490
- ./ballistics dsf --saved-profile my-rifle --range 900 --observed-drop 5.1mil
76
+ await init(); // fetches and instantiates ballistics_engine_bg.wasm relative to this file
77
+ const calc = new WasmBallistics();
78
+ console.log(calc.runCommand('trajectory -v 2700 -b 0.475 -m 168 -d 0.308 --max-range 500'));
79
+ </script>
491
80
  ```
492
81
 
493
- `dsf` takes no ballistic parameters of its own it solves the named saved profile's
494
- own trajectory (no CLI overrides) and derives everything else from `--range` and
495
- `--observed-drop` (`mil`, `moa`, or `in`, no separator between number and unit). An
496
- observation whose target-range Mach exceeds 1.2 is rejected outright, pointing back to
497
- `true-velocity`. Up to 6 distinct Mach-keyed points accumulate per profile; a new point
498
- within 0.05 Mach of an existing one supersedes it (announced on stdout); a 7th distinct
499
- point is rejected, naming `--clear-dsf` to make room. `trajectory --saved-profile` and
500
- `come-ups --profile` then auto-apply the table as a **drop-only** correction — velocity,
501
- energy, and time of flight are byte-identical to the untrued solve — printing a
502
- table-output-only note; JSON/CSV carry the corrected drop numbers with no equivalent
503
- text. `profile save NAME ... --clear-dsf` removes an existing table. See
504
- [CLI_USAGE.md](CLI_USAGE.md#dsf-drop-scale-factor-truing) for the full staging-gate
505
- reference.
82
+ Serve `ballistics_engine.js` and `ballistics_engine_bg.wasm` from the same directory, and make sure
83
+ your host serves `.wasm` with `Content-Type: application/wasm` (all major static hosts and CDNs do
84
+ this by default).
506
85
 
507
- ## Advanced Features
86
+ This `pkg-web/` build is not published to npm as part of this package in the current release —
87
+ it's built locally alongside `pkg/` for direct use or self-hosting. If you need it from npm, either
88
+ vendor the files from `pkg-web/` yourself or publish it as a second package.
508
89
 
509
- ### Online Mode (API Integration)
90
+ ### Node.js without a bundler
510
91
 
511
- The CLI can query a remote ballistics API server instead of calculating locally. This enables access to enhanced BC data, ML-augmented predictions, and doppler-derived drag curves.
92
+ Plain Node `import`/`require` cannot load this package's bundler-target `.wasm` import directly.
93
+ Use the `pkg-web/` build instead, passing the file bytes explicitly (Node's `fetch()` does not
94
+ support `file://` URLs):
512
95
 
513
- > **Important:** The `--online` feature connects to a **proprietary cloud service** that is not covered by the MIT license. When using `--online`, trajectory parameters and your IP address are transmitted to our servers. See [ONLINE_SERVICE.md](ONLINE_SERVICE.md) for full terms, privacy policy, and data handling practices.
96
+ ```js
97
+ import { readFileSync } from 'node:fs';
98
+ import init, { WasmBallistics } from './pkg-web/ballistics_engine.js';
514
99
 
515
- ```bash
516
- # Use online mode to query the API
517
- ./ballistics trajectory \
518
- -v 2700 -b 0.475 -m 168 -d 0.308 \
519
- --online \
520
- --max-range 1000
521
-
522
- # Custom API endpoint
523
- ./ballistics trajectory \
524
- -v 2700 -b 0.475 -m 168 -d 0.308 \
525
- --online \
526
- --api-url https://your-api.example.com/v1/calculate \
527
- --max-range 1000
528
- ```
529
-
530
- **Default API**: `https://api.ballistics.7.62x51mm.sh/v1/calculate`
100
+ const wasmBytes = readFileSync(new URL('./pkg-web/ballistics_engine_bg.wasm', import.meta.url));
101
+ await init({ module_or_path: wasmBytes });
531
102
 
532
- Online mode benefits:
533
- - **Enhanced BC data** - Access to doppler-derived ballistic coefficients
534
- - **ML predictions** - Machine learning augmented trajectory calculations
535
- - **BC segments** - Velocity-dependent BC modeling from measured data
536
- - **Form factor corrections** - Bullet-specific drag adjustments
537
-
538
- **Data transmitted when using --online:**
539
- - All trajectory parameters (BC, mass, velocity, wind, atmospheric conditions, etc.)
540
- - Your IP address and client version
541
- - Request logs retained for 30 days, then deleted
542
-
543
- To use only local calculations (no network, no data transmission):
544
- ```bash
545
- cargo install ballistics-engine --no-default-features
103
+ const calc = new WasmBallistics();
104
+ console.log(calc.runCommand('trajectory -v 2700 -b 0.475 -m 168 -d 0.308 --max-range 500'));
546
105
  ```
547
106
 
548
- ### Integration Methods
549
-
550
- The engine supports two numerical integration methods:
107
+ If you need a CommonJS (`require()`) Node build, generate one yourself:
108
+ `wasm-pack build --target nodejs --no-default-features`.
551
109
 
552
- - **RK45 (Dormand-Prince Adaptive)** - Default method, provides best accuracy with adaptive step sizing
553
- - **RK4 (Runge-Kutta 4th Order Fixed-Step)** - Available with `--use-rk4-fixed` flag for faster computation
110
+ ## Caveats
554
111
 
555
- ### Wind Shear Modeling
556
-
557
- Model altitude-dependent wind variations:
558
-
559
- ```bash
560
- ./ballistics trajectory -v 2700 -b 0.475 -m 168 -d 0.308 \
561
- --wind-speed 10 --wind-direction 90 \
562
- --enable-wind-shear \
563
- --max-range 1000
564
- ```
565
-
566
- ### Transonic Stability Analysis
567
-
568
- Analyze projectile stability through the transonic regime:
569
-
570
- ```bash
571
- ./ballistics trajectory -v 3000 -b 0.475 -m 168 -d 0.308 \
572
- --enable-pitch-damping \
573
- --max-range 2000
574
- ```
575
-
576
- Provides warnings about transonic instability and minimum pitch damping coefficients.
577
-
578
- ### Trajectory Sampling
579
-
580
- Collect trajectory data at regular intervals for detailed analysis:
581
-
582
- ```bash
583
- ./ballistics trajectory -v 2700 -b 0.475 -m 168 -d 0.308 \
584
- --sample-trajectory \
585
- --sample-interval 25 # Sample every 25 meters
586
- --max-range 1000 -o json
587
- ```
588
-
589
- ### Angular Motion Physics
590
-
591
- Model precession and nutation of spinning projectiles:
592
-
593
- ```bash
594
- ./ballistics trajectory -v 2700 -b 0.475 -m 168 -d 0.308 \
595
- --twist-rate 10 \
596
- --enable-precession \
597
- --max-range 1000
598
- ```
599
-
600
- ### Complete Advanced Physics Example
601
-
602
- ```bash
603
- ./ballistics trajectory \
604
- -v 2850 -b 0.690 -m 230 -d 0.338 \
605
- --drag-model g7 \
606
- --twist-rate 8.5 --twist-right \
607
- --enable-magnus \
608
- --enable-coriolis \
609
- --enable-spin-drift \
610
- --enable-wind-shear \
611
- --enable-pitch-damping \
612
- --enable-precession \
613
- --sample-trajectory \
614
- --latitude 38.5 \
615
- --shooting-angle 45 \
616
- --wind-speed 15 --wind-direction 270 \
617
- --altitude 6000 \
618
- --max-range 2000
619
- ```
620
-
621
- ## Physics Modeling
622
-
623
- The ballistics engine implements comprehensive physics modeling for accurate trajectory prediction:
624
-
625
- ### Aerodynamic Effects
626
- - **Drag Modeling** - Full standard-projectile family (G1, G2, G5, G6, G7, G8, GI, GS, RA4) plus custom Cd(Mach) curves, with transonic flow corrections
627
- - **Form Factor** - Projectile efficiency corrections based on shape and design
628
- - **Reynolds Number Effects** - Reynolds diagnostics and an opt-in helper for genuinely low-Re flow; standard drag tables are not multiplied by an extra correction
629
-
630
- ### Gyroscopic Effects
631
- - **Spin Drift** - Lateral deviation due to gyroscopic and Magnus effects
632
- - **Precession** - Gyroscopic precession of spinning projectile
633
- - **Nutation** - Oscillatory motion superimposed on precession
634
- - **Spin Decay** - Reduction in spin rate over time due to aerodynamic damping
635
- - **Pitch Damping** - Aerodynamic moments opposing angular motion
636
-
637
- ### Environmental Effects
638
- - **Coriolis Effect** - Earth's rotation influence on long-range trajectories
639
- - **Magnus Effect** - Force from spinning projectile in crossflow
640
- - **Wind Shear** - Altitude-dependent wind variations
641
- - **Atmospheric Stratification** - Density and sound speed variations with altitude
642
-
643
- ### Stability Modeling
644
- - **Dynamic Stability** - Gyroscopic and aerodynamic stability calculations
645
- - **Yaw of Repose** - Gravity/gyroscopic equilibrium yaw; crosswind yaw is a transient handled by aerodynamic jump
646
- - **Limit Cycle Yaw** - Bounded oscillatory motion analysis
647
-
648
- ## Language Bindings
649
-
650
- Official language bindings are maintained as separate projects:
651
-
652
- - **Python**: [ballistics-engine-py](https://github.com/ajokela/ballistics-engine-py) - PyO3 bindings via maturin
653
- - **Ruby**: [ballistics-engine-rb](https://github.com/ajokela/ballistics-engine-rb) - Magnus bindings via rb_sys
654
-
655
- These bindings depend on the `ballistics-engine` crate published on [crates.io](https://crates.io/crates/ballistics-engine).
656
-
657
- ### WASM / npm Package
658
-
659
- The engine also compiles to WebAssembly (`src/wasm.rs`, `wasm-bindgen`) and already powers
660
- [ballistics.sh](https://ballistics.sh) and [ballistics.rs](https://ballistics.rs) in the browser.
661
- It is not yet published to npm for third-party use — `scripts/build-npm.sh` builds and prepares a
662
- publish-ready package; publishing itself is a manual step (see below).
663
-
664
- ```bash
665
- scripts/build-npm.sh
666
- ```
667
-
668
- This builds two `wasm-bindgen` targets, both with `--no-default-features` (the default
669
- `pdf`/`online` features pull in `printpdf`/`ureq`+`ring`, which do not compile for
670
- `wasm32-unknown-unknown` — see "Updating the WASM Module" in `CLAUDE.md`):
671
-
672
- - **`pkg/`** — `--target bundler`, the package meant for `npm publish`. Consumed via a native
673
- `.wasm` ES import by bundlers that understand it (webpack with `experiments.asyncWebAssembly`,
674
- Vite, Rollup + `@rollup/plugin-wasm`, Parcel).
675
- - **`pkg-web/`** — `--target web`, a no-bundler build for direct `<script type="module">` browser
676
- use or manual Node usage without a bundler — the same `--target` already used to build
677
- ballistics.sh/ballistics.rs's WASM. Documented and built for completeness; not published under
678
- the primary package name in this initial pass.
679
-
680
- `wasm-pack` has no built-in dual-target/"publish both" mode, and stitching bundler- and web-target
681
- output into one package.json via manual `exports` conditions isn't something `wasm-pack` generates
682
- or tests for you — see the comment header of `scripts/build-npm.sh` for the full reasoning. A
683
- single bundler-target package as the published npm artifact, with the web build documented
684
- separately, is the ecosystem-standard shape for `wasm-bindgen` crates on npm.
685
-
686
- The script also post-processes each `package.json` (name, description, license, repository,
687
- keywords, and the `files` list — including an `LICENSE-APACHE` entry `wasm-pack` itself omits even
688
- though it copies the file) and installs `README-npm.md` as the package's `README.md`.
689
-
690
- **Before publishing**, edit `pkg/package.json`'s `"name"` — it ships as the placeholder
691
- `"@SCOPE/ballistics-engine"`. Replace `SCOPE` with the maintainer's real npm org/user scope (a
692
- scope decision, plus an npm account with publish rights to it, are both needed and don't exist yet
693
- as of this writing). Then:
694
-
695
- ```bash
696
- scripts/build-npm.sh
697
- cd pkg
698
- npm pack --dry-run # sanity-check the tarball contents first
699
- npm publish --access public
700
- ```
701
-
702
- (`--access public` is required the first time a scoped package is published, since scoped packages
703
- default to private on free npm accounts; `pkg/package.json` also sets `publishConfig.access` to
704
- `public` so a plain `npm publish` works too.)
705
-
706
- ## FFI Layer
707
-
708
- The library includes a Foreign Function Interface (FFI) layer for integration with iOS, Android, and other platforms. The FFI provides C-compatible bindings for all major functionality.
709
-
710
- <img src="ios.png" alt="iOS Integration Example" width="35%">
711
-
712
- ### FFI Features
713
- - **C-Compatible Structures** - All data structures use C-compatible layouts
714
- - **Safe Memory Management** - Proper handling of memory across language boundaries
715
- - **iOS/Swift Integration** - Ready for use with Swift through bridging headers
716
- - **Android/JNI Support** - Compatible with Java Native Interface
717
- - **Monte Carlo Simulation** - Statistical analysis with parameter variations
718
- - **Error Handling** - Graceful error propagation across FFI boundary
719
-
720
- ### Example FFI Usage (C/Swift)
721
- ```c
722
- // Create input parameters
723
- FFIBallisticInputs inputs = {
724
- .muzzle_velocity = 823.0, // m/s
725
- .ballistic_coefficient = 0.475,
726
- .mass = 0.0109, // kg
727
- .diameter = 0.00782, // meters
728
- .drag_model = 0, // G1
729
- .sight_height = 0.05, // meters
730
- .temperature = 15.0, // Celsius
731
- .altitude = 0.0
732
- };
733
-
734
- // Calculate trajectory. The final argument is the integration step in milliseconds
735
- // (minimum 0.1 ms; smaller or non-finite values return NULL).
736
- FFITrajectoryResult* result = ballistics_calculate_trajectory(&inputs, NULL, NULL, 1000.0, 0.1);
737
-
738
- // NULL also reports invalid inputs or the 250,000-point resource ceiling.
739
- // Increase the step, reduce the range, or use adaptive RK45 for an over-budget solve.
740
- if (result != NULL) {
741
- printf("Max range: %.2f meters\n", result->max_range);
742
- ballistics_free_trajectory_result(result);
743
- }
744
- ```
745
-
746
- ### Monte Carlo Simulation via FFI
747
- ```c
748
- // Set up Monte Carlo parameters
749
- FFIMonteCarloParams params = {
750
- .num_simulations = 1000,
751
- .velocity_std_dev = 10.0, // m/s variation
752
- .angle_std_dev = 0.001, // radian variation (elevation)
753
- .bc_std_dev = 0.01, // BC variation
754
- .wind_speed_std_dev = 2.0, // m/s wind variation
755
- .target_distance = 600.0, // Target at 600m
756
- .azimuth_std_dev = 0.001 // radian variation (horizontal)
757
- };
758
-
759
- // Run simulation with an independent 0.1-radian wind-direction sigma.
760
- // Use ballistics_monte_carlo(...) when no direction variation is desired.
761
- FFIMonteCarloResults* results =
762
- ballistics_monte_carlo_with_direction_std_dev(&inputs, NULL, &params, 0.1);
763
-
764
- // Use statistical results
765
- printf("Mean range: %.2f m (σ=%.2f)\n", results->mean_range, results->std_dev_range);
766
- printf("Hit probability at 600m: %.1f%%\n", results->hit_probability * 100);
767
-
768
- // Access individual shots
769
- for (int i = 0; i < results->num_results; i++) {
770
- printf("Shot %d: Range %.2f m, Impact velocity %.2f m/s\n",
771
- i, results->ranges[i], results->impact_velocities[i]);
772
- }
773
-
774
- // Clean up
775
- ballistics_free_monte_carlo_results(results);
776
- ```
777
-
778
- ## Output Formats
779
-
780
- All commands support three output formats via the `-o` flag:
781
-
782
- - **table** (default) - Formatted ASCII table for terminal display
783
- - **json** - Complete data in JSON format for programmatic use
784
- - **csv** - Comma-separated values for spreadsheet analysis
785
-
786
- ## Practical Examples
787
-
788
- ### Hunting Zero
789
-
790
- Zero a hunting rifle at 200 yards with environmental conditions:
791
-
792
- ```bash
793
- # Calculate zero angle
794
- ./ballistics zero \
795
- -v 2650 -b 0.460 -m 180 -d 0.308 \
796
- --target-distance 200
797
-
798
- # Verify trajectory with auto-zero
799
- ./ballistics trajectory \
800
- -v 2650 -b 0.460 -m 180 -d 0.308 \
801
- --auto-zero 200 \
802
- --max-range 400 \
803
- --wind-speed 15 \
804
- --wind-direction 270 \
805
- --temperature 32 \
806
- --humidity 30 \
807
- --altitude 5000 \
808
- --full
809
- ```
810
-
811
- ### Long Range Shooting
812
-
813
- Analyze trajectory for 1000-yard shot:
814
-
815
- ```bash
816
- ./ballistics trajectory \
817
- -v 2850 -b 0.690 -m 230 -d 0.338 \
818
- --drag-model g7 \
819
- --auto-zero 100 \
820
- --max-range 1100 \
821
- --wind-speed 10 \
822
- --wind-direction 45 \
823
- --full \
824
- -o json > trajectory.json
825
- ```
826
-
827
- ### Load Development
828
-
829
- Compare different loads using Monte Carlo:
830
-
831
- ```bash
832
- # Load 1: Higher velocity, more variation
833
- ./ballistics monte-carlo \
834
- -v 2750 -b 0.475 -m 168 -d 0.308 \
835
- -n 1000 \
836
- --velocity-std 15 \
837
- --target-distance 600
838
-
839
- # Load 2: Lower velocity, more consistent
840
- ./ballistics monte-carlo \
841
- -v 2680 -b 0.475 -m 168 -d 0.308 \
842
- -n 1000 \
843
- --velocity-std 8 \
844
- --target-distance 600
845
- ```
846
-
847
- ## Advanced Features
848
-
849
- ### BC Segmentation
850
-
851
- Velocity-dependent BC modeling accounts for how ballistic coefficient changes as the bullet slows down. Enable with `--use-bc-segments`:
852
-
853
- - Automatically estimates BC segments based on bullet characteristics
854
- - No external data required - uses caliber, weight, and BC
855
- - Identifies bullet type (Match, Hunting, VLD, etc.) from parameters
856
- - Applies physics-based BC degradation curves
857
-
858
- Example:
859
- ```bash
860
- ./ballistics trajectory -v 2700 -b 0.475 -m 168 -d 0.308 --use-bc-segments --max-range 1000
861
- ```
862
-
863
- **Manual velocity-keyed BC segments** — supply your own `VMIN:VMAX:BC` pairs (repeatable,
864
- velocities in `--units`) instead of the auto-estimated/table ones. Keyed to velocity, so it
865
- composes with distance-keyed `--wind-segment`; implies `--use-bc-segments` and overrides
866
- `--bc-table` and `--bc-table-dir`:
867
- ```bash
868
- ./ballistics trajectory -v 2600 -b 0.243 -m 175 -d 0.308 --drag-model g7 --max-range 1000 \
869
- --bc-segment 1800:4000:0.243 --bc-segment 1500:1800:0.228 --bc-segment 1200:1500:0.205
870
- ```
871
-
872
- ### BC5D Correction Tables
873
-
874
- BC5D tables provide ML-derived, 5-dimensional BC corrections indexed by weight, BC, muzzle velocity, current velocity, and drag model. Tables are caliber-specific and capture the complete velocity-dependent behavior.
875
-
876
- **Auto-Download Mode** (requires `online` feature):
877
- ```bash
878
- # Downloads tables automatically on first use
879
- ./ballistics trajectory -v 2700 -b 0.475 -m 168 -d 0.308 --bc-table-auto
880
-
881
- # Force refresh cached tables
882
- ./ballistics trajectory -v 2700 -b 0.475 -m 168 -d 0.308 --bc-table-auto --bc-table-refresh
883
- ```
884
-
885
- **Offline Mode** with pre-downloaded tables:
886
- ```bash
887
- ./ballistics trajectory -v 2700 -b 0.475 -m 168 -d 0.308 --bc-table-dir ./bc_tables/
888
- ```
889
-
890
- **Available calibers:** .224, .243, .264, .277, .284, .308, .338
891
-
892
- **Cache locations:**
893
- - macOS: `~/Library/Caches/ballistics-engine/bc5d/`
894
- - Linux: `~/.cache/ballistics-engine/bc5d/`
895
- - Windows: `%LOCALAPPDATA%\ballistics-engine\cache\bc5d\`
896
-
897
- Tables are approximately 1-1.5 MB each and include CRC32 validation to ensure data integrity.
898
-
899
- ### Advanced Physics Modeling
900
-
901
- When enabled, the engine calculates:
902
- - **Magnus Effect** - Side force from spinning projectiles
903
- - **Spin Drift** - Lateral drift due to gyroscopic effects
904
- - **Coriolis Effect** - Earth rotation effects (with latitude input)
905
- - **Transonic Drag** - Enhanced drag modeling in transonic regime
906
- - **Low-Reynolds Helper** - Opt-in viscous correction below the standard projectile-table regime
907
-
908
- ## Building from Source
909
-
910
- ### Requirements
911
-
912
- - Rust 1.70 or later
913
- - Cargo build system
914
-
915
- ### Build Commands
916
-
917
- ```bash
918
- # Debug build
919
- cargo build
920
-
921
- # Release build (optimized)
922
- cargo build --release
923
-
924
- # Run tests
925
- cargo test
926
-
927
- # Build documentation
928
- cargo doc --open
929
- ```
930
-
931
- ## Library Usage
932
-
933
- Use as a Rust library in your own projects:
934
-
935
- ```rust
936
- use ballistics_engine::{
937
- BallisticInputs, TrajectorySolver,
938
- WindConditions, AtmosphericConditions
939
- };
940
-
941
- fn main() -> Result<(), Box<dyn std::error::Error>> {
942
- let inputs = BallisticInputs {
943
- muzzle_velocity: 823.0, // m/s
944
- launch_angle: 0.0, // radians
945
- ballistic_coefficient: 0.475,
946
- mass: 0.0109, // kg
947
- diameter: 0.00782, // meters
948
- sight_height: 0.05, // meters
949
- ..Default::default()
950
- };
951
-
952
- let wind = WindConditions {
953
- speed: 5.0, // m/s
954
- direction: 1.5708, // 90 degrees in radians
955
- ..Default::default()
956
- };
957
-
958
- let atmosphere = AtmosphericConditions {
959
- temperature: 15.0, // Celsius
960
- pressure: 1013.25, // hPa
961
- humidity: 50.0, // %
962
- altitude: 0.0, // meters
963
- ..Default::default()
964
- };
965
-
966
- let solver = TrajectorySolver::new(inputs, wind, atmosphere);
967
- let result = solver.solve()?;
968
-
969
- println!("Max range: {:.2} m", result.max_range);
970
- println!("Max height: {:.2} m", result.max_height);
971
- println!("Time of flight: {:.3} s", result.time_of_flight);
972
-
973
- Ok(())
974
- }
975
- ```
976
-
977
- ## Performance
978
-
979
- Optimized Rust implementation provides:
980
- - Single trajectory (1000m): ~5ms
981
- - Monte Carlo (1000 runs): ~500ms
982
- - BC estimation: ~50ms
983
- - Zero calculation: ~10ms
984
-
985
- ## Common Ballistic Coefficients
986
-
987
- | Caliber | Weight | BC (G1) | BC (G7) | Description |
988
- |---------|--------|---------|---------|-------------|
989
- | .223 | 55gr | 0.250 | - | FMJ |
990
- | .223 | 77gr | 0.362 | 0.182 | Match |
991
- | .308 | 168gr | 0.475 | 0.224 | Match |
992
- | .308 | 175gr | 0.505 | 0.253 | Match |
993
- | .308 | 180gr | 0.480 | - | Hunting |
994
- | .338 | 300gr | 0.768 | 0.383 | Match |
995
- | 6.5mm | 140gr | 0.620 | 0.310 | Match |
996
- | .50 | 750gr | 1.050 | 0.520 | Match |
997
-
998
- ## Troubleshooting
999
-
1000
- ### Trajectory hits ground early
1001
- - Check if you're using `--auto-zero` or setting `--angle` manually
1002
- - Default angle is 0° (horizontal), which will hit ground quickly
1003
- - Use `--auto-zero <distance>` to automatically calculate proper angle
1004
-
1005
- ### Units confusion
1006
- - Default is Imperial (fps, grains, yards)
1007
- - Use `--units metric` for metric system
1008
- - All inputs must match the selected unit system
1009
-
1010
- ### Unexpected BC behavior
1011
- - G1 and G7 models have different BC values for same bullet
1012
- - G7 typically better for boat-tail bullets
1013
- - BC segmentation automatically applied based on bullet type
1014
-
1015
- ## Contributing
1016
-
1017
- Contributions are welcome! Please:
1018
- 1. Fork the repository
1019
- 2. Create a feature branch
1020
- 3. Add tests for new features
1021
- 4. Run `cargo test` and `cargo fmt`
1022
- 5. Submit a pull request
112
+ - **Size**: the `.wasm` binary is roughly 430 KB (about 175 KB gzipped). It is not code-split or
113
+ lazily loaded — the whole engine loads up front.
114
+ - **Single-threaded**: no SIMD/threads assumptions; no `SharedArrayBuffer` or
115
+ cross-origin-isolation (COOP/COEP) headers required.
116
+ - **No filesystem/network**: table loaders (`loadDragTable`, `loadBc5dTable`) and any file-based
117
+ CLI flags (e.g. native `--drag-table <FILE>`) need the host to fetch bytes and hand them in; see
118
+ `loadDragTable` above.
119
+ - **`pdf`/`online` features are unavailable**: this build excludes them (see above), so
120
+ PDF dope-card export and the online BC-estimation API are not part of the WASM surface.
121
+ - Full API surface (including the `Calculator` builder class) is documented in the bundled
122
+ `.d.ts`; the full CLI flag reference `runCommand` accepts is documented in the source repo's
123
+ `CLI_USAGE.md`.
1023
124
 
1024
125
  ## License
1025
126
 
1026
- This project is licensed under the MIT License - see LICENSE file for details.
1027
-
1028
- **Note:** The MIT license applies to the open source ballistics-engine library, CLI, and FFI bindings. The `--online` feature connects to a proprietary cloud service with separate terms. See [ONLINE_SERVICE.md](ONLINE_SERVICE.md) for details.
1029
-
1030
- ## Acknowledgments
1031
-
1032
- - Ballistics physics based on Robert McCoy's "Modern Exterior Ballistics"
1033
- - Drag tables from military ballistics research
1034
- - BC segmentation algorithms from Bryan Litz's research
1035
- - Community contributions and testing
127
+ MIT OR Apache-2.0 see `LICENSE` and `LICENSE-APACHE` in this package.
1036
128
 
1037
- ## Support
129
+ ## Source
1038
130
 
1039
- For issues, questions, or contributions:
1040
- - GitHub Issues: [github.com/ajokela/ballistics-engine/issues](https://github.com/ajokela/ballistics-engine/issues)
131
+ https://github.com/ajokela/ballistics-engine