Skip to main content

brep_kernel/io/
step.rs

1use crate::analytic_surface::curve_scale;
2use crate::analytic_surface::{circumcenter, AnalyticSurface};
3use crate::topology::{BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, VertexRecord};
4use crate::{make_arc, KernelTolerances, NurbsCurve, NurbsSurface, Vec3};
5use rustc_hash::FxHashMap as HashMap;
6
7#[path = "step/pcurve.rs"]
8pub(crate) mod pcurve;
9use pcurve::{build_pcurve, EmittedCurve, EmittedFrame, EmittedSurface, Pcurve2d};
10#[path = "step/pmi.rs"]
11pub(crate) mod pmi;
12pub use pmi::StepPmi;
13#[path = "step/assembly.rs"]
14pub mod assembly;
15pub use assembly::{
16    export_step_assembly, export_step_assembly_report, StepAssemblyExport, StepExportOccurrence,
17    StepExportProduct,
18};
19#[path = "step/export_tree.rs"]
20mod export_tree;
21pub use export_tree::{assembly_export_tree, PART_ATTRIBUTES, PART_NUMBER};
22#[path = "step/styles.rs"]
23pub(crate) mod styles;
24pub use styles::StepColors;
25
26pub use crate::step_matrix::Mat4;
27pub(crate) use crate::step_matrix::{mat4_mul, MAT4_IDENTITY};
28
29pub(crate) fn transform_point(matrix: &Mat4, point: Vec3) -> Vec3 {
30    crate::AffineTransform {
31        elements: *matrix,
32    }
33    .point(point)
34}
35
36pub(crate) fn step_string(value: &str) -> String {
37    value.replace('\'', "''")
38}
39
40pub(crate) fn real(value: f64) -> Result<String, String> {
41    if !value.is_finite() {
42        return Err(format!("export_step: non-finite number {value}"));
43    }
44    // Analytic frame axes come from cross products that can round to -0.0;
45    // normalize so directions never print a negative zero component.
46    if value == 0.0 {
47        return Ok("0.".into());
48    }
49    if value.fract() == 0.0 && value.abs() < 1e15 {
50        return Ok(format!("{value:.0}."));
51    }
52    let mut output = format!("{value:.15}");
53    while output.ends_with('0') {
54        output.pop();
55    }
56    if output.ends_with('.') {
57        output.push('0');
58    }
59    if output == "-0.0" {
60        output = "0.0".into();
61    }
62    Ok(output)
63}
64
65fn knot_runs(knots: &[f64]) -> (Vec<f64>, Vec<usize>) {
66    let mut values = Vec::new();
67    let mut multiplicities = Vec::new();
68    for &knot in knots {
69        if values
70            .last()
71            .is_some_and(|previous: &f64| (*previous - knot).abs() <= 1e-12)
72        {
73            *multiplicities.last_mut().unwrap() += 1;
74        } else {
75            values.push(knot);
76            multiplicities.push(1);
77        }
78    }
79    (values, multiplicities)
80}
81pub(crate) use crate::edge_subcurve::edge_subcurve;
82
83
84#[derive(Default)]
85pub(crate) struct StepWriter {
86    lines: Vec<String>,
87}
88
89impl StepWriter {
90    pub(crate) fn add(&mut self, body: impl Into<String>) -> usize {
91        let id = self.lines.len() + 1;
92        self.lines.push(format!("#{id}={};", body.into()));
93        id
94    }
95
96    fn data(&self) -> String {
97        self.lines.join("\n")
98    }
99}
100
101pub(crate) fn write_point(writer: &mut StepWriter, point: Vec3) -> Result<usize, String> {
102    Ok(writer.add(format!(
103        "CARTESIAN_POINT('',({},{},{}))",
104        real(point.x)?,
105        real(point.y)?,
106        real(point.z)?
107    )))
108}
109
110pub(crate) fn id_list(ids: &[usize]) -> String {
111    format!(
112        "({})",
113        ids.iter()
114            .map(|id| format!("#{id}"))
115            .collect::<Vec<_>>()
116            .join(",")
117    )
118}
119
120pub(crate) fn write_direction(writer: &mut StepWriter, direction: Vec3) -> Result<usize, String> {
121    Ok(writer.add(format!(
122        "DIRECTION('',({},{},{}))",
123        real(direction.x)?,
124        real(direction.y)?,
125        real(direction.z)?
126    )))
127}
128
129pub(crate) fn write_placement(
130    writer: &mut StepWriter,
131    origin: Vec3,
132    axis: Vec3,
133    ref_direction: Vec3,
134) -> Result<usize, String> {
135    let origin = write_point(writer, origin)?;
136    let axis = write_direction(writer, axis)?;
137    let ref_direction = write_direction(writer, ref_direction)?;
138    Ok(writer.add(format!(
139        "AXIS2_PLACEMENT_3D('',#{origin},#{axis},#{ref_direction})"
140    )))
141}
142
143/// Emit the analytic AP242 surface entity (PLANE / CYLINDRICAL_SURFACE /
144/// CONICAL_SURFACE / SPHERICAL_SURFACE / TOROIDAL_SURFACE) for a recognized
145/// carrier, or `None` when the surface must stay a B-spline. The second value
146/// reports whether the STEP-standard orientation of the emitted entity (plane
147/// normal along the placement axis; revolution normal outward) is the REVERSE
148/// of the stored NURBS orientation, so ADVANCED_FACE can invert `same_sense`
149/// and the face normal survives the round trip. The third describes the
150/// emitted entity's own (u,v) parameterization for the pcurve writer.
151fn write_analytic_surface(
152    writer: &mut StepWriter,
153    surface: &NurbsSurface,
154) -> Result<Option<(usize, bool, EmittedSurface)>, String> {
155    let Some(analytic) = surface.analytic() else {
156        if crate::switch!("BREP_EXTRUSION_EXPORT", true) {
157            if let Some(extrusion) = surface.linear_extrusion() {
158                let magnitude = extrusion.direction.length();
159                let axis = extrusion.direction.normalized()?;
160                // A swept entity's reader rebuilds the finite axial band from
161                // its boundary. That coordinate is unambiguous for a profile
162                // in an axis-normal plane. An advancing profile (for example
163                // a helix) can project onto itself on several turns; retain
164                // the original finite NURBS chart rather than lose its turn.
165                let anchor = extrusion.profile.control_points[0].point()?;
166                let points = extrusion.profile.control_points.iter().map(|p|p.point()).collect::<Result<Vec<_>,_>>()?;
167                let extent = points.iter().map(|p|p.sub(anchor).length()).fold(magnitude,f64::max);
168                let coordinate = points.iter().map(|p|p.length()).fold(anchor.length(),f64::max);
169                let band = 1e-11*extent + 32.0*f64::EPSILON*coordinate;
170                if points.iter().any(|p|p.sub(anchor).dot(axis).abs()>band) { return Ok(None); }
171                let profile = write_curve(writer,&extrusion.profile)?;
172                let direction = write_direction(writer,axis)?;
173                let vector = writer.add(format!("VECTOR('',#{direction},1.)"));
174                let entity = writer.add(format!("SURFACE_OF_LINEAR_EXTRUSION('',#{profile},#{vector})"));
175                return Ok(Some((entity,!extrusion.profile_is_u,EmittedSurface::Extrusion {
176                    profile:extrusion.profile.clone(), direction:axis,
177                    profile_is_u:extrusion.profile_is_u, sweep_start:extrusion.sweep_domain[0], magnitude,
178                })));
179            }
180        }
181        return Ok(None);
182    };
183    match analytic {
184        AnalyticSurface::Plane {
185            origin,
186            u_dir,
187            v_dir,
188            ..
189        } => {
190            // STEP planes are unbounded; the importer re-sizes the patch from
191            // the face's edges, so only origin/normal/ref matter.
192            let (Ok(normal), Ok(x_axis)) = (u_dir.cross(*v_dir).normalized(), u_dir.normalized())
193            else {
194                return Ok(None);
195            };
196            let placement = write_placement(writer, *origin, normal, x_axis)?;
197            // The reader derives the plane's second parameter axis as
198            // normal × ref_direction, so S(x,y) = origin + x·x̂ + y·ŷ with
199            // those exact vectors — an orthonormal frame regardless of how the
200            // stored patch scaled or sheared its own u_dir/v_dir.
201            Ok(Some((
202                writer.add(format!("PLANE('',#{placement})")),
203                false,
204                EmittedSurface::Plane {
205                    origin: *origin,
206                    x_axis,
207                    y_axis: normal.cross(x_axis),
208                },
209            )))
210        }
211        AnalyticSurface::RuledRevolution {
212            frame,
213            rho0,
214            rho1,
215            height,
216        } => {
217            // The recognizer allows height < 0 (descending generatrix), whose
218            // normal is the reverse of the standard outward convention the
219            // importer reconstructs; report that so the face sense compensates.
220            let flipped = *height < 0.0;
221            let radius_scale = 1.0 + rho0.abs().max(rho1.abs());
222            if (rho1 - rho0).abs() <= 1e-9 * radius_scale {
223                if *rho0 <= 0.0 {
224                    return Ok(None);
225                }
226                let placement = write_placement(writer, frame.origin, frame.axis, frame.x_axis)?;
227                return Ok(Some((
228                    writer.add(format!(
229                        "CYLINDRICAL_SURFACE('',#{placement},{})",
230                        real(*rho0)?
231                    )),
232                    flipped,
233                    EmittedSurface::Cylinder {
234                        frame: EmittedFrame {
235                            origin: frame.origin,
236                            x_axis: frame.x_axis,
237                            y_axis: frame.y_axis,
238                            axis: frame.axis,
239                            azimuth_sign: 1.0,
240                        },
241                        radius: *rho0,
242                    },
243                )));
244            }
245            // Cone. The importer re-sizes the carrier from edge samples with a
246            // 1e-4-scaled axial margin and clamps a negative extended-end
247            // radius to zero — which BENDS the rebuilt slope when the apex sits
248            // at an end of the face's axial range. Keep apex-touching cones as
249            // exact NURBS instead of exporting a distorted carrier.
250            let slope = (rho1 - rho0) / height;
251            let apex_margin = 2.0 * (1e-4 * height.abs().max(1.0) + 1e-9) * slope.abs();
252            if rho0.min(*rho1) <= apex_margin {
253                return Ok(None);
254            }
255            // Orient the placement axis so the radius grows along +axis: STEP
256            // semi-angles are positive. Radius at the placement origin stays
257            // rho0 either way because the origin is on-axis at the v = 0 base.
258            let axis = if slope >= 0.0 {
259                frame.axis
260            } else {
261                frame.axis.scale(-1.0)
262            };
263            let placement = write_placement(writer, frame.origin, axis, frame.x_axis)?;
264            Ok(Some((
265                writer.add(format!(
266                    "CONICAL_SURFACE('',#{placement},{},{})",
267                    real(*rho0)?,
268                    real(slope.abs().atan())?
269                )),
270                flipped,
271                EmittedSurface::Cone {
272                    frame: EmittedFrame {
273                        origin: frame.origin,
274                        x_axis: frame.x_axis,
275                        // Reversing the placement axis reverses the derived
276                        // second axis with it, so the emitted azimuth runs
277                        // opposite the stored carrier's u.
278                        y_axis: axis.cross(frame.x_axis),
279                        axis,
280                        azimuth_sign: if slope >= 0.0 { 1.0 } else { -1.0 },
281                    },
282                    radius: *rho0,
283                    semi_angle: slope.abs().atan(),
284                },
285            )))
286        }
287        AnalyticSurface::Sphere { frame, radius } => {
288            // Recognition template and importer reconstruction share the same
289            // south-to-north meridian construction, so the rebuild is exact.
290            let placement = write_placement(writer, frame.origin, frame.axis, frame.x_axis)?;
291            Ok(Some((
292                writer.add(format!(
293                    "SPHERICAL_SURFACE('',#{placement},{})",
294                    real(*radius)?
295                )),
296                false,
297                EmittedSurface::Sphere {
298                    frame: EmittedFrame {
299                        origin: frame.origin,
300                        x_axis: frame.x_axis,
301                        y_axis: frame.y_axis,
302                        axis: frame.axis,
303                        azimuth_sign: 1.0,
304                    },
305                    radius: *radius,
306                },
307            )))
308        }
309        AnalyticSurface::Torus {
310            frame,
311            major_radius,
312            minor_radius,
313        } => {
314            let placement = write_placement(writer, frame.origin, frame.axis, frame.x_axis)?;
315            Ok(Some((
316                writer.add(format!(
317                    "TOROIDAL_SURFACE('',#{placement},{},{})",
318                    real(*major_radius)?,
319                    real(*minor_radius)?
320                )),
321                false,
322                EmittedSurface::Torus {
323                    frame: EmittedFrame {
324                        origin: frame.origin,
325                        x_axis: frame.x_axis,
326                        y_axis: frame.y_axis,
327                        axis: frame.axis,
328                        azimuth_sign: 1.0,
329                    },
330                    major_radius: *major_radius,
331                    minor_radius: *minor_radius,
332                },
333            )))
334        }
335        // No SURFACE_OF_REVOLUTION reader exists yet; general revolutions keep
336        // their exact NURBS form — except a sphere, which a reader knows.
337        AnalyticSurface::Revolution { frame, generatrix, .. } => {
338            let Some((center, radius, reversed)) = polar_meridian_sphere(frame, generatrix) else {
339                return Ok(None);
340            };
341            let placement = write_placement(writer, center, frame.axis, frame.x_axis)?;
342            Ok(Some((
343                writer.add(format!(
344                    "SPHERICAL_SURFACE('',#{placement},{})",
345                    real(radius)?
346                )),
347                reversed,
348                EmittedSurface::Sphere {
349                    frame: EmittedFrame {
350                        origin: center,
351                        x_axis: frame.x_axis,
352                        y_axis: frame.y_axis,
353                        axis: frame.axis,
354                        azimuth_sign: 1.0,
355                    },
356                    radius,
357                },
358            )))
359        }
360    }
361}
362
363/// `BREP_STEP_SPHERE_OF_REVOLUTION` (default on, `=0` restores the B-spline):
364/// a revolution whose generatrix is an arc of a circle centred on the axis is
365/// written as a SPHERICAL_SURFACE, whatever its sweep, whichever way the arc
366/// runs and whether or not it reaches a pole.
367fn sphere_of_revolution_on() -> bool {
368    crate::switch!("BREP_STEP_SPHERE_OF_REVOLUTION", true)
369}
370
371/// The centre and radius of the sphere a general revolution lies on when its
372/// generatrix is an arc of a circle centred on the axis, in the meridian
373/// half-plane, and whether the arc runs north to south there, which makes the
374/// stored normal point inward. A part turn of a half circle about its own
375/// chord is such a surface: a lune between the two poles, which a reader can
376/// bound on a sphere but not on a B-spline patch whose two pole sides have no
377/// length.
378///
379/// The arc is read span by span, so a piece split out of a longer circle
380/// (knots and end weights no longer `make_arc`'s) is taken too: each rational
381/// quadratic span is a circular arc about `centre` exactly when its ends are
382/// at the radius, its middle control point is where the end tangents meet,
383/// and its weights satisfy w1² = w0·w2·cos²(half the span's angle).
384fn polar_meridian_sphere(
385    frame: &crate::analytic_surface::RevolutionFrame,
386    generatrix: &NurbsCurve,
387) -> Option<(Vec3, f64, bool)> {
388    if !sphere_of_revolution_on() {
389        return None;
390    }
391    let controls = &generatrix.control_points;
392    let count = controls.len();
393    if generatrix.degree != 2 || count < 3 || count % 2 == 0 || generatrix.knots.len() != count + 3 {
394        return None;
395    }
396    // Bezier spans: every interior knot twice.
397    let knots = &generatrix.knots;
398    let span_knots = (count - 1) / 2;
399    for span in 1..span_knots {
400        if (knots[1 + 2 * span] - knots[2 + 2 * span]).abs() > 1e-12 {
401            return None;
402        }
403    }
404    let scale = curve_scale(generatrix);
405    let tolerance = 1e-9 * scale.max(1.0);
406    let mut points = Vec::with_capacity(count);
407    for control in controls {
408        if control.w <= 0.0 {
409            return None;
410        }
411        let point = control.point().ok()?;
412        // in the meridian half-plane the frame's x axis and its axis span
413        let d = point.sub(frame.origin);
414        if d.dot(frame.y_axis).abs() > tolerance || d.dot(frame.x_axis) < -tolerance {
415            return None;
416        }
417        points.push(point);
418    }
419    // The centre is on the axis at height `t` above the frame's origin; every
420    // span gives linear conditions on it (ends equidistant, end tangents
421    // square to the radii).
422    let (mut num, mut den) = (0.0, 0.0);
423    for span in 0..span_knots {
424        let (p0, p1, p2) = (points[2 * span], points[2 * span + 1], points[2 * span + 2]);
425        for (direction, through) in [
426            (p2.sub(p0), p0.add(p2).scale(0.5)),
427            (p1.sub(p0), p0),
428            (p1.sub(p2), p2),
429        ] {
430            // direction · (through − origin − t·axis) = 0
431            let a = direction.dot(frame.axis);
432            let b = direction.dot(through.sub(frame.origin));
433            num += a * b;
434            den += a * a;
435        }
436    }
437    if den <= tolerance * tolerance {
438        return None;
439    }
440    let center = frame.origin.add(frame.axis.scale(num / den));
441    let radius = points[0].sub(center).length();
442    if radius <= tolerance {
443        return None;
444    }
445    let mut turn = 0.0;
446    for span in 0..span_knots {
447        let (p0, p1, p2) = (points[2 * span], points[2 * span + 1], points[2 * span + 2]);
448        let (r0, r1, r2) = (p0.sub(center), p1.sub(center), p2.sub(center));
449        if (r0.length() - radius).abs() > tolerance
450            || (r2.length() - radius).abs() > tolerance
451            || p1.sub(p0).dot(r0).abs() > tolerance * radius
452            || p1.sub(p2).dot(r2).abs() > tolerance * radius
453        {
454            return None;
455        }
456        // cos(half the span's angle) = radius / |r1|
457        let cos_half = radius / r1.length();
458        let (w0, w1, w2) = (controls[2 * span].w, controls[2 * span + 1].w, controls[2 * span + 2].w);
459        if !(cos_half > 1e-6) || (w1 * w1 / (w0 * w2) - cos_half * cos_half).abs() > 1e-9 {
460            return None;
461        }
462        // which way the span turns in the (x, axis) half-plane
463        let cross = r0.dot(frame.x_axis) * r2.dot(frame.axis) - r0.dot(frame.axis) * r2.dot(frame.x_axis);
464        if cross.abs() <= tolerance * radius || (turn != 0.0 && cross.signum() != turn) {
465            return None;
466        }
467        turn = cross.signum();
468    }
469    Some((center, radius, turn < 0.0))
470}
471
472/// A curve recognized as an exact `make_arc` product: a circular arc of
473/// `radius` about `axis`, starting at angle 0 on `x_axis` and travelling
474/// counterclockwise through `sweep` — exactly the CIRCLE parameterization the
475/// importer trims between the edge's vertices.
476pub(crate) struct CircularArc {
477    pub(crate) center: Vec3,
478    pub(crate) axis: Vec3,
479    pub(crate) x_axis: Vec3,
480    /// axis × x_axis — the second placement axis a STEP reader derives, so the
481    /// emitted parameterization is C(a) = center + r(cos a·x̂ + sin a·ŷ).
482    pub(crate) y_axis: Vec3,
483    pub(crate) radius: f64,
484    /// Total swept angle: the emitted entity's parameter range is [0, sweep].
485    pub(crate) sweep: f64,
486    /// Rational-quadratic span count of the kernel arc this was recognized
487    /// from — the bridge from the emitted ANGLE back to the kernel's own
488    /// parameter, which a fitted pcurve on a B-spline carrier needs.
489    spans: usize,
490}
491
492
493
494/// Homogeneous-net equality to a scale-relative tolerance (the same
495/// reconstruction contract analytic_surface.rs uses): matching nets mean the
496/// curves are the SAME exact rational arc, not merely close.
497fn curves_match(a: &NurbsCurve, b: &NurbsCurve, scale: f64) -> bool {
498    if a.degree != b.degree
499        || a.knots.len() != b.knots.len()
500        || a.control_points.len() != b.control_points.len()
501    {
502        return false;
503    }
504    if a.knots
505        .iter()
506        .zip(&b.knots)
507        .any(|(x, y)| (x - y).abs() > 1e-12)
508    {
509        return false;
510    }
511    let tolerance = 1e-9 * scale.max(1.0);
512    a.control_points
513        .iter()
514        .zip(&b.control_points)
515        .all(|(p, q)| {
516            (p.x - q.x).abs() <= tolerance
517                && (p.y - q.y).abs() <= tolerance
518                && (p.z - q.z).abs() <= tolerance
519                && (p.w - q.w).abs() <= 1e-9
520        })
521}
522
523/// Recognition by exact reconstruction: extract a candidate circle from three
524/// curve points, rebuild it with `make_arc`, and demand the identical net.
525/// Split subranges of a circle (whose knots are no longer the pristine
526/// make_arc pattern) are rejected and honestly stay NURBS.
527pub(crate) fn recognize_circular_arc(curve: &NurbsCurve) -> Option<CircularArc> {
528    if curve.degree != 2
529        || curve.control_points.len() < 3
530        || curve.control_points.len() % 2 == 0
531        || (curve.control_points.len() - 1) / 2 > 4
532    {
533        return None;
534    }
535    let [t0, t1] = curve.domain().ok()?;
536    let at = |fraction: f64| curve.evaluate(t0 + (t1 - t0) * fraction);
537    // Three points at < 74% of the sweep apart, so consecutive pairs subtend
538    // less than pi and the cross product below gives the travel direction.
539    let p0 = at(0.0).ok()?;
540    let pa = at(0.35).ok()?;
541    let pb = at(0.7).ok()?;
542    let center = circumcenter(p0, pa, pb)?;
543    let radial = p0.sub(center);
544    let radius = radial.length();
545    let scale = curve_scale(curve);
546    if radius <= 1e-9 * scale.max(1.0) {
547        return None;
548    }
549    let x_axis = radial.scale(1.0 / radius);
550    let axis = radial.cross(pa.sub(center)).normalized().ok()?;
551    let y_axis = axis.cross(x_axis);
552    let p_end = at(1.0).ok()?;
553    let sweep = if p_end.sub(p0).length() <= 1e-9 * (1.0 + radius) {
554        std::f64::consts::TAU
555    } else {
556        let closing = p_end.sub(center);
557        let mut angle = closing.dot(y_axis).atan2(closing.dot(x_axis));
558        if angle < 0.0 {
559            angle += std::f64::consts::TAU;
560        }
561        angle
562    };
563    let rebuilt = make_arc(center, x_axis, y_axis, radius, 0.0, sweep).ok()?;
564    curves_match(curve, &rebuilt, scale).then_some(CircularArc {
565        center,
566        axis,
567        x_axis,
568        y_axis,
569        radius,
570        sweep,
571        spans: (curve.control_points.len() - 1) / 2,
572    })
573}
574
575/// Emit LINE or CIRCLE for a recognized analytic edge curve (already oriented
576/// start-to-end by `edge_subcurve`), or `None` for the B-spline fallback.
577///
578/// The second value describes the parameterization ISO 10303-42 gives the
579/// entity that was written, because a pcurve on this edge has to share THAT
580/// parameter — not the kernel's knot values (see `step/pcurve.rs`).
581fn write_analytic_curve(
582    writer: &mut StepWriter,
583    curve: &NurbsCurve,
584) -> Result<Option<(usize, EmittedCurve)>, String> {
585    if curve.degree == 1
586        && curve.control_points.len() == 2
587        && curve
588            .control_points
589            .iter()
590            .all(|control| (control.w - 1.0).abs() <= 1e-12)
591    {
592        let start = curve.control_points[0].point()?;
593        let end = curve.control_points[1].point()?;
594        let Ok(direction) = end.sub(start).normalized() else {
595            return Ok(None);
596        };
597        let point = write_point(writer, start)?;
598        let step_direction = write_direction(writer, direction)?;
599        let vector = writer.add(format!(
600            "VECTOR('',#{step_direction},{})",
601            real(end.sub(start).length())?
602        ));
603        return Ok(Some((
604            writer.add(format!("LINE('',#{point},#{vector})")),
605            // The VECTOR carries the full chord length, so the STEP parameter
606            // of this line is the fraction along the chord: C(s) = start +
607            // s·(end − start) over [0, 1].
608            EmittedCurve::Line { start, end },
609        )));
610    }
611    if let Some(arc) = recognize_circular_arc(curve) {
612        // ref_direction points at the edge's start vertex and the arc runs
613        // counterclockwise about the axis, so the importer's vertex-trimmed
614        // CCW rebuild reproduces the same directed curve with sense .T.
615        let placement = write_placement(writer, arc.center, arc.axis, arc.x_axis)?;
616        return Ok(Some((
617            writer.add(format!("CIRCLE('',#{placement},{})", real(arc.radius)?)),
618            EmittedCurve::Circle {
619                center: arc.center,
620                x_axis: arc.x_axis,
621                y_axis: arc.y_axis,
622                radius: arc.radius,
623                sweep: arc.sweep,
624                spans: arc.spans,
625            },
626        )));
627    }
628    Ok(None)
629}
630
631fn write_curve(writer: &mut StepWriter, curve: &NurbsCurve) -> Result<usize, String> {
632    let points = curve
633        .control_points
634        .iter()
635        .map(|control| write_point(writer, control.point()?))
636        .collect::<Result<Vec<_>, _>>()?;
637    write_bspline_curve(writer, curve, &points)
638}
639
640/// The B_SPLINE_CURVE_WITH_KNOTS entity (or its rational complex form) over
641/// control points that have ALREADY been written — shared by the 3D edge
642/// curves and by the 2D pcurves, whose CARTESIAN_POINTs carry two coordinates
643/// instead of three but whose degree/knots/weights are written identically.
644fn write_bspline_curve(
645    writer: &mut StepWriter,
646    curve: &NurbsCurve,
647    points: &[usize],
648) -> Result<usize, String> {
649    let (knot_values, multiplicities) = knot_runs(&curve.knots);
650    let multiplicities = format!(
651        "({})",
652        multiplicities
653            .iter()
654            .map(usize::to_string)
655            .collect::<Vec<_>>()
656            .join(",")
657    );
658    let knots = format!(
659        "({})",
660        knot_values
661            .iter()
662            .map(|value| real(*value))
663            .collect::<Result<Vec<_>, _>>()?
664            .join(",")
665    );
666    let rational = curve
667        .control_points
668        .iter()
669        .any(|control| (control.w - 1.0).abs() > 1e-12);
670    if !rational {
671        return Ok(writer.add(format!(
672            "B_SPLINE_CURVE_WITH_KNOTS('',{},{},.UNSPECIFIED.,.F.,.F.,{multiplicities},{knots},.UNSPECIFIED.)",
673            curve.degree,
674            id_list(points),
675        )));
676    }
677    let weights = format!(
678        "({})",
679        curve
680            .control_points
681            .iter()
682            .map(|control| real(control.w))
683            .collect::<Result<Vec<_>, _>>()?
684            .join(",")
685    );
686    Ok(writer.add(format!(
687        "(BOUNDED_CURVE()B_SPLINE_CURVE({},{},.UNSPECIFIED.,.F.,.F.)\
688         B_SPLINE_CURVE_WITH_KNOTS({multiplicities},{knots},.UNSPECIFIED.)\
689         CURVE()GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_CURVE({weights})\
690         REPRESENTATION_ITEM(''))",
691        curve.degree,
692        id_list(points),
693    )))
694}
695
696fn write_point_2d(writer: &mut StepWriter, point: [f64; 2]) -> Result<usize, String> {
697    Ok(writer.add(format!(
698        "CARTESIAN_POINT('',({},{}))",
699        real(point[0])?,
700        real(point[1])?
701    )))
702}
703
704fn write_direction_2d(writer: &mut StepWriter, direction: [f64; 2]) -> Result<usize, String> {
705    Ok(writer.add(format!(
706        "DIRECTION('',({},{}))",
707        real(direction[0])?,
708        real(direction[1])?
709    )))
710}
711
712/// Write the 2D geometry of one pcurve.
713///
714/// The `VECTOR` of a 2D LINE carries its TRUE magnitude rather than being
715/// normalized to 1: ISO 10303-42 parameterizes a line as pnt + u·(magnitude ×
716/// orientation), so the magnitude is what makes the 2D parameter equal the 3D
717/// entity's parameter exactly.  (OpenCASCADE normalizes every VECTOR it writes
718/// and then loses that agreement wherever the two speeds differ — its own cone
719/// ruling pcurves are off by cos(semi-angle) — so this is strictly the more
720/// faithful of the two conventions, and identical wherever the speeds agree.)
721fn write_pcurve_geometry(writer: &mut StepWriter, curve: &Pcurve2d) -> Result<usize, String> {
722    match curve {
723        Pcurve2d::Line { point, vector } => {
724            let magnitude = vector[0].hypot(vector[1]);
725            if magnitude <= 0.0 {
726                return Err("export_step: degenerate 2D line pcurve".into());
727            }
728            let point_id = write_point_2d(writer, *point)?;
729            let direction =
730                write_direction_2d(writer, [vector[0] / magnitude, vector[1] / magnitude])?;
731            let vector_id = writer.add(format!(
732                "VECTOR('',#{direction},{})",
733                real(magnitude)?
734            ));
735            Ok(writer.add(format!("LINE('',#{point_id},#{vector_id})")))
736        }
737        Pcurve2d::Circle {
738            center,
739            ref_direction,
740            radius,
741        } => {
742            let center_id = write_point_2d(writer, *center)?;
743            let direction = write_direction_2d(writer, *ref_direction)?;
744            let placement = writer.add(format!(
745                "AXIS2_PLACEMENT_2D('',#{center_id},#{direction})"
746            ));
747            Ok(writer.add(format!("CIRCLE('',#{placement},{})", real(*radius)?)))
748        }
749        Pcurve2d::Spline(spline) => {
750            let points = spline
751                .control_points
752                .iter()
753                .map(|control| {
754                    let point = control.point()?;
755                    write_point_2d(writer, [point.x, point.y])
756                })
757                .collect::<Result<Vec<_>, String>>()?;
758            write_bspline_curve(writer, spline, &points)
759        }
760    }
761}
762
763/// `PCURVE('', surface, DEFINITIONAL_REPRESENTATION('', (2d curve), ctx))` —
764/// the association of one 2D curve with the surface it parameterizes.
765fn write_pcurve_entity(
766    writer: &mut StepWriter,
767    surface_id: usize,
768    context_2d: usize,
769    curve: &Pcurve2d,
770) -> Result<usize, String> {
771    let geometry = write_pcurve_geometry(writer, curve)?;
772    let representation = writer.add(format!(
773        "DEFINITIONAL_REPRESENTATION('',(#{geometry}),#{context_2d})"
774    ));
775    Ok(writer.add(format!("PCURVE('',#{surface_id},#{representation})")))
776}
777
778fn write_surface(writer: &mut StepWriter, surface: &NurbsSurface) -> Result<usize, String> {
779    let rows = surface
780        .control_points
781        .iter()
782        .map(|row| {
783            row.iter()
784                .map(|control| write_point(writer, control.point()?))
785                .collect::<Result<Vec<_>, _>>()
786                .map(|ids| id_list(&ids))
787        })
788        .collect::<Result<Vec<_>, _>>()?;
789    let grid = format!("({})", rows.join(","));
790    let (u_values, u_multiplicities) = knot_runs(&surface.knots_u);
791    let (v_values, v_multiplicities) = knot_runs(&surface.knots_v);
792    let multiplicities = |values: &[usize]| {
793        format!(
794            "({})",
795            values
796                .iter()
797                .map(usize::to_string)
798                .collect::<Vec<_>>()
799                .join(",")
800        )
801    };
802    let knots = |values: &[f64]| -> Result<String, String> {
803        Ok(format!(
804            "({})",
805            values
806                .iter()
807                .map(|value| real(*value))
808                .collect::<Result<Vec<_>, _>>()?
809                .join(",")
810        ))
811    };
812    let u_mults = multiplicities(&u_multiplicities);
813    let v_mults = multiplicities(&v_multiplicities);
814    let u_knots = knots(&u_values)?;
815    let v_knots = knots(&v_values)?;
816    let rational = surface
817        .control_points
818        .iter()
819        .flatten()
820        .any(|control| (control.w - 1.0).abs() > 1e-12);
821    if !rational {
822        return Ok(writer.add(format!(
823            "B_SPLINE_SURFACE_WITH_KNOTS('',{},{},{grid},.UNSPECIFIED.,.F.,.F.,.F.,\
824             {u_mults},{v_mults},{u_knots},{v_knots},.UNSPECIFIED.)",
825            surface.degree_u, surface.degree_v,
826        )));
827    }
828    let weights = format!(
829        "({})",
830        surface
831            .control_points
832            .iter()
833            .map(|row| {
834                row.iter()
835                    .map(|control| real(control.w))
836                    .collect::<Result<Vec<_>, _>>()
837                    .map(|values| format!("({})", values.join(",")))
838            })
839            .collect::<Result<Vec<_>, _>>()?
840            .join(",")
841    );
842    Ok(writer.add(format!(
843        "(BOUNDED_SURFACE()B_SPLINE_SURFACE({},{},{grid},.UNSPECIFIED.,.F.,.F.,.F.)\
844         B_SPLINE_SURFACE_WITH_KNOTS({u_mults},{v_mults},{u_knots},{v_knots},.UNSPECIFIED.)\
845         GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_SURFACE({weights})\
846         REPRESENTATION_ITEM('')SURFACE())",
847        surface.degree_u, surface.degree_v,
848    )))
849}
850
851fn write_length_unit(writer: &mut StepWriter, unit: &str) -> Result<usize, String> {
852    let normalized = unit.to_lowercase();
853    if normalized == "meter" || normalized == "metre" {
854        return Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT($,.METRE.))"));
855    }
856    if normalized == "centimeter" || normalized == "centimetre" {
857        return Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.CENTI.,.METRE.))"));
858    }
859    if matches!(normalized.as_str(), "micron" | "micrometer" | "micrometre") {
860        return Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MICRO.,.METRE.))"));
861    }
862    if normalized == "inch" || normalized == "foot" {
863        let metre = writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT($,.METRE.))");
864        let (factor, name) = if normalized == "inch" {
865            (0.0254, "INCH")
866        } else {
867            (0.3048, "FOOT")
868        };
869        let measure = writer.add(format!(
870            "LENGTH_MEASURE_WITH_UNIT(LENGTH_MEASURE({}),#{metre})",
871            real(factor)?
872        ));
873        return Ok(writer.add(format!(
874            "(CONVERSION_BASED_UNIT('{name}',#{measure})LENGTH_UNIT()NAMED_UNIT(*))"
875        )));
876    }
877    Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))"))
878}
879
880/// The outward shell (an index into `shells`, one of `outer`) that owns the
881/// void `void`: the smallest by volume of those its shell lies inside. The
882/// shells of a valid solid do not meet, so one point of the void (the middle
883/// of its first proper edge) is inside or outside each of them throughout.
884fn void_owner(
885    solid: &BrepSolid,
886    void: usize,
887    outer: &[usize],
888    shells: &[(usize, bool, f64)],
889) -> Result<usize, String> {
890    let probe = solid.shells[void]
891        .faces
892        .iter()
893        .flat_map(|face| &face.loops)
894        .flat_map(|lp| &lp.coedges)
895        .find_map(|coedge| {
896            let edge = solid.edges.iter().find(|edge| edge.id == coedge.edge_id)?;
897            (!edge.degenerate).then(|| edge.curve.evaluate(0.5 * (edge.t0 + edge.t1)).ok()).flatten()
898        })
899        .ok_or("export_step: a void shell with no edge to place it by")?;
900    let mut best: Option<usize> = None;
901    for &candidate in outer {
902        let alone = BrepSolid {
903            shells: vec![solid.shells[candidate].clone()],
904            ..solid.clone()
905        };
906        let class = crate::classify_point(probe, &alone, 1e-7)?.class;
907        if class == crate::PointClass::In && best.is_none_or(|b| shells[candidate].2 < shells[b].2) {
908            best = Some(candidate);
909        }
910    }
911    best.ok_or_else(|| "export_step: a void shell lies inside no outward shell".into())
912}
913
914fn vertex_for(solid: &BrepSolid, id: u64) -> Result<&VertexRecord, String> {
915    solid
916        .vertices
917        .iter()
918        .find(|vertex| vertex.id == id)
919        .ok_or_else(|| format!("export_step: missing vertex {id}"))
920}
921
922fn edge_for(solid: &BrepSolid, id: u64) -> Result<&EdgeRecord, String> {
923    solid
924        .edges
925        .iter()
926        .find(|edge| edge.id == id)
927        .ok_or_else(|| format!("export_step: missing edge {id}"))
928}
929
930fn surface_key(face: &FaceRecord) -> usize {
931    face as *const FaceRecord as usize
932}
933
934/// One use of an edge by a face's loop.  Curve-on-surface geometry is written
935/// per USE — a pcurve names the surface it lives on — so the writer needs the
936/// full adjacency of an edge before it can emit that edge.
937struct CoedgeUse<'a> {
938    surface_key: usize,
939    face: &'a FaceRecord,
940    coedge: &'a CoedgeRecord,
941}
942
943/// The AP242 document plus what the writer measured while producing it.
944///
945/// The pcurve counters are the honest half of the verify-or-omit contract in
946/// `step/pcurve.rs`: a pcurve is written only when the emitted 2D geometry was
947/// proved to reproduce the emitted 3D curve, and every one that could not be
948/// proved is COUNTED here rather than guessed into the file.  A reader
949/// reprojects an omitted pcurve exactly as it must reproject every pcurve in
950/// the files this exporter wrote before curve-on-surface geometry existed.
951#[derive(Clone, Debug, Default)]
952pub struct StepExportReport {
953    /// The Part 21 text.
954    pub text: String,
955    /// `PCURVE` entities written — at most one per coedge use of a
956    /// non-degenerate edge.
957    pub pcurves_written: usize,
958    /// Coedge uses left without a pcurve because no candidate 2D geometry
959    /// verified inside the export band.
960    pub pcurves_omitted: usize,
961    /// Edges written as `SURFACE_CURVE` (their two uses sit on two surfaces).
962    pub surface_curves: usize,
963    /// Edges written as `SEAM_CURVE` (both uses on ONE surface — a periodic
964    /// seam, the case an importer otherwise has to re-detect geometrically).
965    pub seam_curves: usize,
966    /// Edges that kept a bare 3D curve for `edge_geometry`, because no pcurve
967    /// survived (or a seam lost one of the pair it is required to carry).
968    pub bare_curves: usize,
969    /// Collapsed face boundaries written as `VERTEX_LOOP` — cone apexes and
970    /// sphere poles, which this writer used to drop entirely.
971    pub vertex_loops: usize,
972    /// Largest verified ‖S(c₂d(s)) − c₃d(s)‖ among the pcurves actually
973    /// written, in model units.
974    pub max_pcurve_deviation: f64,
975    /// Largest deviation among the BEST candidate for each OMITTED pcurve —
976    /// how far the closest miss was, so an omission can be diagnosed as "a
977    /// candidate applied and missed the band by this much" rather than only
978    /// counted. Zero when nothing was omitted.
979    ///
980    /// It is infinite when ANY omission had no candidate proposed at all, which
981    /// then hides the finite misses behind it — the two omission classes share
982    /// one counter. Splitting them is a follow-up; the max is the useful half,
983    /// because it is the finite value that says whether widening the band would
984    /// have helped.
985    pub worst_omitted_deviation: f64,
986    /// DISTINCT PMI reference names (`{body}`, `{body}:face`, `{body}@x,y,z`)
987    /// that named no entity in the written file, so every annotation on them
988    /// was skipped. Zero for a file whose PMI all resolved. The structured
989    /// (assembly) lane is what can move a reference: a component's geometry is
990    /// written into the PART's product, and a stale reference to a body that no
991    /// longer exists is counted here rather than dropped in silence.
992    pub pmi_unresolved_references: usize,
993    /// PRODUCTs written. `1` for the flat lane; the structured lane writes one
994    /// per distinct part plus one for the root document.
995    pub products: usize,
996    /// `NEXT_ASSEMBLY_USAGE_OCCURRENCE` edges written — the placed component
997    /// instances. Zero for the flat lane.
998    pub occurrences: usize,
999    /// `STYLED_ITEM`s written for GEOMETRY colour — one per coloured body and
1000    /// per coloured face (`step/styles.rs`). Zero when the caller passed no
1001    /// colours, or when none of the names it passed named written geometry;
1002    /// the PMI block's own styled item is not counted here.
1003    pub styled_items: usize,
1004}
1005
1006/// Serialize exact NURBS BREP topology as an AP242 STEP Part 21 document.
1007///
1008/// `unit` LABELS the caller's coordinates (`SI_UNIT($,.METRE.)`, `.MILLI.`,
1009/// inch and foot conversion factors): the writer does not scale them. A
1010/// kernel body is in millimetres, so a metre-unit file wants the body
1011/// pre-scaled by 1e-3 (`transform_brep` with a uniform scale) first; a
1012/// millimetre body written under `"meter"` re-imports at 1e9 × its volume
1013/// (measured 2026-10-03).
1014pub fn export_step(
1015    solids: &[BrepSolid],
1016    name: &str,
1017    unit: &str,
1018    timestamp: &str,
1019) -> Result<String, String> {
1020    export_step_report(solids, name, unit, timestamp).map(|report| report.text)
1021}
1022
1023/// [`export_step`] plus the pcurve-coverage measurements behind the file.
1024/// Every body is written under the part name; no PMI.
1025pub fn export_step_report(
1026    solids: &[BrepSolid],
1027    name: &str,
1028    unit: &str,
1029    timestamp: &str,
1030) -> Result<StepExportReport, String> {
1031    let named: Vec<(String, &BrepSolid)> = solids
1032        .iter()
1033        .map(|solid| (name.to_string(), solid))
1034        .collect();
1035    export_step_report_named(&named, name, unit, timestamp, None, None)
1036}
1037
1038/// The full writer: each body carries its SCENE NAME (`MANIFOLD_SOLID_BREP`
1039/// name — and the key the PMI references resolve through), and an optional
1040/// PMI block is written as AP242 semantic representation + polyline
1041/// presentation + saved views ([`pmi`]).
1042/// Where an exported geometry entity lives: the product whose shape it helps
1043/// define, and the representation that carries it. PMI attaches a shape aspect
1044/// to the OWNING product, which in a structured (assembly) export is the part's
1045/// own product, not the root document's.
1046#[derive(Clone, Copy)]
1047pub(crate) struct StepItemOwner {
1048    pub product_shape: usize,
1049    pub representation: usize,
1050}
1051
1052/// One product's geometry, written but not yet bound to a product definition.
1053/// The name lists are flat (not maps) because the same part can be reachable
1054/// under several occurrence paths, and each path registers its own alias.
1055#[derive(Default)]
1056pub(crate) struct ProductGeometry {
1057    /// Body name -> its STEP solid entity, in emission order. Inward shells
1058    /// belong to one `BREP_WITH_VOIDS`; independent outward shells each emit a
1059    /// `MANIFOLD_SOLID_BREP`. A coloured body is styled on this entity
1060    /// (`step/styles.rs`), and the representation's item list is the ids alone.
1061    pub solids: Vec<(String, usize)>,
1062    /// Face name -> its `ADVANCED_FACE`.
1063    pub faces: Vec<(String, usize)>,
1064    /// Edge name -> its `EDGE_CURVE`.
1065    pub edges: Vec<(String, usize)>,
1066    /// Body name -> that body's `VERTEX_POINT`s (LOCAL point, entity id).
1067    pub vertices: Vec<(String, Vec<(Vec3, usize)>)>,
1068}
1069
1070/// The PMI reference maps, folded from every product's [`ProductGeometry`] once
1071/// its owner is known. A structured export registers each product's entities
1072/// under EVERY occurrence path that reaches it (`ACOMP3:`, `ACOMP5:ACOMP1:`),
1073/// which is exactly how the document names a component's geometry.
1074#[derive(Default)]
1075pub(crate) struct StepNameMaps {
1076    pub faces: HashMap<String, (usize, StepItemOwner)>,
1077    pub edges: HashMap<String, (usize, StepItemOwner)>,
1078    /// Body name -> its owner and its `VERTEX_POINT`s in ROOT (document) space,
1079    /// because that is the frame a `{body}@x,y,z` PMI reference is written in.
1080    pub vertices: HashMap<String, (StepItemOwner, Vec<(Vec3, usize)>)>,
1081}
1082
1083impl StepNameMaps {
1084    /// Register one product's entities under an occurrence path: `prefix` is the
1085    /// chained component namespace (`""` at the root), `world` maps the
1086    /// product's local frame into root space.
1087    pub(crate) fn register(
1088        &mut self,
1089        geometry: &ProductGeometry,
1090        owner: StepItemOwner,
1091        prefix: &str,
1092        world: &Mat4,
1093    ) {
1094        for (name, id) in &geometry.faces {
1095            self.faces
1096                .entry(format!("{prefix}{name}"))
1097                .or_insert((*id, owner));
1098        }
1099        for (name, id) in &geometry.edges {
1100            self.edges
1101                .entry(format!("{prefix}{name}"))
1102                .or_insert((*id, owner));
1103        }
1104        for (name, points) in &geometry.vertices {
1105            let placed = points
1106                .iter()
1107                .map(|(point, id)| (transform_point(world, *point), *id))
1108                .collect();
1109            self.vertices
1110                .entry(format!("{prefix}{name}"))
1111                .or_insert((owner, placed));
1112        }
1113    }
1114}
1115
1116/// The file-wide entities every product's geometry is expressed against. One
1117/// set per FILE, shared by every product a structured export writes.
1118pub(crate) struct StepFileContexts {
1119    pub product_context: usize,
1120    pub definition_context: usize,
1121    pub geometry_context: usize,
1122    pub parametric_context: usize,
1123    pub length_unit: usize,
1124    pub angle_unit: usize,
1125    /// The IDENTITY `AXIS2_PLACEMENT_3D` — the first item of every shape
1126    /// representation, and `item_1` of every assembly placement's
1127    /// `ITEM_DEFINED_TRANSFORMATION` (the child frame's own origin).
1128    pub axis: usize,
1129}
1130
1131/// Write the header entities every AP242 body in this file shares.
1132pub(crate) fn write_file_contexts(
1133    writer: &mut StepWriter,
1134    unit: &str,
1135) -> Result<StepFileContexts, String> {
1136    let application = writer.add("APPLICATION_CONTEXT('managed model based 3d engineering')");
1137    writer.add(format!(
1138        "APPLICATION_PROTOCOL_DEFINITION('international standard','ap242_managed_model_based_3d_engineering',2014,#{application})"
1139    ));
1140    let product_context = writer.add(format!("PRODUCT_CONTEXT('',#{application},'mechanical')"));
1141    let definition_context = writer.add(format!(
1142        "PRODUCT_DEFINITION_CONTEXT('part definition',#{application},'design')"
1143    ));
1144    let length_unit = write_length_unit(writer, unit)?;
1145    let angle_unit = writer.add("(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.))");
1146    let solid_angle_unit = writer.add("(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT())");
1147    let uncertainty = writer.add(format!(
1148        "UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.E-6),#{length_unit},'distance_accuracy_value','')"
1149    ));
1150    let geometry_context = writer.add(format!(
1151        "(GEOMETRIC_REPRESENTATION_CONTEXT(3)\
1152         GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#{uncertainty}))\
1153         GLOBAL_UNIT_ASSIGNED_CONTEXT((#{length_unit},#{angle_unit},#{solid_angle_unit}))\
1154         REPRESENTATION_CONTEXT('',''))"
1155    ));
1156    // ONE parametric context for every DEFINITIONAL_REPRESENTATION in the file.
1157    // It carries no unit assignment, so the importer's file-scale search
1158    // (`derive_length_scale_mm`, which keys on GLOBAL_UNIT_ASSIGNED_CONTEXT /
1159    // LENGTH_UNIT) cannot mistake it for the geometric context.
1160    let parametric_context = writer.add(
1161        "(GEOMETRIC_REPRESENTATION_CONTEXT(2)\
1162         PARAMETRIC_REPRESENTATION_CONTEXT()\
1163         REPRESENTATION_CONTEXT('2D SPACE',''))",
1164    );
1165    let origin = write_point(writer, Vec3::default())?;
1166    let direction_z = writer.add("DIRECTION('',(0.,0.,1.))");
1167    let direction_x = writer.add("DIRECTION('',(1.,0.,0.))");
1168    let axis = writer.add(format!(
1169        "AXIS2_PLACEMENT_3D('',#{origin},#{direction_z},#{direction_x})"
1170    ));
1171    Ok(StepFileContexts {
1172        product_context,
1173        definition_context,
1174        geometry_context,
1175        parametric_context,
1176        length_unit,
1177        angle_unit,
1178        axis,
1179    })
1180}
1181
1182/// The product-definition chain of ONE product: what a `NEXT_ASSEMBLY_USAGE_
1183/// OCCURRENCE` references and what a `SHAPE_DEFINITION_REPRESENTATION` binds to
1184/// its geometry.
1185pub(crate) struct ProductIds {
1186    pub definition: usize,
1187    pub product_shape: usize,
1188}
1189
1190/// PRODUCT -> PRODUCT_DEFINITION -> PRODUCT_DEFINITION_SHAPE for one product.
1191/// `id` is the vendor part number (`PRODUCT.id`); the name is used when empty.
1192/// `category` is the `PRODUCT_RELATED_PRODUCT_CATEGORY` name — `'part'` for a
1193/// leaf, `'assembly'` for a product that places others, which is the
1194/// distinction a receiving system reads to build its own structure tree.
1195pub(crate) fn write_product(
1196    writer: &mut StepWriter,
1197    contexts: &StepFileContexts,
1198    name: &str,
1199    id: &str,
1200    category: &str,
1201) -> ProductIds {
1202    let safe_name = step_string(name);
1203    let safe_id = step_string(if id.is_empty() { name } else { id });
1204    let product_context = contexts.product_context;
1205    let definition_context = contexts.definition_context;
1206    let product = writer.add(format!(
1207        "PRODUCT('{safe_id}','{safe_name}','',(#{product_context}))"
1208    ));
1209    writer.add(format!(
1210        "PRODUCT_RELATED_PRODUCT_CATEGORY('{}','',(#{product}))",
1211        step_string(category)
1212    ));
1213    let formation = writer.add(format!("PRODUCT_DEFINITION_FORMATION('','',#{product})"));
1214    let definition = writer.add(format!(
1215        "PRODUCT_DEFINITION('design','',#{formation},#{definition_context})"
1216    ));
1217    let product_shape = writer.add(format!("PRODUCT_DEFINITION_SHAPE('','',#{definition})"));
1218    ProductIds {
1219        definition,
1220        product_shape,
1221    }
1222}
1223
1224/// Validate every body the way the export gate requires, then write each one's
1225/// exact topology as a `MANIFOLD_SOLID_BREP` named by its scene name.
1226///
1227/// This is the whole geometry writer, factored out of the single-product lane so
1228/// the structured (assembly) lane can call it once PER PRODUCT into the same
1229/// file. It appends to `writer` and reads only file-wide entities, so products
1230/// share surfaces with nothing and cannot collide.
1231pub(crate) fn write_product_geometry(
1232    writer: &mut StepWriter,
1233    contexts: &StepFileContexts,
1234    bodies: &[(String, &BrepSolid)],
1235    report: &mut StepExportReport,
1236) -> Result<ProductGeometry, String> {
1237    for (_, solid) in bodies {
1238        let policy = KernelTolerances::for_solid(solid, 1e-7);
1239        let issues = solid.validate_with_tolerances(&KernelTolerances {
1240            pcurve_consistency: policy.export_knit,
1241            ..policy
1242        });
1243        if !issues.is_empty() {
1244            return Err(format!("export_step: invalid solid: {issues:?}"));
1245        }
1246    }
1247    let parametric_context = contexts.parametric_context;
1248    let mut written = ProductGeometry::default();
1249    for (solid_name, solid) in bodies {
1250        let solid = *solid;
1251        let solid_name = solid_name.as_str();
1252        let band = KernelTolerances::for_solid(solid, 1e-7).export_knit;
1253        // Reader trim repair couples adjacent faces through shared edges. If
1254        // an extrusion boundary already misses the export band, preserve the
1255        // solid's bounded extrusion charts together, not just the loose face.
1256        let retain_extrusion_charts = crate::switch!("BREP_EXTRUSION_EXPORT", true)
1257            && solid.shells.iter().flat_map(|s|&s.faces)
1258                .filter(|face|face.surface.analytic().is_none() && face.surface.linear_extrusion().is_some())
1259                .any(|face|face.loops.iter().flat_map(|l|&l.coedges).any(|coedge| {
1260                    let Ok(edge) = edge_for(solid,coedge.edge_id) else { return true; };
1261                    crate::measure_edge_against_pcurve_image(&face.surface,&coedge.pcurve,
1262                        edge,coedge.forward,band).map_or(true,|m|m.deviation()>band)
1263                }));
1264        let mut vertex_ids = HashMap::<u64, usize>::default();
1265        let mut edge_ids = HashMap::<u64, usize>::default();
1266        let mut surfaces = HashMap::<usize, (usize, bool, EmittedSurface)>::default();
1267        let mut emitted_shells = Vec::new();
1268        for shell in &solid.shells {
1269            // Pass 1 — SURFACES. A pcurve references the surface entity it
1270            // parameterizes, so every surface id has to exist before the first
1271            // edge is written. (Before curve-on-surface geometry the writer
1272            // could emit surfaces after the loops; it no longer can.)
1273            for face in &shell.faces {
1274                let key = surface_key(face);
1275                if surfaces.contains_key(&key) {
1276                    continue;
1277                }
1278                let analytic = if retain_extrusion_charts && face.surface.analytic().is_none() {
1279                    None
1280                } else { write_analytic_surface(writer, &face.surface)? };
1281                let entry = match analytic {
1282                    Some(triple) => triple,
1283                    None => (
1284                        write_surface(writer, &face.surface)?,
1285                        false,
1286                        EmittedSurface::Spline,
1287                    ),
1288                };
1289                surfaces.insert(key, entry);
1290            }
1291
1292            // Pass 2 — ADJACENCY. Which faces use each edge, in first-encounter
1293            // order so the emitted entity numbering stays deterministic.
1294            let mut edge_uses = HashMap::<u64, Vec<CoedgeUse>>::default();
1295            let mut edge_order: Vec<u64> = Vec::new();
1296            for face in &shell.faces {
1297                for loop_record in &face.loops {
1298                    for coedge in &loop_record.coedges {
1299                        let edge = edge_for(solid, coedge.edge_id)?;
1300                        if edge.degenerate {
1301                            continue;
1302                        }
1303                        let uses = edge_uses.entry(edge.id).or_default();
1304                        if uses.is_empty() {
1305                            edge_order.push(edge.id);
1306                        }
1307                        uses.push(CoedgeUse {
1308                            surface_key: surface_key(face),
1309                            face,
1310                            coedge,
1311                        });
1312                    }
1313                }
1314            }
1315
1316            // Pass 3 — EDGES with their curve-on-surface geometry.
1317            for edge_id in &edge_order {
1318                if edge_ids.contains_key(edge_id) {
1319                    continue;
1320                }
1321                let edge = edge_for(solid, *edge_id)?;
1322                let subcurve = edge_subcurve(edge)?;
1323                let (curve, emitted_curve) = match write_analytic_curve(writer, &subcurve)? {
1324                    Some(pair) => pair,
1325                    None => (
1326                        write_curve(writer, &subcurve)?,
1327                        EmittedCurve::Spline { curve: subcurve },
1328                    ),
1329                };
1330                let uses = &edge_uses[edge_id];
1331                // Two uses on ONE surface is a periodic seam: the two halves of
1332                // the edge sit on opposite domain boundaries and the reader is
1333                // told so explicitly instead of having to rediscover it.
1334                let seam = uses.len() == 2 && uses[0].surface_key == uses[1].surface_key;
1335                let mut pcurves: Vec<(usize, Pcurve2d)> = Vec::new();
1336                let mut omitted = 0usize;
1337                if uses.len() == 2 {
1338                    // Slot order for a seam: the FORWARD-oriented coedge first,
1339                    // the reversed one second — the pairing OpenCASCADE writes
1340                    // and reads (BRep_CurveOnClosedSurface's PCurve1/PCurve2).
1341                    let mut ordered: Vec<&CoedgeUse> = uses.iter().collect();
1342                    if seam && !ordered[0].coedge.forward {
1343                        ordered.swap(0, 1);
1344                    }
1345                    for coedge_use in ordered {
1346                        // The stored pcurve runs in LOOP direction; the edge's
1347                        // geometry runs in EDGE direction. Fraction-synchronised
1348                        // reversal is exact, so a reversed coedge's pcurve is
1349                        // simply flipped before it is expressed.
1350                        let oriented = if coedge_use.coedge.forward {
1351                            coedge_use.coedge.pcurve.clone()
1352                        } else {
1353                            coedge_use.coedge.pcurve.reversed()?
1354                        };
1355                        let (surface_id, _, emitted_surface) = &surfaces[&coedge_use.surface_key];
1356                        let outcome = build_pcurve(
1357                            &coedge_use.face.surface,
1358                            emitted_surface,
1359                            &emitted_curve,
1360                            &oriented,
1361                            band,
1362                        )?;
1363                        match outcome.curve {
1364                            Some(curve_2d) => {
1365                                report.max_pcurve_deviation =
1366                                    report.max_pcurve_deviation.max(outcome.deviation);
1367                                pcurves.push((*surface_id, curve_2d));
1368                            }
1369                            None => {
1370                                omitted += 1;
1371                                if outcome.deviation.is_finite() {
1372                                    report.worst_omitted_deviation =
1373                                        report.worst_omitted_deviation.max(outcome.deviation);
1374                                } else {
1375                                    report.worst_omitted_deviation = f64::INFINITY;
1376                                }
1377                            }
1378                        }
1379                    }
1380                }
1381                // A SEAM_CURVE is required to carry BOTH pcurves on the one
1382                // surface, so a seam that lost one falls all the way back to a
1383                // bare 3D curve rather than to a half-described seam.
1384                if seam && pcurves.len() != 2 {
1385                    omitted += pcurves.len();
1386                    pcurves.clear();
1387                }
1388                report.pcurves_omitted += omitted;
1389                report.pcurves_written += pcurves.len();
1390                let geometry = if pcurves.is_empty() {
1391                    report.bare_curves += 1;
1392                    curve
1393                } else {
1394                    let ids = pcurves
1395                        .iter()
1396                        .map(|(surface_id, curve_2d)| {
1397                            write_pcurve_entity(
1398                                writer,
1399                                *surface_id,
1400                                parametric_context,
1401                                curve_2d,
1402                            )
1403                        })
1404                        .collect::<Result<Vec<_>, String>>()?;
1405                    let keyword = if seam {
1406                        report.seam_curves += 1;
1407                        "SEAM_CURVE"
1408                    } else {
1409                        report.surface_curves += 1;
1410                        "SURFACE_CURVE"
1411                    };
1412                    // master_representation is .CURVE_3D.: our 3D curves are
1413                    // the exact authority the whole kernel and the export gate
1414                    // treat them as, and the pcurves above are verified AGAINST
1415                    // them. Promoting an approximation to master would be the
1416                    // one claim this writer must not make.
1417                    writer.add(format!(
1418                        "{keyword}('',#{curve},{},.CURVE_3D.)",
1419                        id_list(&ids)
1420                    ))
1421                };
1422                let start = vertex_step_id(writer, &mut vertex_ids, solid, edge.start_vertex_id)?;
1423                let end = vertex_step_id(writer, &mut vertex_ids, solid, edge.end_vertex_id)?;
1424                let step_id =
1425                    writer.add(format!("EDGE_CURVE('',#{start},#{end},#{geometry},.T.)"));
1426                edge_ids.insert(edge.id, step_id);
1427                if let Some(edge_name) = edge.name.as_deref() {
1428                    written.edges.push((edge_name.to_string(), step_id));
1429                }
1430            }
1431
1432            // Pass 4 — LOOPS and FACES over the ids the passes above fixed.
1433            let mut face_ids = Vec::new();
1434            for face in &shell.faces {
1435                let mut bound_ids = Vec::new();
1436                for (loop_index, loop_record) in face.loops.iter().enumerate() {
1437                    let mut oriented_edges = Vec::new();
1438                    for coedge in &loop_record.coedges {
1439                        let edge = edge_for(solid, coedge.edge_id)?;
1440                        if edge.degenerate {
1441                            continue;
1442                        }
1443                        let edge_id = *edge_ids
1444                            .get(&edge.id)
1445                            .ok_or_else(|| format!("export_step: unwritten edge {}", edge.id))?;
1446                        let orientation = if coedge.forward { ".T." } else { ".F." };
1447                        oriented_edges.push(
1448                            writer.add(format!("ORIENTED_EDGE('',*,*,#{edge_id},{orientation})")),
1449                        );
1450                    }
1451                    let kind = if loop_index == 0 {
1452                        "FACE_OUTER_BOUND"
1453                    } else {
1454                        "FACE_BOUND"
1455                    };
1456                    if oriented_edges.is_empty() {
1457                        // A bound left empty by the degenerate-edge skip is a
1458                        // COLLAPSED boundary — a cone apex, a sphere pole —
1459                        // and AP242 spells that `VERTEX_LOOP`, not nothing.
1460                        // Dropping it (what this writer did before) deletes the
1461                        // apex from the face's parameter domain, so an imported
1462                        // pointed cone lost its apex bound on re-export and
1463                        // every reader had to re-synthesise it from the
1464                        // surface's own degeneracy. A MIXED loop keeps the
1465                        // skip: that is OCCT's own write convention, both our
1466                        // importer and OCC's ShapeFix rebuild those, and the
1467                        // advanced-face conformance class permits vertex loops
1468                        // but not zero-length edge curves.
1469                        let Some(coedge) = loop_record.coedges.first() else {
1470                            continue;
1471                        };
1472                        let collapsed = edge_for(solid, coedge.edge_id)?;
1473                        let vertex = vertex_step_id(
1474                            writer,
1475                            &mut vertex_ids,
1476                            solid,
1477                            collapsed.start_vertex_id,
1478                        )?;
1479                        let vertex_loop = writer.add(format!("VERTEX_LOOP('',#{vertex})"));
1480                        report.vertex_loops += 1;
1481                        bound_ids.push(writer.add(format!("{kind}('',#{vertex_loop},.T.)")));
1482                        continue;
1483                    }
1484                    let edge_loop =
1485                        writer.add(format!("EDGE_LOOP('',{})", id_list(&oriented_edges)));
1486                    bound_ids.push(writer.add(format!("{kind}('',#{edge_loop},.T.)")));
1487                }
1488                let (surface, flipped, _) = surfaces[&surface_key(face)];
1489                // `flipped` analytic entities are written with the reverse of
1490                // the stored NURBS orientation, so invert the flag to keep the
1491                // face normal identical through the round trip.
1492                let sense = if face.same_sense != flipped {
1493                    ".T."
1494                } else {
1495                    ".F."
1496                };
1497                let face_step_id = writer.add(format!(
1498                    "ADVANCED_FACE('',{},#{surface},{sense})",
1499                    id_list(&bound_ids)
1500                ));
1501                if let Some(face_name) = face.name.as_deref() {
1502                    written.faces.push((face_name.to_string(), face_step_id));
1503                }
1504                face_ids.push(face_step_id);
1505            }
1506            let closed_shell = writer.add(format!("CLOSED_SHELL('',{})", id_list(&face_ids)));
1507            let signed_volume = if solid.shells.len() > 1 {
1508                crate::mass_properties::shell_signed_volume(shell)?
1509            } else {
1510                1.0
1511            };
1512            emitted_shells.push((closed_shell, signed_volume < 0.0, signed_volume.abs()));
1513        }
1514        if emitted_shells.iter().any(|&(_, inward, _)| inward) {
1515            let outer: Vec<usize> = (0..emitted_shells.len()).filter(|&i| !emitted_shells[i].1).collect();
1516            if outer.is_empty() {
1517                return Err("export_step: a solid with voids must have an outward shell".into());
1518            }
1519            // Each void belongs to the smallest outward shell around it: one
1520            // body per outward shell, its voids those it owns (several bodies
1521            // nested in each other's hollows are several solids in STEP).
1522            let mut owned: Vec<Vec<usize>> = vec![Vec::new(); emitted_shells.len()];
1523            for void in (0..emitted_shells.len()).filter(|&i| emitted_shells[i].1) {
1524                let owner = if outer.len() == 1 {
1525                    outer[0]
1526                } else {
1527                    void_owner(solid, void, &outer, &emitted_shells)?
1528                };
1529                owned[owner].push(void);
1530            }
1531            for &shell in &outer {
1532                let closed_shell = emitted_shells[shell].0;
1533                let body_id = if owned[shell].is_empty() {
1534                    writer.add(format!("MANIFOLD_SOLID_BREP('{}',#{closed_shell})", step_string(solid_name)))
1535                } else {
1536                    let voids = owned[shell].iter()
1537                        .map(|&void| writer.add(format!("ORIENTED_CLOSED_SHELL('',*,#{},.T.)", emitted_shells[void].0)))
1538                        .collect::<Vec<_>>();
1539                    writer.add(format!(
1540                        "BREP_WITH_VOIDS('{}',#{closed_shell},{})", step_string(solid_name), id_list(&voids)
1541                    ))
1542                };
1543                written.solids.push((solid_name.to_string(), body_id));
1544            }
1545        } else {
1546            for (closed_shell, _, _) in emitted_shells {
1547                let body_id = writer.add(format!(
1548                    "MANIFOLD_SOLID_BREP('{}',#{closed_shell})", step_string(solid_name)
1549                ));
1550                written.solids.push((solid_name.to_string(), body_id));
1551            }
1552        }
1553        // The vertices this solid wrote, for `{solid}@x,y,z` PMI references.
1554        let mut points: Vec<(Vec3, usize)> = Vec::with_capacity(vertex_ids.len());
1555        for (vertex_id, step_id) in &vertex_ids {
1556            points.push((vertex_for(solid, *vertex_id)?.point, *step_id));
1557        }
1558        written.vertices.push((solid_name.to_string(), points));
1559    }
1560    Ok(written)
1561}
1562
1563/// Wrap the written entities in the Part 21 envelope and run the emitted-text
1564/// audits — the last step of every export lane.
1565pub(crate) fn finish_step_file(
1566    writer: StepWriter,
1567    name: &str,
1568    timestamp: &str,
1569    report: &mut StepExportReport,
1570) -> Result<(), String> {
1571    let safe_name = step_string(name);
1572    let safe_timestamp = step_string(timestamp);
1573    let output = [
1574        "ISO-10303-21;".to_string(),
1575        "HEADER;".to_string(),
1576        "FILE_DESCRIPTION((''),'2;1');".to_string(),
1577        format!(
1578            "FILE_NAME('{safe_name}.step','{safe_timestamp}',(''),(''),'brep-kernel-rs','brep-kernel-rs','');"
1579        ),
1580        "FILE_SCHEMA(('AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }'));".to_string(),
1581        "ENDSEC;".to_string(),
1582        "DATA;".to_string(),
1583        writer.data(),
1584        "ENDSEC;".to_string(),
1585        "END-ISO-10303-21;".to_string(),
1586        String::new(),
1587    ]
1588    .join("\n");
1589    let manifold_issues = audit_step_manifold(&output);
1590    if !manifold_issues.is_empty() {
1591        return Err(format!(
1592            "export_step: emitted AP242 manifold audit failed: {}",
1593            manifold_issues.join("; ")
1594        ));
1595    }
1596    let pcurve_issues = audit_step_pcurves(&output);
1597    if !pcurve_issues.is_empty() {
1598        return Err(format!(
1599            "export_step: emitted AP242 pcurve audit failed: {}",
1600            pcurve_issues.join("; ")
1601        ));
1602    }
1603    report.text = output;
1604    Ok(())
1605}
1606
1607/// The full single-product writer: each body carries its SCENE NAME
1608/// (`MANIFOLD_SOLID_BREP` name — and the key the PMI references resolve
1609/// through), and an optional PMI block is written as AP242 semantic
1610/// representation + polyline presentation + saved views (`pmi`).
1611///
1612/// This is the FLAT lane: one `PRODUCT`, every body in it, no assembly
1613/// structure. A document with components goes through
1614/// [`assembly::export_step_assembly_report`] instead.
1615pub fn export_step_report_named(
1616    solids: &[(String, &BrepSolid)],
1617    name: &str,
1618    unit: &str,
1619    timestamp: &str,
1620    pmi: Option<&StepPmi<'_>>,
1621    colors: Option<&StepColors>,
1622) -> Result<StepExportReport, String> {
1623    if solids.is_empty() {
1624        return Err("export_step: at least one solid is required".into());
1625    }
1626    let mut report = StepExportReport {
1627        products: 1,
1628        ..StepExportReport::default()
1629    };
1630    let mut writer = StepWriter::default();
1631    let contexts = write_file_contexts(&mut writer, unit)?;
1632    let geometry = write_product_geometry(&mut writer, &contexts, solids, &mut report)?;
1633    let mut items = vec![contexts.axis];
1634    items.extend(geometry.solids.iter().map(|(_, id)| *id));
1635    let geometry_context = contexts.geometry_context;
1636    let representation = writer.add(format!(
1637        "ADVANCED_BREP_SHAPE_REPRESENTATION('',{},#{geometry_context})",
1638        id_list(&items)
1639    ));
1640    let product = write_product(&mut writer, &contexts, name, "", "part");
1641    let product_shape = product.product_shape;
1642    writer.add(format!(
1643        "SHAPE_DEFINITION_REPRESENTATION(#{product_shape},#{representation})"
1644    ));
1645    // Geometry colour, before the PMI block so a file's presentation styles read
1646    // in geometry order. The flat lane's bodies carry their document names with
1647    // no component namespace, so the ONE prefix to resolve through is the empty
1648    // one.
1649    if let Some(colors) = colors.filter(|colors| !colors.is_empty()) {
1650        let items = styles::styled_items(&geometry, colors, &[String::new()]);
1651        report.styled_items = styles::write_geometry_styles(&mut writer, geometry_context, &items)?;
1652    }
1653    if let Some(pmi) = pmi {
1654        let mut names = StepNameMaps::default();
1655        names.register(
1656            &geometry,
1657            StepItemOwner {
1658                product_shape,
1659                representation,
1660            },
1661            "",
1662            &MAT4_IDENTITY,
1663        );
1664        let context = pmi::StepContext {
1665            product_shape,
1666            representation,
1667            geometry_context,
1668            length_unit: contexts.length_unit,
1669            angle_unit: contexts.angle_unit,
1670            faces: &names.faces,
1671            edges: &names.edges,
1672            vertices: &names.vertices,
1673        };
1674        report.pmi_unresolved_references = pmi::write_pmi(&mut writer, &context, pmi)?;
1675    }
1676    finish_step_file(writer, name, timestamp, &mut report)?;
1677    Ok(report)
1678}
1679
1680/// VERTEX_POINT for a kernel vertex, written once per solid.
1681fn vertex_step_id(
1682    writer: &mut StepWriter,
1683    vertex_ids: &mut HashMap<u64, usize>,
1684    solid: &BrepSolid,
1685    id: u64,
1686) -> Result<usize, String> {
1687    if let Some(step_id) = vertex_ids.get(&id) {
1688        return Ok(*step_id);
1689    }
1690    let point = write_point(writer, vertex_for(solid, id)?.point)?;
1691    let step_id = writer.add(format!("VERTEX_POINT('',#{point})"));
1692    vertex_ids.insert(id, step_id);
1693    Ok(step_id)
1694}
1695
1696/// Entity id -> body, for the serialized-text audits.  One entity per line is
1697/// this writer's own invariant, so the "parse" is a split.
1698fn step_entity_bodies(step: &str) -> HashMap<u64, &str> {
1699    step.lines()
1700        .filter_map(|line| {
1701            let rest = line.strip_prefix('#')?;
1702            let (digits, body) = rest.split_once('=')?;
1703            Some((
1704                digits.parse::<u64>().ok()?,
1705                body.trim_end().trim_end_matches(';'),
1706            ))
1707        })
1708        .collect()
1709}
1710
1711/// Every `#N` reference in an entity body, in order.  For the entities audited
1712/// below that order IS the attribute order (`SURFACE_CURVE` puts its 3D curve
1713/// first and its pcurves after; `PCURVE` puts its surface first).
1714fn step_entity_refs(body: &str) -> Vec<u64> {
1715    let mut refs = Vec::new();
1716    let bytes = body.as_bytes();
1717    let mut index = 0;
1718    while index < bytes.len() {
1719        if bytes[index] == b'#' {
1720            let start = index + 1;
1721            let mut end = start;
1722            while end < bytes.len() && bytes[end].is_ascii_digit() {
1723                end += 1;
1724            }
1725            if end > start {
1726                if let Ok(id) = body[start..end].parse::<u64>() {
1727                    refs.push(id);
1728                }
1729            }
1730            index = end;
1731        } else {
1732            index += 1;
1733        }
1734    }
1735    refs
1736}
1737
1738/// Audit the curve-on-surface half of the emitted graph, on the serialized
1739/// text, for the same reason `audit_step_manifold` exists: valid in-memory
1740/// intent is not proof of a correctly written file.
1741///
1742/// An `EDGE_CURVE` whose geometry is a bare 3D curve is NOT an issue — that is
1743/// the counted, deliberate outcome of the verify-or-omit gate. What is an
1744/// issue is a malformed bundle: a `SURFACE_CURVE` with no or more than two
1745/// associated geometries, a `SEAM_CURVE` that does not carry exactly two, a
1746/// `SEAM_CURVE` whose two pcurves name DIFFERENT surfaces (it is by definition
1747/// one surface's seam), a `SURFACE_CURVE` whose two pcurves name the SAME
1748/// surface (that is a seam, and must say so), or a `PCURVE` that does not
1749/// point at both a surface and a `DEFINITIONAL_REPRESENTATION`.
1750pub fn audit_step_pcurves(step: &str) -> Vec<String> {
1751    let bodies = step_entity_bodies(step);
1752    let mut issues = Vec::new();
1753    for (id, body) in &bodies {
1754        if !body.starts_with("EDGE_CURVE(") {
1755            continue;
1756        }
1757        let refs = step_entity_refs(body);
1758        let Some(geometry) = refs.get(2) else {
1759            issues.push(format!("EDGE_CURVE #{id} has no edge_geometry"));
1760            continue;
1761        };
1762        let Some(wrapper) = bodies.get(geometry) else {
1763            issues.push(format!("EDGE_CURVE #{id} references missing #{geometry}"));
1764            continue;
1765        };
1766        let seam = wrapper.starts_with("SEAM_CURVE(");
1767        if !seam && !wrapper.starts_with("SURFACE_CURVE(") {
1768            continue;
1769        }
1770        let wrapper_refs = step_entity_refs(wrapper);
1771        let pcurves = &wrapper_refs[wrapper_refs.len().min(1)..];
1772        if pcurves.is_empty() || pcurves.len() > 2 || (seam && pcurves.len() != 2) {
1773            issues.push(format!(
1774                "#{geometry} carries {} associated geometries",
1775                pcurves.len()
1776            ));
1777            continue;
1778        }
1779        let mut surfaces = Vec::new();
1780        for pcurve in pcurves {
1781            let Some(pcurve_body) = bodies.get(pcurve) else {
1782                issues.push(format!("#{geometry} references missing #{pcurve}"));
1783                continue;
1784            };
1785            if !pcurve_body.starts_with("PCURVE(") {
1786                issues.push(format!("#{geometry} associate #{pcurve} is not a PCURVE"));
1787                continue;
1788            }
1789            let pcurve_refs = step_entity_refs(pcurve_body);
1790            let representation = pcurve_refs.get(1).and_then(|id| bodies.get(id));
1791            if !representation.is_some_and(|body| body.starts_with("DEFINITIONAL_REPRESENTATION("))
1792            {
1793                issues.push(format!(
1794                    "PCURVE #{pcurve} has no DEFINITIONAL_REPRESENTATION"
1795                ));
1796            }
1797            if let Some(surface) = pcurve_refs.first() {
1798                surfaces.push(*surface);
1799            }
1800        }
1801        if surfaces.len() == 2 && (surfaces[0] == surfaces[1]) != seam {
1802            issues.push(format!(
1803                "#{geometry} pcurves name {} surface(s) but it is a {}",
1804                if surfaces[0] == surfaces[1] { 1 } else { 2 },
1805                if seam { "SEAM_CURVE" } else { "SURFACE_CURVE" }
1806            ));
1807        }
1808    }
1809    issues.sort();
1810    issues
1811}
1812
1813/// Audit the serialized entity graph rather than assuming that valid
1814/// in-memory topology was necessarily written correctly.  Every EDGE_CURVE
1815/// in a closed shell must have exactly two ORIENTED_EDGE users with opposite
1816/// senses.
1817pub fn audit_step_manifold(step: &str) -> Vec<String> {
1818    let marker = "ORIENTED_EDGE('',*,*,#";
1819    let mut uses = HashMap::<u64, Vec<bool>>::default();
1820    for line in step.lines() {
1821        let Some(offset) = line.find(marker) else {
1822            continue;
1823        };
1824        let rest = &line[offset + marker.len()..];
1825        let digits = rest
1826            .chars()
1827            .take_while(|character| character.is_ascii_digit())
1828            .collect::<String>();
1829        let Ok(edge_id) = digits.parse::<u64>() else {
1830            continue;
1831        };
1832        let suffix = &rest[digits.len()..];
1833        let sense = suffix.starts_with(",.T.");
1834        uses.entry(edge_id).or_default().push(sense);
1835    }
1836    let mut issues = uses
1837        .into_iter()
1838        .filter_map(|(edge, senses)| {
1839            (senses.len() != 2 || senses[0] == senses[1]).then(|| {
1840                format!(
1841                    "EDGE_CURVE #{edge} has {} uses with senses {:?}",
1842                    senses.len(),
1843                    senses
1844                )
1845            })
1846        })
1847        .collect::<Vec<_>>();
1848    issues.sort();
1849    issues
1850}
1851
1852