Skip to main content

brep_kernel/brep/
solid_codec.rs

1//! Flat `f64` binary encoding of a `BrepSolid` for zero-JSON WASM transfer.
2//!
3//! Every numeric field of the topology (ids, flags, knots, weighted control
4//! points) is written into one `Vec<f64>` in a fixed traversal order; the
5//! only non-numeric payload — face/edge names — travels in a tiny JSON side
6//! channel keyed by entity id.  The decoder reads the same layout
7//! straight out of a `Float64Array`, replacing `JSON.parse` of megabyte-scale
8//! numeric text with sequential typed-array reads.
9//!
10//! Layout (all values f64):
11//!   header:  [VERSION, solid_id, genus, n_vertices, n_edges, n_shells]
12//!   vertex:  [id, x, y, z]
13//!   edge:    [id, t0, t1, start_vertex_id, end_vertex_id, degenerate] curve
14//!   shell:   [id, n_faces] face*
15//!   face:    [id, same_sense] surface [n_loops] loop*
16//!   loop:    [id, n_coedges] coedge*
17//!   coedge:  [id, edge_id, forward] pcurve
18//!   curve:   [degree, n_knots, knots..., n_control, (x, y, z, w)...]
19//!   surface: [degree_u, degree_v, n_knots_u, knots_u..., n_knots_v,
20//!             knots_v..., n_rows, n_columns, (x, y, z, w)... row-major]
21
22use crate::topology::{
23    BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord,
24};
25use crate::{NurbsCurve, NurbsSurface, Vec3, Vec4};
26use std::collections::BTreeMap;
27
28pub const SOLID_CODEC_VERSION: f64 = 1.0;
29
30/// Largest integer f64 represents exactly. Ids above this would silently
31/// round during encode (and the decoder's integrality check cannot detect
32/// it), corrupting edge/vertex cross-references.
33const MAX_EXACT_ID: u64 = 1 << 53;
34
35fn id_to_f64(id: u64) -> Result<f64, String> {
36    if id > MAX_EXACT_ID {
37        return Err(format!(
38            "solid codec: id {id} exceeds 2^53 and cannot round-trip through f64"
39        ));
40    }
41    Ok(id as f64)
42}
43
44#[derive(serde::Serialize, serde::Deserialize, Default, Debug)]
45pub struct SolidNames {
46    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
47    pub faces: BTreeMap<u64, String>,
48    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
49    pub edges: BTreeMap<u64, String>,
50}
51
52fn push_curve(data: &mut Vec<f64>, curve: &NurbsCurve) {
53    data.push(curve.degree as f64);
54    data.push(curve.knots.len() as f64);
55    data.extend_from_slice(&curve.knots);
56    data.push(curve.control_points.len() as f64);
57    for point in &curve.control_points {
58        data.extend_from_slice(&[point.x, point.y, point.z, point.w]);
59    }
60}
61
62fn push_surface(data: &mut Vec<f64>, surface: &NurbsSurface) {
63    data.push(surface.degree_u as f64);
64    data.push(surface.degree_v as f64);
65    data.push(surface.knots_u.len() as f64);
66    data.extend_from_slice(&surface.knots_u);
67    data.push(surface.knots_v.len() as f64);
68    data.extend_from_slice(&surface.knots_v);
69    data.push(surface.control_points.len() as f64);
70    data.push(surface.control_points[0].len() as f64);
71    for row in &surface.control_points {
72        for point in row {
73            data.extend_from_slice(&[point.x, point.y, point.z, point.w]);
74        }
75    }
76}
77
78pub fn encode_solid(solid: &BrepSolid) -> Result<(Vec<f64>, SolidNames), String> {
79    let mut names = SolidNames::default();
80    let mut data = Vec::with_capacity(4096);
81    data.extend_from_slice(&[
82        SOLID_CODEC_VERSION,
83        id_to_f64(solid.id)?,
84        solid.genus as f64,
85        solid.vertices.len() as f64,
86        solid.edges.len() as f64,
87        solid.shells.len() as f64,
88    ]);
89    for vertex in &solid.vertices {
90        data.extend_from_slice(&[
91            id_to_f64(vertex.id)?,
92            vertex.point.x,
93            vertex.point.y,
94            vertex.point.z,
95        ]);
96    }
97    for edge in &solid.edges {
98        data.extend_from_slice(&[
99            id_to_f64(edge.id)?,
100            edge.t0,
101            edge.t1,
102            id_to_f64(edge.start_vertex_id)?,
103            id_to_f64(edge.end_vertex_id)?,
104            if edge.degenerate { 1.0 } else { 0.0 },
105        ]);
106        push_curve(&mut data, &edge.curve);
107        if let Some(name) = &edge.name {
108            names.edges.insert(edge.id, name.clone());
109        }
110    }
111    for shell in &solid.shells {
112        data.push(id_to_f64(shell.id)?);
113        data.push(shell.faces.len() as f64);
114        for face in &shell.faces {
115            data.push(id_to_f64(face.id)?);
116            data.push(if face.same_sense { 1.0 } else { 0.0 });
117            push_surface(&mut data, &face.surface);
118            data.push(face.loops.len() as f64);
119            for loop_record in &face.loops {
120                data.push(id_to_f64(loop_record.id)?);
121                data.push(loop_record.coedges.len() as f64);
122                for coedge in &loop_record.coedges {
123                    data.extend_from_slice(&[
124                        id_to_f64(coedge.id)?,
125                        id_to_f64(coedge.edge_id)?,
126                        if coedge.forward { 1.0 } else { 0.0 },
127                    ]);
128                    push_curve(&mut data, &coedge.pcurve);
129                }
130            }
131            if let Some(name) = &face.name {
132                names.faces.insert(face.id, name.clone());
133            }
134        }
135    }
136    Ok((data, names))
137}
138
139struct Reader<'a> {
140    data: &'a [f64],
141    cursor: usize,
142}
143
144impl<'a> Reader<'a> {
145    fn next(&mut self) -> Result<f64, String> {
146        let value = *self
147            .data
148            .get(self.cursor)
149            .ok_or("solid codec: truncated buffer")?;
150        self.cursor += 1;
151        Ok(value)
152    }
153
154    fn next_usize(&mut self) -> Result<usize, String> {
155        let value = self.next()?;
156        if value < 0.0 || value.fract() != 0.0 {
157            return Err(format!("solid codec: expected count, got {value}"));
158        }
159        Ok(value as usize)
160    }
161
162    fn next_id(&mut self) -> Result<u64, String> {
163        let value = self.next()?;
164        if value < 0.0 || value.fract() != 0.0 || value > MAX_EXACT_ID as f64 {
165            return Err(format!("solid codec: expected id, got {value}"));
166        }
167        Ok(value as u64)
168    }
169
170    fn next_slice(&mut self, count: usize) -> Result<&'a [f64], String> {
171        // Checked: a corrupted count (up to 2^53 passes the integrality test)
172        // must fail as a truncation error, never wrap the cursor on 32-bit.
173        let end = self
174            .cursor
175            .checked_add(count)
176            .ok_or("solid codec: truncated buffer")?;
177        let slice = self
178            .data
179            .get(self.cursor..end)
180            .ok_or("solid codec: truncated buffer")?;
181        self.cursor = end;
182        Ok(slice)
183    }
184
185    fn curve(&mut self) -> Result<NurbsCurve, String> {
186        let degree = self.next_usize()?;
187        let knot_count = self.next_usize()?;
188        let knots = self.next_slice(knot_count)?.to_vec();
189        let control_count = self.next_usize()?;
190        let raw = self.next_slice(
191            control_count
192                .checked_mul(4)
193                .ok_or("solid codec: truncated buffer")?,
194        )?;
195        let control_points = raw
196            .chunks_exact(4)
197            .map(|chunk| Vec4 {
198                x: chunk[0],
199                y: chunk[1],
200                z: chunk[2],
201                w: chunk[3],
202            })
203            .collect();
204        NurbsCurve::new(degree, knots, control_points)
205    }
206
207    fn surface(&mut self) -> Result<NurbsSurface, String> {
208        let degree_u = self.next_usize()?;
209        let degree_v = self.next_usize()?;
210        let knots_u_count = self.next_usize()?;
211        let knots_u = self.next_slice(knots_u_count)?.to_vec();
212        let knots_v_count = self.next_usize()?;
213        let knots_v = self.next_slice(knots_v_count)?.to_vec();
214        let rows = self.next_usize()?;
215        let columns = self.next_usize()?;
216        // A zero dimension would make the chunks_exact below panic; no valid
217        // surface has an empty control net, so reject corrupted payloads here.
218        if rows == 0 || columns == 0 {
219            return Err("solid codec: surface with empty control net".into());
220        }
221        let raw = self.next_slice(
222            rows.checked_mul(columns)
223                .and_then(|cells| cells.checked_mul(4))
224                .ok_or("solid codec: truncated buffer")?,
225        )?;
226        let control_points = raw
227            .chunks_exact(columns * 4)
228            .map(|row| {
229                row.chunks_exact(4)
230                    .map(|chunk| Vec4 {
231                        x: chunk[0],
232                        y: chunk[1],
233                        z: chunk[2],
234                        w: chunk[3],
235                    })
236                    .collect()
237            })
238            .collect();
239        NurbsSurface::new(degree_u, degree_v, knots_u, knots_v, control_points)
240    }
241}
242
243pub fn decode_solid(data: &[f64], names: &SolidNames) -> Result<BrepSolid, String> {
244    let mut reader = Reader { data, cursor: 0 };
245    let version = reader.next()?;
246    if version != SOLID_CODEC_VERSION {
247        return Err(format!("solid codec: unsupported version {version}"));
248    }
249    let id = reader.next_id()?;
250    let genus = reader.next()? as i64;
251    let vertex_count = reader.next_usize()?;
252    let edge_count = reader.next_usize()?;
253    let shell_count = reader.next_usize()?;
254    let mut vertices = Vec::with_capacity(vertex_count);
255    for _ in 0..vertex_count {
256        vertices.push(VertexRecord {
257            id: reader.next_id()?,
258            point: Vec3::new(reader.next()?, reader.next()?, reader.next()?),
259        });
260    }
261    let mut edges = Vec::with_capacity(edge_count);
262    for _ in 0..edge_count {
263        let id = reader.next_id()?;
264        let t0 = reader.next()?;
265        let t1 = reader.next()?;
266        let start_vertex_id = reader.next_id()?;
267        let end_vertex_id = reader.next_id()?;
268        let degenerate = reader.next()? != 0.0;
269        let curve = reader.curve()?;
270        edges.push(EdgeRecord {
271            id,
272            curve,
273            t0,
274            t1,
275            start_vertex_id,
276            end_vertex_id,
277            degenerate,
278            name: names.edges.get(&id).cloned(),
279        });
280    }
281    let mut shells = Vec::with_capacity(shell_count);
282    for _ in 0..shell_count {
283        let shell_id = reader.next_id()?;
284        let face_count = reader.next_usize()?;
285        let mut faces = Vec::with_capacity(face_count);
286        for _ in 0..face_count {
287            let face_id = reader.next_id()?;
288            let same_sense = reader.next()? != 0.0;
289            let surface = reader.surface()?;
290            let loop_count = reader.next_usize()?;
291            let mut loops = Vec::with_capacity(loop_count);
292            for _ in 0..loop_count {
293                let loop_id = reader.next_id()?;
294                let coedge_count = reader.next_usize()?;
295                let mut coedges = Vec::with_capacity(coedge_count);
296                for _ in 0..coedge_count {
297                    let coedge_id = reader.next_id()?;
298                    let edge_id = reader.next_id()?;
299                    let forward = reader.next()? != 0.0;
300                    let pcurve = reader.curve()?;
301                    coedges.push(CoedgeRecord {
302                        id: coedge_id,
303                        edge_id,
304                        forward,
305                        pcurve,
306                    });
307                }
308                loops.push(LoopRecord {
309                    id: loop_id,
310                    coedges,
311                });
312            }
313            faces.push(FaceRecord {
314                id: face_id,
315                surface,
316                same_sense,
317                loops,
318                name: names.faces.get(&face_id).cloned(),
319            });
320        }
321        shells.push(ShellRecord {
322            id: shell_id,
323            faces,
324        });
325    }
326    if reader.cursor != data.len() {
327        return Err("solid codec: trailing data".into());
328    }
329    Ok(BrepSolid {
330        id,
331        vertices,
332        edges,
333        shells,
334        genus,
335    })
336}
337
338// BREP private tests: d2397960a07083f3