Skip to main content

ifc_lite_processing/symbolic/
primitives.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5use super::output_cap::SymbolicTruncation;
6use serde::{Deserialize, Serialize};
7
8// ────────────────────────────────────────────────────────────────────────────
9// NaN sentinel <-> JSON `null`.
10//
11// Several scalars below use `f32::NAN` as a SENTINEL meaning "never resolved"
12// — `world_y` when the placement chain yields no elevation, and
13// `hatch_angle_secondary` when a fill carries no cross-hatch. The whole point
14// of that sentinel is that "unresolved" must not read as `0.0`, which is a
15// perfectly real elevation / angle.
16//
17// JSON has no NaN. `serde_json` already WRITES a non-finite `f32` as `null`,
18// but the derived `Deserialize` could not READ it back: `invalid type: null,
19// expected f32`. So every JSON hop destroyed the sentinel — most sharply in
20// `apps/server/src/routes/parse/cache_keys.rs`, where the symbolic cache is
21// re-read with `from_slice(..).unwrap_or_else(|_| SymbolicData::default())`,
22// meaning ONE unresolved scalar made the entire cached blob unreadable and
23// every replayed request served no symbolic data at all.
24//
25// `nan_as_null` fixes the READ side only. Its serialize half emits exactly
26// what `serde_json` already emitted (`null` for NaN, the plain number
27// otherwise), so no finite value — `0.0` included — changes shape on the
28// wire. `null` and `0` stay distinct, and an OMITTED key stays a hard
29// deserialization error rather than a third spelling of "unresolved".
30// ────────────────────────────────────────────────────────────────────────────
31
32/// `serialize_with`/`deserialize_with` pair mapping the `f32::NAN`
33/// "unresolved" sentinel to and from JSON `null`.
34///
35/// Read back, any `null` becomes `f32::NAN`. `serde_json` also writes `±inf`
36/// as `null`, so an infinity would return as NaN — no producer in this crate
37/// emits one, and NaN is the correct reading of "not a usable elevation"
38/// either way. Consumers must test `is_nan()`, not `!is_finite()`.
39pub(crate) mod nan_as_null {
40    use serde::{Deserialize, Deserializer, Serializer};
41
42    pub(crate) fn serialize<S>(value: &f32, serializer: S) -> Result<S::Ok, S::Error>
43    where
44        S: Serializer,
45    {
46        if value.is_nan() {
47            serializer.serialize_none()
48        } else {
49            serializer.serialize_f32(*value)
50        }
51    }
52
53    pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<f32, D::Error>
54    where
55        D: Deserializer<'de>,
56    {
57        Ok(Option::<f32>::deserialize(deserializer)?.unwrap_or(f32::NAN))
58    }
59}
60
61// ────────────────────────────────────────────────────────────────────────────
62// Pure-Rust serializable primitive types. The wasm-bindgen wrappers in
63// `rust/wasm-bindings/src/zero_copy.rs` are thin views over these.
64// ────────────────────────────────────────────────────────────────────────────
65
66/// A single 2D polyline for symbolic representations.
67#[derive(Debug, Clone, Serialize, Deserialize)]
68pub struct SymbolicPolyline {
69    /// Express ID of the IFC entity that authored the curve.
70    pub express_id: u32,
71    /// Owning element's IFC type name.
72    pub ifc_type: String,
73    /// Flat 2D points `[x0, y0, x1, y1, …]` in metres.
74    pub points: Vec<f32>,
75    /// True if the curve is a closed loop.
76    pub closed: bool,
77    /// World-Y elevation captured from the placement chain or the
78    /// polyline's own 3D `IfcCartesianPoint` Z component. `f32::NAN` when the
79    /// elevation could not be resolved — distinct from a genuine `0.0`, and
80    /// spelled `null` on the JSON wire (see [`nan_as_null`]).
81    #[serde(with = "nan_as_null")]
82    pub world_y: f32,
83    /// Representation identifier (`Plan`, `Annotation`, `FootPrint`, `Axis`).
84    pub representation: String,
85}
86
87/// A single 2D circle / arc for symbolic representations.
88#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct SymbolicCircle {
90    pub express_id: u32,
91    pub ifc_type: String,
92    pub center_x: f32,
93    pub center_y: f32,
94    pub radius: f32,
95    /// World-Y elevation (see [`SymbolicPolyline::world_y`]).
96    #[serde(with = "nan_as_null")]
97    pub world_y: f32,
98    /// Start angle in radians (0 for full circle).
99    pub start_angle: f32,
100    /// End angle in radians (`TAU` for full circle).
101    pub end_angle: f32,
102    pub representation: String,
103}
104
105impl SymbolicCircle {
106    /// Full-circle constructor.
107    pub fn full(
108        express_id: u32,
109        ifc_type: String,
110        center_x: f32,
111        center_y: f32,
112        radius: f32,
113        world_y: f32,
114        representation: String,
115    ) -> Self {
116        Self {
117            express_id,
118            ifc_type,
119            center_x,
120            center_y,
121            radius,
122            world_y,
123            start_angle: 0.0,
124            end_angle: std::f32::consts::TAU,
125            representation,
126        }
127    }
128}
129
130/// A 2D text annotation (`IfcTextLiteral` / `IfcTextLiteralWithExtent`).
131#[derive(Debug, Clone, Serialize, Deserialize)]
132pub struct SymbolicText {
133    pub express_id: u32,
134    pub ifc_type: String,
135    /// Anchor point on the text baseline (model units).
136    pub x: f32,
137    pub y: f32,
138    /// Baseline orientation as a `(cos, sin)` pair. Defaults to `(1, 0)`.
139    pub dir_x: f32,
140    pub dir_y: f32,
141    /// Font height in model units (already unit-scaled).
142    pub height: f32,
143    /// UTF-8 text content, ALREADY DECODED. It is read through
144    /// `AttributeValue::from_token`, which un-doubles `''` and runs
145    /// `decode_ifc_string` (`\X2\…\X0\`, `\X\NN`, `\S\X`, `\\`) at the parse
146    /// boundary (#2394) — so consumers must NOT decode it again. A second
147    /// decode is not idempotent: it collapses `\\` twice, turning an authored
148    /// `\\server\share` into `\server\share`.
149    pub content: String,
150    /// IFC `BoxAlignment` (`top-left`, `center`, `bottom-right`, …). Empty
151    /// string when absent.
152    pub alignment: String,
153    /// World-Y elevation (see [`SymbolicPolyline::world_y`]).
154    #[serde(with = "nan_as_null")]
155    pub world_y: f32,
156    /// sRGB straight-alpha colour `[r, g, b, a]`. Defaults to dark-grey
157    /// when no IfcStyledItem chain resolves a colour.
158    pub color: [f32; 4],
159    /// Per-instance target screen-pixel cap height. `0.0` = renderer
160    /// global default (~14 px for body text).
161    pub target_px: f32,
162    pub representation: String,
163}
164
165/// A 2D filled region (`IfcAnnotationFillArea`).
166///
167/// Outer ring + optional inner rings (holes) packed into a single `points`
168/// buffer. `holes_offsets[i]` is the vertex index where hole `i` begins —
169/// outer ring spans `[0, holes_offsets[0])` (or all points when no holes).
170#[derive(Debug, Clone, Serialize, Deserialize)]
171pub struct SymbolicFillArea {
172    pub express_id: u32,
173    pub ifc_type: String,
174    /// All ring vertices: outer ring first, then each hole back-to-back.
175    /// Format: `[x0, y0, x1, y1, …]`.
176    pub points: Vec<f32>,
177    /// Inclusive prefix of where each hole begins (in vertex indices).
178    pub holes_offsets: Vec<u32>,
179    /// Fill colour sRGB, 0..1. Defaults to opaque black.
180    pub fill_color: [f32; 4],
181    /// Whether this fill carries a hatching style.
182    pub has_hatching: bool,
183    pub hatch_spacing: f32,
184    pub hatch_angle: f32,
185    /// Secondary cross-hatch angle. NaN if absent — `null` on the JSON wire
186    /// (see [`nan_as_null`]), which is NOT the same as a genuine `0.0` angle.
187    #[serde(with = "nan_as_null")]
188    pub hatch_angle_secondary: f32,
189    pub hatch_line_width: f32,
190    /// World-Y elevation (see [`SymbolicPolyline::world_y`]).
191    #[serde(with = "nan_as_null")]
192    pub world_y: f32,
193    pub representation: String,
194}
195
196/// A single `IfcGridAxis` tag + axis curve (server-friendly endpoint-pair
197/// representation; the wasm pipeline emits the same data via
198/// [`SymbolicPolyline`] axis lines and [`SymbolicText`] bubbles, both of
199/// which are also populated below).
200#[derive(Debug, Clone, Serialize, Deserialize)]
201pub struct SymbolicGridAxis {
202    pub express_id: u32,
203    pub grid_express_id: u32,
204    pub tag: String,
205    /// Endpoint pair `[x0, y0, x1, y1]` in metres (plan view).
206    pub endpoints: [f32; 4],
207    /// World-Y elevation (see [`SymbolicPolyline::world_y`]).
208    #[serde(with = "nan_as_null")]
209    pub world_y: f32,
210}
211
212/// Server-friendly summary of the IFC's 2D symbol data.
213#[derive(Debug, Clone, Default, Serialize, Deserialize)]
214pub struct SymbolicData {
215    /// Axis endpoints for every `IfcGridAxis` (compact summary shape).
216    pub grid_axes: Vec<SymbolicGridAxis>,
217    /// All polylines (`IfcPolyline`, `IfcIndexedPolyCurve`, `IfcEllipse`
218    /// tessellations, `IfcTrimmedCurve` arcs, grid axis lines).
219    pub polylines: Vec<SymbolicPolyline>,
220    /// All circles (`IfcCircle` full disks).
221    pub circles: Vec<SymbolicCircle>,
222    /// All text annotations (`IfcTextLiteral`, grid bubble outlines + tags).
223    pub texts: Vec<SymbolicText>,
224    /// All filled regions (`IfcAnnotationFillArea`).
225    pub fills: Vec<SymbolicFillArea>,
226    /// Set when extraction stopped at [`MAX_SYMBOLIC_ELEMENTS`]; `None` when the
227    /// file was emitted in full.
228    ///
229    /// `#[serde(default)]` so a `SymbolicData` cached before this field existed
230    /// still deserializes (`apps/server/src/routes/parse/cache_keys.rs` reads
231    /// cached JSON), and `skip_serializing_if` so an untruncated response is
232    /// byte-identical to what it was before.
233    #[serde(default, skip_serializing_if = "Option::is_none")]
234    pub truncated: Option<SymbolicTruncation>,
235}
236
237
238impl SymbolicData {
239    /// Total primitives across every collection.
240    pub(super) fn len(&self) -> usize {
241        self.grid_axes.len()
242            + self.polylines.len()
243            + self.circles.len()
244            + self.texts.len()
245            + self.fills.len()
246    }
247
248    /// Returns true if no symbolic primitives were extracted — the server
249    /// can omit the field from its response instead of emitting an empty
250    /// object.
251    pub fn is_empty(&self) -> bool {
252        self.grid_axes.is_empty()
253            && self.polylines.is_empty()
254            && self.circles.is_empty()
255            && self.texts.is_empty()
256            && self.fills.is_empty()
257            // A truncated result is never "empty", even when it carries no
258            // primitives. `apps/server/src/types/response.rs` uses this for
259            // `skip_serializing_if`, so returning true here would drop the
260            // diagnostic on exactly the response that needs it most. Not
261            // reachable from extraction under the shipped bounds, but it
262            // round-trips in from cached JSON.
263            && self.truncated.is_none()
264    }
265}