ifc_lite_geometry/document/
mod.rs

1// SPDX-License-Identifier: MPL-2.0
2
3//! Minimal geometry document: typed identity, revision and placed instances.
4//!
5//! Opt-in and off every default path: ordinary loads never construct a
6//! [`GeometryDocument`], and no existing IFC production output depends on it.
7//!
8//! What this contract is, exactly:
9//! - Definitions are object-local discrete meshes. Every admitted mesh is a
10//!   display approximation of whatever produced it, never authored geometry:
11//!   admission makes no claim of solid validity, exact source fidelity or
12//!   analytic provenance.
13//! - Occurrences place a definition with an f64 affine transform. Placements
14//!   are never baked into the definition's f32 buffers.
15//! - Handles resolve only in the document that minted them.
16//!
17//! - Retained definitions are captured authored extrusions or rational swept
18//!   disks plus their encoded worker request ([`RetainedRequest`]), kept apart
19//!   from display meshes. A worker completion becomes a mesh only through
20//!   [`GeometryDocument::publish_retained_display`], and then as an ordinary
21//!   display approximation. No execution runtime is part of this contract yet.
22//!
23//! Operations over definitions land with their first caller.
24
25mod retained;
26// Refs #7955: qualify the private receipt consumer.
27#[cfg(any(all(test, any(not(target_arch = "wasm32"), feature = "wasm_source_capture")), feature = "retained-runtime"))]
28#[cfg_attr(not(test), allow(dead_code))]
29pub(crate) mod retained_frames;
30// Refs #7955: qualify the private receipt consumer.
31#[cfg(any(all(test, any(not(target_arch = "wasm32"), feature = "wasm_source_capture")), feature = "retained-runtime"))]
32#[cfg_attr(not(test), allow(dead_code))]
33pub(crate) mod retained_affine;
34mod retained_disk;
35mod retained_display;
36mod retained_sweep;
37#[cfg(any(all(test, any(not(target_arch = "wasm32"), feature = "wasm_source_capture")), feature = "retained-runtime"))]
38mod retained_prism;
39#[cfg(any(all(test, any(not(target_arch = "wasm32"), feature = "wasm_source_capture")), feature = "retained-runtime"))]
40pub use retained_prism::{RetainedPrism, PrismRole, PrismLoop, PrismSegment};
41#[cfg(any(all(test, any(not(target_arch = "wasm32"), feature = "wasm_source_capture")), feature = "retained-runtime"))]
42mod retained_face_set;
43#[cfg(any(all(test, any(not(target_arch = "wasm32"), feature = "wasm_source_capture")), feature = "retained-runtime"))]
44pub use retained_face_set::RetainedFaceSet;
45#[cfg(any(all(test, any(not(target_arch = "wasm32"), feature = "wasm_source_capture")), feature = "retained-runtime"))]
46pub use crate::program::bounds::EvaluationBounds;
47mod types;
48mod validation;
49
50pub use retained::{
51    RetainedCompletion, RetainedDefinitionHandle, RetainedDisplayContract, RetainedExtrusion,
52    RetainedRecipe, RetainedRefusal, RetainedRequest, RetainedTessellation,
53};
54pub use retained_disk::RetainedSweptDisk;
55pub use retained_sweep::{RegionQualification, SweepPayload};
56pub use types::{DefinitionHandle, DocumentError, DocumentId, Occurrence, OccurrenceHandle};
57
58use crate::Mesh;
59use std::sync::atomic::{AtomicU64, Ordering};
60use std::sync::Arc;
61
62static NEXT_DOCUMENT: AtomicU64 = AtomicU64::new(1);
63
64#[derive(Debug)]
65struct Definition {
66    source_entity_id: u32,
67    mesh: Mesh,
68}
69
70/// Owns object-local mesh definitions and their placed occurrences for one
71/// loaded model. Every successful admission advances [`Self::revision`];
72/// every refusal leaves the document unchanged.
73#[derive(Debug)]
74pub struct GeometryDocument {
75    id: DocumentId,
76    revision: u64,
77    definitions: Vec<Definition>,
78    occurrences: Vec<Occurrence>,
79    retained: Vec<Arc<retained::RetainedEntry>>,
80}
81
82impl Default for GeometryDocument {
83    fn default() -> Self {
84        Self::new()
85    }
86}
87
88impl GeometryDocument {
89    /// A fresh empty document at revision 0 with a process-unique identity
90    /// (unique for the first 2^64 documents of a process).
91    pub fn new() -> Self {
92        Self {
93            id: DocumentId(NEXT_DOCUMENT.fetch_add(1, Ordering::Relaxed)),
94            revision: 0,
95            definitions: Vec::new(),
96            occurrences: Vec::new(),
97            retained: Vec::new(),
98        }
99    }
100
101    pub fn id(&self) -> DocumentId {
102        self.id
103    }
104
105    /// Number of successful admissions so far.
106    pub fn revision(&self) -> u64 {
107        self.revision
108    }
109
110    /// Takes ownership of an existing discrete mesh as an object-local display
111    /// approximation, attributed to `source_entity_id`.
112    ///
113    /// Refuses [`DocumentError::InvalidMesh`] for incomplete triples, non-finite
114    /// values, mismatched normals or out-of-range indices, and
115    /// [`DocumentError::UnsupportedFrame`] for a mesh carrying a non-zero
116    /// origin, an applied RTC offset, a placement or instancing metadata: the
117    /// caller must move that frame into an occurrence explicitly. Shape checks
118    /// only prevent malformed buffer access; no topology is qualified.
119    pub fn add_mesh_definition(
120        &mut self,
121        source_entity_id: u32,
122        mesh: Mesh,
123    ) -> Result<DefinitionHandle, DocumentError> {
124        validation::validate_mesh(&mesh)?;
125        let revision = self.next_revision()?;
126        let handle = DefinitionHandle {
127            document: self.id,
128            slot: self.definitions.len(),
129        };
130        self.definitions.push(Definition {
131            source_entity_id,
132            mesh,
133        });
134        self.revision = revision;
135        Ok(handle)
136    }
137
138    /// The admitted display mesh, borrowed from the document.
139    pub fn mesh(&self, handle: DefinitionHandle) -> Result<&Mesh, DocumentError> {
140        Ok(&self.definition(handle)?.mesh)
141    }
142
143    pub fn source_entity_id(&self, handle: DefinitionHandle) -> Result<u32, DocumentError> {
144        Ok(self.definition(handle)?.source_entity_id)
145    }
146
147    /// Places `definition` into the caller's model frame.
148    ///
149    /// Refuses [`DocumentError::WrongDocument`] for a foreign definition and
150    /// [`DocumentError::InvalidTransform`] for a non-finite, projective or
151    /// singular `local_to_model` (row-major).
152    pub fn add_occurrence(
153        &mut self,
154        definition: DefinitionHandle,
155        source_entity_id: u32,
156        local_to_model: [f64; 16],
157    ) -> Result<OccurrenceHandle, DocumentError> {
158        self.definition(definition)?;
159        validation::validate_transform(&local_to_model)?;
160        let revision = self.next_revision()?;
161        let handle = OccurrenceHandle {
162            document: self.id,
163            slot: self.occurrences.len(),
164        };
165        self.occurrences.push(Occurrence {
166            source_entity_id,
167            definition,
168            local_to_model,
169        });
170        self.revision = revision;
171        Ok(handle)
172    }
173
174    pub fn occurrence(&self, handle: OccurrenceHandle) -> Result<&Occurrence, DocumentError> {
175        self.check_document(handle.document)?;
176        // Same-document handles are minted in range and nothing is removed.
177        self.occurrences
178            .get(handle.slot)
179            .ok_or(DocumentError::WrongDocument)
180    }
181
182    fn definition(&self, handle: DefinitionHandle) -> Result<&Definition, DocumentError> {
183        self.check_document(handle.document)?;
184        self.definitions
185            .get(handle.slot)
186            .ok_or(DocumentError::WrongDocument)
187    }
188
189    fn check_document(&self, id: DocumentId) -> Result<(), DocumentError> {
190        if id == self.id {
191            Ok(())
192        } else {
193            Err(DocumentError::WrongDocument)
194        }
195    }
196
197    fn next_revision(&self) -> Result<u64, DocumentError> {
198        self.revision
199            .checked_add(1)
200            .ok_or(DocumentError::RevisionExhausted)
201    }
202}
203
204#[cfg(test)]
205#[path = "tests.rs"]
206mod tests;
207
208#[doc(hidden)]
209#[cfg(feature = "retained-runtime")]
210pub mod retained_wire;