ballistics_engine/
card_service.rs

1//! Transport-free card-generation services (come-ups, range table, wind card).
2//!
3//! These replicate the CLI's card commands exactly — same zero solve, same sampled
4//! trajectory, same nearest-sample row selection, same adjustment/bias/CF/click
5//! ordering via [`crate::adjustment`] — as versioned request/response types the
6//! bridge can expose to embedded consumers. The CLI remains the reference
7//! implementation; `tests/card_bridge_golden.rs` asserts row-for-row agreement.
8//!
9//! ## Unit convention
10//!
11//! Unlike solve-json (explicit SI), card requests are denominated in the shooter's own
12//! units, exactly like the CLI flags they mirror: imperial = fps, grains, inches, yards,
13//! °F, inHg, mph; metric = m/s, grams, mm, meters, °C, hPa, m/s. A DOPE card is a display
14//! artifact; its inputs and outputs share the shooter's unit world, and this keeps the
15//! request shape identical to the documented CLI surface.
16//!
17//! ### Per-dimension units (MBA-1519)
18//!
19//! Nobody shoots in one system. A Finnish shooter ranges in metres, dials MIL, and buys
20//! bullets labelled in grains, because that is how the industry sells them; European makers
21//! dual-print `grams / grains` rather than replacing one with the other, and mix within a
22//! single table. So the denominating state on this request is a unit PER DIMENSION, and
23//! [`CardUnits`] is a one-shot preset that fills in every dimension the request does not
24//! state for itself — not a mode the card is "in".
25//!
26//! Concretely: an explicit per-dimension field wins; an absent one falls back to what
27//! `units` implies. A request written before those fields existed states none of them, so
28//! every dimension falls back and the card is byte-for-byte the card it always was
29//! (`tests/card_units_per_dimension.rs` pins that against a stored document).
30//!
31//! The response needed no new FIELD for any of this: [`CardUnitsBlockV1`] has always carried
32//! seven independent label fields, so a card whose distance is metres and whose velocity is
33//! fps already had somewhere to say so. It did need the two angular labels to become
34//! requestable: `elevation_adjustment`/`windage_adjustment` print `"MIL"`/`"MOA"`/`"SMOA"`/
35//! `"IPHY"`/`"CLICKS"` and [`AdjustmentUnit`] deserialized lowercase only, so those two were
36//! the only fields of the block a caller could not echo back. They take the uppercase
37//! spellings as aliases now, which makes "echo the units block into the next request" true
38//! of all seven fields rather than five of them.
39//!
40//! Three candidates do NOT get a new field, and each for its own reason:
41//!
42//! * **Scope adjustment** is already per-dimension, and was first: `adjustment_unit` and
43//!   `windage_unit` are separate fields with separate click graduations, because a shooter
44//!   with a MIL rifle and an MOA rifle has two scopes rather than a preference. SMOA (and
45//!   its `iphy` spelling) is already one of the values they take.
46//! * **Clicks** is not a units dimension. A click is meaningless without a graduation, and
47//!   this module already enforces that: `adjustment_unit == Clicks` without an
48//!   `elevation_click_value` is a refusal. The graduation belongs beside the turret's
49//!   MIL/MOA/SMOA marking, not in a units picker.
50//! * **Twist rate** is a dimension of the design but not of this request — a card request
51//!   carries no twist, so there is nothing here for a twist unit to denominate.
52//!
53//! And the linear-at-distance spellings are NOT units: "inches@100yd" IS SMOA — the same
54//! 1/3600 rad, the same printed number, no conversion — and "cm/100m" is 0.1 mrad, i.e. MIL
55//! with a factor-of-ten display. They are alternate HEADER TEXT for units this request
56//! already has, and adding them as values would give a caller two spellings that produce
57//! identical numbers.
58//!
59//! ### What the response does NOT tell a caller
60//!
61//! Like every other default on this request — `sight_height`, `temperature`, `pressure`,
62//! `humidity`, `windage_unit` — a per-dimension unit taken from the preset is applied
63//! silently, and this surface has no notice channel at all (there is no `assumptions` array
64//! on [`CardResponseV1`], unlike solve-json's `SolveSuccessV1`).
65//!
66//! Be precise about what that costs, because a paragraph of prose can argue it away. The `units`
67//! block names the unit of the SEVEN OUTPUT COLUMNS and nothing else. It says nothing about
68//! the six dimensions that are input-only — `mass`, `diameter`, `sight_height`,
69//! `temperature`, `pressure`, `altitude` — so for those a caller cannot read back off the
70//! card which unit the engine settled on.
71//!
72//! `altitude` is the sharp one, because it is the dimension whose fallback is deliberately
73//! NOT the preset's: an imperial `card.range_table` carrying `altitude: 5000` and no
74//! `altitude_unit` — which a US caller writing an imperial card means as feet — is solved at
75//! 5000 METRES, and no field of the response says so. On a .308 175 gr that is ~1.9 MIL of
76//! elevation at 1000 yd against the same card with `altitude_unit: "feet"`. The BEHAVIOUR
77//! predates the per-dimension fields (`altitude` has always reached
78//! [`AtmosphericConditions`] unconverted); what is new is that the request can now name the
79//! dimension, so the gap is describable instead of merely present.
80//!
81//! No notice was added here, and the reason is narrow rather than principled: any notice —
82//! an `assumptions` array, or extra label fields on the units block — is a change to the
83//! RESPONSE bytes of every card, including the stored documents the reprint path compares
84//! label-for-label and the six goldens that are the whole evidence for this change being
85//! additive on the wire. A response-schema change belongs to a ticket that can move those
86//! goldens honestly. Until then the remedy is on the request: a caller that cares which
87//! altitude it got states `altitude_unit`, and a card built by an app should state every
88//! dimension rather than lean on a preset.
89
90use serde::{Deserialize, Serialize};
91
92use crate::adjustment::{
93    adjustment_display, adjustment_unit_label, parse_click_value, windage_adjustment_display,
94    AdjustmentUnit, ClickValue,
95};
96use crate::atmosphere::{
97    AirField, AirRefusal, AirUnits, AltitudeUnit, PressureUnit, RelativeHumidity,
98    StationAtmospherePresence, TemperatureUnit, DEFAULT_HUMIDITY_PERCENT,
99};
100use crate::hold_curve::{
101    card_sample_max_range_m, range_not_sampled_message, run_sampled_flight_with_station_presence,
102    sample_at_range, CardTruncation, SampledFlight, CARD_SAMPLE_INTERVAL_M,
103};
104use crate::{AtmosphericConditions, BCSegmentData, BallisticInputs, DragModel, WindConditions};
105
106/// Schema version of the card request/response contract.
107pub const CARD_SCHEMA_VERSION_V1: u32 = 1;
108
109const GRAINS_TO_KG: f64 = crate::constants::GRAINS_TO_KG;
110
111/// The unit PRESET for a card request: a one-shot bulk action that fills in every
112/// per-dimension unit the request does not state for itself, not a mode the card is in.
113///
114/// It stays because it is the whole of the pre-MBA-1519 contract and because "give me an
115/// imperial card" remains the overwhelmingly common request. What changed is its standing:
116/// it is now the FALLBACK for each dimension rather than the denominator of all of them.
117#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
118#[serde(rename_all = "lowercase")]
119pub enum CardUnits {
120    #[default]
121    Imperial,
122    Metric,
123}
124
125// --- Per-dimension units (MBA-1519) ------------------------------------------------------
126//
127// One enum per dimension the card request actually denominates. Each is a plain value list;
128// the mapping from a value to a conversion factor and to a printed label lives in exactly
129// one place, `Units` below, so a dimension cannot convert one way and be labelled another.
130//
131// Every enum carries serde aliases for the spelling the RESPONSE prints for that unit
132// (`"m/s"`, `"ft-lb"`, `"in"`, `"yd"`, ...), and so does [`AdjustmentUnit`] over in
133// `adjustment.rs` for the two uppercase dial labels. A caller that reads a card's `units`
134// block and writes those strings straight back into the next request is doing the obvious
135// thing, and it now works — for all seven fields of the block — instead of failing on a
136// request that denies unknown values.
137
138/// Range axis: what `zero_distance`, `start`/`end`/`step` and every row's `range` are in.
139#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
140#[serde(rename_all = "lowercase")]
141pub enum CardDistanceUnit {
142    #[serde(alias = "yd", alias = "yard")]
143    Yards,
144    #[serde(alias = "m", alias = "metres", alias = "meter", alias = "metre")]
145    Meters,
146}
147
148/// Speed of the bullet: `muzzle_velocity`, `bc_segments` band edges, the `velocity` column.
149#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
150#[serde(rename_all = "lowercase")]
151pub enum CardVelocityUnit {
152    #[serde(alias = "ft/s")]
153    Fps,
154    #[serde(alias = "m/s")]
155    Mps,
156}
157
158/// Bullet weight. Grains and grams differ by 15.43x, and on the BC path mass never enters
159/// the drag denominator — it touches energy and stability only — so a grams-for-grains slip
160/// yields a trajectory that looks entirely normal. Which is exactly why the unit has to be
161/// stated per-dimension rather than inferred: the dual-printed `g / gr` box a European
162/// shooter is holding is the normal case, not an edge one.
163///
164/// The one-character wire tokens `"g"` and `"gr"` are deliberately NOT accepted, though
165/// `"gram"`/`"grams"` and `"grain"`/`"grains"` are. Those two tokens are the slip this
166/// dimension exists to prevent: a 175-grain load sent as `"g"` solves to bit-identical
167/// dials, drift, velocity and time — only the energy column moves, 1009 ft-lb to 15575 — and
168/// the response has no mass label for a reader to catch it on. Nor can a plausibility guard
169/// catch it: bullets run roughly 5–800 grains and roughly 0.3–52 grams, so the two ranges
170/// OVERLAP across 5–52, where 48 grains (a .22 varmint bullet) and 48 grams (a .50 BMG) are
171/// both ordinary. There is no threshold to put a guard at, so the defence has to be the
172/// spelling, and the spelled-out name is the one thing a caller cannot typo into the other
173/// unit.
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
175#[serde(rename_all = "lowercase")]
176pub enum CardMassUnit {
177    #[serde(alias = "grain")]
178    Grains,
179    #[serde(alias = "gram")]
180    Grams,
181}
182
183/// A small linear length. Shared by the request's two TARGET-SIDE linear dimensions
184/// (sight-to-bore geometry and the linear drop column) because they take the same values,
185/// never because they are the same setting: they are separate fields and resolve
186/// independently.
187///
188/// Bullet diameter is NOT one of them — it has [`CardDiameterUnit`], a narrower vocabulary.
189#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
190#[serde(rename_all = "lowercase")]
191pub enum CardLinearUnit {
192    #[serde(alias = "in", alias = "inch")]
193    Inches,
194    #[serde(alias = "centimeters", alias = "centimetres")]
195    Cm,
196    #[serde(alias = "millimeters", alias = "millimetres")]
197    Mm,
198}
199
200/// Bullet diameter: inches or millimetres, the two units a calibre is ever quoted in.
201///
202/// Its own enum rather than a third user of [`CardLinearUnit`], which would also accept
203/// `cm`. The design's dimension table lists inches and mm for this dimension and no third
204/// value, and a wire vocabulary on a `deny_unknown_fields` paid contract is far cheaper to
205/// widen later than to narrow: nobody quotes a calibre in centimetres, so `0.782` cm is
206/// likelier to be a slipped `7.82` mm than a request anyone meant.
207#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
208#[serde(rename_all = "lowercase")]
209pub enum CardDiameterUnit {
210    #[serde(alias = "in", alias = "inch")]
211    Inches,
212    #[serde(alias = "millimeters", alias = "millimetres")]
213    Mm,
214}
215
216/// Wind and crossing-target speed. Four values, not two: a European card reads km/h and a
217/// coastal one reads knots, and neither is expressible by picking a system.
218#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
219#[serde(rename_all = "lowercase")]
220pub enum CardWindSpeedUnit {
221    Mph,
222    #[serde(alias = "m/s")]
223    Mps,
224    #[serde(alias = "km/h", alias = "kmh")]
225    Kph,
226    #[serde(alias = "kn", alias = "kt", alias = "knot")]
227    Knots,
228}
229
230/// Air temperature.
231#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
232#[serde(rename_all = "lowercase")]
233pub enum CardTemperatureUnit {
234    #[serde(alias = "f", alias = "degf")]
235    Fahrenheit,
236    #[serde(alias = "c", alias = "degc")]
237    Celsius,
238}
239
240/// Station pressure. `hpa` and `mbar` are the same number, which is why mbar is an alias
241/// rather than a value of its own.
242#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
243#[serde(rename_all = "lowercase")]
244pub enum CardPressureUnit {
245    #[serde(alias = "in-hg", alias = "inchesofmercury")]
246    InHg,
247    #[serde(alias = "mbar", alias = "millibar")]
248    HPa,
249}
250
251/// Terminal energy column.
252#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
253#[serde(rename_all = "lowercase")]
254pub enum CardEnergyUnit {
255    #[serde(alias = "ft-lb", alias = "ftlbs", alias = "footpounds")]
256    FtLb,
257    // "J" as well as "j": the response's energy label is the capitalized SI symbol, and the
258    // aliases exist precisely so a caller can echo a card's own labels back at it.
259    #[serde(alias = "j", alias = "J", alias = "joule")]
260    Joules,
261}
262
263/// Site elevation. See [`CardRequestV1::altitude_unit`] for why this one dimension's
264/// default does not come from the preset.
265#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
266#[serde(rename_all = "lowercase")]
267pub enum CardAltitudeUnit {
268    #[serde(alias = "ft", alias = "foot")]
269    Feet,
270    #[serde(alias = "m", alias = "metres", alias = "meter", alias = "metre")]
271    Meters,
272}
273
274/// Everything the three card surfaces share: load, zero, atmosphere, display axes.
275///
276/// Field values are in this request's PER-DIMENSION units: each dimensional field names the
277/// `*_unit` field that denominates it, and each of those falls back to what `units` implies
278/// when it is absent (see the module docs). Stating none of them is the pre-MBA-1519 shape
279/// and reproduces the pre-MBA-1519 card exactly.
280///
281/// ## Adding a field here is additive on the WIRE and breaking in RUST
282///
283/// This is a deserialization target: the supported way to build one is
284/// `serde_json::from_str`/`from_value` on a JSON document, which is what the bridge and every
285/// binding do, and an optional new field costs such a caller nothing. A downstream Rust crate
286/// that constructs it with a struct literal has no such luck — every added field is an
287/// `E0063: missing fields` against code that compiled before, which is exactly what MBA-1519's
288/// eleven fields do to a crate written against 0.39.x. The remedy is one line per field
289/// (`altitude_unit: None`, and so on for the rest); the intended path is to deserialize.
290///
291/// `#[non_exhaustive]` was considered and NOT applied. It would break the same callers in the
292/// same release, and — with no `Default` and no builder on this type — it would leave a
293/// downstream crate no way to construct the request at all, trading one fixable compile error
294/// for a permanent one. So the breakage is stated in the CHANGELOG for the release that causes
295/// it rather than encoded in the type, and a future field will be stated the same way.
296#[derive(Debug, Clone, Deserialize)]
297#[serde(deny_unknown_fields)]
298pub struct CardRequestV1 {
299    /// The preset that fills in every `*_unit` field below that this request leaves absent.
300    #[serde(default)]
301    pub units: CardUnits,
302
303    // Load
304    /// Muzzle speed, in `velocity_unit`.
305    pub muzzle_velocity: f64,
306    pub ballistic_coefficient: f64,
307    /// Bullet weight, in `mass_unit`.
308    pub mass: f64,
309    /// Bullet diameter, in `diameter_unit`.
310    pub diameter: f64,
311    #[serde(default)]
312    pub drag_model: DragModelV1,
313    /// Sight height over bore, in `sight_height_unit`; CLI default 1.5 in.
314    #[serde(default = "sight_height_unset")]
315    pub sight_height: f64,
316
317    // Zero
318    /// Zero range, in `distance_unit`.
319    pub zero_distance: f64,
320    /// Deliberate POI offset at the zero range, in `drop_unit` — it is a displacement on
321    /// the target, which is the dimension the drop column reports; 0 = zeroed dead-on.
322    #[serde(default)]
323    pub zero_poi_vertical: f64,
324    /// Deliberate lateral POI offset at the zero range, in `drop_unit`.
325    #[serde(default)]
326    pub zero_poi_horizontal: f64,
327    /// Lateral sight-to-bore mount offset, in `sight_height_unit` — it is rifle geometry
328    /// measured beside the sight height, not a figure read off a target.
329    #[serde(default)]
330    pub sight_offset_lateral: f64,
331
332    // Atmosphere (CLI defaults: 59 °F / 15 °C, 29.92 inHg / 1013.25 hPa, 50 %, 0 alt)
333    /// Station temperature, in `temperature_unit`.
334    #[serde(default)]
335    pub temperature: Option<f64>,
336    /// Station pressure, in `pressure_unit`.
337    #[serde(default)]
338    pub pressure: Option<f64>,
339    /// Relative humidity, PERCENT, 0 to 100 (50 = 50 %). Dimensionless, so no unit field governs
340    /// it. Omitted means [`DEFAULT_HUMIDITY_PERCENT`]. A sensor reading within
341    /// [`crate::HUMIDITY_SENSOR_TOLERANCE_PERCENT`] (5 points) of 0 to 100 (101.7 in fog, -2 in
342    /// very dry air) is the saturated or dry air it reads and flies exactly as 100 or 0; a value
343    /// beyond that band (or not finite) is refused as an invalid request, never clamped.
344    #[serde(default = "default_humidity")]
345    pub humidity: f64,
346    /// Site elevation, in `altitude_unit` — which defaults to METRES whatever `units` says.
347    #[serde(default)]
348    pub altitude: f64,
349
350    // Wind for the flight (in `wind_speed_unit`; wind-FROM degrees). The wind card ignores
351    // these and sweeps its own speed list.
352    #[serde(default)]
353    pub wind_speed: f64,
354    #[serde(default)]
355    pub wind_direction_deg: f64,
356
357    // Card domain, in `distance_unit`
358    pub start: f64,
359    pub end: f64,
360    pub step: f64,
361
362    // --- Per-dimension units (MBA-1519) --------------------------------------------------
363    //
364    // Every one of these is `Option`al and `#[serde(default)]`: `CardRequestV1` denies
365    // unknown fields and backs paid surfaces (the Pro DOPE card, the saved-card reprint, the
366    // PDF export), so a stored request written before they existed has to keep parsing and
367    // keep producing the identical document. `None` means "take it from `units`", which is
368    // what every such request says about every dimension.
369    //
370    // What is deliberately NOT here: a scope-adjustment unit (`adjustment_unit` /
371    // `windage_unit` below already are that dimension, SMOA included), a clicks unit (a
372    // click needs a graduation, which is `elevation_click_value`), a twist-rate unit (this
373    // request carries no twist), and the linear-at-distance spellings (header text for SMOA
374    // and MIL, not units). The module docs give the full reasoning.
375    /// Unit of `zero_distance`, `start`, `end`, `step` and every row's `range`.
376    /// Default: yards (imperial) / metres (metric).
377    ///
378    /// Distance is the dimension where reinterpreting the number does the most damage the
379    /// most quietly: "300" yards and "300" metres are targets 9.36% apart, and a stored zero,
380    /// a DOPE row and a target-size hold are all attached to a PHYSICAL distance rather than
381    /// to a unit-free label. So a card's distance unit is stated, never inferred from a
382    /// neighbouring dimension.
383    #[serde(default)]
384    pub distance_unit: Option<CardDistanceUnit>,
385    /// Unit of `muzzle_velocity`, the `bc_segments` band edges and the `velocity` column.
386    /// Default: fps (imperial) / m/s (metric).
387    #[serde(default)]
388    pub velocity_unit: Option<CardVelocityUnit>,
389    /// Unit of `mass`. Default: grains (imperial) / grams (metric).
390    #[serde(default)]
391    pub mass_unit: Option<CardMassUnit>,
392    /// Unit of `diameter`. Default: inches (imperial) / mm (metric). Those two values and no
393    /// others — see [`CardDiameterUnit`].
394    #[serde(default)]
395    pub diameter_unit: Option<CardDiameterUnit>,
396    /// Unit of `sight_height` and `sight_offset_lateral` — the sight-to-bore geometry.
397    /// Default: inches (imperial) / mm (metric).
398    ///
399    /// This is a dimension the design's table does not contain, added deliberately rather
400    /// than by oversight: without it, the only home for the sight height would be
401    /// `drop_unit`, and then asking for a drop column in centimetres would silently reread a
402    /// 1.5-inch sight height as 1.5 cm. It is a twelfth field on a `deny_unknown_fields`
403    /// contract that cannot be withdrawn without a breaking change, which is the cost being
404    /// accepted here.
405    ///
406    /// Separate from `drop_unit` on purpose. They are the same unit today only because both
407    /// presets happen to give them the same value; they are different measurements (one is
408    /// taken on the rifle with calipers, the other is read off a target downrange), and
409    /// folding them together would mean a caller who asks for a drop column in centimetres
410    /// silently reinterprets a 1.5-inch sight height as 1.5 cm.
411    #[serde(default)]
412    pub sight_height_unit: Option<CardLinearUnit>,
413    /// Unit of the `drop_linear` / `wind_linear` columns and of `zero_poi_vertical` /
414    /// `zero_poi_horizontal`. Default: inches (imperial) / mm (metric).
415    ///
416    /// The ANGULAR half of the design's drop dimension is `adjustment_unit` /
417    /// `windage_unit`, which have always been separate fields; this is the linear half, and
418    /// `cm` is available here because a metric card prints 250 cm of drop, not 2500 mm.
419    #[serde(default)]
420    pub drop_unit: Option<CardLinearUnit>,
421    /// Unit of `wind_speed`, of every entry in `wind_speeds`, and of `pdf.target_speed`.
422    /// Default: mph (imperial) / m/s (metric).
423    #[serde(default)]
424    pub wind_speed_unit: Option<CardWindSpeedUnit>,
425    /// Unit of `temperature` and of the temperature default. Default: °F (imperial) / °C
426    /// (metric).
427    #[serde(default)]
428    pub temperature_unit: Option<CardTemperatureUnit>,
429    /// Unit of `pressure` and of the pressure default. Default: inHg (imperial) / hPa
430    /// (metric).
431    #[serde(default)]
432    pub pressure_unit: Option<CardPressureUnit>,
433    /// Unit of the `energy` column. Default: ft-lb (imperial) / J (metric).
434    #[serde(default)]
435    pub energy_unit: Option<CardEnergyUnit>,
436    /// Unit of `altitude`. Default: **metres, whatever `units` says** — this is the one
437    /// dimension whose fallback is not the preset's.
438    ///
439    /// `altitude` has ignored the `units` scalar since this module was written: it is passed
440    /// to [`AtmosphericConditions`] unconverted, and that field is documented metres, so an
441    /// imperial card's altitude has always been metres too (the PDF header divides it by
442    /// 0.3048 regardless of `units` for exactly that reason). Letting the imperial preset
443    /// start filling this with `feet` would therefore not be additive: every stored imperial
444    /// card carrying `altitude: 1000` would silently become a card shot at 304.8 m instead
445    /// of 1000 m, which is a different density altitude and a different trajectory.
446    ///
447    /// So the preset does not reach this field. A caller that wants feet says `"feet"`, and
448    /// gets the first way this request has ever had to express one.
449    #[serde(default)]
450    pub altitude_unit: Option<CardAltitudeUnit>,
451
452    // Display axes
453    #[serde(default)]
454    pub adjustment_unit: AdjustmentUnit,
455    /// Windage axis unit; defaults to the elevation axis.
456    #[serde(default)]
457    pub windage_unit: Option<AdjustmentUnit>,
458    /// Turret graduations as suffixed strings ("0.1mil", "0.25moa"); required when
459    /// the corresponding axis unit is `clicks`. Windage falls back to elevation.
460    #[serde(default)]
461    pub elevation_click_value: Option<String>,
462    #[serde(default)]
463    pub windage_click_value: Option<String>,
464    /// Scope tracking correction factors (MBA-1358); 1.0 = tracks true.
465    #[serde(default = "default_cf")]
466    pub elevation_cf: f64,
467    #[serde(default = "default_cf")]
468    pub windage_cf: f64,
469    /// Selected zero set's dial corrections, true angular MIL (MBA-1360).
470    #[serde(default)]
471    pub zero_set_elevation_bias_mil: f64,
472    #[serde(default)]
473    pub zero_set_windage_bias_mil: f64,
474
475    /// Wind card only: the sweep of wind speeds, each in `wind_speed_unit` (so km/h and
476    /// knots are available here too), one output column each.
477    #[serde(default)]
478    pub wind_speeds: Vec<f64>,
479    /// Wind card only: wind-FROM angles in degrees; default `[90]` (full-value from
480    /// the right), matching the CLI.
481    #[serde(default)]
482    pub wind_angles_deg: Vec<f64>,
483
484    /// Explicit velocity-banded BC schedule, mirroring the CLI's repeatable
485    /// `--bc-segment VMIN:VMAX:BC`. Velocities are in the request's `velocity_unit`,
486    /// exactly like the CLI flag. When supplied it
487    /// wins over `bc5d_table_path`, and — CLI parity — the scalar
488    /// `ballistic_coefficient` remains the interior-gap fallback unchanged. The
489    /// schedule feeds BOTH the zero solve and every sampled trajectory.
490    ///
491    /// Bands may be listed in any order and may touch or leave gaps, but must not overlap; at
492    /// most [`crate::solve_json::MAX_BC_SEGMENTS_V1`] bands; each `bc` within 0.0001..=100, the
493    /// bound solve-json puts on a BC. `[]` and `null` mean no ladder (MBA-1600).
494    #[serde(default)]
495    pub bc_segments: Option<Vec<CardBcSegmentV1>>,
496    /// Filesystem path to a caliber-specific BC5D correction table
497    /// (`bc5d_<caliber>.bin`, the exact format the CLI's `--bc-table-dir`
498    /// consumes). The table is CRC-verified, a velocity-keyed BC schedule is
499    /// generated for this load (same ladder as the CLI), and the scalar BC gets the
500    /// table's muzzle correction as the interior-gap fallback. Ignored when
501    /// `bc_segments` is supplied. Not available on wasm32 builds (no filesystem);
502    /// there it is rejected with an invalid-request error.
503    #[serde(default)]
504    pub bc5d_table_path: Option<String>,
505
506    /// Presentation-only options for the printable PDF dope card (`card.pdf`). Nothing in
507    /// here touches the ballistics: the numbers in the PDF are the rows
508    /// [`range_table_v1`] returns, computed by the same call.
509    ///
510    /// It lives on the shared request — rather than in a `card.pdf`-only wrapper type — so
511    /// an app stores ONE `CardRequestV1` per saved card and replays that exact document
512    /// against either surface: `card.range_table` for the screen, `card.pdf` for the
513    /// printout. The on-screen commands ignore this block.
514    ///
515    /// Deliberately NOT `#[cfg(feature = "pdf")]`, even though everything that consumes it
516    /// is: `CardRequestV1` denies unknown fields, so gating the field would make a
517    /// pdf-less build REJECT a stored request that carries it, breaking exactly the
518    /// round-trip the field exists to support. A pdf-less build parses it and never reads
519    /// it; only the `card.pdf` command itself disappears.
520    #[serde(default)]
521    pub pdf: Option<PdfCardOptionsV1>,
522}
523
524/// Presentation knobs for the PDF dope card: the header/footer labels the printed card
525/// carries and the table's font size. The ballistics axes it prints (elevation unit,
526/// windage unit, click graduations, tracking CFs, zero-set biases) are NOT here — they are
527/// already fields on [`CardRequestV1`], shared with the on-screen card, precisely so the
528/// two cannot disagree about what a row means.
529///
530/// Every field is optional and defaults to the CLI dope card's own default.
531#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
532#[serde(deny_unknown_fields)]
533pub struct PdfCardOptionsV1 {
534    /// Leading text of header line 1 — the CLI's rifle/profile name. Default
535    /// `"Dope Card"`. Long headers are truncated to fit the page.
536    #[serde(default)]
537    pub title: Option<String>,
538    /// Header `Loc:` label. Default empty.
539    #[serde(default)]
540    pub location: Option<String>,
541    /// Footer `Powder:` label. Default empty.
542    #[serde(default)]
543    pub powder: Option<String>,
544    /// Footer `Bullet:` label. Default empty.
545    #[serde(default)]
546    pub bullet: Option<String>,
547    /// Crossing-target speed for the Lead column, in the request's `wind_speed_unit` — the
548    /// same convention as the CLI's `--target-speed`
549    /// (MBA-1325). The lead is `speed * time-of-flight` for a full-value 90° crossing,
550    /// held on the windage axis, exactly as `trajectory -o pdf` computes it.
551    ///
552    /// Absent means "this card carries no lead data": the Lead column renders as em-dashes
553    /// rather than a column of confident-looking zeroes. An explicit `0.0` is a different
554    /// statement — a stationary target, whose lead genuinely is zero — and prints zeroes,
555    /// matching the CLI's `--target-speed 0` default.
556    #[serde(default)]
557    pub target_speed: Option<f64>,
558    /// Data-table font scale. Must be finite and within
559    /// [`crate::pdf_dope_card::FONT_SCALE_RANGE`] (0.5..=3.0); out-of-band values are
560    /// rejected rather than silently clamped, so what a stored request asks for is what it
561    /// gets. Mutually exclusive with `font_preset`. Default 1.0.
562    #[serde(default)]
563    pub font_scale: Option<f64>,
564    /// Named font scale: `"small"` (0.8), `"medium"` (1.0), `"large"` (1.4) — the CLI's
565    /// `--font-preset` vocabulary, single-letter aliases included. An unrecognized preset
566    /// is an error here (the CLI warns and falls back to medium; a stored request should
567    /// not silently render at a size it did not ask for). Mutually exclusive with
568    /// `font_scale`.
569    #[serde(default)]
570    pub font_preset: Option<String>,
571    /// Render the data rows in bold. Default false.
572    #[serde(default)]
573    pub bold_data: bool,
574}
575
576/// One velocity band of an explicit velocity-keyed BC schedule
577/// (`CardRequestV1::bc_segments`). `velocity_min`/`velocity_max` are in the
578/// request's `velocity_unit` and must satisfy `velocity_min < velocity_max`;
579/// `bc` is the BC (for the request's `drag_model`) that applies inside the band.
580/// `bc` must lie in 0.0001..=100. Responses state the bands a card flew in the same shape,
581/// in [`CardBcLadderV1::segments`] (MBA-1601).
582#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
583#[serde(deny_unknown_fields)]
584pub struct CardBcSegmentV1 {
585    pub velocity_min: f64,
586    pub velocity_max: f64,
587    pub bc: f64,
588}
589
590/// The BC ladder a card's rows flew (MBA-1601): [`CardResponseV1::bc_ladder`].
591///
592/// Under a ladder the scalar [`CardResponseV1::bc_for_solve`] is only the interior-gap
593/// fallback, so this block is what states the BCs the card actually flew.
594#[derive(Debug, Clone, PartialEq, Serialize)]
595pub struct CardBcLadderV1 {
596    /// Where the ladder came from: `"bc_segments"` (the request's own bands) or
597    /// `"bc5d_table"` (the ladder `bc5d_table_path` generated for this load).
598    pub source: &'static str,
599    /// The bands as flown, `velocity_min`/`velocity_max` in the response's `units.velocity`.
600    /// For `bc_segments` these are the request's bands verbatim and in request order; for
601    /// `bc5d_table` the generated ladder, fastest band first.
602    pub segments: Vec<CardBcSegmentV1>,
603    /// True when some airspeed between the slowest and the fastest band lies in no band: there,
604    /// and blended into the bands within up to 25 fps either side of a gap edge, `bc_for_solve`
605    /// flies. False means `bc_for_solve` never flew on this card. It describes the ladder, not
606    /// the flight: a gap the card's airspeeds never reach still reads true.
607    pub interior_gap: bool,
608}
609
610/// The `sight_height` sentinel for "not supplied".
611///
612/// A serde field default is a nullary function: it cannot see the request, so it cannot know
613/// which `sight_height_unit` the figure would have to be in. NaN stands in until `resolve()`
614/// swaps it for `Units::default_sight_height`, which does know.
615fn sight_height_unset() -> f64 {
616    f64::NAN
617}
618fn default_humidity() -> f64 {
619    DEFAULT_HUMIDITY_PERCENT
620}
621fn default_cf() -> f64 {
622    1.0
623}
624
625/// Drag model selector mirroring the CLI's `--drag-model` strings.
626#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
627#[serde(rename_all = "lowercase")]
628pub enum DragModelV1 {
629    G1,
630    #[default]
631    G7,
632    G2,
633    G5,
634    G6,
635    G8,
636    GI,
637    GS,
638    RA4,
639}
640
641impl From<DragModelV1> for DragModel {
642    fn from(v: DragModelV1) -> Self {
643        match v {
644            DragModelV1::G1 => DragModel::G1,
645            DragModelV1::G7 => DragModel::G7,
646            DragModelV1::G2 => DragModel::G2,
647            DragModelV1::G5 => DragModel::G5,
648            DragModelV1::G6 => DragModel::G6,
649            DragModelV1::G8 => DragModel::G8,
650            DragModelV1::GI => DragModel::GI,
651            DragModelV1::GS => DragModel::GS,
652            DragModelV1::RA4 => DragModel::RA4,
653        }
654    }
655}
656
657#[derive(Debug, Clone, Serialize)]
658pub struct CardRowV1 {
659    /// Range in the request's `distance_unit`; `CardUnitsBlockV1::distance` names it.
660    pub range: f64,
661    #[serde(skip_serializing_if = "Option::is_none")]
662    pub drop_linear: Option<f64>,
663    #[serde(skip_serializing_if = "Option::is_none")]
664    pub drop_adj: Option<f64>,
665    #[serde(skip_serializing_if = "Option::is_none")]
666    pub come_up: Option<f64>,
667    #[serde(skip_serializing_if = "Option::is_none")]
668    pub wind_linear: Option<f64>,
669    #[serde(skip_serializing_if = "Option::is_none")]
670    pub wind_adj: Option<f64>,
671    #[serde(skip_serializing_if = "Option::is_none")]
672    pub velocity: Option<f64>,
673    #[serde(skip_serializing_if = "Option::is_none")]
674    pub energy: Option<f64>,
675    #[serde(skip_serializing_if = "Option::is_none")]
676    pub time: Option<f64>,
677    #[serde(skip_serializing_if = "Vec::is_empty", default)]
678    pub wind_columns: Vec<f64>,
679}
680
681#[derive(Debug, Clone, Serialize)]
682pub struct CardUnitsBlockV1 {
683    pub distance: &'static str,
684    pub velocity: &'static str,
685    pub energy: &'static str,
686    pub drop: &'static str,
687    pub wind_speed: &'static str,
688    pub elevation_adjustment: String,
689    pub windage_adjustment: String,
690}
691
692#[derive(Debug, Clone, Serialize)]
693pub struct CardResponseV1 {
694    pub schema_version: u32,
695    pub kind: &'static str,
696    pub zero_distance: f64,
697    /// The scalar BC fed to the zero solve and every sampled flight: the request's published
698    /// `ballistic_coefficient`, or, when `bc5d_table_path` generated a ladder, that BC with
699    /// the table's muzzle-velocity correction applied.
700    ///
701    /// With no [`Self::bc_ladder`] it is the BC every row flew, and the printed footer's
702    /// `BC:`. With a `bc_ladder` it is only the interior-gap fallback: it flies only where
703    /// `bc_ladder.interior_gap` allows, and never under a gapless ladder (every ladder a
704    /// correction table builds), so it must not be presented as the card's BC (MBA-1601).
705    pub bc_for_solve: f64,
706    /// The BC ladder these rows flew, present only when one fed the solve: the request's
707    /// `bc_segments`, or the ladder its `bc5d_table_path` generated (MBA-1601).
708    ///
709    /// Additive and absent on every card without a ladder, so those responses are
710    /// byte-identical to before. A saved card has to be able to state the BCs its numbers
711    /// came from long after the correction table has been replaced on disk, and under a
712    /// ladder `bc_for_solve` alone does not do that.
713    #[serde(skip_serializing_if = "Option::is_none", default)]
714    pub bc_ladder: Option<CardBcLadderV1>,
715    pub units: CardUnitsBlockV1,
716    /// Wind card only: the swept speeds, one per `wind_columns` entry.
717    #[serde(skip_serializing_if = "Vec::is_empty", default)]
718    pub wind_speeds: Vec<f64>,
719    /// Wind card only: one block of rows per wind angle.
720    #[serde(skip_serializing_if = "Vec::is_empty", default)]
721    pub wind_angles_deg: Vec<f64>,
722    pub rows: Vec<CardRowV1>,
723    /// Wind card with multiple angles: rows for angles beyond the first.
724    #[serde(skip_serializing_if = "Vec::is_empty", default)]
725    pub extra_angle_rows: Vec<Vec<CardRowV1>>,
726    /// Present ONLY when the solved flight stopped short of the rows requested, in which case
727    /// `rows` holds every row it did reach and nothing past them (MBA-1476 follow-up).
728    ///
729    /// Additive and absent on every card that ran to its requested `end`, so a caller reading
730    /// an untruncated card sees byte-identical JSON to before. It is a field rather than only
731    /// a log line because the apps and the Flask layer consume this shape: a card that quietly
732    /// returns fewer rows than were asked for, with nothing on the response saying so, is the
733    /// same class of silent failure as the substituted row this work removed.
734    #[serde(skip_serializing_if = "Option::is_none", default)]
735    pub truncation: Option<CardTruncationV1>,
736}
737
738/// The wire form of [`CardTruncation`]: the rows a card could not print and why.
739/// Distances are in the response's own `units.distance`.
740#[derive(Debug, Clone, Copy, Serialize)]
741pub struct CardTruncationV1 {
742    /// The furthest row the request asked for.
743    pub requested_end: f64,
744    /// The last row actually present in `rows`.
745    pub last_row: f64,
746    /// How far the solved flight got — a property of the load, not of the request.
747    pub reach: f64,
748}
749
750impl CardTruncationV1 {
751    fn new(truncation: CardTruncation) -> Self {
752        Self {
753            requested_end: truncation.requested_end,
754            last_row: truncation.last_row,
755            reach: truncation.reach,
756        }
757    }
758}
759
760/// Back to the engine type, so the wording lives on [`CardTruncation`] alone and no surface
761/// has to restate the field mapping in order to say the same sentence.
762impl From<CardTruncationV1> for CardTruncation {
763    fn from(wire: CardTruncationV1) -> Self {
764        Self {
765            requested_end: wire.requested_end,
766            last_row: wire.last_row,
767            reach: wire.reach,
768        }
769    }
770}
771
772#[derive(Debug, thiserror::Error)]
773pub enum CardServiceError {
774    /// Air refused during the zero or sampled flight; retain its typed cause for the caller.
775    #[error("{0}")]
776    Atmosphere(#[source] crate::atmosphere::AtmosphereError),
777    #[error("invalid request: {0}")]
778    InvalidRequest(String),
779    #[error("zero solve failed: {0}")]
780    ZeroSolve(String),
781    #[error("trajectory failed: {0}")]
782    Trajectory(String),
783    /// PDF rendering itself failed (font load/parse, or an empty row set). Gated with the
784    /// only code path that can produce it, so a build without `pdf` sees an unchanged enum.
785    #[cfg(feature = "pdf")]
786    #[error("pdf generation failed: {0}")]
787    Pdf(String),
788    /// The card is too big to print ([`MAX_PDF_ROWS`] / [`MAX_PDF_PAGES`]). A resource
789    /// refusal, not a failure: the request was well formed and the caller can be told
790    /// exactly what is true of the card (how many rows, how many pages), so the message is
791    /// carried verbatim rather than prefixed.
792    #[cfg(feature = "pdf")]
793    #[error("{0}")]
794    TooLarge(String),
795}
796
797// --- Unit conversions: byte-identical constants to the CLI's UnitConverter ---
798//
799// One resolved unit per dimension, and one place where a unit becomes a factor. Every
800// imperial arm and every metric arm below is the SAME EXPRESSION the single-scalar version
801// of this module used for that dimension — the imperial arm for the dimensions the imperial
802// preset fills, the metric arm for the metric preset's — so a request that states no
803// per-dimension unit performs exactly the multiplications it always performed, in the same
804// order, and lands on the same bits. The only genuinely new arms are the values neither
805// preset produces (cm, km/h, knots, and feet of altitude), which no pre-existing request can
806// select.
807//
808// The reverse conversions are deliberately NOT expressed as `to_metric` composed with a
809// division. `Mph -> v` and `Mph -> (v * 0.44704) / 0.44704` are not the same f64, and the
810// pre-existing behaviour is the former.
811
812/// m/s per km/h.
813const KPH_TO_MPS: f64 = 1.0 / 3.6;
814/// m/s per knot: one nautical mile (1852 m) per hour, exactly.
815const KNOTS_TO_MPS: f64 = 1852.0 / 3600.0;
816
817struct Units {
818    distance: CardDistanceUnit,
819    velocity: CardVelocityUnit,
820    mass: CardMassUnit,
821    diameter: CardDiameterUnit,
822    sight_height: CardLinearUnit,
823    drop: CardLinearUnit,
824    wind_speed: CardWindSpeedUnit,
825    temperature: CardTemperatureUnit,
826    pressure: CardPressureUnit,
827    energy: CardEnergyUnit,
828    altitude: CardAltitudeUnit,
829}
830
831impl Units {
832    /// Settle every dimension: the request's own field where it states one, otherwise what
833    /// the [`CardUnits`] preset implies.
834    ///
835    /// Pure, cheap, and free of validation, so the PDF path can settle the axes it prints in
836    /// the header without repeating the request checks `resolve_inner` performs.
837    fn resolve(req: &CardRequestV1) -> Self {
838        let imperial = req.units == CardUnits::Imperial;
839        let linear = if imperial {
840            CardLinearUnit::Inches
841        } else {
842            CardLinearUnit::Mm
843        };
844        Self {
845            distance: req.distance_unit.unwrap_or(if imperial {
846                CardDistanceUnit::Yards
847            } else {
848                CardDistanceUnit::Meters
849            }),
850            velocity: req.velocity_unit.unwrap_or(if imperial {
851                CardVelocityUnit::Fps
852            } else {
853                CardVelocityUnit::Mps
854            }),
855            mass: req.mass_unit.unwrap_or(if imperial {
856                CardMassUnit::Grains
857            } else {
858                CardMassUnit::Grams
859            }),
860            diameter: req.diameter_unit.unwrap_or(if imperial {
861                CardDiameterUnit::Inches
862            } else {
863                CardDiameterUnit::Mm
864            }),
865            sight_height: req.sight_height_unit.unwrap_or(linear),
866            drop: req.drop_unit.unwrap_or(linear),
867            wind_speed: req.wind_speed_unit.unwrap_or(if imperial {
868                CardWindSpeedUnit::Mph
869            } else {
870                CardWindSpeedUnit::Mps
871            }),
872            temperature: req.temperature_unit.unwrap_or(if imperial {
873                CardTemperatureUnit::Fahrenheit
874            } else {
875                CardTemperatureUnit::Celsius
876            }),
877            pressure: req.pressure_unit.unwrap_or(if imperial {
878                CardPressureUnit::InHg
879            } else {
880                CardPressureUnit::HPa
881            }),
882            energy: req.energy_unit.unwrap_or(if imperial {
883                CardEnergyUnit::FtLb
884            } else {
885                CardEnergyUnit::Joules
886            }),
887            // NOT `imperial`-dependent: `altitude` has always been metres in both systems.
888            // See CardRequestV1::altitude_unit for why the preset must never reach it.
889            altitude: req.altitude_unit.unwrap_or(CardAltitudeUnit::Meters),
890        }
891    }
892
893    // --- into SI, for the solver ---
894
895    fn velocity_to_metric(&self, v: f64) -> f64 {
896        match self.velocity {
897            CardVelocityUnit::Fps => v * 0.3048,
898            CardVelocityUnit::Mps => v,
899        }
900    }
901    fn mass_to_kg(&self, v: f64) -> f64 {
902        match self.mass {
903            CardMassUnit::Grains => v * GRAINS_TO_KG,
904            CardMassUnit::Grams => v * 0.001,
905        }
906    }
907    fn distance_to_metric(&self, v: f64) -> f64 {
908        match self.distance {
909            CardDistanceUnit::Yards => v * 0.9144,
910            CardDistanceUnit::Meters => v,
911        }
912    }
913    fn linear_to_metric(unit: CardLinearUnit, v: f64) -> f64 {
914        match unit {
915            CardLinearUnit::Inches => v * 0.0254,
916            CardLinearUnit::Cm => v * 0.01,
917            CardLinearUnit::Mm => v * 0.001,
918        }
919    }
920    fn diameter_to_metric(&self, v: f64) -> f64 {
921        match self.diameter {
922            CardDiameterUnit::Inches => v * 0.0254,
923            CardDiameterUnit::Mm => v * 0.001,
924        }
925    }
926    fn sight_height_to_metric(&self, v: f64) -> f64 {
927        Self::linear_to_metric(self.sight_height, v)
928    }
929    fn drop_to_metric(&self, v: f64) -> f64 {
930        Self::linear_to_metric(self.drop, v)
931    }
932    fn wind_to_metric(&self, v: f64) -> f64 {
933        match self.wind_speed {
934            CardWindSpeedUnit::Mph => v * 0.44704,
935            CardWindSpeedUnit::Mps => v,
936            CardWindSpeedUnit::Kph => v * KPH_TO_MPS,
937            CardWindSpeedUnit::Knots => v * KNOTS_TO_MPS,
938        }
939    }
940    fn temperature_to_metric(&self, v: f64) -> f64 {
941        match self.temperature {
942            CardTemperatureUnit::Fahrenheit => (v - 32.0) * 5.0 / 9.0,
943            CardTemperatureUnit::Celsius => v,
944        }
945    }
946    fn pressure_to_metric(&self, v: f64) -> f64 {
947        match self.pressure {
948            CardPressureUnit::InHg => v * 33.8639,
949            CardPressureUnit::HPa => v,
950        }
951    }
952    /// `altitude` in metres, which is what [`AtmosphericConditions::altitude`] wants and
953    /// what every request that predates `altitude_unit` already supplied.
954    fn altitude_to_metric(&self, v: f64) -> f64 {
955        match self.altitude {
956            CardAltitudeUnit::Feet => v * 0.3048,
957            CardAltitudeUnit::Meters => v,
958        }
959    }
960
961    // --- back out, for the printed row ---
962
963    fn velocity_from_metric(&self, v: f64) -> f64 {
964        match self.velocity {
965            CardVelocityUnit::Fps => v / 0.3048,
966            CardVelocityUnit::Mps => v,
967        }
968    }
969    fn distance_from_metric(&self, v: f64) -> f64 {
970        match self.distance {
971            CardDistanceUnit::Yards => v / 0.9144,
972            CardDistanceUnit::Meters => v,
973        }
974    }
975    fn energy_from_metric(&self, v: f64) -> f64 {
976        match self.energy {
977            CardEnergyUnit::FtLb => v * 0.737562,
978            CardEnergyUnit::Joules => v,
979        }
980    }
981    fn drop_linear_from_metric(&self, v: f64) -> f64 {
982        match self.drop {
983            CardLinearUnit::Inches => v / 0.0254,
984            CardLinearUnit::Cm => v * 100.0,
985            CardLinearUnit::Mm => v * 1000.0,
986        }
987    }
988
989    // --- column labels; the response's `units` block IS this, field for field ---
990
991    /// Label for the distance axis, for error messages that must name a range.
992    fn distance_label(&self) -> &'static str {
993        match self.distance {
994            CardDistanceUnit::Yards => "yd",
995            CardDistanceUnit::Meters => "m",
996        }
997    }
998    fn velocity_label(&self) -> &'static str {
999        match self.velocity {
1000            CardVelocityUnit::Fps => "fps",
1001            CardVelocityUnit::Mps => "m/s",
1002        }
1003    }
1004    fn energy_label(&self) -> &'static str {
1005        match self.energy {
1006            CardEnergyUnit::FtLb => "ft-lb",
1007            CardEnergyUnit::Joules => "J",
1008        }
1009    }
1010    fn drop_label(&self) -> &'static str {
1011        match self.drop {
1012            CardLinearUnit::Inches => "in",
1013            CardLinearUnit::Cm => "cm",
1014            CardLinearUnit::Mm => "mm",
1015        }
1016    }
1017    fn wind_speed_label(&self) -> &'static str {
1018        match self.wind_speed {
1019            CardWindSpeedUnit::Mph => "mph",
1020            CardWindSpeedUnit::Mps => "m/s",
1021            CardWindSpeedUnit::Kph => "km/h",
1022            CardWindSpeedUnit::Knots => "kn",
1023        }
1024    }
1025
1026    // --- the CLI's own axes, for the call sites that are pinned to CLI constants ---
1027    //
1028    // These do NOT reuse the conversions above. The BC5D path and the PDF header each
1029    // hardcode a factor that `main.rs` hardcodes at the same call site (3.280_839_895 vs
1030    // 1/0.3048; 15.4324 vs the exact grains-per-gram), and the golden tests pin the CLI's
1031    // digits. Sharing one factor between them would change numbers this work must not.
1032    //
1033    // Each of these helpers is compiled exactly where its call site is, rather than being
1034    // blanket-allowed as dead code, so that a helper which stops being called anywhere is
1035    // still a warning. For most of them that means a cfg attribute; `velocity_to_fps_bc5d`
1036    // carries none because its call site is the always-compiled `bc_segments` arm of
1037    // `resolve_bc_schedule`, so it is reached in every build.
1038
1039    /// Display velocity -> fps using `parse_bc_segment`'s factor.
1040    fn velocity_to_fps_bc5d(&self, v: f64) -> f64 {
1041        match self.velocity {
1042            CardVelocityUnit::Fps => v,
1043            CardVelocityUnit::Mps => v * 3.280_839_895,
1044        }
1045    }
1046    /// fps -> display velocity, the inverse of [`Self::velocity_to_fps_bc5d`], for the band
1047    /// edges of a generated BC5D ladder (which no wasm32 build has).
1048    #[cfg(not(target_arch = "wasm32"))]
1049    fn velocity_from_fps_bc5d(&self, v: f64) -> f64 {
1050        match self.velocity {
1051            CardVelocityUnit::Fps => v,
1052            CardVelocityUnit::Mps => v / 3.280_839_895,
1053        }
1054    }
1055    /// Bullet weight -> grains using the CLI's BC5D/PDF factor.
1056    #[cfg(any(feature = "pdf", not(target_arch = "wasm32")))]
1057    fn mass_to_grains_cli(&self, v: f64) -> f64 {
1058        match self.mass {
1059            CardMassUnit::Grains => v,
1060            CardMassUnit::Grams => v * 15.4324,
1061        }
1062    }
1063    /// Bullet diameter -> inches, the BC5D table's caliber axis (which no wasm32 build has,
1064    /// there being no filesystem to read a table from).
1065    #[cfg(not(target_arch = "wasm32"))]
1066    fn diameter_to_inches(&self, v: f64) -> f64 {
1067        match self.diameter {
1068            CardDiameterUnit::Inches => v,
1069            CardDiameterUnit::Mm => v / 25.4,
1070        }
1071    }
1072    /// Muzzle velocity -> fps for the PDF header (`main.rs` divides by 0.3048 here).
1073    #[cfg(feature = "pdf")]
1074    fn velocity_to_fps_pdf(&self, v: f64) -> f64 {
1075        match self.velocity {
1076            CardVelocityUnit::Fps => v,
1077            CardVelocityUnit::Mps => v / 0.3048,
1078        }
1079    }
1080    /// Pressure -> inHg for the PDF header (`main.rs` uses 33.8639 on both PDF call sites,
1081    /// NOT `pdf_dope_card::INHG_TO_HPA`).
1082    #[cfg(feature = "pdf")]
1083    fn pressure_to_inhg(&self, v: f64) -> f64 {
1084        match self.pressure {
1085            CardPressureUnit::InHg => v,
1086            CardPressureUnit::HPa => v / 33.8639,
1087        }
1088    }
1089    /// Pressure -> hPa for the PDF header, same factor.
1090    #[cfg(feature = "pdf")]
1091    fn pressure_to_hpa(&self, v: f64) -> f64 {
1092        match self.pressure {
1093            CardPressureUnit::InHg => v * 33.8639,
1094            CardPressureUnit::HPa => v,
1095        }
1096    }
1097    /// Temperature -> °F for the PDF header.
1098    #[cfg(feature = "pdf")]
1099    fn temperature_to_fahrenheit(&self, v: f64) -> f64 {
1100        match self.temperature {
1101            CardTemperatureUnit::Fahrenheit => v,
1102            CardTemperatureUnit::Celsius => v * 9.0 / 5.0 + 32.0,
1103        }
1104    }
1105    /// Wind or crossing speed -> mph for the PDF header.
1106    #[cfg(feature = "pdf")]
1107    fn wind_to_mph(&self, v: f64) -> f64 {
1108        match self.wind_speed {
1109            CardWindSpeedUnit::Mph => v,
1110            CardWindSpeedUnit::Mps => v / 0.44704,
1111            CardWindSpeedUnit::Kph => v * KPH_TO_MPS / 0.44704,
1112            CardWindSpeedUnit::Knots => v * KNOTS_TO_MPS / 0.44704,
1113        }
1114    }
1115    /// Altitude -> feet for the PDF header, which reports the altitude the SOLVE used.
1116    #[cfg(feature = "pdf")]
1117    fn altitude_to_feet(&self, v: f64) -> f64 {
1118        match self.altitude {
1119            CardAltitudeUnit::Feet => v,
1120            CardAltitudeUnit::Meters => v / 0.3048,
1121        }
1122    }
1123
1124    // --- defaults that are themselves denominated ---
1125
1126    /// The CLI's 1.5-inch sight height, restated in this request's `sight_height_unit`.
1127    /// The millimetre figure is the module's long-standing 38.0 (a rounded 1.5 in, not a
1128    /// conversion of it), and the centimetre figure is that same length, exactly.
1129    fn default_sight_height(&self) -> f64 {
1130        match self.sight_height {
1131            CardLinearUnit::Inches => 1.5,
1132            CardLinearUnit::Cm => 3.8,
1133            CardLinearUnit::Mm => 38.0,
1134        }
1135    }
1136    /// The CLI's 59 °F / 15 °C standard temperature, in this request's `temperature_unit`.
1137    fn default_temperature(&self) -> f64 {
1138        match self.temperature {
1139            CardTemperatureUnit::Fahrenheit => 59.0,
1140            CardTemperatureUnit::Celsius => 15.0,
1141        }
1142    }
1143    /// The CLI's 29.92 inHg / 1013.25 hPa standard pressure, in this request's
1144    /// `pressure_unit`.
1145    fn default_pressure(&self) -> f64 {
1146        match self.pressure {
1147            CardPressureUnit::InHg => 29.92,
1148            CardPressureUnit::HPa => 1013.25,
1149        }
1150    }
1151}
1152
1153struct Resolved {
1154    u: Units,
1155    velocity_m: f64,
1156    mass_kg: f64,
1157    diameter_m: f64,
1158    sight_height_m: f64,
1159    zero_distance_m: f64,
1160    zero_poi_vertical_m: f64,
1161    zero_poi_horizontal_m: f64,
1162    sight_offset_lateral_m: f64,
1163    temperature_c: f64,
1164    pressure_hpa: f64,
1165    /// The request's `humidity`, validated by [`RelativeHumidity`]: the percent every solve of
1166    /// the card flies.
1167    humidity_percent: f64,
1168    /// Which of `temperature` / `pressure` the request carried (0.49.0). A field the request
1169    /// carried is a reading and flies as given; an absent one is the default above, resolved
1170    /// by the legacy rule (ICAO standard air at a real altitude).
1171    station_presence: StationAtmospherePresence,
1172    /// Site elevation in metres — which is what `altitude` already was for every request
1173    /// that states no `altitude_unit`, so this is a rename of an identity, not a conversion.
1174    altitude_m: f64,
1175    end_m: f64,
1176    elevation_click: Option<ClickValue>,
1177    windage_click: Option<ClickValue>,
1178    windage_unit: AdjustmentUnit,
1179    drag_model: DragModel,
1180    /// Scalar BC actually fed to the zero solve and every sampled run. Equals the
1181    /// request's `ballistic_coefficient` unless a BC5D table applied its muzzle
1182    /// correction (CLI parity: the scalar is the schedule's interior-gap fallback).
1183    bc_for_solve: f64,
1184    /// Velocity-keyed BC schedule (velocities in fps, the unit the solver compares
1185    /// against), from explicit `bc_segments` or generated from `bc5d_table_path`.
1186    bc_segments_fps: Option<Vec<BCSegmentData>>,
1187    /// The same schedule as the response states it ([`CardResponseV1::bc_ladder`]).
1188    bc_ladder: Option<CardBcLadderV1>,
1189}
1190
1191fn resolve(req: &CardRequestV1) -> Result<Resolved, CardServiceError> {
1192    resolve_inner(req, true)
1193}
1194
1195/// [`resolve`] WITHOUT the BC-schedule step — the request's declared axes, click
1196/// graduations and unit conversions, and nothing that touches the filesystem.
1197///
1198/// This is the resolve `card.pdf` performs when it prints caller-supplied rows: those rows
1199/// were computed elsewhere (they are the stored `card.range_table` response), so opening
1200/// `bc5d_table_path` here would do nothing but couple a reprint to whether that file is
1201/// still on the device — which is exactly the coupling printing stored rows exists to
1202/// break. `bc_for_solve` is left at the request's published BC and `bc_ladder` at `None`;
1203/// neither is used for the footer on that path (the stored card's own are).
1204#[cfg(feature = "pdf")]
1205fn resolve_axes_only(req: &CardRequestV1) -> Result<Resolved, CardServiceError> {
1206    resolve_inner(req, false)
1207}
1208
1209/// The card request's station air refused in the card's own words, or `None` when it flies:
1210/// `humidity = 106: relative humidity must be a percent from 0 to 100 (...)` for a humidity
1211/// beyond the sensor band, `humidity = 100 at 212 °F and 29.92 inHg: no such air exists: ...`
1212/// for air that cannot exist, `pressure = -1 inHg: pressure must be greater than 0` and
1213/// `temperature = -500 °F: temperature must be above absolute zero (-459.67 °F)` for a reading no
1214/// air has. The temperature and pressure are the station values every solve of the card flies,
1215/// and every altitude is stated, in the request's own units; the path is the member to blame in
1216/// the request (`$.humidity`, `$.temperature`, `$.pressure`, `$.altitude`).
1217///
1218/// Every card command checks this before it solves anything, and the bridge reports it in
1219/// `error.details` when it is the refusal the service made.
1220/// A card's station refusal, or a typed refusal discovered during its flight.
1221pub fn air_refusal_for_error(
1222    req: &CardRequestV1,
1223    error: Option<&crate::atmosphere::AtmosphereError>,
1224) -> Option<AirRefusal> {
1225    if let Some(error) = error {
1226        let units = Units::resolve(req);
1227        return Some(error.temperature_refusal(
1228            AirField {
1229                name: "temperature",
1230                path: "$.temperature",
1231            },
1232            AirUnits {
1233                temperature: match units.temperature {
1234                    CardTemperatureUnit::Fahrenheit => TemperatureUnit::Fahrenheit,
1235                    CardTemperatureUnit::Celsius => TemperatureUnit::Celsius,
1236                },
1237                altitude: match units.altitude {
1238                    CardAltitudeUnit::Feet => AltitudeUnit::Feet,
1239                    CardAltitudeUnit::Meters => AltitudeUnit::Meters,
1240                },
1241                ..AirUnits::default()
1242            },
1243        ));
1244    }
1245    air_refusal(req)
1246}
1247
1248pub fn air_refusal(req: &CardRequestV1) -> Option<AirRefusal> {
1249    let u = Units::resolve(req);
1250    let station_presence =
1251        StationAtmospherePresence::new(req.temperature.is_some(), req.pressure.is_some());
1252    let temperature = req.temperature.unwrap_or_else(|| u.default_temperature());
1253    let pressure = req.pressure.unwrap_or_else(|| u.default_pressure());
1254    AtmosphericConditions {
1255        temperature: u.temperature_to_metric(temperature),
1256        pressure: u.pressure_to_metric(pressure),
1257        humidity: req.humidity,
1258        altitude: u.altitude_to_metric(req.altitude),
1259    }
1260    .air_refusal(
1261        station_presence,
1262        [
1263            AirField {
1264                name: "humidity",
1265                path: "$.humidity",
1266            },
1267            AirField {
1268                name: "temperature",
1269                path: "$.temperature",
1270            },
1271            AirField {
1272                name: "pressure",
1273                path: "$.pressure",
1274            },
1275            AirField {
1276                name: "altitude",
1277                path: "$.altitude",
1278            },
1279        ],
1280        req.humidity,
1281        AirUnits {
1282            temperature: match u.temperature {
1283                CardTemperatureUnit::Fahrenheit => TemperatureUnit::Fahrenheit,
1284                CardTemperatureUnit::Celsius => TemperatureUnit::Celsius,
1285            },
1286            pressure: match u.pressure {
1287                CardPressureUnit::InHg => PressureUnit::InchesOfMercury,
1288                CardPressureUnit::HPa => PressureUnit::Hectopascals,
1289            },
1290            altitude: match u.altitude {
1291                CardAltitudeUnit::Feet => AltitudeUnit::Feet,
1292                CardAltitudeUnit::Meters => AltitudeUnit::Meters,
1293            },
1294        },
1295    )
1296}
1297
1298fn resolve_inner(
1299    req: &CardRequestV1,
1300    load_bc_schedule: bool,
1301) -> Result<Resolved, CardServiceError> {
1302    let u = Units::resolve(req);
1303
1304    for (name, v) in [
1305        ("muzzle_velocity", req.muzzle_velocity),
1306        ("ballistic_coefficient", req.ballistic_coefficient),
1307        ("mass", req.mass),
1308        ("diameter", req.diameter),
1309        ("zero_distance", req.zero_distance),
1310        ("start", req.start),
1311        ("end", req.end),
1312        ("step", req.step),
1313    ] {
1314        if !v.is_finite() || v <= 0.0 {
1315            return Err(CardServiceError::InvalidRequest(format!(
1316                "{name} must be finite and positive, got {v}"
1317            )));
1318        }
1319    }
1320    if req.end < req.start {
1321        return Err(CardServiceError::InvalidRequest(
1322            "end must be >= start".into(),
1323        ));
1324    }
1325    if !(0.5..=1.5).contains(&req.elevation_cf) || !(0.5..=1.5).contains(&req.windage_cf) {
1326        return Err(CardServiceError::InvalidRequest(
1327            "tracking correction factors must lie in (0.5, 1.5)".into(),
1328        ));
1329    }
1330    // The station air: the engine's one humidity validator (a percent in
1331    // [0, 100], a sensor reading within 5 points of it read as the end, anything farther
1332    // out refused and never clamped; 0.49.0 flew 150 as 100 % here) and the solver's one
1333    // impossible-air rule, refused here in the card's words before any solve, so a card of air
1334    // that cannot exist names that air rather than a failed zero solve. The bridge reports the
1335    // same refusal in `error.details`.
1336    if let Some(refusal) = air_refusal(req) {
1337        return Err(CardServiceError::InvalidRequest(
1338            refusal.message().to_string(),
1339        ));
1340    }
1341    let humidity = RelativeHumidity::try_percent(req.humidity).map_err(|error| {
1342        CardServiceError::InvalidRequest(error.at_field("humidity").to_string())
1343    })?;
1344
1345    // Each of these three defaults is itself denominated, so it is taken from the dimension
1346    // that governs the field rather than from the preset (`Units` restates the CLI's own
1347    // figures per unit). `sight_height`'s sentinel is NaN because a serde field default
1348    // cannot see the request it belongs to.
1349    let sight_height = if req.sight_height.is_nan() {
1350        u.default_sight_height()
1351    } else {
1352        req.sight_height
1353    };
1354    // Presence is taken BEFORE the collapse below, which yields the legacy default for an
1355    // absent field (and must keep doing so: at sea level that default is what flies).
1356    let station_presence =
1357        StationAtmospherePresence::new(req.temperature.is_some(), req.pressure.is_some());
1358    let temperature = req.temperature.unwrap_or_else(|| u.default_temperature());
1359    let pressure = req.pressure.unwrap_or_else(|| u.default_pressure());
1360
1361    let parse_click =
1362        |label: &str, s: &Option<String>| -> Result<Option<ClickValue>, CardServiceError> {
1363            s.as_deref()
1364                .map(|raw| {
1365                    parse_click_value(raw)
1366                        .map_err(|e| CardServiceError::InvalidRequest(format!("{label}: {e}")))
1367                })
1368                .transpose()
1369        };
1370    let elevation_click = parse_click("elevation_click_value", &req.elevation_click_value)?;
1371    let windage_click =
1372        parse_click("windage_click_value", &req.windage_click_value)?.or(elevation_click);
1373
1374    if req.adjustment_unit == AdjustmentUnit::Clicks && elevation_click.is_none() {
1375        return Err(CardServiceError::InvalidRequest(
1376            "adjustment_unit 'clicks' requires elevation_click_value".into(),
1377        ));
1378    }
1379    let windage_unit = req.windage_unit.unwrap_or(req.adjustment_unit);
1380    if windage_unit == AdjustmentUnit::Clicks && windage_click.is_none() {
1381        return Err(CardServiceError::InvalidRequest(
1382            "windage_unit 'clicks' requires a click graduation".into(),
1383        ));
1384    }
1385
1386    let (bc_for_solve, bc_segments_fps, bc_ladder) = if load_bc_schedule {
1387        resolve_bc_schedule(req, &u)?
1388    } else {
1389        (req.ballistic_coefficient, None, None)
1390    };
1391
1392    Ok(Resolved {
1393        bc_for_solve,
1394        bc_segments_fps,
1395        bc_ladder,
1396        velocity_m: u.velocity_to_metric(req.muzzle_velocity),
1397        mass_kg: u.mass_to_kg(req.mass),
1398        diameter_m: u.diameter_to_metric(req.diameter),
1399        sight_height_m: u.sight_height_to_metric(sight_height),
1400        zero_distance_m: u.distance_to_metric(req.zero_distance),
1401        zero_poi_vertical_m: u.drop_to_metric(req.zero_poi_vertical),
1402        zero_poi_horizontal_m: u.drop_to_metric(req.zero_poi_horizontal),
1403        sight_offset_lateral_m: u.sight_height_to_metric(req.sight_offset_lateral),
1404        temperature_c: u.temperature_to_metric(temperature),
1405        pressure_hpa: u.pressure_to_metric(pressure),
1406        humidity_percent: humidity.percent(),
1407        station_presence,
1408        altitude_m: u.altitude_to_metric(req.altitude),
1409        end_m: u.distance_to_metric(req.end),
1410        elevation_click,
1411        windage_click,
1412        windage_unit,
1413        drag_model: req.drag_model.into(),
1414        u,
1415    })
1416}
1417
1418/// `(scalar BC for the solve, optional fps-keyed schedule, the same schedule as the response
1419/// states it)`. The last two are both present or both absent.
1420type BcSchedule = (f64, Option<Vec<BCSegmentData>>, Option<CardBcLadderV1>);
1421
1422/// Resolve the velocity-keyed BC schedule for a card request, mirroring the CLI's
1423/// precedence exactly: explicit `bc_segments` win outright (and leave the scalar BC
1424/// untouched, like `--bc-segment` restoring the pre-table BC); otherwise a
1425/// `bc5d_table_path` generates the same segment ladder `--bc-table-dir` does and
1426/// applies the table's muzzle correction to the scalar fallback BC.
1427///
1428/// Returns a [`BcSchedule`].
1429fn resolve_bc_schedule(req: &CardRequestV1, u: &Units) -> Result<BcSchedule, CardServiceError> {
1430    if let Some(segments) = req.bc_segments.as_ref().filter(|s| !s.is_empty()) {
1431        if segments.len() > crate::solve_json::MAX_BC_SEGMENTS_V1 {
1432            return Err(CardServiceError::InvalidRequest(format!(
1433                "bc_segments must have at most {} bands, got {}",
1434                crate::solve_json::MAX_BC_SEGMENTS_V1,
1435                segments.len()
1436            )));
1437        }
1438        let (bc_min, bc_max) = crate::solve_json::limits::BALLISTIC_COEFFICIENT;
1439        let mut converted = Vec::with_capacity(segments.len());
1440        for (index, segment) in segments.iter().enumerate() {
1441            if !segment.velocity_min.is_finite()
1442                || !segment.velocity_max.is_finite()
1443                || !segment.bc.is_finite()
1444            {
1445                return Err(CardServiceError::InvalidRequest(format!(
1446                    "bc_segments[{index}]: velocity_min, velocity_max, and bc must be finite"
1447                )));
1448            }
1449            if segment.velocity_min >= segment.velocity_max {
1450                return Err(CardServiceError::InvalidRequest(format!(
1451                    "bc_segments[{index}]: velocity_min must be < velocity_max"
1452                )));
1453            }
1454            if segment.bc <= 0.0 {
1455                return Err(CardServiceError::InvalidRequest(format!(
1456                    "bc_segments[{index}]: bc must be > 0"
1457                )));
1458            }
1459            if !(bc_min..=bc_max).contains(&segment.bc) {
1460                return Err(CardServiceError::InvalidRequest(format!(
1461                    "bc_segments[{index}]: bc must be between {bc_min} and {bc_max}, got {}",
1462                    segment.bc
1463                )));
1464            }
1465            converted.push(BCSegmentData {
1466                // Display velocity -> fps with the exact factor the CLI's parse_bc_segment
1467                // uses; the band edges are in `velocity_unit`, like `muzzle_velocity`.
1468                velocity_min: u.velocity_to_fps_bc5d(segment.velocity_min),
1469                velocity_max: u.velocity_to_fps_bc5d(segment.velocity_max),
1470                bc_value: segment.bc,
1471            });
1472        }
1473        reject_overlapping_bc_segments(segments, u)?;
1474        // Built only once the ladder has passed every check above.
1475        let ladder = CardBcLadderV1 {
1476            source: "bc_segments",
1477            segments: segments.clone(),
1478            interior_gap: crate::bc_estimation::has_interior_gap(&converted),
1479        };
1480        return Ok((req.ballistic_coefficient, Some(converted), Some(ladder)));
1481    }
1482
1483    let Some(path) = req.bc5d_table_path.as_deref() else {
1484        return Ok((req.ballistic_coefficient, None, None));
1485    };
1486
1487    #[cfg(target_arch = "wasm32")]
1488    {
1489        let _ = (path, u);
1490        Err(CardServiceError::InvalidRequest(
1491            "bc5d_table_path is not supported on this target (no filesystem); supply \
1492             bc_segments instead"
1493                .into(),
1494        ))
1495    }
1496    #[cfg(not(target_arch = "wasm32"))]
1497    {
1498        // The table's CONTENT must be for this shot's caliber, not merely CRC-valid: a
1499        // wrong-caliber table silently biases every row of the card (see
1500        // Bc5dTable::ensure_caliber_matches), so a mismatch is refused here rather than
1501        // applied — and rather than quietly falling back to an uncorrected card, which
1502        // the caller could not distinguish from a corrected one.
1503        let diameter_in = u.diameter_to_inches(req.diameter);
1504        let table = crate::bc_table_5d::path_cache::load_verified_for_caliber(
1505            std::path::Path::new(path),
1506            diameter_in,
1507        )
1508        .map_err(|e| CardServiceError::InvalidRequest(format!("bc5d_table_path: {e}")))?;
1509
1510        // The BC5D axes are grains + fps; convert from the request's units the same
1511        // way the CLI does. The v2 tables carry only G1/G7 planes — anything else is
1512        // typed as G1, matching the CLI/WASM coercion.
1513        let weight_grains = u.mass_to_grains_cli(req.mass);
1514        let muzzle_fps = u.velocity_to_fps_bc5d(req.muzzle_velocity);
1515        let drag_type = if req.drag_model == DragModelV1::G7 {
1516            "G7"
1517        } else {
1518            "G1"
1519        };
1520        let base_bc = req.ballistic_coefficient;
1521
1522        match table.generate_segments(base_bc, drag_type, weight_grains, Some(muzzle_fps)) {
1523            Some(segments) => {
1524                // CLI parity: the scalar BC becomes the muzzle-corrected fallback for
1525                // interior coverage gaps (main.rs: trued_bc = base * muzzle_correction).
1526                let fallback_bc = table.get_effective_bc(
1527                    weight_grains,
1528                    base_bc,
1529                    muzzle_fps,
1530                    muzzle_fps,
1531                    drag_type,
1532                );
1533                // The generated ladder, stated in the request's own velocity unit.
1534                let ladder = CardBcLadderV1 {
1535                    source: "bc5d_table",
1536                    segments: segments
1537                        .iter()
1538                        .map(|s| CardBcSegmentV1 {
1539                            velocity_min: u.velocity_from_fps_bc5d(s.velocity_min),
1540                            velocity_max: u.velocity_from_fps_bc5d(s.velocity_max),
1541                            bc: s.bc_value,
1542                        })
1543                        .collect(),
1544                    interior_gap: crate::bc_estimation::has_interior_gap(&segments),
1545                };
1546                Ok((fallback_bc, Some(segments), Some(ladder)))
1547            }
1548            // A neutral table (every sampled cell ~= 1.0) carries no correction:
1549            // keep the published scalar BC, exactly like the CLI.
1550            None => Ok((base_bc, None, None)),
1551        }
1552    }
1553}
1554
1555/// Refuse a card ladder whose bands overlap (MBA-1600). Card accepts bands in any order, so they
1556/// are compared in `velocity_min` order; touching edges and gaps are legal. The engine's lookup
1557/// flies the FIRST listed band containing a speed and blends nothing across an overlap
1558/// (`bc_estimation.rs`), so an overlapping ladder would fly differently by listing order.
1559/// Compared in the request's `velocity_unit`: the fps conversion is monotonic, so a ladder that
1560/// does not overlap here cannot overlap after it. Messages quote the caller's own indices.
1561fn reject_overlapping_bc_segments(
1562    segments: &[CardBcSegmentV1],
1563    u: &Units,
1564) -> Result<(), CardServiceError> {
1565    let mut order: Vec<usize> = (0..segments.len()).collect();
1566    // Stable sort: equal velocity_min keep request order, so the later-listed band is reported.
1567    order.sort_by(|&a, &b| {
1568        segments[a]
1569            .velocity_min
1570            .total_cmp(&segments[b].velocity_min)
1571    });
1572    for pair in order.windows(2) {
1573        let (lower, upper) = (pair[0], pair[1]);
1574        let (lo, hi) = (&segments[lower], &segments[upper]);
1575        if hi.velocity_min < lo.velocity_max {
1576            let unit = u.velocity_label();
1577            return Err(CardServiceError::InvalidRequest(format!(
1578                "bc_segments[{upper}] ({} to {} {unit}) overlaps bc_segments[{lower}] ({} to {} \
1579                 {unit}): bands may touch or leave gaps but must not overlap",
1580                hi.velocity_min, hi.velocity_max, lo.velocity_min, lo.velocity_max
1581            )));
1582        }
1583    }
1584    Ok(())
1585}
1586
1587fn solve_zero(r: &Resolved) -> Result<f64, CardServiceError> {
1588    let zero_inputs = BallisticInputs {
1589        bc_value: r.bc_for_solve,
1590        bc_type: r.drag_model,
1591        bullet_mass: r.mass_kg,
1592        muzzle_velocity: r.velocity_m,
1593        bullet_diameter: r.diameter_m,
1594        bullet_length: crate::truing::fallback_bullet_length_m(r.diameter_m, r.mass_kg),
1595        sight_height: r.sight_height_m,
1596        use_rk4: true,
1597        zero_poi_vertical_m: r.zero_poi_vertical_m,
1598        zero_poi_horizontal_m: r.zero_poi_horizontal_m,
1599        sight_offset_lateral_m: r.sight_offset_lateral_m,
1600        // The zero MUST be solved with the same velocity-keyed BC schedule the
1601        // sampled flights use (the 0.22.11 auto-zero lesson: a schedule that changes
1602        // early-flight drag would otherwise mis-zero every row).
1603        use_bc_segments: r.bc_segments_fps.is_some(),
1604        bc_segments_data: r.bc_segments_fps.clone(),
1605        ..Default::default()
1606    };
1607    let atmosphere = AtmosphericConditions {
1608        temperature: r.temperature_c,
1609        pressure: r.pressure_hpa,
1610        humidity: r.humidity_percent,
1611        altitude: r.altitude_m,
1612    };
1613    crate::calculate_zero_angle_with_station_presence(
1614        zero_inputs,
1615        r.zero_distance_m,
1616        r.sight_height_m,
1617        WindConditions::default(),
1618        atmosphere,
1619        r.station_presence,
1620    )
1621    .map_err(|e| match e.atmosphere_error() {
1622        Some(air) => CardServiceError::Atmosphere(air.clone()),
1623        None => CardServiceError::ZeroSolve(e.to_string()),
1624    })
1625}
1626
1627#[allow(clippy::too_many_arguments)]
1628fn sampled(
1629    r: &Resolved,
1630    wind_speed_m: f64,
1631    wind_direction_deg: f64,
1632    zero_angle: f64,
1633) -> Result<SampledFlight, CardServiceError> {
1634    run_sampled_flight_with_station_presence(
1635        r.velocity_m,
1636        r.bc_for_solve,
1637        r.mass_kg,
1638        r.diameter_m,
1639        r.drag_model,
1640        r.sight_height_m,
1641        r.temperature_c,
1642        r.pressure_hpa,
1643        r.humidity_percent,
1644        r.altitude_m,
1645        wind_speed_m,
1646        wind_direction_deg,
1647        // MBA-1476: at least one whole grid cell past the last row asked for — see
1648        // card_sample_max_range_m for why that headroom decides reachability.
1649        card_sample_max_range_m(r.end_m),
1650        // MBA-1476: the engine's own card grid, never the request's row spacing.
1651        CARD_SAMPLE_INTERVAL_M,
1652        zero_angle,
1653        // The same schedule as the zero solve above, on every card surface
1654        // (come-ups, range table, wind card) consistently.
1655        r.bc_segments_fps.clone(),
1656        None,
1657        None,
1658        r.zero_poi_vertical_m,
1659        r.zero_poi_horizontal_m,
1660        r.sight_offset_lateral_m,
1661        Some(r.zero_distance_m),
1662        r.station_presence,
1663    )
1664    .map_err(
1665        |e| match crate::atmosphere::AtmosphereError::in_error(&*e) {
1666            Some(air) => CardServiceError::Atmosphere(air.clone()),
1667            None => CardServiceError::Trajectory(e.to_string()),
1668        },
1669    )
1670}
1671
1672/// Read one card row's sample off a solved flight, or `None` when the flight does not span it
1673/// (MBA-1476).
1674///
1675/// The nearest-sample-within-one-and-a-half-steps search this replaces answered a range the
1676/// flight had no sample for with a neighbour's numbers, invisibly. There is no tolerance to
1677/// tune here: [`sample_at_range`] interpolates exactly at the requested range whenever the
1678/// flight spans it, and a range it cannot span yields nothing at all. The caller ends the card
1679/// there and records a [`CardTruncation`] — it never substitutes, and it never drops the row
1680/// without saying so.
1681fn row_sample(
1682    samples: &[crate::trajectory_sampling::TrajectorySample],
1683    range_m: f64,
1684) -> Option<crate::trajectory_sampling::TrajectorySample> {
1685    sample_at_range(samples, range_m)
1686}
1687
1688/// The error a card returns when its flight reaches NONE of the rows requested — there is no
1689/// card to truncate, so this stays a refusal (MBA-1476 follow-up).
1690fn no_rows_error(first_row_display: f64, reach_m: f64, u: &Units) -> CardServiceError {
1691    CardServiceError::Trajectory(range_not_sampled_message(
1692        first_row_display,
1693        u.distance_from_metric(reach_m),
1694        u.distance_label(),
1695    ))
1696}
1697
1698/// Record the truncation of a card whose row loop stopped early, in display units.
1699fn truncation_of(
1700    requested_end: f64,
1701    last_row: f64,
1702    reach_m: f64,
1703    u: &Units,
1704) -> Option<CardTruncationV1> {
1705    Some(CardTruncationV1::new(CardTruncation {
1706        requested_end,
1707        last_row,
1708        reach: u.distance_from_metric(reach_m),
1709    }))
1710}
1711
1712/// The response's per-dimension label block: one label per dimension, read off the same
1713/// resolved [`Units`] the rows were converted with, so a column cannot be computed in one
1714/// unit and headed with another.
1715fn units_block(req: &CardRequestV1, u: &Units, windage_unit: AdjustmentUnit) -> CardUnitsBlockV1 {
1716    CardUnitsBlockV1 {
1717        distance: u.distance_label(),
1718        velocity: u.velocity_label(),
1719        energy: u.energy_label(),
1720        drop: u.drop_label(),
1721        wind_speed: u.wind_speed_label(),
1722        elevation_adjustment: adjustment_unit_label(req.adjustment_unit),
1723        windage_adjustment: adjustment_unit_label(windage_unit),
1724    }
1725}
1726
1727/// Come-ups: elevation dial per range plus the incremental come-up between rows.
1728/// Mirrors the CLI's `come-ups` command row-for-row.
1729pub fn come_ups_v1(req: &CardRequestV1) -> Result<CardResponseV1, CardServiceError> {
1730    let r = resolve(req)?;
1731    let zero_angle = solve_zero(&r)?;
1732    let flight = sampled(
1733        &r,
1734        r.u.wind_to_metric(req.wind_speed),
1735        req.wind_direction_deg,
1736        zero_angle,
1737    )?;
1738
1739    let mut rows: Vec<CardRowV1> = Vec::new();
1740    let mut truncation = None;
1741    let mut prev_drop_adj: f64 = 0.0;
1742    let mut current_range = req.start;
1743    while current_range <= req.end + 0.1 {
1744        let range_m = r.u.distance_to_metric(current_range);
1745        let Some(sample) = row_sample(&flight.samples, range_m) else {
1746            let Some(last) = rows.last() else {
1747                return Err(no_rows_error(current_range, flight.reach_m, &r.u));
1748            };
1749            truncation = truncation_of(req.end, last.range, flight.reach_m, &r.u);
1750            break;
1751        };
1752        let drop_yd = r.u.distance_from_metric(sample.drop_m);
1753        // MBA-1476: the row's OWN range, not a nearby sample's — the angular conversion
1754        // divides by the distance the row is labelled with.
1755        let drop_adj = adjustment_display(
1756            drop_yd,
1757            current_range,
1758            req.adjustment_unit,
1759            r.elevation_click,
1760            req.zero_set_elevation_bias_mil,
1761            req.elevation_cf,
1762        )
1763        .value;
1764        rows.push(CardRowV1 {
1765            range: current_range,
1766            drop_linear: None,
1767            drop_adj: Some(drop_adj),
1768            come_up: Some(drop_adj - prev_drop_adj),
1769            wind_linear: None,
1770            wind_adj: None,
1771            velocity: Some(r.u.velocity_from_metric(sample.velocity_mps)),
1772            energy: Some(r.u.energy_from_metric(sample.energy_j)),
1773            time: Some(sample.time_s),
1774            wind_columns: Vec::new(),
1775        });
1776        prev_drop_adj = drop_adj;
1777        current_range += req.step;
1778    }
1779
1780    Ok(CardResponseV1 {
1781        schema_version: CARD_SCHEMA_VERSION_V1,
1782        kind: "come_ups",
1783        zero_distance: req.zero_distance,
1784        bc_for_solve: r.bc_for_solve,
1785        bc_ladder: r.bc_ladder.clone(),
1786        units: units_block(req, &r.u, req.adjustment_unit),
1787        wind_speeds: Vec::new(),
1788        wind_angles_deg: Vec::new(),
1789        rows,
1790        extra_angle_rows: Vec::new(),
1791        truncation,
1792    })
1793}
1794
1795/// Range table: drop and wind on possibly different display axes.
1796/// Mirrors the CLI's `range-table` command row-for-row (two solves: with wind for
1797/// drift, without wind for the pure elevation axis).
1798pub fn range_table_v1(req: &CardRequestV1) -> Result<CardResponseV1, CardServiceError> {
1799    // Discards the PDF-only extras; see `range_table_rows`.
1800    range_table_rows(req, None).map(|(card, _lead, _bc)| card)
1801}
1802
1803/// The one range-table computation, shared by the on-screen `card.range_table` and the
1804/// printable `card.pdf`.
1805///
1806/// Returns `(the card, the Lead column, the scalar BC the solve ran with)`:
1807///
1808/// * The card is exactly what `card.range_table` serializes — `range_table_v1` is a
1809///   discarding wrapper, so the PDF's Range/Drop/Wind figures ARE the on-screen figures.
1810///   They are taken from here rather than recomputed because recomputing them is the one
1811///   way the printed card could ever disagree with the rows the shooter already read.
1812/// * The Lead column parallels `card.rows` one-to-one. `lead_target_speed` is in the
1813///   request's `wind_speed_unit`; `None` (no lead requested) yields all `None`, which the
1814///   PDF renders as em-dashes rather than fake zeroes.
1815/// * The BC is `Resolved::bc_for_solve` — the published BC unless a BC5D table applied its
1816///   muzzle correction — which the PDF footer prints when the card flew no ladder. The
1817///   footer must state the BC the numbers above it came from, not the one the request
1818///   nominated; under a ladder that is the card's `bc_ladder` range (MBA-1601), and this
1819///   scalar is only its interior-gap fallback.
1820fn range_table_rows(
1821    req: &CardRequestV1,
1822    lead_target_speed: Option<f64>,
1823) -> Result<(CardResponseV1, Vec<Option<f64>>, f64), CardServiceError> {
1824    let r = resolve(req)?;
1825    let zero_angle = solve_zero(&r)?;
1826    let wind_flight = sampled(
1827        &r,
1828        r.u.wind_to_metric(req.wind_speed),
1829        req.wind_direction_deg,
1830        zero_angle,
1831    )?;
1832    let no_wind_flight = sampled(&r, 0.0, 0.0, zero_angle)?;
1833    // Both flights feed every row, so the card can only run as far as the shorter of them.
1834    let reach_m = wind_flight.reach_m.min(no_wind_flight.reach_m);
1835    let lead_speed_mps = lead_target_speed.map(|speed| r.u.wind_to_metric(speed));
1836
1837    let mut rows: Vec<CardRowV1> = Vec::new();
1838    let mut lead_adj = Vec::new();
1839    let mut truncation = None;
1840    let mut current_range = req.start;
1841    while current_range <= req.end + 0.1 {
1842        let range_m = r.u.distance_to_metric(current_range);
1843        let (Some(nw), Some(w)) = (
1844            row_sample(&no_wind_flight.samples, range_m),
1845            row_sample(&wind_flight.samples, range_m),
1846        ) else {
1847            let Some(last) = rows.last() else {
1848                return Err(no_rows_error(current_range, reach_m, &r.u));
1849            };
1850            truncation = truncation_of(req.end, last.range, reach_m, &r.u);
1851            break;
1852        };
1853        // MBA-1476: the row's OWN range on both axes.
1854        let range_display = current_range;
1855        let drop_yd = r.u.distance_from_metric(nw.drop_m);
1856        let drop_adj = adjustment_display(
1857            drop_yd,
1858            range_display,
1859            req.adjustment_unit,
1860            r.elevation_click,
1861            req.zero_set_elevation_bias_mil,
1862            req.elevation_cf,
1863        )
1864        .value;
1865        let drift_yd = r.u.distance_from_metric(w.wind_drift_m);
1866        let wind_adj = windage_adjustment_display(
1867            drift_yd,
1868            range_display,
1869            r.windage_unit,
1870            r.windage_click,
1871            req.zero_set_windage_bias_mil,
1872            req.windage_cf,
1873        )
1874        .value;
1875        // Lead is the windage-axis hold for a full-value 90° crossing target:
1876        // `speed * time-of-flight` (MBA-1287's shared moving-target math), on the
1877        // no-wind sample whose time this row already reports. It is a COMPONENT
1878        // hold composed on top of the wind dial, which already carries the
1879        // zero-set bias, so it stays bias-free (bias 0.0) while still being
1880        // divided by the windage tracking CF — the same treatment
1881        // `main.rs::dope_card_row_from_sample` gives the CLI's Lead column.
1882        lead_adj.push(lead_speed_mps.map(|speed_mps| {
1883            let lead_display = r.u.distance_from_metric(
1884                crate::lead_from_tof(speed_mps, 90.0, nw.time_s, nw.distance_m).lead_m,
1885            );
1886            windage_adjustment_display(
1887                lead_display,
1888                range_display,
1889                r.windage_unit,
1890                r.windage_click,
1891                0.0,
1892                req.windage_cf,
1893            )
1894            .value
1895        }));
1896        rows.push(CardRowV1 {
1897            range: current_range,
1898            drop_linear: Some(r.u.drop_linear_from_metric(nw.drop_m)),
1899            drop_adj: Some(drop_adj),
1900            come_up: None,
1901            wind_linear: Some(r.u.drop_linear_from_metric(w.wind_drift_m)),
1902            wind_adj: Some(wind_adj),
1903            velocity: Some(r.u.velocity_from_metric(nw.velocity_mps)),
1904            energy: Some(r.u.energy_from_metric(nw.energy_j)),
1905            time: Some(nw.time_s),
1906            wind_columns: Vec::new(),
1907        });
1908        current_range += req.step;
1909    }
1910
1911    debug_assert_eq!(rows.len(), lead_adj.len(), "Lead column must parallel rows");
1912    Ok((
1913        CardResponseV1 {
1914            schema_version: CARD_SCHEMA_VERSION_V1,
1915            kind: "range_table",
1916            zero_distance: req.zero_distance,
1917            bc_for_solve: r.bc_for_solve,
1918            bc_ladder: r.bc_ladder.clone(),
1919            units: units_block(req, &r.u, r.windage_unit),
1920            wind_speeds: Vec::new(),
1921            wind_angles_deg: Vec::new(),
1922            rows,
1923            extra_angle_rows: Vec::new(),
1924            truncation,
1925        },
1926        lead_adj,
1927        r.bc_for_solve,
1928    ))
1929}
1930
1931/// Wind card: drift matrix, ranges x wind speeds, per wind-FROM angle.
1932/// Mirrors the CLI's `wind-card` command cell-for-cell. The windage axis uses
1933/// `adjustment_unit` (the CLI's wind-card has a single unit for the matrix).
1934pub fn wind_card_v1(req: &CardRequestV1) -> Result<CardResponseV1, CardServiceError> {
1935    if req.wind_speeds.is_empty() {
1936        return Err(CardServiceError::InvalidRequest(
1937            "wind_card requires at least one entry in wind_speeds".into(),
1938        ));
1939    }
1940    let r = resolve(req)?;
1941    let zero_angle = solve_zero(&r)?;
1942
1943    let angles: Vec<f64> = if req.wind_angles_deg.is_empty() {
1944        vec![90.0]
1945    } else {
1946        req.wind_angles_deg.clone()
1947    };
1948
1949    let mut ranges: Vec<f64> = Vec::new();
1950    let mut current = req.start;
1951    while current <= req.end + 0.1 {
1952        ranges.push(current);
1953        current += req.step;
1954    }
1955
1956    // Every angle/speed combination is its own flight and they do not all reach equally far
1957    // (a crosswind bleeds a little velocity), but the matrix has ONE range axis. So the card
1958    // runs to the shortest of them: `reachable` is the number of leading ranges every flight
1959    // supplies, and the ragged tails are trimmed once, below.
1960    let mut reachable = ranges.len();
1961    let mut reach_m = f64::INFINITY;
1962    let mut per_angle_drifts: Vec<Vec<Vec<f64>>> = Vec::new();
1963    for &angle_deg in &angles {
1964        let mut all_drifts: Vec<Vec<f64>> = vec![Vec::new(); ranges.len()];
1965        for &ws in &req.wind_speeds {
1966            let flight = sampled(&r, r.u.wind_to_metric(ws), angle_deg, zero_angle)?;
1967            reach_m = reach_m.min(flight.reach_m);
1968            for (ri, &range_display) in ranges.iter().enumerate().take(reachable) {
1969                let range_m = r.u.distance_to_metric(range_display);
1970                // MBA-1476: a range the flight cannot supply used to become a 0.0 cell —
1971                // indistinguishable from "no drift at all" on a wind card.
1972                let Some(sample) = row_sample(&flight.samples, range_m) else {
1973                    reachable = ri;
1974                    break;
1975                };
1976                let drift_yd = r.u.distance_from_metric(sample.wind_drift_m);
1977                let drift_adj = adjustment_display(
1978                    drift_yd,
1979                    range_display,
1980                    req.adjustment_unit,
1981                    r.windage_click,
1982                    req.zero_set_windage_bias_mil,
1983                    req.windage_cf,
1984                )
1985                .value;
1986                all_drifts[ri].push(drift_adj);
1987            }
1988        }
1989        per_angle_drifts.push(all_drifts);
1990    }
1991
1992    let truncation = if reachable < ranges.len() {
1993        if reachable == 0 {
1994            return Err(no_rows_error(ranges[0], reach_m, &r.u));
1995        }
1996        let last = ranges[reachable - 1];
1997        ranges.truncate(reachable);
1998        truncation_of(req.end, last, reach_m, &r.u)
1999    } else {
2000        None
2001    };
2002
2003    let mut per_angle_rows: Vec<Vec<CardRowV1>> = per_angle_drifts
2004        .into_iter()
2005        .map(|all_drifts| {
2006            ranges
2007                .iter()
2008                .zip(all_drifts)
2009                .map(|(&range, wind_columns)| CardRowV1 {
2010                    range,
2011                    drop_linear: None,
2012                    drop_adj: None,
2013                    come_up: None,
2014                    wind_linear: None,
2015                    wind_adj: None,
2016                    velocity: None,
2017                    energy: None,
2018                    time: None,
2019                    wind_columns,
2020                })
2021                .collect()
2022        })
2023        .collect();
2024
2025    let first = per_angle_rows.remove(0);
2026    Ok(CardResponseV1 {
2027        schema_version: CARD_SCHEMA_VERSION_V1,
2028        kind: "wind_card",
2029        zero_distance: req.zero_distance,
2030        bc_for_solve: r.bc_for_solve,
2031        bc_ladder: r.bc_ladder.clone(),
2032        units: units_block(req, &r.u, req.adjustment_unit),
2033        wind_speeds: req.wind_speeds.clone(),
2034        wind_angles_deg: angles,
2035        rows: first,
2036        extra_angle_rows: per_angle_rows,
2037        truncation,
2038    })
2039}
2040
2041// ---------------------------------------------------------------------------------------
2042// Printable PDF dope card (`card.pdf`), feature `pdf`.
2043//
2044// Two ways in, one renderer:
2045//
2046// * REPRINT — the caller supplies the rows: `StoredCardV1` carries the stored
2047//   `card.range_table` response verbatim. Nothing is solved, no correction table is opened,
2048//   and the footer's BC and provenance come from that document. Only under this construction
2049//   is a reprint of a saved card actually a reprint: it cannot drift when the engine is
2050//   bumped, or when the BC5D table file at the stored path is overwritten in place by a
2051//   table-set refresh.
2052// * SOLVE — no rows supplied: `range_table_rows` runs, which is the same call
2053//   `card.range_table` makes (`range_table_v1` is a discarding wrapper over it). This is the
2054//   pre-existing behaviour, unchanged, and what the CLI-shaped caller gets.
2055//
2056// Neither path recomputes an adjustment, a unit conversion or a trajectory that the card it
2057// prints already performed.
2058// ---------------------------------------------------------------------------------------
2059
2060/// The one card kind `card.pdf` can print, in the `kind` spelling
2061/// [`CardResponseV1::kind`] uses.
2062///
2063/// A come-ups card's Come-Up column and a wind card's swept drift matrix are not columns a
2064/// range-table card has, so a request for either is REFUSED rather than answered with a
2065/// range table — an `ok` response whose defining field was silently ignored is the defect
2066/// (a stored wind card exported as a range table asserted 0.0 drift on every row while the
2067/// screen showed up to -0.42 MIL).
2068#[cfg(feature = "pdf")]
2069pub const PDF_CARD_KIND: &str = "range_table";
2070
2071/// Rows a printable card may carry.
2072///
2073/// Checked from the row count itself, before a document exists — the byte cap
2074/// (`bridge::MAX_PDF_BYTES`) can only refuse a 26 MB `Vec<u8>` that has already been built
2075/// and paginated. At ~0.5 KiB/row over the ~815 KiB font floor this bound keeps every
2076/// accepted card comfortably inside that cap, which remains the backstop for the other way
2077/// to make a huge document: header/footer labels, which are drawn verbatim on every page.
2078#[cfg(feature = "pdf")]
2079pub const MAX_PDF_ROWS: usize = 5_000;
2080
2081/// Pages a printable card may run to. Bounds the one row set the row cap above cannot:
2082/// few enough rows, but at a font scale that fits very few of them per page.
2083#[cfg(feature = "pdf")]
2084pub const MAX_PDF_PAGES: usize = 60;
2085
2086/// Where the printed rows came from — reported so a caller can verify it got a reprint
2087/// rather than a re-solve, which is otherwise indistinguishable from the document.
2088#[cfg(feature = "pdf")]
2089#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2090pub enum PdfRowSource {
2091    /// Solved by this call, exactly as `card.range_table` would for the same request.
2092    Solve,
2093    /// Supplied by the caller: a stored `card.range_table` response, printed as-is.
2094    StoredRows,
2095}
2096
2097#[cfg(feature = "pdf")]
2098impl PdfRowSource {
2099    /// Wire spelling for the bridge's `source` field.
2100    pub fn as_str(self) -> &'static str {
2101        match self {
2102            Self::Solve => "solve",
2103            Self::StoredRows => "stored_rows",
2104        }
2105    }
2106}
2107
2108/// A card whose rows already exist: print THESE numbers instead of solving.
2109///
2110/// `card` is the stored `card.range_table` response, pasted verbatim — an app keeps that
2111/// document for every saved card and shows it on screen, so handing the same bytes back is
2112/// what makes the paper and the screen the same card by construction rather than by
2113/// coincidence. The two provenance strings are printed in the footer so a card in a
2114/// shooter's pocket can be reconciled with a screen afterwards; both are optional, and an
2115/// absent or empty one prints nothing at all rather than a placeholder.
2116#[cfg(feature = "pdf")]
2117#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
2118#[serde(deny_unknown_fields)]
2119pub struct StoredCardV1 {
2120    /// The stored response, exactly as this engine emitted it.
2121    pub card: StoredCardResponseV1,
2122    /// Engine version that produced the rows (`engine_version` from the bridge envelope of
2123    /// the call that produced them). Absent/empty prints no engine line.
2124    ///
2125    /// Since 0.49.0 the reprint header's air depends on this version; send the
2126    /// `engine_version` of the call that produced the rows. Rows from 0.49.0 or later flew a
2127    /// typed temperature or pressure as typed, so the header states it that way. Rows from an
2128    /// older engine, or from an absent, empty or unreadable version, flew the pre-0.49.0 rule
2129    /// (a typed 15 °C / 59 °F or 1013.25 hPa / 29.92 inHg at a real altitude was replaced by
2130    /// ICAO standard air), and the header states that air instead, so it never describes air
2131    /// the printed rows did not fly.
2132    #[serde(default)]
2133    pub engine_version: Option<String>,
2134    /// Correction-table version the rows were solved against — the published BC5D table-set
2135    /// version an app records at save time. Absent/empty prints no table line, which is the
2136    /// honest rendering of "this card used no correction table".
2137    #[serde(default)]
2138    pub bc5d_table_version: Option<String>,
2139}
2140
2141/// Whether stored card rows were solved by an engine that flies a typed station reading as
2142/// typed (0.49.0 or later), judged from [`StoredCardV1::engine_version`].
2143///
2144/// The version is read as `MAJOR.MINOR.PATCH`, ignoring a leading `v` and any `-pre` or
2145/// `+build` suffix. An absent, empty or unparseable version is `false`: such rows are treated
2146/// as pre-0.49.0 rows, which is what they are when an app recorded no version.
2147#[cfg(feature = "pdf")]
2148fn stored_rows_are_presence_aware(engine_version: &Option<String>) -> bool {
2149    let Some(version) = engine_version.as_deref() else {
2150        return false;
2151    };
2152    let version = version.trim();
2153    let version = version.strip_prefix('v').unwrap_or(version);
2154    let core = version.split(['-', '+']).next().unwrap_or("");
2155    let parts: Vec<&str> = core.split('.').collect();
2156    let [major, minor, patch] = parts.as_slice() else {
2157        return false;
2158    };
2159    let (Ok(major), Ok(minor), Ok(_patch)) = (
2160        major.parse::<u64>(),
2161        minor.parse::<u64>(),
2162        patch.parse::<u64>(),
2163    ) else {
2164        return false;
2165    };
2166    (major, minor) >= (0, 49)
2167}
2168
2169/// A stored [`CardResponseV1`], as a deserializable mirror.
2170///
2171/// [`CardResponseV1`] is `Serialize` only (and its `units` block holds `&'static str`s), so
2172/// a stored response is read back through this twin. It accepts the response document
2173/// unchanged, field for field: `kind` and `units` are load-bearing here — they say what the
2174/// rows ARE and what a row MEANS — while the descriptive scalars are optional so a card
2175/// stored by an older engine still prints.
2176///
2177/// **Deliberately NOT `deny_unknown_fields`** (unlike [`CardRequestV1`], where the caller
2178/// really is the author of the document). What arrives here is this engine's own output,
2179/// round-tripped through an app's storage — never hand-written input — so strictness buys
2180/// no validation and costs a hard cross-version break: the FIRST field ever added to
2181/// `CardResponseV1` would make every card saved by the newer platform completely
2182/// unexportable on the older one. The two apps carry independent engine pins and ship
2183/// through separate stores, so that staggering is the normal case, not a downgrade. An
2184/// unknown field is therefore ignored, exactly as the apps' own decoders ignore it, and the
2185/// stored cells still reach the paper. The same reasoning applies to
2186/// [`StoredCardUnitsBlockV1`] and [`StoredCardRowV1`] below.
2187#[cfg(feature = "pdf")]
2188#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
2189pub struct StoredCardResponseV1 {
2190    /// Which card this is. Anything but [`PDF_CARD_KIND`] is refused.
2191    pub kind: String,
2192    /// Column labels and the range unit of the stored rows. The printed headings are
2193    /// these, not the request's, because these are what the rows were computed in.
2194    pub units: StoredCardUnitsBlockV1,
2195    /// The rows to print, in order.
2196    pub rows: Vec<StoredCardRowV1>,
2197    #[serde(default)]
2198    pub schema_version: Option<u32>,
2199    #[serde(default)]
2200    pub zero_distance: Option<f64>,
2201    /// The scalar BC the stored rows were computed with; printed in the footer when the card
2202    /// carries no `bc_ladder`. Absent (a card saved by an engine before
2203    /// [`CardResponseV1::bc_for_solve`] existed) falls back to the request's published
2204    /// `ballistic_coefficient`. Under a ladder it is only the interior-gap fallback, and the
2205    /// footer prints the ladder's range instead (MBA-1601).
2206    #[serde(default)]
2207    pub bc_for_solve: Option<f64>,
2208    /// The [`CardResponseV1::bc_ladder`] block, round-tripped (MBA-1601): present when the
2209    /// stored rows flew a BC ladder, and then the footer's `BC:` states the ladder's range.
2210    ///
2211    /// A card saved before the block existed has none, and reprints its stored scalar exactly
2212    /// as before: the reprint never re-derives a ladder from the request, so a solve and a
2213    /// reprint of the same document cannot be labelled differently. Regenerating such a card
2214    /// prints the range.
2215    #[serde(default)]
2216    pub bc_ladder: Option<StoredCardBcLadderV1>,
2217    /// Present only on a wind card, and therefore a refusal here.
2218    #[serde(default)]
2219    pub wind_speeds: Vec<f64>,
2220    #[serde(default)]
2221    pub wind_angles_deg: Vec<f64>,
2222    #[serde(default)]
2223    pub extra_angle_rows: Vec<Vec<StoredCardRowV1>>,
2224    /// Present only when the stored card itself stopped short of the rows its request asked
2225    /// for — the [`CardResponseV1::truncation`] block, round-tripped (MBA-1477).
2226    ///
2227    /// Without this the reprint path loses the notice: `StoredCardResponseV1` ignores unknown
2228    /// fields by design, so a saved card whose rows stopped short came back through here as an
2229    /// unremarkable short card and printed with nothing on the paper saying rows were missing.
2230    /// The screen it was saved from said so; the paper made from that very document did not.
2231    ///
2232    /// A card saved before this field existed simply has no block, which is indistinguishable
2233    /// from an untruncated card and is the best that can be said of it.
2234    #[serde(default)]
2235    pub truncation: Option<StoredCardTruncationV1>,
2236}
2237
2238/// The truncation block of a stored response (see [`CardTruncationV1`], which this mirrors).
2239///
2240/// All three numbers are REQUIRED, unlike the descriptive scalars elsewhere in a stored card:
2241/// they are printed together as one sentence, and a block missing one of them would print
2242/// "TRUNCATED at 0 yd" on a field card. A card that was not truncated omits the whole block,
2243/// which is the only shape that means "nothing to say".
2244#[cfg(feature = "pdf")]
2245#[derive(Debug, Clone, Copy, PartialEq, Deserialize)]
2246pub struct StoredCardTruncationV1 {
2247    pub requested_end: f64,
2248    pub last_row: f64,
2249    pub reach: f64,
2250}
2251
2252/// The `bc_ladder` block of a stored response (see [`CardBcLadderV1`], which this mirrors).
2253/// Unknown fields are ignored, for the reason [`StoredCardResponseV1`] gives.
2254///
2255/// `segments` and `interior_gap` are REQUIRED, like the numbers of a stored truncation block:
2256/// the footer is printed from them together, and a block missing either cannot say which BCs
2257/// flew. A card that flew no ladder omits the whole block.
2258#[cfg(feature = "pdf")]
2259#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
2260pub struct StoredCardBcLadderV1 {
2261    pub segments: Vec<StoredCardBcSegmentV1>,
2262    pub interior_gap: bool,
2263    /// `"bc_segments"` or `"bc5d_table"`; informational, not printed.
2264    #[serde(default)]
2265    pub source: Option<String>,
2266}
2267
2268/// One band of a stored `bc_ladder` (see [`CardBcSegmentV1`], which this mirrors). Unknown
2269/// fields are ignored, for the reason [`StoredCardResponseV1`] gives.
2270#[cfg(feature = "pdf")]
2271#[derive(Debug, Clone, Copy, Default, PartialEq, Deserialize)]
2272pub struct StoredCardBcSegmentV1 {
2273    pub velocity_min: f64,
2274    pub velocity_max: f64,
2275    pub bc: f64,
2276}
2277
2278#[cfg(feature = "pdf")]
2279impl From<StoredCardTruncationV1> for CardTruncationV1 {
2280    fn from(stored: StoredCardTruncationV1) -> Self {
2281        Self {
2282            requested_end: stored.requested_end,
2283            last_row: stored.last_row,
2284            reach: stored.reach,
2285        }
2286    }
2287}
2288
2289/// The `units` block of a stored response (see [`CardUnitsBlockV1`], which this mirrors).
2290/// Unknown fields are ignored, for the reason [`StoredCardResponseV1`] gives.
2291#[cfg(feature = "pdf")]
2292#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
2293pub struct StoredCardUnitsBlockV1 {
2294    /// `"yd"` / `"m"` — the unit the stored `range` values are in.
2295    pub distance: String,
2296    /// Drop column label ("MIL"/"MOA"/"SMOA"/"IPHY"/"CLICKS").
2297    pub elevation_adjustment: String,
2298    /// Wind and Lead column label; may differ from the elevation label (MBA-1410).
2299    pub windage_adjustment: String,
2300    #[serde(default)]
2301    pub velocity: Option<String>,
2302    #[serde(default)]
2303    pub energy: Option<String>,
2304    #[serde(default)]
2305    pub drop: Option<String>,
2306    #[serde(default)]
2307    pub wind_speed: Option<String>,
2308}
2309
2310/// One stored row (see [`CardRowV1`], which this mirrors). Only `range` is required; a
2311/// column the stored card did not carry stays `None` and prints as an em-dash rather than a
2312/// fabricated zero. Unknown fields are ignored, for the reason [`StoredCardResponseV1`]
2313/// gives.
2314#[cfg(feature = "pdf")]
2315#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
2316pub struct StoredCardRowV1 {
2317    pub range: f64,
2318    #[serde(default)]
2319    pub drop_linear: Option<f64>,
2320    #[serde(default)]
2321    pub drop_adj: Option<f64>,
2322    #[serde(default)]
2323    pub come_up: Option<f64>,
2324    #[serde(default)]
2325    pub wind_linear: Option<f64>,
2326    #[serde(default)]
2327    pub wind_adj: Option<f64>,
2328    #[serde(default)]
2329    pub velocity: Option<f64>,
2330    #[serde(default)]
2331    pub energy: Option<f64>,
2332    /// Time of flight, seconds. The Lead column of a reprint is derived from this — pure
2333    /// arithmetic on a number the stored card already carries, not a new trajectory. A row
2334    /// without it prints an em-dash for Lead.
2335    #[serde(default)]
2336    pub time: Option<f64>,
2337    #[serde(default)]
2338    pub wind_columns: Vec<f64>,
2339}
2340
2341/// A rendered PDF dope card: the document plus the facts a transport needs to describe it
2342/// without re-parsing the bytes.
2343#[cfg(feature = "pdf")]
2344#[derive(Debug, Clone)]
2345pub struct PdfCardV1 {
2346    pub pdf_bytes: Vec<u8>,
2347    /// Pages in `pdf_bytes`, from [`crate::pdf_dope_card::dope_card_page_count`] — the
2348    /// same function the generator paginated by, not a second estimate of it.
2349    pub page_count: usize,
2350    /// Rows printed. On the solve path this is the on-screen `card.range_table` row count;
2351    /// on the reprint path it is the stored row count, so a caller can confirm every stored
2352    /// row reached the paper.
2353    pub row_count: usize,
2354    /// Solved here, or printed from caller-supplied rows.
2355    pub source: PdfRowSource,
2356    /// Characters of the header title (`pdf.title`) the card's font could not draw —
2357    /// distinct, in order of first use, and empty when the title printed in full.
2358    ///
2359    /// Not an error: the document is complete and every ROW printed. But a title is how a
2360    /// shooter tells one card from another, and Liberation Sans covers no CJK, Arabic,
2361    /// Hebrew, Thai or emoji, so a name in any of those used to vanish from the paper with
2362    /// `ok: true` and nothing said. Each such character prints as
2363    /// [`crate::pdf_dope_card::UNPRINTABLE_SUBSTITUTE`] and is named here, so a caller that
2364    /// accepts any non-empty card name (both apps do) can warn at export time instead of
2365    /// handing over an unidentifiable card.
2366    pub unprintable_title_chars: String,
2367    /// Present ONLY when the printed rows stop short of the card that was asked for — the
2368    /// same block [`CardResponseV1::truncation`] carries, for the same reason (MBA-1477).
2369    ///
2370    /// Both paths fill it: a SOLVE takes the truncation of the very `card.range_table` rows
2371    /// it printed, and a REPRINT takes the one the stored card was saved with. Until this
2372    /// existed the PDF was the only card surface with no truncation signal at all — not the
2373    /// stderr warning a CLI reader gets, not the `truncated` block in CLI JSON, not
2374    /// `CardResponseV1::truncation` on the bridge — so a caller could not even tell that the
2375    /// document it was about to hand a shooter was short. It is also printed in the
2376    /// document's own footer, which is the half that survives being carried to a range.
2377    pub truncation: Option<CardTruncationV1>,
2378}
2379
2380/// Resolve the effective table font scale from the mutually exclusive `font_scale` /
2381/// `font_preset` options.
2382#[cfg(feature = "pdf")]
2383fn resolve_font_scale(opts: &PdfCardOptionsV1) -> Result<f32, CardServiceError> {
2384    use crate::pdf_dope_card::{FontSizePreset, FONT_SCALE_RANGE};
2385
2386    match (opts.font_scale, opts.font_preset.as_deref()) {
2387        (Some(_), Some(_)) => Err(CardServiceError::InvalidRequest(
2388            "pdf.font_scale and pdf.font_preset are mutually exclusive; supply one".into(),
2389        )),
2390        (Some(scale), None) => {
2391            let scale = scale as f32;
2392            if !scale.is_finite() || !FONT_SCALE_RANGE.contains(&scale) {
2393                return Err(CardServiceError::InvalidRequest(format!(
2394                    "pdf.font_scale must be finite and within {}..={}, got {}",
2395                    FONT_SCALE_RANGE.start(),
2396                    FONT_SCALE_RANGE.end(),
2397                    opts.font_scale.unwrap_or(f64::NAN)
2398                )));
2399            }
2400            Ok(scale)
2401        }
2402        (None, Some(preset)) => FontSizePreset::from_str(preset)
2403            .map(|p| p.scale())
2404            .ok_or_else(|| {
2405                CardServiceError::InvalidRequest(format!(
2406                    "pdf.font_preset '{preset}' is not one of small, medium, large"
2407                ))
2408            }),
2409        (None, None) => Ok(1.0),
2410    }
2411}
2412
2413/// The rows to print plus everything the header/footer states about where they came from.
2414/// Filled by exactly one of the two paths in [`pdf_card_v1`], which then share one
2415/// renderer, so a reprint and a solve cannot be laid out or labelled differently.
2416#[cfg(feature = "pdf")]
2417struct RowsToPrint {
2418    rows: Vec<crate::card::CardRow>,
2419    source: PdfRowSource,
2420    /// Footer `BC:` — the scalar BC these rows were computed with, printed when `bc_label`
2421    /// is empty.
2422    bc: f64,
2423    /// Footer `BC:` text for a card that flew a BC ladder (its range, from
2424    /// [`crate::pdf_dope_card::ladder_bc_label`]); empty for a card that flew none (MBA-1601).
2425    bc_label: String,
2426    /// Footer `Engine:` — empty prints nothing.
2427    engine_version: String,
2428    /// Footer `Table:` — empty prints nothing.
2429    table_version: String,
2430    /// Drop column label.
2431    elevation_unit_label: String,
2432    /// Wind and Lead column label.
2433    windage_unit_label: String,
2434    /// Footer truncation notice — `None` on a card that reached every row it asked for.
2435    /// Both paths fill it, so the printed notice cannot depend on where the rows came from.
2436    truncation: Option<CardTruncationV1>,
2437}
2438
2439/// Turn a stored response's rows into printable rows, deriving only the Lead column.
2440///
2441/// The Drop and Wind cells are the stored values, untouched. Lead is `target_speed x stored
2442/// ToF` held on the windage axis — the same [`crate::lead_from_tof`] arithmetic
2443/// `range_table_rows` performs, applied to the time of flight the stored row already
2444/// carries. No trajectory, no zero solve, no correction table.
2445#[cfg(feature = "pdf")]
2446fn stored_rows_to_print(
2447    stored: &StoredCardResponseV1,
2448    req: &CardRequestV1,
2449    r: &Resolved,
2450    target_speed: Option<f64>,
2451) -> Vec<crate::card::CardRow> {
2452    use crate::card::CardRow;
2453
2454    let lead_speed_mps = target_speed.map(|speed| r.u.wind_to_metric(speed));
2455    stored
2456        .rows
2457        .iter()
2458        .map(|row| CardRow {
2459            range: row.range,
2460            drop_linear: row.drop_linear,
2461            drop_adj: row.drop_adj,
2462            come_up: row.come_up,
2463            wind_linear: row.wind_linear,
2464            wind_adj: row.wind_adj,
2465            velocity: row.velocity,
2466            energy: row.energy,
2467            time: row.time,
2468            lead_adj: lead_speed_mps.zip(row.time).map(|(speed_mps, tof_s)| {
2469                let range_m = r.u.distance_to_metric(row.range);
2470                let lead_display = r.u.distance_from_metric(
2471                    crate::lead_from_tof(speed_mps, 90.0, tof_s, range_m).lead_m,
2472                );
2473                // Bias-free (it composes on top of the wind dial, which carries the
2474                // zero-set bias) but still divided by the windage tracking CF — the exact
2475                // treatment `range_table_rows` and the CLI's Lead column give it.
2476                windage_adjustment_display(
2477                    lead_display,
2478                    row.range,
2479                    r.windage_unit,
2480                    r.windage_click,
2481                    0.0,
2482                    req.windage_cf,
2483                )
2484                .value
2485            }),
2486            wind_columns: row.wind_columns.clone(),
2487        })
2488        .collect()
2489}
2490
2491/// Reject a stored card that is not the range table it must be, cell values included.
2492#[cfg(feature = "pdf")]
2493fn validate_stored_card(
2494    stored: &StoredCardV1,
2495    req: &CardRequestV1,
2496    r: &Resolved,
2497) -> Result<(), CardServiceError> {
2498    let card = &stored.card;
2499    if card.kind != PDF_CARD_KIND {
2500        return Err(CardServiceError::InvalidRequest(format!(
2501            "card.pdf prints a {PDF_CARD_KIND} card; the stored card's kind is '{}'. Its \
2502             columns are not a range table's, so it is refused rather than reprinted as one",
2503            card.kind
2504        )));
2505    }
2506    // The same "this is not a range table" test the REQUEST gets (see the `wind_speeds` /
2507    // `wind_angles_deg` loop in `pdf_card_v1`), field for field. The two halves used to
2508    // disagree — `wind_angles_deg` was refused on the request and accepted here — and the
2509    // stored half is the one that has to hold when a future kind starts emitting it.
2510    for (field, present) in [
2511        ("wind_speeds", !card.wind_speeds.is_empty()),
2512        ("wind_angles_deg", !card.wind_angles_deg.is_empty()),
2513        ("extra_angle_rows", !card.extra_angle_rows.is_empty()),
2514    ] {
2515        if present {
2516            return Err(CardServiceError::InvalidRequest(format!(
2517                "the stored card carries {field}, a wind card's defining field, so it is not the \
2518                 {PDF_CARD_KIND} response it claims to be"
2519            )));
2520        }
2521    }
2522    if card.rows.is_empty() {
2523        return Err(CardServiceError::InvalidRequest(
2524            "the stored card has no rows; an empty dope card is not a document".into(),
2525        ));
2526    }
2527
2528    // A row means something only in a unit. If the stored labels and the request's own axes
2529    // disagree, the two are not the same card — printing anyway would put one unit's numbers
2530    // under another unit's heading, which is precisely the failure the shared request shape
2531    // exists to prevent.
2532    let elevation = adjustment_unit_label(req.adjustment_unit);
2533    let windage = adjustment_unit_label(r.windage_unit);
2534    let distance = r.u.distance_label();
2535    for (field, stored_label, request_label) in [
2536        ("units.distance", card.units.distance.as_str(), distance),
2537        (
2538            "units.elevation_adjustment",
2539            card.units.elevation_adjustment.as_str(),
2540            elevation.as_str(),
2541        ),
2542        (
2543            "units.windage_adjustment",
2544            card.units.windage_adjustment.as_str(),
2545            windage.as_str(),
2546        ),
2547    ] {
2548        if stored_label != request_label {
2549            return Err(CardServiceError::InvalidRequest(format!(
2550                "the stored card's {field} is '{stored_label}' but this request's own axes say \
2551                 '{request_label}' — the stored rows and the request are not the same card"
2552            )));
2553        }
2554    }
2555
2556    // Same rule as the cells below: a non-finite figure would print "NaN"/"inf" — here in a
2557    // sentence telling a shooter where their card stops, which is worse than in a column.
2558    if let Some(t) = &card.truncation {
2559        for (field, value) in [
2560            ("requested_end", t.requested_end),
2561            ("last_row", t.last_row),
2562            ("reach", t.reach),
2563        ] {
2564            if !value.is_finite() {
2565                return Err(CardServiceError::InvalidRequest(format!(
2566                    "the stored card's truncation.{field} is not a finite number"
2567                )));
2568            }
2569        }
2570    }
2571
2572    // The footer prints the ladder's BC range from this block, so a block with nothing to
2573    // print, or a BC no ladder could fly, is refused rather than printed (MBA-1601).
2574    if let Some(ladder) = &card.bc_ladder {
2575        if ladder.segments.is_empty() {
2576            return Err(CardServiceError::InvalidRequest(
2577                "the stored card's bc_ladder has no segments".into(),
2578            ));
2579        }
2580        for (index, segment) in ladder.segments.iter().enumerate() {
2581            if !(segment.bc.is_finite() && segment.bc > 0.0) {
2582                return Err(CardServiceError::InvalidRequest(format!(
2583                    "the stored card's bc_ladder.segments[{index}].bc is not a finite positive \
2584                     number"
2585                )));
2586            }
2587        }
2588    }
2589
2590    // A non-finite cell would print "NaN"/"inf" on a field card.
2591    for (index, row) in card.rows.iter().enumerate() {
2592        for (field, value) in [
2593            ("range", Some(row.range)),
2594            ("drop_adj", row.drop_adj),
2595            ("wind_adj", row.wind_adj),
2596            ("time", row.time),
2597        ] {
2598            if value.is_some_and(|v| !v.is_finite()) {
2599                return Err(CardServiceError::InvalidRequest(format!(
2600                    "the stored card's rows[{index}].{field} is not a finite number"
2601                )));
2602            }
2603        }
2604    }
2605    Ok(())
2606}
2607
2608/// Render the printable PDF dope card for a card request.
2609///
2610/// `stored` decides where the numbers come from, and it is the whole point of this surface:
2611///
2612/// * `Some(card)` — REPRINT. The rows are the caller's: the stored `card.range_table`
2613///   response for this same request. Nothing is solved, `bc5d_table_path` is never opened,
2614///   and the footer's BC, engine version and table version are the stored card's. A saved
2615///   card's ROWS therefore reprint identically after an engine bump, after the correction
2616///   table at the stored path is overwritten in place, and even after that file is deleted.
2617///   The header is not stored: it states the air the stored request resolves to on this
2618///   engine (MBA-1593), so a card saved before 0.49.0 at altitude without a pressure or
2619///   temperature reprints with the corrected header over its unchanged rows.
2620/// * `None` — SOLVE. `range_table_rows` runs, i.e. literally the rows [`range_table_v1`]
2621///   would return for this request, and the footer states THIS build's version. Unchanged
2622///   behaviour for a caller that has no stored rows.
2623///
2624/// Either way this prints a [`PDF_CARD_KIND`] card and nothing else: a request carrying a
2625/// wind card's `wind_speeds`/`wind_angles_deg`, or a stored card of another kind, is refused.
2626/// Both paths map their rows onto the CLI's Range/Drop/Wind/Lead dope card, plus the Lead
2627/// column that `CardRequestV1::pdf`'s `target_speed` asks for. The Range column is
2628/// denominated in the stored/requested `distance_unit`, unlike `trajectory -o pdf`, whose
2629/// dope card is always yards.
2630///
2631/// The header/footer block is always imperial, matching both CLI PDF call sites: whatever the
2632/// request's velocity/temperature/pressure/altitude/wind/weight dimensions are denominated in,
2633/// they are converted for display only. The `Solver:` label reports this build (`online` with
2634/// the `online` feature, otherwise `offline`) and the timestamp is generation time, so neither
2635/// is caller-settable — and neither is a number a shooter dials.
2636#[cfg(feature = "pdf")]
2637pub fn pdf_card_v1(
2638    req: &CardRequestV1,
2639    stored: Option<&StoredCardV1>,
2640) -> Result<PdfCardV1, CardServiceError> {
2641    use crate::atmosphere::{resolve_station_conditions_with_presence, PressureReferenceMode};
2642    use crate::pdf_dope_card::{
2643        dope_card_page_count, generate_dope_card_pdf, ladder_bc_label, DopeCardConfig,
2644        HeaderAtmosphere, RangeUnit,
2645    };
2646
2647    let opts = req.pdf.clone().unwrap_or_default();
2648    let drag_model = DragModel::from(req.drag_model).to_string();
2649    // Validate presentation options BEFORE spending a zero solve and two trajectories on a
2650    // request that cannot be rendered anyway.
2651    let font_scale = resolve_font_scale(&opts)?;
2652    // A non-finite crossing speed would print "inf"/"NaN" in every Lead cell rather than
2653    // failing. (A NEGATIVE speed is accepted, matching the CLI: it reads as the mover
2654    // crossing the other way and simply flips the sign of the hold.)
2655    if opts.target_speed.is_some_and(|speed| !speed.is_finite()) {
2656        return Err(CardServiceError::InvalidRequest(
2657            "pdf.target_speed must be finite".into(),
2658        ));
2659    }
2660
2661    // A wind card's defining fields cannot be honoured by a range-table PDF. Refuse them
2662    // instead of returning a document whose Wind column contradicts the screen.
2663    for (field, present) in [
2664        ("wind_speeds", !req.wind_speeds.is_empty()),
2665        ("wind_angles_deg", !req.wind_angles_deg.is_empty()),
2666    ] {
2667        if present {
2668            return Err(CardServiceError::InvalidRequest(format!(
2669                "card.pdf prints a {PDF_CARD_KIND} card; this request carries {field}, a wind \
2670                 card's defining field, which a range-table PDF cannot show and would silently \
2671                 ignore. There is no wind_card or come_ups PDF in this build"
2672            )));
2673        }
2674    }
2675
2676    let to_print = match stored {
2677        Some(stored) => {
2678            // Axes and click graduations only: no BC schedule, so no correction table is
2679            // opened for a card whose numbers are already decided.
2680            let r = resolve_axes_only(req)?;
2681            validate_stored_card(stored, req, &r)?;
2682            let bc = stored
2683                .card
2684                .bc_for_solve
2685                .unwrap_or(req.ballistic_coefficient);
2686            RowsToPrint {
2687                rows: stored_rows_to_print(&stored.card, req, &r, opts.target_speed),
2688                source: PdfRowSource::StoredRows,
2689                bc,
2690                // Only the stored card's own ladder block: a card saved without one reprints
2691                // its scalar as before, never a ladder re-derived from the request.
2692                bc_label: stored
2693                    .card
2694                    .bc_ladder
2695                    .as_ref()
2696                    .map(|ladder| {
2697                        let bcs: Vec<f64> = ladder.segments.iter().map(|s| s.bc).collect();
2698                        ladder_bc_label(&drag_model, &bcs, bc, ladder.interior_gap)
2699                    })
2700                    .unwrap_or_default(),
2701                engine_version: stored.engine_version.clone().unwrap_or_default(),
2702                table_version: stored.bc5d_table_version.clone().unwrap_or_default(),
2703                elevation_unit_label: stored.card.units.elevation_adjustment.clone(),
2704                windage_unit_label: stored.card.units.windage_adjustment.clone(),
2705                // The truncation the card was SAVED with. Nothing is re-derived from the
2706                // stored row set here — a reprint prints the card it was handed, and that
2707                // includes what the card already said about itself.
2708                truncation: stored.card.truncation.map(CardTruncationV1::from),
2709            }
2710        }
2711        None => {
2712            let (card, lead_adj, bc_for_solve) = range_table_rows(req, opts.target_speed)?;
2713            if card.rows.is_empty() {
2714                // `generate_dope_card_pdf` refuses an empty row set, and rightly: an empty
2715                // dope card is not a document. Name the cause the caller can act on instead.
2716                return Err(CardServiceError::InvalidRequest(format!(
2717                    "no card rows in {}..={} — the trajectory does not reach this range domain, \
2718                     or step is coarser than the samples",
2719                    req.start, req.end
2720                )));
2721            }
2722            RowsToPrint {
2723                rows: card
2724                    .rows
2725                    .iter()
2726                    .zip(&lead_adj)
2727                    .map(|(row, lead)| crate::card::CardRow {
2728                        range: row.range,
2729                        drop_linear: row.drop_linear,
2730                        drop_adj: row.drop_adj,
2731                        come_up: row.come_up,
2732                        wind_linear: row.wind_linear,
2733                        wind_adj: row.wind_adj,
2734                        velocity: row.velocity,
2735                        energy: row.energy,
2736                        time: row.time,
2737                        lead_adj: *lead,
2738                        wind_columns: row.wind_columns.clone(),
2739                    })
2740                    .collect(),
2741                source: PdfRowSource::Solve,
2742                bc: bc_for_solve,
2743                // The ladder `card.range_table` reports for these very rows.
2744                bc_label: card
2745                    .bc_ladder
2746                    .as_ref()
2747                    .map(|ladder| {
2748                        let bcs: Vec<f64> = ladder.segments.iter().map(|s| s.bc).collect();
2749                        ladder_bc_label(&drag_model, &bcs, bc_for_solve, ladder.interior_gap)
2750                    })
2751                    .unwrap_or_default(),
2752                // No table version is knowable from a path, so none is claimed; the engine
2753                // version is this build's, which is what produced these rows.
2754                engine_version: env!("CARGO_PKG_VERSION").to_string(),
2755                table_version: String::new(),
2756                // The labels `card.range_table`'s `units` block reports for this request:
2757                // Drop in the elevation unit, Wind AND Lead in the (possibly different,
2758                // MBA-1410) windage unit.
2759                elevation_unit_label: card.units.elevation_adjustment.clone(),
2760                windage_unit_label: card.units.windage_adjustment.clone(),
2761                // The truncation of the very rows above, not a second determination of it:
2762                // `range_table_rows` IS `card.range_table`, so the paper and the screen
2763                // truncate identically or not at all.
2764                truncation: card.truncation,
2765            }
2766        }
2767    };
2768
2769    // Refuse on the row/page count now that the rows are known — before a document is built.
2770    // The byte cap downstream can only measure a document it already paid for.
2771    let page_count = dope_card_page_count(to_print.rows.len(), font_scale);
2772    if to_print.rows.len() > MAX_PDF_ROWS || page_count > MAX_PDF_PAGES {
2773        return Err(CardServiceError::TooLarge(format!(
2774            "this card has too many rows to print: {} rows, {page_count} pages (the limits are \
2775             {MAX_PDF_ROWS} rows and {MAX_PDF_PAGES} pages)",
2776            to_print.rows.len()
2777        )));
2778    }
2779
2780    // The request's own axes, for the header. Resolved here rather than taken from above
2781    // because neither branch hands a `Resolved` back — the reprint's is scoped to its arm and
2782    // the solve's lives inside `range_table_rows`. Resolving twice is safe precisely because
2783    // `Units::resolve` is a pure function of the request: the header cannot land on axes the
2784    // rows were not computed in.
2785    let u = Units::resolve(req);
2786    // The atmosphere defaults `resolve()` applies, restated for the header so the printed
2787    // conditions are the ones the solve used rather than blanks.
2788    let temperature = req.temperature.unwrap_or_else(|| u.default_temperature());
2789    let pressure = req.pressure.unwrap_or_else(|| u.default_pressure());
2790    // NOTE: `CardRequestV1::altitude` defaults to METRES whatever the `units` preset says —
2791    // the one dimension whose fallback is not the preset's, because it never was (see
2792    // `CardRequestV1::altitude_unit`). The header reports the altitude the solve actually
2793    // used, so it converts out of whatever `altitude_unit` settled on.
2794    let altitude_ft = u.altitude_to_feet(req.altitude);
2795    // MBA-1593: and the AIR the solve actually flew. `resolve()` hands the solver this
2796    // (°C, hPa) pair, which it resolves as an absolute station reading (a card request has no
2797    // QNH mode): a sea-level default at a real altitude becomes ICAO air there. The header
2798    // used to print the pair as handed, so a 1500 m card with no pressure read DA:0 ft. The
2799    // stated figures use the CLI dope card's own 33.8639 inHg <-> hPa factor (main.rs uses it
2800    // on both PDF call sites), NOT pdf_dope_card::INHG_TO_HPA, matching the shipped header.
2801    //
2802    // 0.49.0: a field the request carried is a reading and the solve flies it as typed, so the
2803    // solve path's header resolves with the request's presence, exactly as the rows were
2804    // solved. A reprint's rows were solved by whichever engine produced them, so its header
2805    // takes presence only when those rows are from 0.49.0 or later, and otherwise states the
2806    // pre-0.49.0 air they flew (see `StoredCardV1::engine_version`).
2807    let supplied = (
2808        u.temperature_to_metric(temperature),
2809        u.pressure_to_metric(pressure),
2810    );
2811    let request_presence =
2812        StationAtmospherePresence::new(req.temperature.is_some(), req.pressure.is_some());
2813    let header_presence = match stored {
2814        Some(stored) if !stored_rows_are_presence_aware(&stored.engine_version) => {
2815            StationAtmospherePresence::NEITHER
2816        }
2817        _ => request_presence,
2818    };
2819    let flown = resolve_station_conditions_with_presence(
2820        supplied.0,
2821        supplied.1,
2822        u.altitude_to_metric(req.altitude),
2823        PressureReferenceMode::Absolute,
2824        header_presence,
2825    );
2826    let header_air = HeaderAtmosphere::new(
2827        u.temperature_to_fahrenheit(temperature),
2828        u.pressure_to_inhg(pressure),
2829        u.pressure_to_hpa(pressure),
2830    )
2831    .as_flown(supplied, flown);
2832
2833    let config = DopeCardConfig {
2834        rifle_name: opts
2835            .title
2836            .clone()
2837            .unwrap_or_else(|| "Dope Card".to_string()),
2838        location: opts.location.clone().unwrap_or_default(),
2839        density_altitude_ft: header_air.density_altitude_ft,
2840        pressure_inhg: header_air.pressure_inhg,
2841        pressure_hpa: header_air.pressure_hpa,
2842        temperature_f: header_air.temperature_f,
2843        altitude_ft,
2844        wind_speed_mph: u.wind_to_mph(req.wind_speed),
2845        // Absent target speed prints 0 here (there is no lead to state) while the Lead
2846        // column itself stays em-dashed; an explicit 0.0 prints the same 0 and zeroes.
2847        target_speed_mph: match opts.target_speed {
2848            Some(speed) => u.wind_to_mph(speed),
2849            None => 0.0,
2850        },
2851        solver_mode: if cfg!(feature = "online") {
2852            "online".to_string()
2853        } else {
2854            "offline".to_string()
2855        },
2856        powder: opts.powder.clone().unwrap_or_default(),
2857        bullet: opts.bullet.clone().unwrap_or_default(),
2858        weight_gr: u.mass_to_grains_cli(req.mass),
2859        // The BC these rows came from: the stored card's own, or this solve's (which is the
2860        // muzzle-corrected value when a BC5D table applied one). Under a BC ladder the footer
2861        // prints `bc_label`, the ladder's range, instead (MBA-1601).
2862        bc: to_print.bc,
2863        drag_model,
2864        bc_label: to_print.bc_label.clone(),
2865        velocity_fps: u.velocity_to_fps_pdf(req.muzzle_velocity),
2866        font_scale,
2867        bold_data: opts.bold_data,
2868        // The card's own axes: Drop in the elevation unit, Wind AND Lead in the (possibly
2869        // different, MBA-1410) windage unit — from the document that owns the rows.
2870        elevation_unit_label: to_print.elevation_unit_label.clone(),
2871        windage_unit_label: to_print.windage_unit_label.clone(),
2872        // Provenance on the paper, so a printed card and a screen can be reconciled later.
2873        engine_version: to_print.engine_version.clone(),
2874        table_version: to_print.table_version.clone(),
2875        // MBA-1477: and the truncation on the paper too, in the one wording every card
2876        // surface uses, denominated in the card's own distance unit (which
2877        // `validate_stored_card` has already forced to agree with the request's).
2878        truncation_note: to_print
2879            .truncation
2880            .map(|t| CardTruncation::from(t).printed_note(u.distance_label()))
2881            .unwrap_or_default(),
2882    };
2883
2884    let range_unit = match u.distance {
2885        CardDistanceUnit::Yards => RangeUnit::Yards,
2886        CardDistanceUnit::Meters => RangeUnit::Meters,
2887    };
2888    // Read BEFORE the document is built, off the same string the header will draw, so the
2889    // report describes this card's own title rather than a truncation of it.
2890    let unprintable_title_chars = crate::pdf_dope_card::unprintable_chars(&config.rifle_name);
2891    let pdf_bytes = generate_dope_card_pdf(&config, &to_print.rows, range_unit)
2892        .map_err(|e| CardServiceError::Pdf(e.to_string()))?;
2893
2894    Ok(PdfCardV1 {
2895        page_count,
2896        row_count: to_print.rows.len(),
2897        source: to_print.source,
2898        pdf_bytes,
2899        unprintable_title_chars,
2900        truncation: to_print.truncation,
2901    })
2902}
2903
2904#[cfg(all(test, feature = "pdf"))]
2905mod stored_engine_version_tests {
2906    use super::stored_rows_are_presence_aware;
2907
2908    #[test]
2909    fn only_a_readable_version_of_0_49_or_later_is_presence_aware() {
2910        let aware = |v: Option<&str>| stored_rows_are_presence_aware(&v.map(str::to_string));
2911        for version in [
2912            "0.49.0",
2913            "v0.49.1-rc1",
2914            "0.49.0+build.7",
2915            "0.50.0",
2916            "0.100.3",
2917            "1.0.0",
2918        ] {
2919            assert!(aware(Some(version)), "{version}");
2920        }
2921        for version in [
2922            "0.48.0", "0.48.9", "0.9.99", "", "unknown", "0.49", "0.49.x", "x0.49.0",
2923        ] {
2924            assert!(!aware(Some(version)), "{version}");
2925        }
2926        assert!(!aware(None));
2927    }
2928}