1use crate::topology::{
29 BodyKind, BrepSolid, CellRecord, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord,
30 VertexRecord,
31};
32pub use crate::{NurbsCurve, NurbsSurface, Vec3, Vec4};
33use std::collections::BTreeMap;
34
35pub const SOLID_CODEC_VERSION: f64 = 1.0;
39pub const SOLID_CODEC_VERSION_KIND: f64 = 1.1;
41
42pub const MAX_EXACT_ID: u64 = 1 << 53;
46
47pub fn id_to_f64(id: u64) -> Result<f64, String> {
48 if id > MAX_EXACT_ID {
49 return Err(format!(
50 "solid codec: id {id} exceeds 2^53 and cannot round-trip through f64"
51 ));
52 }
53 Ok(id as f64)
54}
55
56#[derive(serde::Serialize, serde::Deserialize, Default, Debug)]
57pub struct SolidNames {
58 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
59 pub faces: BTreeMap<u64, String>,
60 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
61 pub edges: BTreeMap<u64, String>,
62 #[serde(default, skip_serializing_if = "std::collections::BTreeSet::is_empty")]
66 pub imported_edges: std::collections::BTreeSet<u64>,
67 #[serde(default, skip_serializing_if = "std::collections::BTreeSet::is_empty")]
69 pub imported_coedges: std::collections::BTreeSet<u64>,
70}
71
72fn push_curve(data: &mut Vec<f64>, curve: &NurbsCurve) {
73 data.push(curve.degree as f64);
74 data.push(curve.knots.len() as f64);
75 data.extend_from_slice(&curve.knots);
76 data.push(curve.control_points.len() as f64);
77 for point in &curve.control_points {
78 data.extend_from_slice(&[point.x, point.y, point.z, point.w]);
79 }
80}
81
82fn push_surface(data: &mut Vec<f64>, surface: &NurbsSurface) {
83 data.push(surface.degree_u as f64);
84 data.push(surface.degree_v as f64);
85 data.push(surface.knots_u.len() as f64);
86 data.extend_from_slice(&surface.knots_u);
87 data.push(surface.knots_v.len() as f64);
88 data.extend_from_slice(&surface.knots_v);
89 data.push(surface.control_points.len() as f64);
90 data.push(surface.control_points[0].len() as f64);
91 for row in &surface.control_points {
92 for point in row {
93 data.extend_from_slice(&[point.x, point.y, point.z, point.w]);
94 }
95 }
96}
97
98pub fn encode_solid(solid: &BrepSolid) -> Result<(Vec<f64>, SolidNames), String> {
99 if !solid.cells.is_empty() && solid.kind != BodyKind::Cellular {
100 return Err("solid codec: cells require declared Cellular kind".into());
101 }
102 let mut names = SolidNames::default();
103 let mut data = Vec::with_capacity(4096);
104 if solid.kind.is_solid() {
105 data.extend_from_slice(&[SOLID_CODEC_VERSION, id_to_f64(solid.id)?, solid.genus as f64]);
106 } else {
107 data.extend_from_slice(&[
108 SOLID_CODEC_VERSION_KIND,
109 id_to_f64(solid.id)?,
110 solid.genus as f64,
111 solid.kind.codec_code(),
112 ]);
113 }
114 data.extend_from_slice(&[
115 solid.vertices.len() as f64,
116 solid.edges.len() as f64,
117 solid.shells.len() as f64,
118 ]);
119 for vertex in &solid.vertices {
120 data.extend_from_slice(&[
121 id_to_f64(vertex.id)?,
122 vertex.point.x,
123 vertex.point.y,
124 vertex.point.z,
125 ]);
126 }
127 for edge in &solid.edges {
128 data.extend_from_slice(&[
129 id_to_f64(edge.id)?,
130 edge.t0,
131 edge.t1,
132 id_to_f64(edge.start_vertex_id)?,
133 id_to_f64(edge.end_vertex_id)?,
134 if edge.degenerate { 1.0 } else { 0.0 },
135 ]);
136 push_curve(&mut data, &edge.curve);
137 if edge.curve.is_imported() {
138 names.imported_edges.insert(edge.id);
139 }
140 if let Some(name) = &edge.name {
141 names.edges.insert(edge.id, name.clone());
142 }
143 }
144 for shell in &solid.shells {
145 data.push(id_to_f64(shell.id)?);
146 data.push(shell.faces.len() as f64);
147 for face in &shell.faces {
148 data.push(id_to_f64(face.id)?);
149 data.push(if face.same_sense { 1.0 } else { 0.0 });
150 push_surface(&mut data, &face.surface);
151 data.push(face.loops.len() as f64);
152 for loop_record in &face.loops {
153 data.push(id_to_f64(loop_record.id)?);
154 data.push(loop_record.coedges.len() as f64);
155 for coedge in &loop_record.coedges {
156 data.extend_from_slice(&[
157 id_to_f64(coedge.id)?,
158 id_to_f64(coedge.edge_id)?,
159 if coedge.forward { 1.0 } else { 0.0 },
160 ]);
161 push_curve(&mut data, &coedge.pcurve);
162 if coedge.pcurve.is_imported() {
163 names.imported_coedges.insert(coedge.id);
164 }
165 }
166 }
167 if let Some(name) = &face.name {
168 names.faces.insert(face.id, name.clone());
169 }
170 }
171 }
172 if !solid.cells.is_empty() {
175 data.push(solid.cells.len() as f64);
176 for cell in &solid.cells {
177 data.extend_from_slice(&[id_to_f64(cell.id)?, if cell.void { 1.0 } else { 0.0 },
178 cell.faces.len() as f64]);
179 for &(face, forward) in &cell.faces {
180 data.extend_from_slice(&[id_to_f64(face)?, if forward { 1.0 } else { 0.0 }]);
181 }
182 }
183 }
184 Ok((data, names))
185}
186
187struct Reader<'a> {
188 data: &'a [f64],
189 cursor: usize,
190}
191
192impl<'a> Reader<'a> {
193 fn next(&mut self) -> Result<f64, String> {
194 let value = *self
195 .data
196 .get(self.cursor)
197 .ok_or("solid codec: truncated buffer")?;
198 self.cursor += 1;
199 Ok(value)
200 }
201
202 fn next_usize(&mut self) -> Result<usize, String> {
203 let value = self.next()?;
204 if value < 0.0 || value.fract() != 0.0 {
205 return Err(format!("solid codec: expected count, got {value}"));
206 }
207 Ok(value as usize)
208 }
209
210 fn next_id(&mut self) -> Result<u64, String> {
211 let value = self.next()?;
212 if value < 0.0 || value.fract() != 0.0 || value > MAX_EXACT_ID as f64 {
213 return Err(format!("solid codec: expected id, got {value}"));
214 }
215 Ok(value as u64)
216 }
217
218 fn next_slice(&mut self, count: usize) -> Result<&'a [f64], String> {
219 let end = self
222 .cursor
223 .checked_add(count)
224 .ok_or("solid codec: truncated buffer")?;
225 let slice = self
226 .data
227 .get(self.cursor..end)
228 .ok_or("solid codec: truncated buffer")?;
229 self.cursor = end;
230 Ok(slice)
231 }
232
233 fn curve(&mut self) -> Result<NurbsCurve, String> {
234 let degree = self.next_usize()?;
235 let knot_count = self.next_usize()?;
236 let knots = self.next_slice(knot_count)?.to_vec();
237 let control_count = self.next_usize()?;
238 let raw = self.next_slice(
239 control_count
240 .checked_mul(4)
241 .ok_or("solid codec: truncated buffer")?,
242 )?;
243 let control_points = raw
244 .chunks_exact(4)
245 .map(|chunk| Vec4 {
246 x: chunk[0],
247 y: chunk[1],
248 z: chunk[2],
249 w: chunk[3],
250 })
251 .collect();
252 NurbsCurve::new(degree, knots, control_points)
253 }
254
255 fn surface(&mut self) -> Result<NurbsSurface, String> {
256 let degree_u = self.next_usize()?;
257 let degree_v = self.next_usize()?;
258 let knots_u_count = self.next_usize()?;
259 let knots_u = self.next_slice(knots_u_count)?.to_vec();
260 let knots_v_count = self.next_usize()?;
261 let knots_v = self.next_slice(knots_v_count)?.to_vec();
262 let rows = self.next_usize()?;
263 let columns = self.next_usize()?;
264 if rows == 0 || columns == 0 {
267 return Err("solid codec: surface with empty control net".into());
268 }
269 let raw = self.next_slice(
270 rows.checked_mul(columns)
271 .and_then(|cells| cells.checked_mul(4))
272 .ok_or("solid codec: truncated buffer")?,
273 )?;
274 let control_points = raw
275 .chunks_exact(columns * 4)
276 .map(|row| {
277 row.chunks_exact(4)
278 .map(|chunk| Vec4 {
279 x: chunk[0],
280 y: chunk[1],
281 z: chunk[2],
282 w: chunk[3],
283 })
284 .collect()
285 })
286 .collect();
287 NurbsSurface::new(degree_u, degree_v, knots_u, knots_v, control_points)
288 }
289}
290
291pub fn decode_solid(data: &[f64], names: &SolidNames) -> Result<BrepSolid, String> {
292 let mut reader = Reader { data, cursor: 0 };
293 let version = reader.next()?;
294 if version != SOLID_CODEC_VERSION && version != SOLID_CODEC_VERSION_KIND {
295 return Err(format!("solid codec: unsupported version {version}"));
296 }
297 let id = reader.next_id()?;
298 let genus = reader.next()? as i64;
299 let kind = if version == SOLID_CODEC_VERSION_KIND {
300 let code = reader.next()?;
301 BodyKind::from_codec_code(code)
302 .ok_or_else(|| format!("solid codec: unknown body kind {code}"))?
303 } else {
304 BodyKind::Solid
305 };
306 let vertex_count = reader.next_usize()?;
307 let edge_count = reader.next_usize()?;
308 let shell_count = reader.next_usize()?;
309 let mut vertices = Vec::with_capacity(vertex_count);
310 for _ in 0..vertex_count {
311 vertices.push(VertexRecord {
312 id: reader.next_id()?,
313 point: Vec3::new(reader.next()?, reader.next()?, reader.next()?),
314 });
315 }
316 let mut edges = Vec::with_capacity(edge_count);
317 for _ in 0..edge_count {
318 let id = reader.next_id()?;
319 let t0 = reader.next()?;
320 let t1 = reader.next()?;
321 let start_vertex_id = reader.next_id()?;
322 let end_vertex_id = reader.next_id()?;
323 let degenerate = reader.next()? != 0.0;
324 let mut curve = reader.curve()?;
325 curve.set_imported(names.imported_edges.contains(&id));
326 edges.push(EdgeRecord {
327 id,
328 curve,
329 t0,
330 t1,
331 start_vertex_id,
332 end_vertex_id,
333 degenerate,
334 name: names.edges.get(&id).cloned(),
335 });
336 }
337 let mut shells = Vec::with_capacity(shell_count);
338 for _ in 0..shell_count {
339 let shell_id = reader.next_id()?;
340 let face_count = reader.next_usize()?;
341 let mut faces = Vec::with_capacity(face_count);
342 for _ in 0..face_count {
343 let face_id = reader.next_id()?;
344 let same_sense = reader.next()? != 0.0;
345 let surface = reader.surface()?;
346 let loop_count = reader.next_usize()?;
347 let mut loops = Vec::with_capacity(loop_count);
348 for _ in 0..loop_count {
349 let loop_id = reader.next_id()?;
350 let coedge_count = reader.next_usize()?;
351 let mut coedges = Vec::with_capacity(coedge_count);
352 for _ in 0..coedge_count {
353 let coedge_id = reader.next_id()?;
354 let edge_id = reader.next_id()?;
355 let forward = reader.next()? != 0.0;
356 let mut pcurve = reader.curve()?;
357 pcurve.set_imported(names.imported_coedges.contains(&coedge_id));
358 coedges.push(CoedgeRecord {
359 id: coedge_id,
360 edge_id,
361 forward,
362 pcurve,
363 });
364 }
365 loops.push(LoopRecord {
366 id: loop_id,
367 coedges,
368 });
369 }
370 faces.push(FaceRecord {
371 id: face_id,
372 surface,
373 same_sense,
374 loops,
375 name: names.faces.get(&face_id).cloned(),
376 });
377 }
378 shells.push(ShellRecord {
379 id: shell_id,
380 faces,
381 });
382 }
383 let mut cells = Vec::new();
384 if kind == BodyKind::Cellular && reader.cursor < data.len() {
385 let count = reader.next_usize()?;
386 if count == 0 || count > (data.len()-reader.cursor)/3 {
387 return Err("solid codec: invalid cell count".into());
388 }
389 for _ in 0..count {
390 let id = reader.next_id()?;
391 let void = match reader.next()? {
392 0.0 => false, 1.0 => true,
393 _ => return Err("solid codec: invalid cell void flag".into()),
394 };
395 let face_count = reader.next_usize()?;
396 if face_count > (data.len()-reader.cursor)/2 {
397 return Err("solid codec: truncated cell faces".into());
398 }
399 let mut faces = Vec::with_capacity(face_count);
400 for _ in 0..face_count {
401 let face = reader.next_id()?;
402 let forward = match reader.next()? {
403 0.0 => false, 1.0 => true,
404 _ => return Err("solid codec: invalid cell face sense".into()),
405 };
406 faces.push((face, forward));
407 }
408 cells.push(CellRecord { id, faces, void });
409 }
410 }
411 if reader.cursor != data.len() {
412 return Err("solid codec: trailing data".into());
413 }
414 Ok(BrepSolid {
415 mass_properties_cache: Default::default(),
416 id,
417 vertices,
418 edges,
419 shells,
420 genus,
421 kind,
422 cells,
423 })
424}