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 (and a void region for each
13//! 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 the solid, then a void per cavity shell.
356        let outer = outer_shell(solid)?;
357        let infinite = self.reserve();
358        let material = self.reserve();
359        let cavities: Vec<usize> = (0..solid.shells.len()).filter(|&s| s != outer).collect();
360        let cavity_regions: Vec<u32> = cavities.iter().map(|_| self.reserve()).collect();
361        // A shell on each side of every kernel shell: its solid side in the
362        // solid region, its void side in the infinite void or its cavity.
363        let mut solid_shells = Vec::new();
364        let mut void_shells = Vec::new();
365        for s in 0..solid.shells.len() {
366            solid_shells.push(self.reserve());
367            void_shells.push(self.reserve());
368            let _ = s;
369        }
370        // Vertices and their points.
371        let mut vertex_index: HashMap<u64, u32> = HashMap::default();
372        let mut point_nodes = Vec::new();
373        for v in &solid.vertices {
374            let vertex = self.reserve();
375            let point = self.reserve();
376            vertex_index.insert(v.id, vertex);
377            point_nodes.push((vertex, point, v.point));
378        }
379        // Edges: only those some face's loop uses (degenerate pole edges
380        // are not edges in XT: the loop runs through the pole vertex).
381        let mut used: HashMap<u64, Vec<(u32, bool, u32)>> = HashMap::default(); // edge -> (fin, forward, loop)
382        let edges_by_id: HashMap<u64, &crate::topology::EdgeRecord> = solid.edges.iter().map(|e| (e.id, e)).collect();
383        // Edges further from their faces than the resolution are written
384        // tolerant (§5.3.11): no curve, a tolerance, and on each fin a
385        // trimmed SP-curve, the coedge's own curve in its face's parameters.
386        let tolerant: HashMap<u64, f64> = edge_deviations(solid)
387            .into_iter()
388            .filter(|&(_, d)| d > RESOLUTION_MM)
389            .map(|(id, d)| (id, (2.0 * d).max(10.0 * RESOLUTION_MM) / MM_PER_METRE))
390            .collect();
391        let vertex_points: HashMap<u64, Vec3> = solid.vertices.iter().map(|v| (v.id, v.point)).collect();
392        let mut vertex_tolerance: HashMap<u64, f64> = HashMap::default();
393        for e in &solid.edges {
394            if let Some(&t) = tolerant.get(&e.id) {
395                for v in [e.start_vertex_id, e.end_vertex_id] {
396                    let slot = vertex_tolerance.entry(v).or_insert(0.0);
397                    *slot = slot.max(t);
398                }
399            }
400        }
401        let mut sp_curves = Vec::new();
402        // Faces, loops and fins.
403        let mut face_records = Vec::new();
404        for (s, shell) in solid.shells.iter().enumerate() {
405            for face in &shell.faces {
406                let face_index = self.reserve();
407                // A face with a tolerant edge keeps the kernel's own surface,
408                // whose parameters its SP-curves are in.
409                let has_tolerant = face.loops.iter().flat_map(|l| &l.coedges).any(|c| tolerant.contains_key(&c.edge_id));
410                let surface = if has_tolerant {
411                    let index = self.reserve();
412                    let id = self.id();
413                    self.b_surface(&face.surface, index, vec![("node_id", int(id)), ("owner", ptr(face_index)), ("sense", Value::Char(b'+'))])?
414                } else {
415                    self.surface(&face.surface, face_index)?
416                };
417                let positive = face.same_sense != surface.flipped;
418                let mut loop_indices = Vec::new();
419                for lp in &face.loops {
420                    let coedges: Vec<&crate::topology::CoedgeRecord> = lp
421                        .coedges
422                        .iter()
423                        .filter(|c| edges_by_id.get(&c.edge_id).is_some_and(|e| !e.degenerate))
424                        .collect();
425                    let fins: Vec<(u64, bool)> = coedges.iter().map(|c| (c.edge_id, c.forward)).collect();
426                    if fins.is_empty() {
427                        continue;
428                    }
429                    let loop_index = self.reserve();
430                    let fin_indices: Vec<u32> = fins.iter().map(|_| self.reserve()).collect();
431                    for (k, &(edge_id, forward)) in fins.iter().enumerate() {
432                        used.entry(edge_id).or_default().push((fin_indices[k], forward, loop_index));
433                    }
434                    let id = self.id();
435                    self.put(loop_index, 15, vec![("node_id", int(id)), ("halfedge", ptr(fin_indices[0])), ("face", ptr(face_index))])?;
436                    for (k, &(edge_id, forward)) in fins.iter().enumerate() {
437                        let n = fin_indices.len();
438                        let edge = edges_by_id[&edge_id];
439                        let vertex_id = if forward { edge.end_vertex_id } else { edge.start_vertex_id };
440                        let vertex = *vertex_index.get(&vertex_id).ok_or_else(|| format!("edge {edge_id} has an unknown vertex"))?;
441                        let mut fields = vec![
442                            ("loop", ptr(loop_index)),
443                            ("forward", ptr(fin_indices[(k + 1) % n])),
444                            ("backward", ptr(fin_indices[(k + n - 1) % n])),
445                            ("vertex", ptr(vertex)),
446                            ("sense", Value::Char(if forward { b'+' } else { b'-' })),
447                        ];
448                        if tolerant.contains_key(&edge_id) {
449                            let start_id = if forward { edge.start_vertex_id } else { edge.end_vertex_id };
450                            let ends = (vertex_points[&start_id], vertex_points[&vertex_id]);
451                            let (trimmed, basis) = self.fin_curve(&coedges[k].pcurve, surface.index, fin_indices[k], body, ends)?;
452                            fields.push(("curve", ptr(trimmed)));
453                            sp_curves.push(basis);
454                            sp_curves.push(trimmed);
455                        }
456                        self.put(fin_indices[k], 17, fields)?;
457                    }
458                    loop_indices.push(loop_index);
459                }
460                for pair in loop_indices.windows(2) {
461                    self.set(pair[0], "next", ptr(pair[1]))?;
462                }
463                face_records.push((s, face_index, surface.index, positive, loop_indices.first().copied().unwrap_or(0)));
464            }
465        }
466        // Edges, their curves and the fin pairing.
467        let mut edge_nodes = Vec::new();
468        let mut curve_nodes = Vec::new();
469        let mut vertex_fins: HashMap<u32, Vec<u32>> = HashMap::default();
470        for edge in &solid.edges {
471            let Some(fins) = used.get(&edge.id) else { continue };
472            let (positive, negative) = match fins.as_slice() {
473                [a, b] if a.1 && !b.1 => (a.0, b.0),
474                [a, b] if !a.1 && b.1 => (b.0, a.0),
475                _ => return Err(format!("edge {} is used by {} fins, not one each way; only manifold solids are exported", edge.id, fins.len())),
476            };
477            let edge_index = self.reserve();
478            let (curve, tolerance) = match tolerant.get(&edge.id) {
479                Some(&t) => (0, Some(t)),
480                None => {
481                    let curve = self.curve(edge, edge_index)?;
482                    curve_nodes.push(curve);
483                    (curve, None)
484                }
485            };
486            let id = self.id();
487            self.put(
488                edge_index,
489                16,
490                vec![
491                    ("node_id", int(id)),
492                    ("tolerance", Value::Real(tolerance)),
493                    ("halfedge", ptr(positive)),
494                    ("curve", ptr(curve)),
495                    ("owner", ptr(body)),
496                ],
497            )?;
498            for (fin, other) in [(positive, negative), (negative, positive)] {
499                self.set(fin, "other", ptr(other))?;
500                self.set(fin, "edge", ptr(edge_index))?;
501                let vertex = match &self.nodes[&fin].values[self.nodes[&fin].layout.fields.iter().position(|f| f.name == "vertex").unwrap()] {
502                    Value::Int(Some(v)) => *v as u32,
503                    _ => 0,
504                };
505                vertex_fins.entry(vertex).or_default().push(fin);
506            }
507            edge_nodes.push(edge_index);
508        }
509        // Fin chains at vertices, vertices and points.
510        let mut vertex_nodes = Vec::new();
511        let mut points = Vec::new();
512        let vertex_ids: HashMap<u32, u64> = vertex_index.iter().map(|(&id, &v)| (v, id)).collect();
513        for (vertex, point, position) in point_nodes {
514            let fins = vertex_fins.get(&vertex).cloned().unwrap_or_default();
515            if fins.is_empty() {
516                continue; // a pole vertex only a degenerate edge reached
517            }
518            for pair in fins.windows(2) {
519                self.set(pair[0], "next_at_vx", ptr(pair[1]))?;
520            }
521            let id = self.id();
522            self.put(
523                vertex,
524                18,
525                vec![
526                    ("node_id", int(id)),
527                    ("halfedge", ptr(fins[0])),
528                    ("point", ptr(point)),
529                    ("tolerance", Value::Real(vertex_ids.get(&vertex).and_then(|v| vertex_tolerance.get(v)).copied())),
530                    ("owner", ptr(body)),
531                ],
532            )?;
533            let id = self.id();
534            self.put(point, 29, vec![("node_id", int(id)), ("owner", ptr(vertex)), ("pvec", metres(position))])?;
535            vertex_nodes.push(vertex);
536            points.push(point);
537        }
538        // Faces, chained in their shells.
539        let mut back: HashMap<usize, Vec<u32>> = HashMap::default();
540        let mut surfaces = Vec::new();
541        for &(s, face, surface, positive, first_loop) in &face_records {
542            let id = self.id();
543            self.put(
544                face,
545                14,
546                vec![
547                    ("node_id", int(id)),
548                    ("tolerance", Value::Real(None)),
549                    ("loop", ptr(first_loop)),
550                    ("shell", ptr(solid_shells[s])),
551                    ("surface", ptr(surface)),
552                    ("sense", Value::Char(if positive { b'+' } else { b'-' })),
553                    ("front_shell", ptr(void_shells[s])),
554                ],
555            )?;
556            back.entry(s).or_default().push(face);
557            surfaces.push(surface);
558        }
559        for faces in back.values() {
560            for pair in faces.windows(2) {
561                self.set(pair[0], "next", ptr(pair[1]))?;
562                self.set(pair[1], "previous", ptr(pair[0]))?;
563                self.set(pair[0], "next_front", ptr(pair[1]))?;
564                self.set(pair[1], "previous_front", ptr(pair[0]))?;
565            }
566        }
567        // Shells and regions.
568        for s in 0..solid.shells.len() {
569            let faces = back.get(&s).cloned().unwrap_or_default();
570            let head = faces.first().copied().unwrap_or(0);
571            let id = self.id();
572            self.put(solid_shells[s], 13, vec![("node_id", int(id)), ("body", ptr(body)), ("face", ptr(head)), ("region", ptr(material))])?;
573            let void_region = if s == outer { infinite } else { cavity_regions[cavities.iter().position(|&c| c == s).unwrap()] };
574            let id = self.id();
575            self.put(void_shells[s], 13, vec![("node_id", int(id)), ("front_face", ptr(head)), ("region", ptr(void_region))])?;
576        }
577        // The solid region's shells: the outer first, then the cavities'.
578        let mut material_shells = vec![solid_shells[outer]];
579        material_shells.extend(cavities.iter().map(|&c| solid_shells[c]));
580        for pair in material_shells.windows(2) {
581            self.set(pair[0], "next", ptr(pair[1]))?;
582        }
583        let mut regions = vec![(infinite, void_shells[outer], b'V'), (material, material_shells[0], b'S')];
584        for (k, &c) in cavities.iter().enumerate() {
585            regions.push((cavity_regions[k], void_shells[c], b'V'));
586        }
587        for (k, &(region, shell, kind)) in regions.iter().enumerate() {
588            let id = self.id();
589            let next = regions.get(k + 1).map_or(0, |r| r.0);
590            let previous = if k == 0 { 0 } else { regions[k - 1].0 };
591            self.put(
592                region,
593                19,
594                vec![("node_id", int(id)), ("body", ptr(body)), ("next", ptr(next)), ("previous", ptr(previous)), ("shell", ptr(shell)), ("type", Value::Char(kind))],
595            )?;
596        }
597        // Body chains of edges, vertices and geometry.
598        self.chain(&edge_nodes, "next", "previous")?;
599        self.chain(&vertex_nodes, "next", "previous")?;
600        let mut boundary_surfaces = surfaces.clone();
601        boundary_surfaces.dedup();
602        self.chain(&boundary_surfaces, "next", "previous")?;
603        curve_nodes.extend(sp_curves);
604        self.chain(&curve_nodes, "next", "previous")?;
605        self.chain(&points, "next", "previous")?;
606        // The body's name and colour, as Parasolid's SDL/TYSA attributes
607        // (the definitions as Parasolid 30.1 writes them).
608        let mut attributes = Vec::new();
609        if let Some(name) = export.name.filter(|n| !n.is_empty()) {
610            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)?;
611            let values = self.add(84, vec![("values", Value::Text(name.to_string()))])?;
612            attributes.push((definition, values));
613        }
614        if let Some([r, g, b]) = export.color {
615            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)?;
616            let values = self.add(83, vec![("values", Value::Array([r, g, b].iter().map(|&x| Value::Real(Some(x))).collect()))])?;
617            attributes.push((definition, values));
618        }
619        let attribute_nodes: Vec<u32> = attributes.iter().map(|_| self.reserve()).collect();
620        for (k, &(definition, values)) in attributes.iter().enumerate() {
621            let id = self.id();
622            let next = attribute_nodes.get(k + 1).copied().unwrap_or(0);
623            let previous = if k == 0 { 0 } else { attribute_nodes[k - 1] };
624            self.put(
625                attribute_nodes[k],
626                81,
627                vec![
628                    ("node_id", int(id)),
629                    ("definition", ptr(definition)),
630                    ("owner", ptr(body)),
631                    ("next", ptr(next)),
632                    ("previous", ptr(previous)),
633                    ("fields", Value::Array(vec![ptr(values)])),
634                ],
635            )?;
636        }
637        let highest = self.next_id;
638        self.put(
639            body,
640            12,
641            vec![
642                ("highest_node_id", int(highest)),
643                ("attributes_features", ptr(attribute_nodes.first().copied().unwrap_or(0))),
644                ("res_size", Value::Real(Some(1e3))),
645                ("res_linear", Value::Real(Some(1e-8))),
646                ("state", int(1)),
647                ("body_type", int(1)),
648                ("nom_geom_state", int(1)),
649                ("shell", ptr(solid_shells[outer])),
650                ("boundary_surface", ptr(boundary_surfaces.first().copied().unwrap_or(0))),
651                ("boundary_curve", ptr(curve_nodes.first().copied().unwrap_or(0))),
652                ("boundary_point", ptr(points.first().copied().unwrap_or(0))),
653                ("region", ptr(infinite)),
654                ("edge", ptr(edge_nodes.first().copied().unwrap_or(0))),
655                ("vertex", ptr(vertex_nodes.first().copied().unwrap_or(0))),
656            ],
657        )?;
658        Ok(body)
659    }
660
661    /// An attribute definition (§5.4): its identifier, type, actions, the
662    /// node types it may be attached to and its one field's type (2 real, 3
663    /// string). Definitions are chained through `next`, each written once.
664    fn attribute_definition(&mut self, identifier: &str, type_id: i64, actions: [i64; 8], owners: [bool; 14], field: i64) -> Result<u32, String> {
665        if let Some(&index) = self.definitions.get(identifier) {
666            return Ok(index);
667        }
668        let index = self.reserve();
669        let name = self.add(79, vec![("string", Value::Text(identifier.to_string()))])?;
670        self.put(
671            index,
672            80,
673            vec![
674                ("identifier", ptr(name)),
675                ("type_id", int(type_id)),
676                ("actions", Value::Array(actions.iter().map(|&a| int(a)).collect())),
677                ("field_names", ptr(0)),
678                ("legal_owners", Value::Array(owners.iter().map(|&o| Value::Char(if o { b'T' } else { b'F' })).collect())),
679                ("fields", Value::Array(vec![int(field)])),
680            ],
681        )?;
682        if let Some(&last) = self.definition_order.last() {
683            self.set(last, "next", ptr(index))?;
684        }
685        self.definition_order.push(index);
686        self.definitions.insert(identifier.to_string(), index);
687        Ok(index)
688    }
689
690    fn chain(&mut self, nodes: &[u32], next: &str, previous: &str) -> Result<(), String> {
691        for pair in nodes.windows(2) {
692            self.set(pair[0], next, ptr(pair[1]))?;
693            self.set(pair[1], previous, ptr(pair[0]))?;
694        }
695        Ok(())
696    }
697
698    /// A face's surface, owned by the face.
699    fn surface(&mut self, surface: &NurbsSurface, face: u32) -> Result<WrittenSurface, String> {
700        let index = self.reserve();
701        let id = self.id();
702        let common = |fields: &mut Vec<(&str, Value)>| {
703            fields.push(("node_id", int(id)));
704            fields.push(("owner", ptr(face)));
705            fields.push(("sense", Value::Char(b'+')));
706        };
707        let mut fields = Vec::new();
708        common(&mut fields);
709        let analytic = surface.analytic().cloned();
710        let (node_type, flipped) = match analytic {
711            Some(AnalyticSurface::Plane { origin, u_dir, v_dir, .. }) => {
712                let (Ok(normal), Ok(x)) = (u_dir.cross(v_dir).normalized(), u_dir.normalized()) else {
713                    return self.b_surface(surface, index, fields);
714                };
715                fields.push(("pvec", metres(origin)));
716                fields.push(("normal", unit(normal)));
717                fields.push(("x_axis", unit(x)));
718                (50, false)
719            }
720            Some(AnalyticSurface::RuledRevolution { frame, rho0, rho1, height }) => {
721                let flipped = height < 0.0;
722                let scale = 1.0 + rho0.abs().max(rho1.abs());
723                if (rho1 - rho0).abs() <= 1e-9 * scale {
724                    if rho0 <= 0.0 {
725                        return self.b_surface(surface, index, fields);
726                    }
727                    fields.push(("pvec", metres(frame.origin)));
728                    fields.push(("axis", unit(frame.axis)));
729                    fields.push(("radius", Value::Real(Some(rho0 / MM_PER_METRE))));
730                    fields.push(("x_axis", unit(frame.x_axis)));
731                    (51, flipped)
732                } else {
733                    // The radius grows along the written axis (as written
734                    // files have it), from rho0 at the origin.
735                    let slope = (rho1 - rho0) / height;
736                    // The point the radius is given at: the generatrix's
737                    // start, or its end when the start is the apex.
738                    let (origin, radius) = if rho0 > 0.0 { (frame.origin, rho0) } else { (frame.origin.add(frame.axis.scale(height)), rho1) };
739                    if radius <= 0.0 {
740                        return self.b_surface(surface, index, fields);
741                    }
742                    let axis = if slope >= 0.0 { frame.axis } else { frame.axis.scale(-1.0) };
743                    let half = slope.abs().atan();
744                    fields.push(("pvec", metres(origin)));
745                    fields.push(("axis", unit(axis)));
746                    fields.push(("radius", Value::Real(Some(radius / MM_PER_METRE))));
747                    fields.push(("sin_half_angle", Value::Real(Some(half.sin()))));
748                    fields.push(("cos_half_angle", Value::Real(Some(half.cos()))));
749                    fields.push(("x_axis", unit(frame.x_axis)));
750                    (52, flipped)
751                }
752            }
753            Some(AnalyticSurface::Sphere { frame, radius }) => {
754                fields.push(("centre", metres(frame.origin)));
755                fields.push(("radius", Value::Real(Some(radius / MM_PER_METRE))));
756                fields.push(("axis", unit(frame.axis)));
757                fields.push(("x_axis", unit(frame.x_axis)));
758                (53, false)
759            }
760            Some(AnalyticSurface::Torus { frame, major_radius, minor_radius }) => {
761                if minor_radius >= major_radius {
762                    return self.b_surface(surface, index, fields);
763                }
764                fields.push(("centre", metres(frame.origin)));
765                fields.push(("axis", unit(frame.axis)));
766                fields.push(("major_radius", Value::Real(Some(major_radius / MM_PER_METRE))));
767                fields.push(("minor_radius", Value::Real(Some(minor_radius / MM_PER_METRE))));
768                fields.push(("x_axis", unit(frame.x_axis)));
769                (54, false)
770            }
771            _ => return self.b_surface(surface, index, fields),
772        };
773        self.put(index, node_type, fields)?;
774        Ok(WrittenSurface { index, flipped })
775    }
776
777    /// A B_SURFACE and its NURBS_SURF: the kernel's net, positions in
778    /// metres, rational vertices premultiplied with the weight last, v
779    /// varying fastest (§5.2.2.7).
780    fn b_surface(&mut self, surface: &NurbsSurface, index: u32, mut fields: Vec<(&str, Value)>) -> Result<WrittenSurface, String> {
781        let rational = surface.control_points.iter().flatten().any(|p| (p.w - 1.0).abs() > 1e-12);
782        let nu = surface.control_points.len();
783        let nv = surface.control_points.first().map_or(0, Vec::len);
784        let dim = if rational { 4 } else { 3 };
785        let mut vertices = Vec::with_capacity(nu * nv * dim);
786        for row in &surface.control_points {
787            for p in row {
788                vertices.push(Value::Real(Some(p.x / MM_PER_METRE)));
789                vertices.push(Value::Real(Some(p.y / MM_PER_METRE)));
790                vertices.push(Value::Real(Some(p.z / MM_PER_METRE)));
791                if rational {
792                    vertices.push(Value::Real(Some(p.w)));
793                }
794            }
795        }
796        let (uk, um) = knot_runs(&surface.knots_u);
797        let (vk, vm) = knot_runs(&surface.knots_v);
798        let nurbs = self.reserve();
799        let bv = self.add(45, vec![("vertices", Value::Array(vertices))])?;
800        let ukm = self.add(127, vec![("mult", Value::Array(um.iter().map(|&m| int(m as i64)).collect()))])?;
801        let vkm = self.add(127, vec![("mult", Value::Array(vm.iter().map(|&m| int(m as i64)).collect()))])?;
802        let uks = self.add(128, vec![("knots", Value::Array(uk.iter().map(|&k| Value::Real(Some(k))).collect()))])?;
803        let vks = self.add(128, vec![("knots", Value::Array(vk.iter().map(|&k| Value::Real(Some(k))).collect()))])?;
804        self.put(
805            nurbs,
806            126,
807            vec![
808                ("u_periodic", Value::Char(b'F')),
809                ("v_periodic", Value::Char(b'F')),
810                ("u_degree", int(surface.degree_u as i64)),
811                ("v_degree", int(surface.degree_v as i64)),
812                ("n_u_vertices", int(nu as i64)),
813                ("n_v_vertices", int(nv as i64)),
814                ("u_knot_type", int(1)),
815                ("v_knot_type", int(1)),
816                ("n_u_knots", int(uk.len() as i64)),
817                ("n_v_knots", int(vk.len() as i64)),
818                ("rational", Value::Char(if rational { b'T' } else { b'F' })),
819                ("u_closed", Value::Char(b'F')),
820                ("v_closed", Value::Char(b'F')),
821                ("surface_form", int(1)),
822                ("vertex_dim", int(dim as i64)),
823                ("bspline_vertices", ptr(bv)),
824                ("u_knot_mult", ptr(ukm)),
825                ("v_knot_mult", ptr(vkm)),
826                ("u_knots", ptr(uks)),
827                ("v_knots", ptr(vks)),
828            ],
829        )?;
830        fields.push(("nurbs", ptr(nurbs)));
831        self.put(index, 124, fields)?;
832        Ok(WrittenSurface { index, flipped: false })
833    }
834
835    /// An edge's curve over the edge, start to end, owned by the edge.
836    fn curve(&mut self, edge: &crate::topology::EdgeRecord, owner: u32) -> Result<u32, String> {
837        let curve = brep_topology::edge_subcurve::edge_subcurve(edge)?;
838        let index = self.reserve();
839        let id = self.id();
840        let mut fields = vec![("node_id", int(id)), ("owner", ptr(owner)), ("sense", Value::Char(b'+'))];
841        let straight = curve.degree == 1 && curve.control_points.len() == 2 && curve.control_points.iter().all(|p| (p.w - 1.0).abs() <= 1e-12);
842        if straight {
843            let start = curve.control_points[0].point()?;
844            let end = curve.control_points[1].point()?;
845            if let Ok(direction) = end.sub(start).normalized() {
846                fields.push(("pvec", metres(start)));
847                fields.push(("direction", unit(direction)));
848                self.put(index, 30, fields)?;
849                return Ok(index);
850            }
851        }
852        if let Some(arc) = crate::step::recognize_circular_arc(&curve) {
853            fields.push(("centre", metres(arc.center)));
854            fields.push(("normal", unit(arc.axis)));
855            fields.push(("x_axis", unit(arc.x_axis)));
856            fields.push(("radius", Value::Real(Some(arc.radius / MM_PER_METRE))));
857            self.put(index, 31, fields)?;
858            return Ok(index);
859        }
860        self.b_curve(&curve, index, fields)?;
861        Ok(index)
862    }
863
864    /// A tolerant edge's fin curve: a TRIMMED_CURVE running along the fin
865    /// (from the fin's start to its vertex), over an SP_CURVE whose 2D B-curve
866    /// is the coedge's curve in its face's surface parameters. Returns
867    /// (trimmed, SP-curve).
868    fn fin_curve(&mut self, pcurve: &NurbsCurve, surface: u32, fin: u32, body: u32, ends: (Vec3, Vec3)) -> Result<(u32, u32), String> {
869        let [p0, p1] = pcurve.domain()?;
870        let basis = self.reserve();
871        let b_curve = self.reserve();
872        let rational = pcurve.control_points.iter().any(|p| (p.w - 1.0).abs() > 1e-12);
873        let dim = if rational { 3 } else { 2 };
874        let mut vertices = Vec::new();
875        for p in &pcurve.control_points {
876            vertices.push(Value::Real(Some(p.x)));
877            vertices.push(Value::Real(Some(p.y)));
878            if rational {
879                vertices.push(Value::Real(Some(p.w)));
880            }
881        }
882        let (knots, mults) = knot_runs(&pcurve.knots);
883        let nurbs = self.reserve();
884        let bv = self.add(45, vec![("vertices", Value::Array(vertices))])?;
885        let km = self.add(127, vec![("mult", Value::Array(mults.iter().map(|&m| int(m as i64)).collect()))])?;
886        let ks = self.add(128, vec![("knots", Value::Array(knots.iter().map(|&k| Value::Real(Some(k))).collect()))])?;
887        self.put(
888            nurbs,
889            136,
890            vec![
891                ("degree", int(pcurve.degree as i64)),
892                ("n_vertices", int(pcurve.control_points.len() as i64)),
893                ("vertex_dim", int(dim)),
894                ("n_knots", int(knots.len() as i64)),
895                ("knot_type", int(1)),
896                ("periodic", Value::Char(b'F')),
897                ("closed", Value::Char(b'F')),
898                ("rational", Value::Char(if rational { b'T' } else { b'F' })),
899                ("curve_form", int(1)),
900                ("bspline_vertices", ptr(bv)),
901                ("knot_mult", ptr(km)),
902                ("knots", ptr(ks)),
903            ],
904        )?;
905        self.put(b_curve, 134, vec![("sense", Value::Char(b'+')), ("nurbs", ptr(nurbs))])?;
906        let id = self.id();
907        self.put(basis, 137, vec![("node_id", int(id)), ("owner", ptr(body)), ("sense", Value::Char(b'+')), ("surface", ptr(surface)), ("b_curve", ptr(b_curve))])?;
908        let trimmed = self.reserve();
909        let id = self.id();
910        self.put(
911            trimmed,
912            133,
913            vec![
914                ("node_id", int(id)),
915                ("owner", ptr(fin)),
916                ("sense", Value::Char(b'+')),
917                ("basis_curve", ptr(basis)),
918                ("point_1", metres(ends.0)),
919                ("point_2", metres(ends.1)),
920                ("parm_1", Value::Real(Some(p0))),
921                ("parm_2", Value::Real(Some(p1))),
922            ],
923        )?;
924        Ok((trimmed, basis))
925    }
926
927    fn b_curve(&mut self, curve: &NurbsCurve, index: u32, mut fields: Vec<(&str, Value)>) -> Result<(), String> {
928        let rational = curve.control_points.iter().any(|p| (p.w - 1.0).abs() > 1e-12);
929        let dim = if rational { 4 } else { 3 };
930        let mut vertices = Vec::new();
931        for p in &curve.control_points {
932            vertices.push(Value::Real(Some(p.x / MM_PER_METRE)));
933            vertices.push(Value::Real(Some(p.y / MM_PER_METRE)));
934            vertices.push(Value::Real(Some(p.z / MM_PER_METRE)));
935            if rational {
936                vertices.push(Value::Real(Some(p.w)));
937            }
938        }
939        let (knots, mults) = knot_runs(&curve.knots);
940        let nurbs = self.reserve();
941        let bv = self.add(45, vec![("vertices", Value::Array(vertices))])?;
942        let km = self.add(127, vec![("mult", Value::Array(mults.iter().map(|&m| int(m as i64)).collect()))])?;
943        let ks = self.add(128, vec![("knots", Value::Array(knots.iter().map(|&k| Value::Real(Some(k))).collect()))])?;
944        let closed = match (curve.control_points.first(), curve.control_points.last()) {
945            (Some(a), Some(b)) => a.point()?.sub(b.point()?).length() <= 1e-9,
946            _ => false,
947        };
948        self.put(
949            nurbs,
950            136,
951            vec![
952                ("degree", int(curve.degree as i64)),
953                ("n_vertices", int(curve.control_points.len() as i64)),
954                ("vertex_dim", int(dim as i64)),
955                ("n_knots", int(knots.len() as i64)),
956                ("knot_type", int(1)),
957                ("periodic", Value::Char(b'F')),
958                ("closed", Value::Char(if closed { b'T' } else { b'F' })),
959                ("rational", Value::Char(if rational { b'T' } else { b'F' })),
960                ("curve_form", int(1)),
961                ("bspline_vertices", ptr(bv)),
962                ("knot_mult", ptr(km)),
963                ("knots", ptr(ks)),
964            ],
965        )?;
966        fields.push(("nurbs", ptr(nurbs)));
967        self.put(index, 134, fields)
968    }
969}
970
971/// The kernel shell that bounds the others: the one whose signed volume is
972/// positive (an outer shell faces out, a cavity's into the cavity), the
973/// largest if several are.
974fn outer_shell(solid: &BrepSolid) -> Result<usize, String> {
975    if solid.shells.is_empty() {
976        return Err("the solid has no shells".into());
977    }
978    if solid.shells.len() == 1 {
979        return Ok(0);
980    }
981    let volume = |s: usize| {
982        let mut one = solid.clone();
983        one.shells = vec![solid.shells[s].clone()];
984        one.mass_properties_cache = Default::default();
985        crate::solid_signed_volume(&one).unwrap_or(f64::NAN)
986    };
987    let volumes: Vec<f64> = (0..solid.shells.len()).map(volume).collect();
988    (0..solid.shells.len())
989        .filter(|&s| volumes[s] > 0.0)
990        .max_by(|&a, &b| volumes[a].total_cmp(&volumes[b]))
991        .ok_or_else(|| format!("no shell of the solid encloses positive volume ({volumes:?})"))
992}
993
994/// Distinct knots and their multiplicities.
995fn knot_runs(knots: &[f64]) -> (Vec<f64>, Vec<usize>) {
996    let mut values: Vec<f64> = Vec::new();
997    let mut mults: Vec<usize> = Vec::new();
998    for &k in knots {
999        match values.last() {
1000            Some(&last) if (k - last).abs() <= 0.0 => *mults.last_mut().unwrap() += 1,
1001            _ => {
1002                values.push(k);
1003                mults.push(1);
1004            }
1005        }
1006    }
1007    (values, mults)
1008}
1009
1010fn default_value(kind: Kind) -> Value {
1011    match kind {
1012        Kind::Int => Value::Int(Some(0)),
1013        Kind::Real => Value::Real(None),
1014        Kind::Vector => Value::Vector(None),
1015        Kind::Interval => Value::Interval([None; 2]),
1016        Kind::Box => Value::Box([None; 6]),
1017        Kind::Char | Kind::Unknown => Value::Char(b'?'),
1018    }
1019}
1020
1021fn int(v: i64) -> Value {
1022    Value::Int(Some(v))
1023}
1024
1025fn ptr(index: u32) -> Value {
1026    Value::Int(Some(i64::from(index)))
1027}
1028
1029fn metres(p: Vec3) -> Value {
1030    Value::Vector(Some([p.x / MM_PER_METRE, p.y / MM_PER_METRE, p.z / MM_PER_METRE]))
1031}
1032
1033fn unit(v: Vec3) -> Value {
1034    Value::Vector(Some([v.x, v.y, v.z]))
1035}