Skip to main content

brep_kernel/io/parasolid/
to_xt.rs

1//! Kernel solids to a Parasolid text part (`.x_t`): the export.
2//!
3//! The part is written in Parasolid V30.1's schema (`SCH_3001168_30100`) with
4//! its layouts described as embedded schema deltas against the base, exactly
5//! as Parasolid 30.1 writes them (the 152,096 ABC part files; every one of the
6//! 2000-file sample is written back byte for byte by [`super::writer`]).
7//! Parasolid V30 and later read the layouts natively; V14 and later read them
8//! through the deltas (§2.1.2, which promises older versions no more than
9//! that).
10//!
11//! The topology is the reference's for a manifold solid (§4.3, §5.3): an
12//! infinite void region and a solid region for each lump (and a void region
13//! for each cavity), a shell per region side, faces chained as back faces of their
14//! solid region's shell and front faces of the void region's, a loop per
15//! boundary, and two fins per edge, the positive one running with the edge
16//! and pointing at its end vertex. Geometry is exact: analytic carriers the
17//! kernel recognises as planes, cylinders, cones, spheres and tori are
18//! written as such, lines and circular arcs as lines and circles, everything
19//! else as the kernel's own B-surfaces and B-curves. Lengths are metres.
20
21use std::rc::Rc;
22
23use rustc_hash::FxHashMap as HashMap;
24
25use crate::analytic_surface::AnalyticSurface;
26use crate::topology::BrepSolid;
27use crate::{NurbsCurve, NurbsSurface, Vec3};
28
29use super::geometry::MM_PER_METRE;
30use super::reader::{Node, NodeLayout, Value};
31use super::schema::{self, Count, Kind};
32use super::writer::{records, Tokens};
33
34/// The schema the part is written in, and the version that wrote it.
35const SCHEMA: &str = "SCH_3001168_30100_13006";
36const MODELLER: &str = ": TRANSMIT FILE created by modeller version 3001168";
37/// The largest node type schema 30100 has (as its writers state it).
38const MAX_NODE_TYPE: i64 = 214;
39
40/// One body to export, with what the importer reads back as its name and
41/// colour.
42pub struct XtExportBody<'a> {
43    pub solid: &'a BrepSolid,
44    pub name: Option<&'a str>,
45    /// RGB in 0..1.
46    pub color: Option<[f64; 3]>,
47}
48
49/// What an export wrote, and how exact its edges are.
50#[derive(Clone, Debug, Default)]
51pub struct XtExportReport {
52    pub text: String,
53    pub edges: usize,
54    /// Edges some point of which lies further from one of its faces than
55    /// Parasolid's linear resolution (1e-8 m): written as accurate edges
56    /// all the same (see the module doc).
57    pub edges_over_resolution: usize,
58    /// The furthest any edge lies from one of its faces, in mm.
59    pub worst_edge_mm: f64,
60}
61
62/// Parasolid's linear resolution, in mm.
63const RESOLUTION_MM: f64 = 1e-5;
64
65/// Write `bodies` as a Parasolid text part: one body as the root, or several
66/// listed by a POINTER_LIS_BLOCK root (§2.1, §5.4.2).
67pub fn export_parasolid_text(bodies: &[XtExportBody], application: &str) -> Result<String, String> {
68    export_parasolid_report(bodies, application).map(|r| r.text)
69}
70
71/// [`export_parasolid_text`] with how far the edges written lie from their
72/// faces.
73pub fn export_parasolid_report(bodies: &[XtExportBody], application: &str) -> Result<XtExportReport, String> {
74    export(bodies, application, false)
75}
76
77/// The same part as a neutral binary file (`.x_b`): the keyword header in
78/// text (with FORMAT=binary), then the part data in neutral binary (§3.3.3).
79/// `text` holds the bytes, which are not UTF-8: use [`export_parasolid_binary`].
80pub fn export_parasolid_binary(bodies: &[XtExportBody], application: &str) -> Result<Vec<u8>, String> {
81    let (_, bytes) = build(bodies, application, true)?;
82    Ok(bytes)
83}
84
85fn export(bodies: &[XtExportBody], application: &str, binary: bool) -> Result<XtExportReport, String> {
86    let (text, _) = build(bodies, application, binary)?;
87    let mut report = XtExportReport { text, ..Default::default() };
88    for body in bodies {
89        let (edges, over, worst) = edge_deviation(body.solid);
90        report.edges += edges;
91        report.edges_over_resolution += over;
92        report.worst_edge_mm = report.worst_edge_mm.max(worst);
93    }
94    Ok(report)
95}
96
97/// The part as text, or (when `binary`) as bytes.
98fn build(bodies: &[XtExportBody], application: &str, binary: bool) -> Result<(String, Vec<u8>), String> {
99    if bodies.is_empty() {
100        return Err("export_parasolid: nothing to export".into());
101    }
102    let mut b = Builder::default();
103    let root = if bodies.len() == 1 { None } else { Some(b.reserve()) };
104    let mut body_indices = Vec::new();
105    for (k, body) in bodies.iter().enumerate() {
106        let index = b.body(body).map_err(|e| format!("export_parasolid: body {}: {e}", k + 1))?;
107        body_indices.push(index);
108    }
109    if let Some(root) = root {
110        b.pointer_list(root, &body_indices)?;
111    }
112    // Node ids are distinct across the file, so every body's highest is the
113    // file's.
114    let highest = b.next_id;
115    for &body in &body_indices {
116        b.set(body, "highest_node_id", int(highest))?;
117    }
118    let first = root.unwrap_or(body_indices[0]);
119    let mut order: Vec<u32> = b.nodes.keys().copied().filter(|&i| i != first).collect();
120    order.sort_unstable();
121    order.insert(0, first);
122    let mut described = rustc_hash::FxHashSet::default();
123    if binary {
124        let mut tokens = super::writer::BinaryTokens::default();
125        tokens.prologue(MODELLER, SCHEMA, Some(MAX_NODE_TYPE), 0)?;
126        for index in order {
127            let node = &b.nodes[&index];
128            let describe = described.insert(node.node_type());
129            tokens.node(node, describe, 0)?;
130        }
131        tokens.terminator()?;
132        let mut bytes = header(application, "binary").into_bytes();
133        bytes.extend(tokens.data);
134        return Ok((String::new(), bytes));
135    }
136    let mut tokens = Tokens::default();
137    tokens.data.push('T');
138    tokens.string(MODELLER);
139    tokens.string(SCHEMA);
140    tokens.int(Some(MAX_NODE_TYPE));
141    tokens.int(Some(0));
142    for index in order {
143        let node = &b.nodes[&index];
144        let describe = described.insert(node.node_type());
145        tokens.node(node, describe, 0)?;
146    }
147    tokens.int(Some(1));
148    tokens.int(Some(0));
149    Ok((format!("{}{}", header(application, "text"), records(&tokens.data)), Vec::new()))
150}
151
152/// For each non-degenerate edge, the largest distance of nine points along
153/// it from the surfaces of the faces that use it: (edges, edges over the
154/// resolution, worst in mm).
155fn edge_deviation(solid: &BrepSolid) -> (usize, usize, f64) {
156    let deviations = edge_deviations(solid);
157    let over = deviations.values().filter(|&&d| d > RESOLUTION_MM).count();
158    let worst = deviations.values().copied().fold(0.0f64, f64::max);
159    (deviations.len(), over, worst)
160}
161
162/// Each non-degenerate edge's largest distance (mm) from the surfaces of the
163/// faces using it, over nine points along it.
164fn edge_deviations(solid: &BrepSolid) -> HashMap<u64, f64> {
165    let mut faces_of: HashMap<u64, Vec<&NurbsSurface>> = HashMap::default();
166    for shell in &solid.shells {
167        for face in &shell.faces {
168            for lp in &face.loops {
169                for c in &lp.coedges {
170                    faces_of.entry(c.edge_id).or_default().push(&face.surface);
171                }
172            }
173        }
174    }
175    let mut out = HashMap::default();
176    for edge in solid.edges.iter().filter(|e| !e.degenerate) {
177        let Some(surfaces) = faces_of.get(&edge.id) else { continue };
178        let Ok(curve) = brep_topology::edge_subcurve::edge_subcurve(edge) else { continue };
179        let Ok([a, b]) = curve.domain() else { continue };
180        let mut edge_worst = 0.0f64;
181        for k in 0..=8 {
182            let Ok(p) = curve.evaluate(a + (b - a) * k as f64 / 8.0) else { continue };
183            for surface in surfaces {
184                if let Ok(projection) = crate::project_point_to_surface(surface, p) {
185                    edge_worst = edge_worst.max(projection.point.sub(p).length());
186                }
187            }
188        }
189        out.insert(edge.id, edge_worst);
190    }
191    out
192}
193
194/// The keyword header (§3.1), as Parasolid writes it: a key a line.
195fn header(application: &str, format: &str) -> String {
196    let escape = |value: &str| {
197        let mut out = String::new();
198        for c in value.chars() {
199            match c {
200                '\n' => out.push_str("^n"),
201                ' ' => out.push_str("^-"),
202                ';' => out.push_str("^;"),
203                '^' => out.push_str("^^"),
204                c if c.is_ascii_graphic() => out.push(c),
205                _ => out.push('?'),
206            }
207        }
208        out
209    };
210    let mut out = String::new();
211    out.push_str("**ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz**************************\n");
212    out.push_str("**PARASOLID !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~0123456789**************************\n");
213    out.push_str("**PART1;\n");
214    for (key, value) in [
215        ("MC", "unknown"),
216        ("MC_MODEL", "unknown"),
217        ("MC_ID", "unknown"),
218        ("OS", "unknown"),
219        ("OS_RELEASE", "unknown"),
220        ("FRU", "BREP Parasolid writer"),
221        ("APPL", application),
222        ("SITE", "unknown"),
223        ("USER", "unknown"),
224        ("FORMAT", format),
225        ("GUISE", "transmit"),
226        ("KEY", "unknown"),
227        ("FILE", "unknown"),
228        ("DATE", "unknown"),
229    ] {
230        out.push_str(&format!("{key}={};\n", escape(value)));
231    }
232    out.push_str("**PART2;\n");
233    out.push_str(&format!("SCH={};\n", SCHEMA.trim_end_matches("_13006")));
234    out.push_str("USFLD_SIZE=0;\n");
235    out.push_str("**PART3;\n");
236    out.push_str("**END_OF_HEADER*****************************************************************\n");
237    out
238}
239
240#[derive(Default)]
241struct Builder {
242    nodes: HashMap<u32, Node>,
243    definitions: HashMap<String, u32>,
244    definition_order: Vec<u32>,
245    layouts: HashMap<u16, Rc<NodeLayout>>,
246    next_index: u32,
247    next_id: i64,
248}
249
250/// What a surface was written as, and whether its natural normal is the
251/// reverse of the kernel surface's.
252struct WrittenSurface {
253    index: u32,
254    flipped: bool,
255}
256
257impl Builder {
258    fn reserve(&mut self) -> u32 {
259        self.next_index += 1;
260        self.next_index
261    }
262
263    fn id(&mut self) -> i64 {
264        self.next_id += 1;
265        self.next_id
266    }
267
268    fn layout(&mut self, node_type: u16) -> Result<Rc<NodeLayout>, String> {
269        if let Some(layout) = self.layouts.get(&node_type) {
270            return Ok(layout.clone());
271        }
272        let mut layout = super::reader::stored_layout(schema::V30_SCHEMA, node_type)?;
273        layout.delta = schema::v30_delta(node_type).map(str::to_string);
274        let layout = Rc::new(layout);
275        self.layouts.insert(node_type, layout.clone());
276        Ok(layout)
277    }
278
279    /// Put a node of `node_type` at `index` with the named fields set; every
280    /// other field is a null pointer, zero, an unset real or vector.
281    fn put(&mut self, index: u32, node_type: u16, fields: Vec<(&str, Value)>) -> Result<(), String> {
282        let layout = self.layout(node_type)?;
283        let mut values: Vec<Value> = layout
284            .fields
285            .iter()
286            .map(|f| match (f.count, f.kind) {
287                (Count::Scalar, kind) => default_value(kind),
288                (Count::Fixed(n), kind) => Value::Array(vec![default_value(kind); n]),
289                (Count::Variable, Kind::Char) => Value::Text(String::new()),
290                (Count::Variable, _) => Value::Array(Vec::new()),
291            })
292            .collect();
293        for (name, value) in fields {
294            let at = layout
295                .fields
296                .iter()
297                .position(|f| f.name == name)
298                .ok_or_else(|| format!("{} has no field {name}", layout.name))?;
299            values[at] = value;
300        }
301        self.nodes.insert(index, Node { index, layout, values });
302        Ok(())
303    }
304
305    fn add(&mut self, node_type: u16, fields: Vec<(&str, Value)>) -> Result<u32, String> {
306        let index = self.reserve();
307        self.put(index, node_type, fields)?;
308        Ok(index)
309    }
310
311    fn set(&mut self, index: u32, name: &str, value: Value) -> Result<(), String> {
312        let node = self.nodes.get_mut(&index).ok_or_else(|| format!("node {index} is not written yet"))?;
313        let at = node
314            .layout
315            .fields
316            .iter()
317            .position(|f| f.name == name)
318            .ok_or_else(|| format!("{} has no field {name}", node.layout.name))?;
319        node.values[at] = value;
320        Ok(())
321    }
322
323    /// A POINTER_LIS_BLOCK root listing the bodies: blocks of 20 entries.
324    fn pointer_list(&mut self, root: u32, bodies: &[u32]) -> Result<(), String> {
325        let chunks: Vec<&[u32]> = bodies.chunks(20).collect();
326        let mut indices = vec![root];
327        for _ in 1..chunks.len() {
328            indices.push(self.reserve());
329        }
330        for (k, chunk) in chunks.iter().enumerate() {
331            let mut entries: Vec<Value> = chunk.iter().map(|&i| ptr(i)).collect();
332            entries.resize(20, ptr(0));
333            let next = indices.get(k + 1).copied().unwrap_or(0);
334            self.put(
335                indices[k],
336                74,
337                vec![
338                    ("n_entries", int(if k == 0 { bodies.len() as i64 } else { chunk.len() as i64 })),
339                    ("index_map_offset", int(0)),
340                    ("next_block", ptr(next)),
341                    ("entries", Value::Array(entries)),
342                ],
343            )?;
344        }
345        Ok(())
346    }
347
348    fn body(&mut self, export: &XtExportBody) -> Result<u32, String> {
349        let solid = export.solid;
350        if solid.kind != crate::BodyKind::Solid {
351            return Err(format!("a {:?} body is not exported yet; only solids are", solid.kind));
352        }
353        let body = self.reserve();
354        // Regions: the infinite void first (the body's region chain head),
355        // then for each lump its solid region and a void per cavity shell.
356        let Lumps { lumps, within } = lumps(solid)?;
357        let infinite = self.reserve();
358        let materials: Vec<u32> = lumps.iter().map(|_| self.reserve()).collect();
359        let cavity_regions: Vec<Vec<u32>> = lumps.iter().map(|(_, cavities)| cavities.iter().map(|_| self.reserve()).collect()).collect();
360        // Each kernel shell's lump, and its void side's region.
361        let mut material_of = vec![0u32; solid.shells.len()];
362        let mut void_of = vec![0u32; solid.shells.len()];
363        for (k, (outer, cavities)) in lumps.iter().enumerate() {
364            material_of[*outer] = materials[k];
365            void_of[*outer] = within[k].map_or(infinite, |(j, c)| cavity_regions[j][c]);
366            for (j, &c) in cavities.iter().enumerate() {
367                material_of[c] = materials[k];
368                void_of[c] = cavity_regions[k][j];
369            }
370        }
371        // A shell on each side of every kernel shell: its solid side in the
372        // solid region, its void side in the infinite void or its cavity.
373        let mut solid_shells = Vec::new();
374        let mut void_shells = Vec::new();
375        for s in 0..solid.shells.len() {
376            solid_shells.push(self.reserve());
377            void_shells.push(self.reserve());
378            let _ = s;
379        }
380        // Vertices and their points.
381        let mut vertex_index: HashMap<u64, u32> = HashMap::default();
382        let mut point_nodes = Vec::new();
383        for v in &solid.vertices {
384            let vertex = self.reserve();
385            let point = self.reserve();
386            vertex_index.insert(v.id, vertex);
387            point_nodes.push((vertex, point, v.point));
388        }
389        // Edges: only those some face's loop uses (degenerate pole edges
390        // are not edges in XT: the loop runs through the pole vertex).
391        let mut used: HashMap<u64, Vec<(u32, bool, u32)>> = HashMap::default(); // edge -> (fin, forward, loop)
392        let edges_by_id: HashMap<u64, &crate::topology::EdgeRecord> = solid.edges.iter().map(|e| (e.id, e)).collect();
393        // Edges further from their faces than the resolution are written
394        // tolerant (§5.3.11): no curve, a tolerance, and on each fin a
395        // trimmed SP-curve, the coedge's own curve in its face's parameters.
396        let tolerant: HashMap<u64, f64> = edge_deviations(solid)
397            .into_iter()
398            .filter(|&(_, d)| d > RESOLUTION_MM)
399            .map(|(id, d)| (id, (2.0 * d).max(10.0 * RESOLUTION_MM) / MM_PER_METRE))
400            .collect();
401        let vertex_points: HashMap<u64, Vec3> = solid.vertices.iter().map(|v| (v.id, v.point)).collect();
402        let mut vertex_tolerance: HashMap<u64, f64> = HashMap::default();
403        for e in &solid.edges {
404            if let Some(&t) = tolerant.get(&e.id) {
405                for v in [e.start_vertex_id, e.end_vertex_id] {
406                    let slot = vertex_tolerance.entry(v).or_insert(0.0);
407                    *slot = slot.max(t);
408                }
409            }
410        }
411        let mut sp_curves = Vec::new();
412        // Faces, loops and fins.
413        let mut face_records = Vec::new();
414        for (s, shell) in solid.shells.iter().enumerate() {
415            for face in &shell.faces {
416                let face_index = self.reserve();
417                // A face with a tolerant edge keeps the kernel's own surface,
418                // whose parameters its SP-curves are in.
419                let has_tolerant = face.loops.iter().flat_map(|l| &l.coedges).any(|c| tolerant.contains_key(&c.edge_id));
420                let surface = if has_tolerant {
421                    let index = self.reserve();
422                    let id = self.id();
423                    self.b_surface(&face.surface, index, vec![("node_id", int(id)), ("owner", ptr(face_index)), ("sense", Value::Char(b'+'))])?
424                } else {
425                    self.surface(&face.surface, face_index)?
426                };
427                let positive = face.same_sense != surface.flipped;
428                let mut loop_indices = Vec::new();
429                for lp in &face.loops {
430                    let coedges: Vec<&crate::topology::CoedgeRecord> = lp
431                        .coedges
432                        .iter()
433                        .filter(|c| edges_by_id.get(&c.edge_id).is_some_and(|e| !e.degenerate))
434                        .collect();
435                    let fins: Vec<(u64, bool)> = coedges.iter().map(|c| (c.edge_id, c.forward)).collect();
436                    if fins.is_empty() {
437                        continue;
438                    }
439                    let loop_index = self.reserve();
440                    let fin_indices: Vec<u32> = fins.iter().map(|_| self.reserve()).collect();
441                    for (k, &(edge_id, forward)) in fins.iter().enumerate() {
442                        used.entry(edge_id).or_default().push((fin_indices[k], forward, loop_index));
443                    }
444                    let id = self.id();
445                    self.put(loop_index, 15, vec![("node_id", int(id)), ("halfedge", ptr(fin_indices[0])), ("face", ptr(face_index))])?;
446                    for (k, &(edge_id, forward)) in fins.iter().enumerate() {
447                        let n = fin_indices.len();
448                        let edge = edges_by_id[&edge_id];
449                        let vertex_id = if forward { edge.end_vertex_id } else { edge.start_vertex_id };
450                        let vertex = *vertex_index.get(&vertex_id).ok_or_else(|| format!("edge {edge_id} has an unknown vertex"))?;
451                        let mut fields = vec![
452                            ("loop", ptr(loop_index)),
453                            ("forward", ptr(fin_indices[(k + 1) % n])),
454                            ("backward", ptr(fin_indices[(k + n - 1) % n])),
455                            ("vertex", ptr(vertex)),
456                            ("sense", Value::Char(if forward { b'+' } else { b'-' })),
457                        ];
458                        if tolerant.contains_key(&edge_id) {
459                            let start_id = if forward { edge.start_vertex_id } else { edge.end_vertex_id };
460                            let ends = (vertex_points[&start_id], vertex_points[&vertex_id]);
461                            let (trimmed, basis) = self.fin_curve(&coedges[k].pcurve, surface.index, fin_indices[k], body, ends)?;
462                            fields.push(("curve", ptr(trimmed)));
463                            sp_curves.push(basis);
464                            sp_curves.push(trimmed);
465                        }
466                        self.put(fin_indices[k], 17, fields)?;
467                    }
468                    loop_indices.push(loop_index);
469                }
470                for pair in loop_indices.windows(2) {
471                    self.set(pair[0], "next", ptr(pair[1]))?;
472                }
473                face_records.push((s, face_index, surface.index, positive, loop_indices.first().copied().unwrap_or(0)));
474            }
475        }
476        // Edges, their curves and the fin pairing.
477        let mut edge_nodes = Vec::new();
478        let mut curve_nodes = Vec::new();
479        let mut vertex_fins: HashMap<u32, Vec<u32>> = HashMap::default();
480        for edge in &solid.edges {
481            let Some(fins) = used.get(&edge.id) else { continue };
482            let (positive, negative) = match fins.as_slice() {
483                [a, b] if a.1 && !b.1 => (a.0, b.0),
484                [a, b] if !a.1 && b.1 => (b.0, a.0),
485                _ => return Err(format!("edge {} is used by {} fins, not one each way; only manifold solids are exported", edge.id, fins.len())),
486            };
487            let edge_index = self.reserve();
488            let (curve, tolerance) = match tolerant.get(&edge.id) {
489                Some(&t) => (0, Some(t)),
490                None => {
491                    let curve = self.curve(edge, edge_index)?;
492                    curve_nodes.push(curve);
493                    (curve, None)
494                }
495            };
496            let id = self.id();
497            self.put(
498                edge_index,
499                16,
500                vec![
501                    ("node_id", int(id)),
502                    ("tolerance", Value::Real(tolerance)),
503                    ("halfedge", ptr(positive)),
504                    ("curve", ptr(curve)),
505                    ("owner", ptr(body)),
506                ],
507            )?;
508            for (fin, other) in [(positive, negative), (negative, positive)] {
509                self.set(fin, "other", ptr(other))?;
510                self.set(fin, "edge", ptr(edge_index))?;
511                let vertex = match &self.nodes[&fin].values[self.nodes[&fin].layout.fields.iter().position(|f| f.name == "vertex").unwrap()] {
512                    Value::Int(Some(v)) => *v as u32,
513                    _ => 0,
514                };
515                vertex_fins.entry(vertex).or_default().push(fin);
516            }
517            edge_nodes.push(edge_index);
518        }
519        // Fin chains at vertices, vertices and points.
520        let mut vertex_nodes = Vec::new();
521        let mut points = Vec::new();
522        let vertex_ids: HashMap<u32, u64> = vertex_index.iter().map(|(&id, &v)| (v, id)).collect();
523        for (vertex, point, position) in point_nodes {
524            let fins = vertex_fins.get(&vertex).cloned().unwrap_or_default();
525            if fins.is_empty() {
526                continue; // a pole vertex only a degenerate edge reached
527            }
528            for pair in fins.windows(2) {
529                self.set(pair[0], "next_at_vx", ptr(pair[1]))?;
530            }
531            let id = self.id();
532            self.put(
533                vertex,
534                18,
535                vec![
536                    ("node_id", int(id)),
537                    ("halfedge", ptr(fins[0])),
538                    ("point", ptr(point)),
539                    ("tolerance", Value::Real(vertex_ids.get(&vertex).and_then(|v| vertex_tolerance.get(v)).copied())),
540                    ("owner", ptr(body)),
541                ],
542            )?;
543            let id = self.id();
544            self.put(point, 29, vec![("node_id", int(id)), ("owner", ptr(vertex)), ("pvec", metres(position))])?;
545            vertex_nodes.push(vertex);
546            points.push(point);
547        }
548        // Faces, chained in their shells.
549        let mut back: HashMap<usize, Vec<u32>> = HashMap::default();
550        let mut surfaces = Vec::new();
551        for &(s, face, surface, positive, first_loop) in &face_records {
552            let id = self.id();
553            self.put(
554                face,
555                14,
556                vec![
557                    ("node_id", int(id)),
558                    ("tolerance", Value::Real(None)),
559                    ("loop", ptr(first_loop)),
560                    ("shell", ptr(solid_shells[s])),
561                    ("surface", ptr(surface)),
562                    ("sense", Value::Char(if positive { b'+' } else { b'-' })),
563                    ("front_shell", ptr(void_shells[s])),
564                ],
565            )?;
566            back.entry(s).or_default().push(face);
567            surfaces.push(surface);
568        }
569        for faces in back.values() {
570            for pair in faces.windows(2) {
571                self.set(pair[0], "next", ptr(pair[1]))?;
572                self.set(pair[1], "previous", ptr(pair[0]))?;
573                self.set(pair[0], "next_front", ptr(pair[1]))?;
574                self.set(pair[1], "previous_front", ptr(pair[0]))?;
575            }
576        }
577        // Shells and regions.
578        for s in 0..solid.shells.len() {
579            let faces = back.get(&s).cloned().unwrap_or_default();
580            let head = faces.first().copied().unwrap_or(0);
581            let id = self.id();
582            self.put(solid_shells[s], 13, vec![("node_id", int(id)), ("body", ptr(body)), ("face", ptr(head)), ("region", ptr(material_of[s]))])?;
583            let id = self.id();
584            self.put(void_shells[s], 13, vec![("node_id", int(id)), ("front_face", ptr(head)), ("region", ptr(void_of[s]))])?;
585        }
586        // The infinite void's shells: the outer void side of each lump not
587        // inside another's cavity. A cavity's: its own void side, then the
588        // outer void side of each lump inside it. Each solid region's: its
589        // outer first, then its cavities'.
590        let voids_in = |place: Option<(usize, usize)>| -> Vec<u32> {
591            let mut shells: Vec<u32> = place.map(|(j, c)| void_shells[lumps[j].1[c]]).into_iter().collect();
592            shells.extend((0..lumps.len()).filter(|&k| within[k] == place).map(|k| void_shells[lumps[k].0]));
593            shells
594        };
595        let mut regions = Vec::new();
596        let mut void_region = |region: u32, place: Option<(usize, usize)>, this: &mut Self| -> Result<(), String> {
597            let shells = voids_in(place);
598            for pair in shells.windows(2) {
599                this.set(pair[0], "next", ptr(pair[1]))?;
600            }
601            regions.push((region, shells[0], b'V'));
602            Ok(())
603        };
604        void_region(infinite, None, self)?;
605        let mut material_regions = Vec::new();
606        for (k, (outer, cavities)) in lumps.iter().enumerate() {
607            let mut material_shells = vec![solid_shells[*outer]];
608            material_shells.extend(cavities.iter().map(|&c| solid_shells[c]));
609            for pair in material_shells.windows(2) {
610                self.set(pair[0], "next", ptr(pair[1]))?;
611            }
612            material_regions.push((materials[k], material_shells[0], b'S'));
613            for j in 0..cavities.len() {
614                void_region(cavity_regions[k][j], Some((k, j)), self)?;
615            }
616        }
617        // The infinite void heads the chain, then the solid regions, then
618        // the cavities' voids.
619        let regions: Vec<(u32, u32, u8)> = regions[..1].iter().chain(&material_regions).chain(&regions[1..]).copied().collect();
620        for (k, &(region, shell, kind)) in regions.iter().enumerate() {
621            let id = self.id();
622            let next = regions.get(k + 1).map_or(0, |r| r.0);
623            let previous = if k == 0 { 0 } else { regions[k - 1].0 };
624            self.put(
625                region,
626                19,
627                vec![("node_id", int(id)), ("body", ptr(body)), ("next", ptr(next)), ("previous", ptr(previous)), ("shell", ptr(shell)), ("type", Value::Char(kind))],
628            )?;
629        }
630        // Body chains of edges, vertices and geometry.
631        self.chain(&edge_nodes, "next", "previous")?;
632        self.chain(&vertex_nodes, "next", "previous")?;
633        let mut boundary_surfaces = surfaces.clone();
634        boundary_surfaces.dedup();
635        self.chain(&boundary_surfaces, "next", "previous")?;
636        curve_nodes.extend(sp_curves);
637        self.chain(&curve_nodes, "next", "previous")?;
638        self.chain(&points, "next", "previous")?;
639        // The body's name and colour, as Parasolid's SDL/TYSA attributes
640        // (the definitions as Parasolid 30.1 writes them).
641        let mut attributes = Vec::new();
642        if let Some(name) = export.name.filter(|n| !n.is_empty()) {
643            let definition = self.attribute_definition("SDL/TYSA_NAME", 8017, [0; 8], [true, true, true, true, true, true, true, true, true, true, true, true, true, false], 3)?;
644            let values = self.add(84, vec![("values", Value::Text(name.to_string()))])?;
645            attributes.push((definition, values));
646        }
647        if let Some([r, g, b]) = export.color {
648            let definition = self.attribute_definition("SDL/TYSA_COLOUR_2", 8040, [0, 0, 0, 0, 3, 5, 0, 0], [true, true, true, false, false, false, false, false, false, false, false, false, false, false], 2)?;
649            let values = self.add(83, vec![("values", Value::Array([r, g, b].iter().map(|&x| Value::Real(Some(x))).collect()))])?;
650            attributes.push((definition, values));
651        }
652        let attribute_nodes: Vec<u32> = attributes.iter().map(|_| self.reserve()).collect();
653        for (k, &(definition, values)) in attributes.iter().enumerate() {
654            let id = self.id();
655            let next = attribute_nodes.get(k + 1).copied().unwrap_or(0);
656            let previous = if k == 0 { 0 } else { attribute_nodes[k - 1] };
657            self.put(
658                attribute_nodes[k],
659                81,
660                vec![
661                    ("node_id", int(id)),
662                    ("definition", ptr(definition)),
663                    ("owner", ptr(body)),
664                    ("next", ptr(next)),
665                    ("previous", ptr(previous)),
666                    ("fields", Value::Array(vec![ptr(values)])),
667                ],
668            )?;
669        }
670        let highest = self.next_id;
671        self.put(
672            body,
673            12,
674            vec![
675                ("highest_node_id", int(highest)),
676                ("attributes_features", ptr(attribute_nodes.first().copied().unwrap_or(0))),
677                ("res_size", Value::Real(Some(1e3))),
678                ("res_linear", Value::Real(Some(1e-8))),
679                ("state", int(1)),
680                ("body_type", int(1)),
681                ("nom_geom_state", int(1)),
682                ("shell", ptr(solid_shells[lumps[0].0])),
683                ("boundary_surface", ptr(boundary_surfaces.first().copied().unwrap_or(0))),
684                ("boundary_curve", ptr(curve_nodes.first().copied().unwrap_or(0))),
685                ("boundary_point", ptr(points.first().copied().unwrap_or(0))),
686                ("region", ptr(infinite)),
687                ("edge", ptr(edge_nodes.first().copied().unwrap_or(0))),
688                ("vertex", ptr(vertex_nodes.first().copied().unwrap_or(0))),
689            ],
690        )?;
691        Ok(body)
692    }
693
694    /// An attribute definition (§5.4): its identifier, type, actions, the
695    /// node types it may be attached to and its one field's type (2 real, 3
696    /// string). Definitions are chained through `next`, each written once.
697    fn attribute_definition(&mut self, identifier: &str, type_id: i64, actions: [i64; 8], owners: [bool; 14], field: i64) -> Result<u32, String> {
698        if let Some(&index) = self.definitions.get(identifier) {
699            return Ok(index);
700        }
701        let index = self.reserve();
702        let name = self.add(79, vec![("string", Value::Text(identifier.to_string()))])?;
703        self.put(
704            index,
705            80,
706            vec![
707                ("identifier", ptr(name)),
708                ("type_id", int(type_id)),
709                ("actions", Value::Array(actions.iter().map(|&a| int(a)).collect())),
710                ("field_names", ptr(0)),
711                ("legal_owners", Value::Array(owners.iter().map(|&o| Value::Char(if o { b'T' } else { b'F' })).collect())),
712                ("fields", Value::Array(vec![int(field)])),
713            ],
714        )?;
715        if let Some(&last) = self.definition_order.last() {
716            self.set(last, "next", ptr(index))?;
717        }
718        self.definition_order.push(index);
719        self.definitions.insert(identifier.to_string(), index);
720        Ok(index)
721    }
722
723    fn chain(&mut self, nodes: &[u32], next: &str, previous: &str) -> Result<(), String> {
724        for pair in nodes.windows(2) {
725            self.set(pair[0], next, ptr(pair[1]))?;
726            self.set(pair[1], previous, ptr(pair[0]))?;
727        }
728        Ok(())
729    }
730
731    /// A face's surface, owned by the face.
732    fn surface(&mut self, surface: &NurbsSurface, face: u32) -> Result<WrittenSurface, String> {
733        let index = self.reserve();
734        let id = self.id();
735        let common = |fields: &mut Vec<(&str, Value)>| {
736            fields.push(("node_id", int(id)));
737            fields.push(("owner", ptr(face)));
738            fields.push(("sense", Value::Char(b'+')));
739        };
740        let mut fields = Vec::new();
741        common(&mut fields);
742        let analytic = surface.analytic().cloned();
743        let (node_type, flipped) = match analytic {
744            Some(AnalyticSurface::Plane { origin, u_dir, v_dir, .. }) => {
745                let (Ok(normal), Ok(x)) = (u_dir.cross(v_dir).normalized(), u_dir.normalized()) else {
746                    return self.b_surface(surface, index, fields);
747                };
748                fields.push(("pvec", metres(origin)));
749                fields.push(("normal", unit(normal)));
750                fields.push(("x_axis", unit(x)));
751                (50, false)
752            }
753            Some(AnalyticSurface::RuledRevolution { frame, rho0, rho1, height }) => {
754                let flipped = height < 0.0;
755                let scale = 1.0 + rho0.abs().max(rho1.abs());
756                if (rho1 - rho0).abs() <= 1e-9 * scale {
757                    if rho0 <= 0.0 {
758                        return self.b_surface(surface, index, fields);
759                    }
760                    fields.push(("pvec", metres(frame.origin)));
761                    fields.push(("axis", unit(frame.axis)));
762                    fields.push(("radius", Value::Real(Some(rho0 / MM_PER_METRE))));
763                    fields.push(("x_axis", unit(frame.x_axis)));
764                    (51, flipped)
765                } else {
766                    // The radius grows along the written axis (as written
767                    // files have it), from rho0 at the origin.
768                    let slope = (rho1 - rho0) / height;
769                    // The point the radius is given at: the generatrix's
770                    // start, or its end when the start is the apex.
771                    let (origin, radius) = if rho0 > 0.0 { (frame.origin, rho0) } else { (frame.origin.add(frame.axis.scale(height)), rho1) };
772                    if radius <= 0.0 {
773                        return self.b_surface(surface, index, fields);
774                    }
775                    let axis = if slope >= 0.0 { frame.axis } else { frame.axis.scale(-1.0) };
776                    let half = slope.abs().atan();
777                    fields.push(("pvec", metres(origin)));
778                    fields.push(("axis", unit(axis)));
779                    fields.push(("radius", Value::Real(Some(radius / MM_PER_METRE))));
780                    fields.push(("sin_half_angle", Value::Real(Some(half.sin()))));
781                    fields.push(("cos_half_angle", Value::Real(Some(half.cos()))));
782                    fields.push(("x_axis", unit(frame.x_axis)));
783                    (52, flipped)
784                }
785            }
786            Some(AnalyticSurface::Sphere { frame, radius }) => {
787                fields.push(("centre", metres(frame.origin)));
788                fields.push(("radius", Value::Real(Some(radius / MM_PER_METRE))));
789                fields.push(("axis", unit(frame.axis)));
790                fields.push(("x_axis", unit(frame.x_axis)));
791                (53, false)
792            }
793            Some(AnalyticSurface::Torus { frame, major_radius, minor_radius }) => {
794                if minor_radius >= major_radius {
795                    return self.b_surface(surface, index, fields);
796                }
797                fields.push(("centre", metres(frame.origin)));
798                fields.push(("axis", unit(frame.axis)));
799                fields.push(("major_radius", Value::Real(Some(major_radius / MM_PER_METRE))));
800                fields.push(("minor_radius", Value::Real(Some(minor_radius / MM_PER_METRE))));
801                fields.push(("x_axis", unit(frame.x_axis)));
802                (54, false)
803            }
804            _ => return self.b_surface(surface, index, fields),
805        };
806        self.put(index, node_type, fields)?;
807        Ok(WrittenSurface { index, flipped })
808    }
809
810    /// A B_SURFACE and its NURBS_SURF: the kernel's net, positions in
811    /// metres, rational vertices premultiplied with the weight last, v
812    /// varying fastest (§5.2.2.7).
813    fn b_surface(&mut self, surface: &NurbsSurface, index: u32, mut fields: Vec<(&str, Value)>) -> Result<WrittenSurface, String> {
814        let rational = surface.control_points.iter().flatten().any(|p| (p.w - 1.0).abs() > 1e-12);
815        let nu = surface.control_points.len();
816        let nv = surface.control_points.first().map_or(0, Vec::len);
817        let dim = if rational { 4 } else { 3 };
818        let mut vertices = Vec::with_capacity(nu * nv * dim);
819        for row in &surface.control_points {
820            for p in row {
821                vertices.push(Value::Real(Some(p.x / MM_PER_METRE)));
822                vertices.push(Value::Real(Some(p.y / MM_PER_METRE)));
823                vertices.push(Value::Real(Some(p.z / MM_PER_METRE)));
824                if rational {
825                    vertices.push(Value::Real(Some(p.w)));
826                }
827            }
828        }
829        let (uk, um) = knot_runs(&surface.knots_u);
830        let (vk, vm) = knot_runs(&surface.knots_v);
831        let nurbs = self.reserve();
832        let bv = self.add(45, vec![("vertices", Value::Array(vertices))])?;
833        let ukm = self.add(127, vec![("mult", Value::Array(um.iter().map(|&m| int(m as i64)).collect()))])?;
834        let vkm = self.add(127, vec![("mult", Value::Array(vm.iter().map(|&m| int(m as i64)).collect()))])?;
835        let uks = self.add(128, vec![("knots", Value::Array(uk.iter().map(|&k| Value::Real(Some(k))).collect()))])?;
836        let vks = self.add(128, vec![("knots", Value::Array(vk.iter().map(|&k| Value::Real(Some(k))).collect()))])?;
837        self.put(
838            nurbs,
839            126,
840            vec![
841                ("u_periodic", Value::Char(b'F')),
842                ("v_periodic", Value::Char(b'F')),
843                ("u_degree", int(surface.degree_u as i64)),
844                ("v_degree", int(surface.degree_v as i64)),
845                ("n_u_vertices", int(nu as i64)),
846                ("n_v_vertices", int(nv as i64)),
847                ("u_knot_type", int(1)),
848                ("v_knot_type", int(1)),
849                ("n_u_knots", int(uk.len() as i64)),
850                ("n_v_knots", int(vk.len() as i64)),
851                ("rational", Value::Char(if rational { b'T' } else { b'F' })),
852                ("u_closed", Value::Char(b'F')),
853                ("v_closed", Value::Char(b'F')),
854                ("surface_form", int(1)),
855                ("vertex_dim", int(dim as i64)),
856                ("bspline_vertices", ptr(bv)),
857                ("u_knot_mult", ptr(ukm)),
858                ("v_knot_mult", ptr(vkm)),
859                ("u_knots", ptr(uks)),
860                ("v_knots", ptr(vks)),
861            ],
862        )?;
863        fields.push(("nurbs", ptr(nurbs)));
864        self.put(index, 124, fields)?;
865        Ok(WrittenSurface { index, flipped: false })
866    }
867
868    /// An edge's curve over the edge, start to end, owned by the edge.
869    fn curve(&mut self, edge: &crate::topology::EdgeRecord, owner: u32) -> Result<u32, String> {
870        let curve = brep_topology::edge_subcurve::edge_subcurve(edge)?;
871        let index = self.reserve();
872        let id = self.id();
873        let mut fields = vec![("node_id", int(id)), ("owner", ptr(owner)), ("sense", Value::Char(b'+'))];
874        let straight = curve.degree == 1 && curve.control_points.len() == 2 && curve.control_points.iter().all(|p| (p.w - 1.0).abs() <= 1e-12);
875        if straight {
876            let start = curve.control_points[0].point()?;
877            let end = curve.control_points[1].point()?;
878            if let Ok(direction) = end.sub(start).normalized() {
879                fields.push(("pvec", metres(start)));
880                fields.push(("direction", unit(direction)));
881                self.put(index, 30, fields)?;
882                return Ok(index);
883            }
884        }
885        if let Some(arc) = crate::step::recognize_circular_arc(&curve) {
886            fields.push(("centre", metres(arc.center)));
887            fields.push(("normal", unit(arc.axis)));
888            fields.push(("x_axis", unit(arc.x_axis)));
889            fields.push(("radius", Value::Real(Some(arc.radius / MM_PER_METRE))));
890            self.put(index, 31, fields)?;
891            return Ok(index);
892        }
893        self.b_curve(&curve, index, fields)?;
894        Ok(index)
895    }
896
897    /// A tolerant edge's fin curve: a TRIMMED_CURVE running along the fin
898    /// (from the fin's start to its vertex), over an SP_CURVE whose 2D B-curve
899    /// is the coedge's curve in its face's surface parameters. Returns
900    /// (trimmed, SP-curve).
901    fn fin_curve(&mut self, pcurve: &NurbsCurve, surface: u32, fin: u32, body: u32, ends: (Vec3, Vec3)) -> Result<(u32, u32), String> {
902        let [p0, p1] = pcurve.domain()?;
903        let basis = self.reserve();
904        let b_curve = self.reserve();
905        let rational = pcurve.control_points.iter().any(|p| (p.w - 1.0).abs() > 1e-12);
906        let dim = if rational { 3 } else { 2 };
907        let mut vertices = Vec::new();
908        for p in &pcurve.control_points {
909            vertices.push(Value::Real(Some(p.x)));
910            vertices.push(Value::Real(Some(p.y)));
911            if rational {
912                vertices.push(Value::Real(Some(p.w)));
913            }
914        }
915        let (knots, mults) = knot_runs(&pcurve.knots);
916        let nurbs = self.reserve();
917        let bv = self.add(45, vec![("vertices", Value::Array(vertices))])?;
918        let km = self.add(127, vec![("mult", Value::Array(mults.iter().map(|&m| int(m as i64)).collect()))])?;
919        let ks = self.add(128, vec![("knots", Value::Array(knots.iter().map(|&k| Value::Real(Some(k))).collect()))])?;
920        self.put(
921            nurbs,
922            136,
923            vec![
924                ("degree", int(pcurve.degree as i64)),
925                ("n_vertices", int(pcurve.control_points.len() as i64)),
926                ("vertex_dim", int(dim)),
927                ("n_knots", int(knots.len() as i64)),
928                ("knot_type", int(1)),
929                ("periodic", Value::Char(b'F')),
930                ("closed", Value::Char(b'F')),
931                ("rational", Value::Char(if rational { b'T' } else { b'F' })),
932                ("curve_form", int(1)),
933                ("bspline_vertices", ptr(bv)),
934                ("knot_mult", ptr(km)),
935                ("knots", ptr(ks)),
936            ],
937        )?;
938        self.put(b_curve, 134, vec![("sense", Value::Char(b'+')), ("nurbs", ptr(nurbs))])?;
939        let id = self.id();
940        self.put(basis, 137, vec![("node_id", int(id)), ("owner", ptr(body)), ("sense", Value::Char(b'+')), ("surface", ptr(surface)), ("b_curve", ptr(b_curve))])?;
941        let trimmed = self.reserve();
942        let id = self.id();
943        self.put(
944            trimmed,
945            133,
946            vec![
947                ("node_id", int(id)),
948                ("owner", ptr(fin)),
949                ("sense", Value::Char(b'+')),
950                ("basis_curve", ptr(basis)),
951                ("point_1", metres(ends.0)),
952                ("point_2", metres(ends.1)),
953                ("parm_1", Value::Real(Some(p0))),
954                ("parm_2", Value::Real(Some(p1))),
955            ],
956        )?;
957        Ok((trimmed, basis))
958    }
959
960    fn b_curve(&mut self, curve: &NurbsCurve, index: u32, mut fields: Vec<(&str, Value)>) -> Result<(), String> {
961        let rational = curve.control_points.iter().any(|p| (p.w - 1.0).abs() > 1e-12);
962        let dim = if rational { 4 } else { 3 };
963        let mut vertices = Vec::new();
964        for p in &curve.control_points {
965            vertices.push(Value::Real(Some(p.x / MM_PER_METRE)));
966            vertices.push(Value::Real(Some(p.y / MM_PER_METRE)));
967            vertices.push(Value::Real(Some(p.z / MM_PER_METRE)));
968            if rational {
969                vertices.push(Value::Real(Some(p.w)));
970            }
971        }
972        let (knots, mults) = knot_runs(&curve.knots);
973        let nurbs = self.reserve();
974        let bv = self.add(45, vec![("vertices", Value::Array(vertices))])?;
975        let km = self.add(127, vec![("mult", Value::Array(mults.iter().map(|&m| int(m as i64)).collect()))])?;
976        let ks = self.add(128, vec![("knots", Value::Array(knots.iter().map(|&k| Value::Real(Some(k))).collect()))])?;
977        let closed = match (curve.control_points.first(), curve.control_points.last()) {
978            (Some(a), Some(b)) => a.point()?.sub(b.point()?).length() <= 1e-9,
979            _ => false,
980        };
981        self.put(
982            nurbs,
983            136,
984            vec![
985                ("degree", int(curve.degree as i64)),
986                ("n_vertices", int(curve.control_points.len() as i64)),
987                ("vertex_dim", int(dim as i64)),
988                ("n_knots", int(knots.len() as i64)),
989                ("knot_type", int(1)),
990                ("periodic", Value::Char(b'F')),
991                ("closed", Value::Char(if closed { b'T' } else { b'F' })),
992                ("rational", Value::Char(if rational { b'T' } else { b'F' })),
993                ("curve_form", int(1)),
994                ("bspline_vertices", ptr(bv)),
995                ("knot_mult", ptr(km)),
996                ("knots", ptr(ks)),
997            ],
998        )?;
999        fields.push(("nurbs", ptr(nurbs)));
1000        self.put(index, 134, fields)
1001    }
1002}
1003
1004/// A solid's lumps, largest first, each its outer shell and its cavities'
1005/// shells; and for each lump the cavity (lump, cavity index) it sits inside,
1006/// if any.
1007struct Lumps {
1008    lumps: Vec<(usize, Vec<usize>)>,
1009    within: Vec<Option<(usize, usize)>>,
1010}
1011
1012/// The solid's lumps: each shell whose signed volume is positive bounds one
1013/// (an outer shell faces out), and each other shell (a cavity's, facing into
1014/// the cavity) lies in the smallest of them that holds a point of it. Each
1015/// lump is a solid region of its own (§4.3); a lump inside another's cavity
1016/// has its outside in that cavity's void region.
1017fn lumps(solid: &BrepSolid) -> Result<Lumps, String> {
1018    if solid.shells.is_empty() {
1019        return Err("the solid has no shells".into());
1020    }
1021    if solid.shells.len() == 1 {
1022        return Ok(Lumps { lumps: vec![(0, Vec::new())], within: vec![None] });
1023    }
1024    let alone = |s: usize| {
1025        let mut one = solid.clone();
1026        one.shells = vec![solid.shells[s].clone()];
1027        one.mass_properties_cache = Default::default();
1028        one
1029    };
1030    let volumes: Vec<f64> = (0..solid.shells.len()).map(|s| crate::solid_signed_volume(&alone(s)).unwrap_or(f64::NAN)).collect();
1031    // A shell enclosing no volume (or none measurable) is neither an outer
1032    // shell nor a cavity's: measured against its own size (the cube of its
1033    // vertices' box diagonal), so a small cavity in a large solid counts.
1034    let points: HashMap<u64, Vec3> = solid.vertices.iter().map(|v| (v.id, v.point)).collect();
1035    let ends: HashMap<u64, [u64; 2]> = solid.edges.iter().map(|e| (e.id, [e.start_vertex_id, e.end_vertex_id])).collect();
1036    let size = |s: usize| -> f64 {
1037        let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);
1038        let coedges = solid.shells[s].faces.iter().flat_map(|f| &f.loops).flat_map(|l| &l.coedges);
1039        for p in coedges.filter_map(|c| ends.get(&c.edge_id)).flatten().filter_map(|v| points.get(v)) {
1040            for (k, x) in [p.x, p.y, p.z].into_iter().enumerate() {
1041                lo[k] = lo[k].min(x);
1042                hi[k] = hi[k].max(x);
1043            }
1044        }
1045        (0..3).map(|k| (hi[k] - lo[k]).max(0.0).powi(2)).sum::<f64>().sqrt()
1046    };
1047    if let Some(s) = (0..volumes.len()).find(|&s| !volumes[s].is_finite() || volumes[s].abs() <= 1e-12 * size(s).powi(3)) {
1048        return Err(format!("shell {s} of the solid encloses no volume to tell an outer shell from a cavity by ({})", volumes[s]));
1049    }
1050    let mut outers: Vec<usize> = (0..solid.shells.len()).filter(|&s| volumes[s] > 0.0).collect();
1051    if outers.is_empty() {
1052        return Err(format!("no shell of the solid encloses positive volume ({volumes:?})"));
1053    }
1054    outers.sort_by(|&a, &b| volumes[b].total_cmp(&volumes[a]));
1055    let mut lumps: Vec<(usize, Vec<usize>)> = outers.iter().map(|&o| (o, Vec::new())).collect();
1056    if outers.len() == 1 {
1057        lumps[0].1 = (0..solid.shells.len()).filter(|&s| s != outers[0]).collect();
1058        return Ok(Lumps { lumps, within: vec![None] });
1059    }
1060    let bounded: Vec<BrepSolid> = outers.iter().map(|&o| alone(o)).collect();
1061    let vertices: HashMap<u64, Vec3> = solid.vertices.iter().map(|v| (v.id, v.point)).collect();
1062    let edges: HashMap<u64, u64> = solid.edges.iter().map(|e| (e.id, e.start_vertex_id)).collect();
1063    let point_of = |s: usize| -> Result<Vec3, String> {
1064        solid.shells[s]
1065            .faces
1066            .iter()
1067            .flat_map(|f| &f.loops)
1068            .flat_map(|l| &l.coedges)
1069            .find_map(|coedge| edges.get(&coedge.edge_id).and_then(|v| vertices.get(v)))
1070            .copied()
1071            .ok_or_else(|| format!("shell {s} has no vertex"))
1072    };
1073    let inside = |p: Vec3, body: &BrepSolid| crate::classify_point(p, body, 1e-6).is_ok_and(|c| c.class == crate::PointClass::In);
1074    for c in (0..solid.shells.len()).filter(|&s| volumes[s] < 0.0) {
1075        let point = point_of(c)?;
1076        // The smallest lump holding it: lumps are largest first.
1077        let holder = (0..outers.len())
1078            .rev()
1079            .find(|&k| inside(point, &bounded[k]))
1080            .ok_or_else(|| format!("cavity shell {c} lies in no lump of the solid"))?;
1081        lumps[holder].1.push(c);
1082    }
1083    // A lump inside another's outer shell is in one of its cavities: the
1084    // smallest cavity whose shell, with that lump's outer, leaves it out.
1085    let mut within = vec![None; lumps.len()];
1086    for k in 0..lumps.len() {
1087        let point = point_of(lumps[k].0)?;
1088        let mut best: Option<((usize, usize), f64)> = None;
1089        for (j, (outer, cavities)) in lumps.iter().enumerate() {
1090            if j == k || !inside(point, &bounded[j]) {
1091                continue;
1092            }
1093            for (ci, &c) in cavities.iter().enumerate() {
1094                let mut hollow = solid.clone();
1095                hollow.shells = vec![solid.shells[*outer].clone(), solid.shells[c].clone()];
1096                hollow.mass_properties_cache = Default::default();
1097                if !inside(point, &hollow) && best.map_or(true, |(_, v)| -volumes[c] < v) {
1098                    best = Some(((j, ci), -volumes[c]));
1099                }
1100            }
1101        }
1102        within[k] = best.map(|(place, _)| place);
1103    }
1104    Ok(Lumps { lumps, within })
1105}
1106
1107/// Distinct knots and their multiplicities.
1108fn knot_runs(knots: &[f64]) -> (Vec<f64>, Vec<usize>) {
1109    let mut values: Vec<f64> = Vec::new();
1110    let mut mults: Vec<usize> = Vec::new();
1111    for &k in knots {
1112        match values.last() {
1113            Some(&last) if (k - last).abs() <= 0.0 => *mults.last_mut().unwrap() += 1,
1114            _ => {
1115                values.push(k);
1116                mults.push(1);
1117            }
1118        }
1119    }
1120    (values, mults)
1121}
1122
1123fn default_value(kind: Kind) -> Value {
1124    match kind {
1125        Kind::Int => Value::Int(Some(0)),
1126        Kind::Real => Value::Real(None),
1127        Kind::Vector => Value::Vector(None),
1128        Kind::Interval => Value::Interval([None; 2]),
1129        Kind::Box => Value::Box([None; 6]),
1130        Kind::Char | Kind::Unknown => Value::Char(b'?'),
1131    }
1132}
1133
1134fn int(v: i64) -> Value {
1135    Value::Int(Some(v))
1136}
1137
1138fn ptr(index: u32) -> Value {
1139    Value::Int(Some(i64::from(index)))
1140}
1141
1142fn metres(p: Vec3) -> Value {
1143    Value::Vector(Some([p.x / MM_PER_METRE, p.y / MM_PER_METRE, p.z / MM_PER_METRE]))
1144}
1145
1146fn unit(v: Vec3) -> Value {
1147    Value::Vector(Some([v.x, v.y, v.z]))
1148}