ifc_lite_imported_geometry/
scene.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
5//! Ordered, source-independent imported operation owner. Source composition and
6//! codecs supply definitions; this owner issues work and accepts only its own
7//! outstanding operation. No decoder, source callback or borrowed buffer survives
8//! admission. The original f64 source remains alongside assembled display data.
9
10use std::collections::{HashSet, VecDeque};
11use crate::{assemble, execute, plan, ExecutedOperation, ImportError, ImportedAssembly,
12    ImportedDefinition, ImportedOutput, ImportedSource, ReadyOperation};
13
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub enum SceneError {
16    IdentityMismatch,
17    DuplicateOccurrence,
18    OperationPending,
19    NoOperationPending,
20    Incomplete,
21    Failed(ImportError),
22}
23
24impl std::fmt::Display for SceneError {
25    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26        match self {
27            Self::IdentityMismatch => f.write_str("Imported scene: stale store, revision or operation"),
28            Self::DuplicateOccurrence => f.write_str("Imported scene: duplicate occurrence identity"),
29            Self::OperationPending => f.write_str("Imported scene: an operation is already pending"),
30            Self::NoOperationPending => f.write_str("Imported scene: no operation is pending"),
31            Self::Incomplete => f.write_str("Imported scene: assembly is incomplete"),
32            Self::Failed(error) => error.fmt(f),
33        }
34    }
35}
36impl std::error::Error for SceneError {}
37
38/// All output is held until successful completion; an error cannot publish a
39/// partially imported scene. Native and generated hosts use the same owner.
40#[derive(Debug)]
41pub struct ImportedGeometryProgram {
42    store: u64,
43    revision: u64,
44    definitions: VecDeque<ImportedDefinition>,
45    pending: Option<ReadyOperation>,
46    assemblies: Vec<ImportedAssembly>,
47    failure: Option<ImportError>,
48}
49
50impl ImportedGeometryProgram {
51    pub fn new(store: u64, revision: u64, definitions: Vec<ImportedDefinition>) -> Result<Self, SceneError> {
52        let mut occurrences = HashSet::new();
53        for definition in &definitions {
54            let identity = definition.identity;
55            if identity.store != store || identity.revision != revision {
56                return Err(SceneError::IdentityMismatch);
57            }
58            // One definition may be reached by multiple real traversal edges.
59            // Occurrence identity, rather than definition identity, is unique.
60            if !occurrences.insert(identity.occurrence) {
61                return Err(SceneError::DuplicateOccurrence);
62            }
63        }
64        Ok(Self { store, revision, definitions: definitions.into(), pending: None,
65            assemblies: Vec::new(), failure: None })
66    }
67
68    pub fn single(definition: ImportedDefinition) -> Self {
69        Self { store: definition.identity.store, revision: definition.identity.revision,
70            definitions: VecDeque::from([definition]), pending: None,
71            assemblies: Vec::new(), failure: None }
72    }
73
74    /// The owner keeps the Ready alive. A caller can execute it after releasing
75    /// all format-adapter buffers; completion never accepts caller-supplied source.
76    pub fn next_operation(&mut self) -> Result<Option<&ReadyOperation>, SceneError> {
77        self.check_failure()?;
78        if self.pending.is_some() { return Err(SceneError::OperationPending); }
79        self.pending = self.definitions.pop_front().map(plan);
80        Ok(self.pending.as_ref())
81    }
82
83    /// A stale/foreign completion is refused without consuming the issued work.
84    /// Variant matching prevents a points result replacing an admitted mesh.
85    pub fn complete(&mut self, executed: ExecutedOperation) -> Result<(), SceneError> {
86        self.check_failure()?;
87        let pending = self.pending.as_ref().ok_or(SceneError::NoOperationPending)?;
88        if !std::sync::Arc::ptr_eq(&pending.seal, &executed.seal) { return Err(SceneError::IdentityMismatch); }
89        let identity = pending.definition.identity;
90        if executed.identity != identity || identity.store != self.store || identity.revision != self.revision {
91            return Err(SceneError::IdentityMismatch);
92        }
93        let same_kind = matches!((&pending.definition.source, &executed.output),
94            (ImportedSource::Mesh(_), ImportedOutput::Mesh(_)) |
95            (ImportedSource::Points(_), ImportedOutput::Points(_)));
96        if !same_kind { return Err(SceneError::IdentityMismatch); }
97        let pending = self.pending.take().ok_or(SceneError::NoOperationPending)?;
98        self.assemblies.push(assemble(pending, executed).map_err(SceneError::Failed)?);
99        Ok(())
100    }
101
102    pub fn fail(&mut self, error: ImportError) {
103        if self.failure.is_none() { self.failure = Some(error); }
104        self.pending = None;
105        self.definitions.clear();
106        self.assemblies.clear();
107    }
108
109    pub fn finish(self) -> Result<Vec<ImportedAssembly>, SceneError> {
110        self.check_failure()?;
111        if self.pending.is_some() || !self.definitions.is_empty() { return Err(SceneError::Incomplete); }
112        Ok(self.assemblies)
113    }
114
115    fn check_failure(&self) -> Result<(), SceneError> {
116        match &self.failure {
117            Some(error) => Err(SceneError::Failed(error.clone())),
118            None => Ok(()),
119        }
120    }
121}
122
123/// Packet and native entry share the actual plan/execute/complete path.
124pub fn evaluate(definition: ImportedDefinition) -> Result<ImportedAssembly, ImportError> {
125    let mut program = ImportedGeometryProgram::single(definition);
126    let ready = program.next_operation().map_err(|_| ImportError::IdentityMismatch)?
127        .ok_or(ImportError::IdentityMismatch)?;
128    let result = execute(ready)?;
129    program.complete(result).map_err(|_| ImportError::IdentityMismatch)?;
130    program.finish().map_err(|_| ImportError::IdentityMismatch)?
131        .pop().ok_or(ImportError::IdentityMismatch)
132}
133
134#[cfg(test)]
135#[path = "scene_tests.rs"]
136mod tests;