ifc_lite_geometry/document/
retained.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Retained authored-source requests, kept apart from display meshes.
3//!
4//! A retained definition owns one captured authored source ([`RetainedRecipe`]:
5//! an extrusion, a swept disk or a face set) plus its encoded numerical request
6//! ([`SweepPayload`]). It is never a mesh and never enters
7//! [`GeometryDocument::mesh`]. The only way from a retained definition to a
8//! mesh is [`GeometryDocument::publish_retained_display`], which admits a
9//! worker's tessellation as an ordinary display-approximation definition.
10
11use super::retained_disk::{self, RetainedSweptDisk};
12use super::retained_sweep::{self, SweepPayload};
13use super::{
14    validation, DefinitionHandle, DocumentError, DocumentId, GeometryDocument, OccurrenceHandle,
15};
16use crate::analytic::AnalyticExtrusion;
17use std::sync::Arc;
18
19/// A retained source definition owned by exactly one [`GeometryDocument`].
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub struct RetainedDefinitionHandle {
22    document: DocumentId,
23    slot: usize,
24}
25
26/// One authored `IfcExtrudedAreaSolid`, extracted inside
27/// [`crate::analytic::with_source_capture`] so its original records survive.
28/// Coefficients stay in raw IFC file length units; nothing is sampled.
29#[derive(Debug, Clone, PartialEq)]
30pub struct RetainedExtrusion {
31    pub source: AnalyticExtrusion,
32    /// Raw IFC file length unit -> metres.
33    pub length_unit_scale: f64,
34}
35
36/// The captured authored source or derived cutter a retained definition owns.
37#[derive(Debug, Clone, PartialEq)]
38#[non_exhaustive]
39pub enum RetainedRecipe {
40    Extrusion(RetainedExtrusion),
41    SweptDisk(RetainedSweptDisk),
42    #[cfg(any(all(test, any(not(target_arch = "wasm32"), feature = "wasm_source_capture")), feature = "retained-runtime"))]
43    Prism(super::RetainedPrism),
44    /// Authored triangles: source-exact, no numerical approximation (#8291).
45    #[cfg(any(all(test, any(not(target_arch = "wasm32"), feature = "wasm_source_capture")), feature = "retained-runtime"))]
46    FaceSet(super::RetainedFaceSet),
47}
48
49impl RetainedRecipe {
50    #[cfg(any(all(test, any(not(target_arch = "wasm32"), feature = "wasm_source_capture")), feature = "retained-runtime"))]
51    pub(crate) fn lower(&self) -> Result<SweepPayload, RetainedRefusal> {
52        match self {
53            Self::Extrusion(recipe) => retained_sweep::lower(recipe),
54            Self::SweptDisk(recipe) => retained_disk::lower(recipe),
55            Self::Prism(recipe) => recipe.lower(),
56            Self::FaceSet(recipe) => recipe.lower(),
57        }
58    }
59
60    /// Attributed STEP source id; a published display retains that attribution.
61    pub fn solid_id(&self) -> u32 {
62        match self {
63            Self::Extrusion(recipe) => recipe.source.solid_id,
64            Self::SweptDisk(recipe) => recipe.solid_id,
65            #[cfg(any(all(test, any(not(target_arch = "wasm32"), feature = "wasm_source_capture")), feature = "retained-runtime"))]
66            Self::Prism(recipe) => recipe.source_id,
67            #[cfg(any(all(test, any(not(target_arch = "wasm32"), feature = "wasm_source_capture")), feature = "retained-runtime"))]
68            Self::FaceSet(recipe) => recipe.source_id,
69        }
70    }
71}
72
73/// Every refusal of the retained contract. A refused call leaves the document
74/// and its revision unchanged; a refused completion is never published.
75#[derive(Debug, thiserror::Error, PartialEq, Eq)]
76#[non_exhaustive]
77pub enum RetainedRefusal {
78    /// The source is outside the encodable numerical domain or inconsistent.
79    #[error("invalid retained source: {0}")]
80    InvalidSource(&'static str),
81    /// The analytic extractor already refused this source family or record.
82    #[error("unsupported retained source: {0}")]
83    UnsupportedSource(String),
84    /// Extracted without [`crate::analytic::with_source_capture`]: the original
85    /// trim, sense and placement records are unavailable, so nothing is retained.
86    #[error("original authored source records were not captured")]
87    SourceNotCaptured,
88    /// Worker incarnation 0, or a completion from a worker other than the live one.
89    #[error("completion does not belong to the live worker incarnation")]
90    WrongWorker,
91    /// The completion's evaluation frame differs from the request's frame.
92    #[error("completion frame does not match the request")]
93    FrameMismatch,
94    #[error("invalid retained tessellation: {0}")]
95    InvalidTessellation(&'static str),
96    /// Revision-local worker faces are not persistent IFC face identities.
97    #[error("persistent IFC face provenance is unavailable")]
98    PersistentFaceProvenanceUnavailable,
99    /// Flat corner normals are not smooth analytic surface normals.
100    #[error("analytic surface normals are unavailable")]
101    AnalyticNormalsUnavailable,
102    /// No style, material or texture is attributed to a retained display.
103    #[error("IFC appearance is unavailable")]
104    IfcAppearanceUnavailable,
105    #[error(transparent)]
106    Document(#[from] DocumentError),
107}
108
109/// What a caller wants a retained display mesh to mean. Only
110/// [`Self::UnstyledFlatSourceOnly`] is supported; every other claim is refused
111/// with its own [`RetainedRefusal`] rather than silently downgraded.
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113#[non_exhaustive]
114pub enum RetainedDisplayContract {
115    /// Flat-shaded, unstyled tessellation of the raw authored solid only. No
116    /// enclosing boolean, opening, style or persistent face identity applies.
117    UnstyledFlatSourceOnly,
118    PersistentIfcFaces,
119    AnalyticSurfaceNormals,
120    IfcAppearance,
121}
122
123#[derive(Debug)]
124pub(super) struct RetainedEntry {
125    recipe: RetainedRecipe,
126    payload: SweepPayload,
127}
128
129/// An immutable snapshot of one retained definition for one worker.
130///
131/// It is valid only while the document stays at the revision it was prepared
132/// at and only for the worker incarnation it names: any document mutation, or
133/// a worker restart, makes its completion unpublishable. Nothing replays it
134/// implicitly. It describes the raw authored solid only, never enclosing CSG
135/// or openings.
136#[derive(Debug, Clone)]
137pub struct RetainedRequest {
138    document: DocumentId,
139    revision: u64,
140    definition: RetainedDefinitionHandle,
141    worker_incarnation: u64,
142    entry: Arc<RetainedEntry>,
143}
144
145impl RetainedRequest {
146    /// Same immutable admission, including the original source allocation.
147    // Refs #7955: private receipt comparison.
148    #[cfg(any(all(test, any(not(target_arch = "wasm32"), feature = "wasm_source_capture")), feature = "retained-runtime"))]
149    #[cfg_attr(not(test), allow(dead_code))]
150    pub(crate) fn same_admission(&self, other: &Self) -> bool {
151        self.document == other.document && self.revision == other.revision
152            && self.definition == other.definition && self.worker_incarnation == other.worker_incarnation
153            && Arc::ptr_eq(&self.entry, &other.entry)
154    }
155
156    pub fn definition(&self) -> RetainedDefinitionHandle {
157        self.definition
158    }
159    /// Document revision this request was prepared at.
160    pub fn document_revision(&self) -> u64 {
161        self.revision
162    }
163    pub fn worker_incarnation(&self) -> u64 {
164        self.worker_incarnation
165    }
166    pub fn recipe(&self) -> &RetainedRecipe {
167        &self.entry.recipe
168    }
169    /// The encoded request a worker evaluates.
170    pub fn payload(&self) -> &SweepPayload {
171        &self.entry.payload
172    }
173}
174
175/// A worker's owned f64 result. Flat corner normals and revision-local faces
176/// stay distinct from smooth analytic shading and persistent IFC faces.
177/// Positions are in the request's evaluation frame (metres).
178#[derive(Debug, Clone, Default)]
179pub struct RetainedTessellation {
180    pub positions: Vec<f64>,
181    pub indices: Vec<u32>,
182    /// Three components per triangle corner, not per vertex.
183    pub flat_corner_normals: Vec<f64>,
184    /// One worker-local face index per triangle, below `source_face_count`.
185    pub revision_local_faces: Vec<u32>,
186    pub source_face_count: u32,
187    /// Open boundary and non-manifold spine edge counts; both must be zero.
188    pub boundary_edges: u32,
189    pub spine_edges: u32,
190}
191
192/// A worker completion for one request, with the frame the worker used.
193#[derive(Debug)]
194pub struct RetainedCompletion {
195    request: RetainedRequest,
196    pub tessellation: RetainedTessellation,
197    /// Column-major evaluation metres -> raw solid-local file units.
198    pub source_from_evaluation: [f64; 16],
199    pub evaluation_from_source: [f64; 16],
200}
201
202impl RetainedCompletion {
203    /// Host-trusted assembly: this does not authenticate the buffers or the
204    /// runtime that produced them; the document only checks identity and shape.
205    pub fn new(
206        request: RetainedRequest,
207        tessellation: RetainedTessellation,
208        source_from_evaluation: [f64; 16],
209        evaluation_from_source: [f64; 16],
210    ) -> Self {
211        Self {
212            request,
213            tessellation,
214            source_from_evaluation,
215            evaluation_from_source,
216        }
217    }
218    pub fn request(&self) -> &RetainedRequest {
219        &self.request
220    }
221}
222
223impl GeometryDocument {
224    /// Encodes and retains one captured authored extrusion. Refuses every
225    /// source the request encoding cannot represent exactly; see
226    /// [`RetainedRefusal`] and [`SweepPayload`] for the supported families.
227    pub fn add_retained_extrusion(
228        &mut self,
229        recipe: RetainedExtrusion,
230    ) -> Result<RetainedDefinitionHandle, RetainedRefusal> {
231        let payload = retained_sweep::lower(&recipe)?;
232        self.retain(RetainedRecipe::Extrusion(recipe), payload)
233    }
234
235    /// Encodes and retains one captured authored swept disk. Refuses every
236    /// source wire format 2 cannot represent exactly; see `retained_disk`'s
237    /// module documentation for the supported family.
238    pub fn add_retained_swept_disk(
239        &mut self,
240        recipe: RetainedSweptDisk,
241    ) -> Result<RetainedDefinitionHandle, RetainedRefusal> {
242        let payload = retained_disk::lower(&recipe)?;
243        self.retain(RetainedRecipe::SweptDisk(recipe), payload)
244    }
245
246    /// Retain a derived cutter in its own metre evaluation frame (#7955 CUT-0).
247    #[cfg(any(all(test, any(not(target_arch = "wasm32"), feature = "wasm_source_capture")), feature = "retained-runtime"))]
248    pub fn add_retained_prism(&mut self, recipe: super::RetainedPrism) -> Result<RetainedDefinitionHandle, RetainedRefusal> {
249        let payload = recipe.lower()?;
250        self.retain(RetainedRecipe::Prism(recipe), payload)
251    }
252
253    /// Retain one captured authored face set (#8291).
254    #[cfg(any(all(test, any(not(target_arch = "wasm32"), feature = "wasm_source_capture")), feature = "retained-runtime"))]
255    pub fn add_retained_face_set(&mut self, recipe: super::RetainedFaceSet) -> Result<RetainedDefinitionHandle, RetainedRefusal> {
256        let payload = recipe.lower()?;
257        self.retain(RetainedRecipe::FaceSet(recipe), payload)
258    }
259
260    fn retain(
261        &mut self,
262        recipe: RetainedRecipe,
263        payload: SweepPayload,
264    ) -> Result<RetainedDefinitionHandle, RetainedRefusal> {
265        let revision = self.next_revision()?;
266        let handle = RetainedDefinitionHandle {
267            document: self.id,
268            slot: self.retained.len(),
269        };
270        self.retained
271            .push(Arc::new(RetainedEntry { recipe, payload }));
272        self.revision = revision;
273        Ok(handle)
274    }
275
276    pub fn retained_recipe(
277        &self,
278        handle: RetainedDefinitionHandle,
279    ) -> Result<&RetainedRecipe, DocumentError> {
280        Ok(&self.retained_entry(handle)?.recipe)
281    }
282
283    pub fn retained_payload(
284        &self,
285        handle: RetainedDefinitionHandle,
286    ) -> Result<&SweepPayload, DocumentError> {
287        Ok(&self.retained_entry(handle)?.payload)
288    }
289
290    /// Snapshots `definition` for the worker incarnation the caller selected.
291    pub fn prepare_retained(
292        &self,
293        definition: RetainedDefinitionHandle,
294        worker_incarnation: u64,
295    ) -> Result<RetainedRequest, RetainedRefusal> {
296        if worker_incarnation == 0 {
297            return Err(RetainedRefusal::WrongWorker);
298        }
299        Ok(RetainedRequest {
300            document: self.id,
301            revision: self.revision,
302            definition,
303            worker_incarnation,
304            entry: Arc::clone(self.retained_entry(definition)?),
305        })
306    }
307
308    /// Host-trusted bookkeeping check, not origin authentication: the caller
309    /// states which worker incarnation it observes as live.
310    pub fn validate_retained_completion(
311        &self,
312        packet: &RetainedCompletion,
313        live_worker_incarnation: u64,
314    ) -> Result<(), RetainedRefusal> {
315        let request = &packet.request;
316        self.check_document(request.document)?;
317        if live_worker_incarnation == 0 || request.worker_incarnation != live_worker_incarnation {
318            return Err(RetainedRefusal::WrongWorker);
319        }
320        if request.revision != self.revision {
321            return Err(DocumentError::StaleRevision.into());
322        }
323        // Retained entries are immutable, so the revision check above also
324        // pins the request's recipe and payload.
325        let current = self.retained_entry(request.definition)?;
326        if packet.source_from_evaluation != current.payload.source_from_evaluation
327            || packet.evaluation_from_source != current.payload.evaluation_from_source
328        {
329            return Err(RetainedRefusal::FrameMismatch);
330        }
331        Ok(())
332    }
333
334    /// Deliberate, atomic retained -> display conversion. Validates the
335    /// completion, the display claim, the narrowed mesh, every occurrence
336    /// (row-major, evaluation frame -> caller's model frame) and the revision
337    /// budget before changing anything. The result is an ordinary display
338    /// definition attributed to the solid: a display approximation, never
339    /// authored geometry. Publishing advances the revision, so every other
340    /// outstanding request of this document becomes stale.
341    pub fn publish_retained_display(
342        &mut self,
343        packet: &RetainedCompletion,
344        live_worker_incarnation: u64,
345        contract: RetainedDisplayContract,
346        occurrences: &[(u32, [f64; 16])],
347    ) -> Result<(DefinitionHandle, Vec<OccurrenceHandle>), RetainedRefusal> {
348        match contract {
349            RetainedDisplayContract::UnstyledFlatSourceOnly => {}
350            RetainedDisplayContract::PersistentIfcFaces => {
351                return Err(RetainedRefusal::PersistentFaceProvenanceUnavailable)
352            }
353            RetainedDisplayContract::AnalyticSurfaceNormals => {
354                return Err(RetainedRefusal::AnalyticNormalsUnavailable)
355            }
356            RetainedDisplayContract::IfcAppearance => {
357                return Err(RetainedRefusal::IfcAppearanceUnavailable)
358            }
359        }
360        self.validate_retained_completion(packet, live_worker_incarnation)?;
361        let mesh = super::retained_display::display_mesh(&packet.tessellation)?;
362        validation::validate_mesh(&mesh)?;
363        for (_, transform) in occurrences {
364            validation::validate_transform(transform)?;
365        }
366        let additions = u64::try_from(occurrences.len())
367            .ok()
368            .and_then(|count| count.checked_add(1))
369            .ok_or(DocumentError::RevisionExhausted)?;
370        self.revision
371            .checked_add(additions)
372            .ok_or(DocumentError::RevisionExhausted)?;
373        let solid_id = packet.request.entry.recipe.solid_id();
374        let definition = self.add_mesh_definition(solid_id, mesh)?;
375        let mut handles = Vec::with_capacity(occurrences.len());
376        for &(entity_id, transform) in occurrences {
377            handles.push(self.add_occurrence(definition, entity_id, transform)?);
378        }
379        Ok((definition, handles))
380    }
381
382    fn retained_entry(
383        &self,
384        handle: RetainedDefinitionHandle,
385    ) -> Result<&Arc<RetainedEntry>, DocumentError> {
386        self.check_document(handle.document)?;
387        self.retained
388            .get(handle.slot)
389            .ok_or(DocumentError::WrongDocument)
390    }
391}
392
393#[cfg(test)]
394#[path = "retained_tests.rs"]
395mod tests;