ifc_lite_geometry_runtime/
worker_affine.rs1use super::dependencies::MAX_OPERATIONS;
8use super::{BrepHandle, RetainedDependencyResult, RetainedLineage, RetainedRealization};
9use super::{SmlibWorker, WorkerError};
10use crate::protocol::KernelCommand;
11use std::sync::atomic::{AtomicBool, Ordering};
12use std::sync::Arc;
13
14const AFFINE_COPY: u32 = 16;
16const REPLY_BYTES: usize = 16 + 4 * 14;
18const MAX_CLASS_OBJECTS: u64 = 100_000;
20
21#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct AffineCertificate {
27 source_classes: [u32; 12],
28}
29
30impl AffineCertificate {
31 pub fn source_classes(&self) -> &[u32; 12] {
32 &self.source_classes
33 }
34 pub fn representation(&self) -> &'static str {
36 "generic-rational-brep-v1"
37 }
38 fn decode(bytes: &[u8]) -> Result<Self, &'static str> {
39 let word =
40 |i: usize| u32::from_le_bytes([bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3]]);
41 if bytes.len() != 56 || word(0) != 1 || word(4) != 1 {
42 return Err("invalid affine conversion certificate");
43 }
44 let source_classes: [u32; 12] = std::array::from_fn(|i| word(8 + 4 * i));
45 let total = |classes: &[u32]| classes.iter().map(|&n| u64::from(n)).sum::<u64>();
46 if total(&source_classes[..6]) > MAX_CLASS_OBJECTS
47 || total(&source_classes[6..]) > MAX_CLASS_OBJECTS
48 {
49 return Err("affine certificate exceeds class budget");
50 }
51 Ok(Self { source_classes })
52 }
53}
54
55fn validate_affine(m: &[f64; 16]) -> Result<(), &'static str> {
58 if !m.iter().all(|x| x.is_finite() && x.abs() <= 1e9)
59 || m[3] != 0.
60 || m[7] != 0.
61 || m[11] != 0.
62 || m[15] != 1.
63 {
64 return Err("expected a finite bounded affine matrix");
65 }
66 let det = m[0] * (m[5] * m[10] - m[9] * m[6]) - m[4] * (m[1] * m[10] - m[9] * m[2])
67 + m[8] * (m[1] * m[6] - m[5] * m[2]);
68 if det == 0. {
69 return Err("singular affine matrix");
70 }
71 Ok(())
72}
73
74pub enum RetainedTransformInput<'a> {
77 Source(&'a RetainedRealization),
78 Result(&'a RetainedDependencyResult),
79 Affine(&'a RetainedAffineCopy),
80}
81
82type Input = (BrepHandle, Arc<RetainedLineage>, usize);
83
84impl RetainedTransformInput<'_> {
85 fn parts(&self) -> Result<Input, WorkerError> {
86 match self {
87 Self::Source(source) => {
88 source.validate_live()?;
89 let completion = source.completion();
90 let lineage = RetainedLineage::Definition {
91 request: Box::new(completion.request().clone()),
92 source_from_evaluation: completion.source_from_evaluation,
93 evaluation_from_source: completion.evaluation_from_source,
94 };
95 Ok((source.solid(), Arc::new(lineage), 0))
96 }
97 Self::Result(result) => result.parts(),
98 Self::Affine(copy) => copy.parts(),
99 }
100 }
101}
102
103#[derive(Debug, Clone, PartialEq)]
105pub struct AffineCopyIdentity {
106 pub input: BrepHandle,
107 pub column_major: [f64; 16],
108 pub certificate: AffineCertificate,
109}
110
111#[derive(Debug)]
115pub struct RetainedAffineCopy {
116 solid: BrepHandle,
117 owner: crate::RuntimeOwner,
118 _lease: Arc<super::objects::ManagedObjectLease>,
119 object_live: Arc<AtomicBool>,
120 identity: AffineCopyIdentity,
121 lineage: Arc<RetainedLineage>,
122 operations: usize,
123}
124
125impl RetainedAffineCopy {
126 pub fn solid(&self) -> BrepHandle {
127 self.solid
128 }
129 pub fn operation_identity(&self) -> &AffineCopyIdentity {
130 &self.identity
131 }
132 pub fn lineage(&self) -> &RetainedLineage {
134 &self.lineage
135 }
136 pub fn owner(&self) -> &crate::RuntimeOwner {
137 &self.owner
138 }
139 pub fn validate_live(&self) -> Result<(), WorkerError> {
141 if self.owner.incarnation() == Some(self.solid.worker)
142 && self.object_live.load(Ordering::Acquire)
143 {
144 Ok(())
145 } else {
146 Err(WorkerError::WrongWorker)
147 }
148 }
149 pub(super) fn parts(&self) -> Result<Input, WorkerError> {
150 self.validate_live()?;
151 Ok((self.solid, self.lineage.clone(), self.operations))
152 }
153}
154
155impl SmlibWorker {
156 pub fn copy_retained_affine(
161 &mut self,
162 input: RetainedTransformInput<'_>,
163 column_major: [f64; 16],
164 ) -> Result<RetainedAffineCopy, WorkerError> {
165 validate_affine(&column_major).map_err(WorkerError::InvalidArgument)?;
166 let (source, lineage, count) = input.parts()?;
167 self.object_liveness(source)?;
168 let operations = count
169 .checked_add(1)
170 .filter(|&n| n <= MAX_OPERATIONS)
171 .ok_or(WorkerError::ResourceLimit("retained operation depth"))?;
172 if self.capabilities()? & AFFINE_COPY == 0 {
173 return Err(WorkerError::Protocol(
174 "affine rational copy extension unavailable",
175 ));
176 }
177 let solid = self.wire(source)?;
178 let bytes = self.call(KernelCommand::CopyAffine {
179 session: self.session,
180 solid,
181 column_major,
182 })?;
183 if bytes.len() != REPLY_BYTES {
184 return Err(self.poison("invalid affine copy reply size"));
185 }
186 let certificate = AffineCertificate::decode(&bytes[16..]).map_err(|e| self.poison(e))?;
187 let solid = self.handle(bytes[..16].to_vec())?;
188 Ok(RetainedAffineCopy {
189 _lease: self.manage_object(solid)?,
190 object_live: self.object_liveness(solid)?,
191 owner: self.retained_owner(),
192 solid,
193 identity: AffineCopyIdentity {
194 input: source,
195 column_major,
196 certificate: certificate.clone(),
197 },
198 lineage: Arc::new(RetainedLineage::AffineCopy {
199 input: lineage,
200 column_major,
201 certificate,
202 }),
203 operations,
204 })
205 }
206}
207
208#[cfg(test)]
209#[path = "worker_affine_tests.rs"]
210mod tests;