meshbrep 0.4.0

Rebuild an exact B-rep (planes, cylinders, cones, spheres, tori, B-spline surfaces) from a triangle mesh tagged with the surface each triangle came from, write it as STEP AP214, and make fillet and chamfer tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
//! A deterministic STEP AP214 writer.
//!
//! The file depends only on the B-rep and the options: entities are
//! numbered in a fixed traversal order, numbers are written in Rust's
//! shortest round-trip form, and the header's names and date are the
//! caller's (fixed defaults otherwise, never the clock).

use std::fmt::Write as _;

use crate::math::*;
use crate::model::{BSpline, BSplineSurface, Brep, Curve, Face, Surface};

/// Names and dates for the file header and the product.
#[derive(Clone, Debug, PartialEq)]
pub struct StepOptions {
    /// The product's name and id.
    pub product_name: String,
    /// `FILE_NAME`'s name.
    pub file_name: String,
    /// `FILE_NAME`'s time stamp (ISO 8601). Fixed by default, so that the
    /// same model always gives the same bytes.
    pub timestamp: String,
    /// `FILE_NAME`'s author.
    pub author: String,
    /// `FILE_NAME`'s organisation.
    pub organization: String,
    /// `FILE_NAME`'s originating system. Defaults to this crate's name and
    /// version; set it to keep files identical across crate versions.
    pub originating_system: String,
    /// `FILE_DESCRIPTION`'s text.
    pub description: String,
}

impl Default for StepOptions {
    fn default() -> Self {
        StepOptions {
            product_name: "part".into(),
            file_name: "part.step".into(),
            timestamp: "1970-01-01T00:00:00".into(),
            author: String::new(),
            organization: String::new(),
            originating_system: concat!("meshbrep ", env!("CARGO_PKG_VERSION")).into(),
            description: String::new(),
        }
    }
}

/// A STEP string literal: quotes doubled, backslashes doubled, non-ASCII
/// as `\X2\…\X0\` (UTF-16 hex), per ISO 10303-21.
fn string(s: &str) -> String {
    let mut out = String::from("'");
    let mut wide: Vec<u16> = Vec::new();
    let flush = |wide: &mut Vec<u16>, out: &mut String| {
        if !wide.is_empty() {
            out.push_str("\\X2\\");
            for u in wide.iter() {
                let _ = write!(out, "{u:04X}");
            }
            out.push_str("\\X0\\");
            wide.clear();
        }
    };
    for c in s.chars() {
        if c.is_ascii() && !c.is_ascii_control() {
            flush(&mut wide, &mut out);
            match c {
                '\'' => out.push_str("''"),
                '\\' => out.push_str("\\\\"),
                _ => out.push(c),
            }
        } else {
            let mut buf = [0u16; 2];
            wide.extend_from_slice(c.encode_utf16(&mut buf));
        }
    }
    flush(&mut wide, &mut out);
    out.push('\'');
    out
}

/// A STEP real: shortest round-trip digits, always with a decimal point.
fn real(x: f64) -> String {
    let mut out = String::new();
    push_real(&mut out, x, &mut String::new());
    out
}

/// [`real`], appended to `out` (`scratch` is reused between calls). The
/// writer formats millions of these on a large faceted model, and the
/// temporary strings cost as much as the digits.
fn push_real(out: &mut String, x: f64, scratch: &mut String) {
    if x == 0.0 {
        out.push_str("0.");
        return;
    }
    if push_integral(out, x) {
        return;
    }
    scratch.clear();
    let _ = write!(scratch, "{x:E}");
    let (mant, exp) = scratch.split_once('E').expect("exponent");
    out.push_str(mant);
    if !mant.contains('.') {
        out.push('.');
    }
    if exp != "0" {
        out.push('E');
        out.push_str(exp);
    }
}

/// [`push_real`] of a whole number below 2^53 in magnitude, without the
/// formatting machinery: CAD coordinates and directions often are (a
/// cube's corners, an axis's 1). Returns `false`, having written nothing,
/// for any other `x`.
///
/// The text is the one `{:E}` gives. Below 2^53 consecutive doubles are at
/// most 1 apart, so a whole number's shortest round-trip digits are its
/// own decimal digits without their trailing zeros: any other string of
/// that many digits or fewer is at least 1 away, outside the half-unit
/// that would read back as the same double (and no tie between two
/// candidates can arise).
fn push_integral(out: &mut String, x: f64) -> bool {
    const LIMIT: f64 = 9_007_199_254_740_992.0; // 2^53
    let a = x.abs();
    if !a.is_finite() || a >= LIMIT || a.fract() != 0.0 || a == 0.0 {
        return false;
    }
    let mut v = a as u64;
    let mut buf = [0u8; 20];
    let mut i = buf.len();
    while v > 0 {
        i -= 1;
        buf[i] = b'0' + (v % 10) as u8;
        v /= 10;
    }
    let digits = &buf[i..];
    let exponent = digits.len() - 1;
    let mut end = digits.len();
    while end > 1 && digits[end - 1] == b'0' {
        end -= 1;
    }
    if x < 0.0 {
        out.push('-');
    }
    out.push(char::from(digits[0]));
    out.push('.');
    for &d in &digits[1..end] {
        out.push(char::from(d));
    }
    if exponent > 0 {
        out.push('E');
        push_uint(out, exponent);
    }
    true
}

/// Reals already formatted, by their bits: a direct-mapped cache in front
/// of [`push_real`]. A faceted model writes each coordinate several times
/// (a vertex's point, the lines that start there, the planes through it),
/// and the shortest round-trip formatting is half of writing it. A hit
/// copies the text the same bits gave before, so the file is the same
/// with or without it.
struct Reals {
    slots: Vec<Slot>,
    /// log2 of the number of slots.
    bits: u32,
    scratch: String,
}

#[derive(Clone, Copy)]
struct Slot {
    bits: u64,
    /// 0 for an empty slot (no real's text is empty).
    len: u8,
    text: [u8; Reals::MAX_LEN],
}

impl Reals {
    /// The longest text [`push_real`] gives: a sign, 17 digits, the point,
    /// `E`, the exponent's sign and three digits.
    const MAX_LEN: usize = 24;

    /// A cache for about `reals` distinct values: a slot each, from 256
    /// to 65,536 (2.6 MB). Sized by the model, since setting up the
    /// largest for a cube took longer than writing it.
    fn new(reals: usize) -> Reals {
        Reals {
            slots: Vec::new(),
            bits: reals.next_power_of_two().trailing_zeros().clamp(8, 16),
            scratch: String::new(),
        }
    }

    fn push(&mut self, out: &mut String, x: f64) {
        if x == 0.0 {
            out.push_str("0.");
            return;
        }
        if push_integral(out, x) {
            return;
        }
        if self.slots.is_empty() {
            self.slots = vec![
                Slot {
                    bits: 0,
                    len: 0,
                    text: [0; Reals::MAX_LEN],
                };
                1 << self.bits
            ];
        }
        let bits = x.to_bits();
        let at = (bits.wrapping_mul(0x9e37_79b9_7f4a_7c15) >> (64 - self.bits)) as usize;
        let slot = &mut self.slots[at];
        if slot.len > 0 && slot.bits == bits {
            let text = &slot.text[..slot.len as usize];
            out.push_str(std::str::from_utf8(text).expect("ASCII"));
            return;
        }
        let start = out.len();
        push_real(out, x, &mut self.scratch);
        let text = &out.as_bytes()[start..];
        if text.len() <= Reals::MAX_LEN {
            slot.bits = bits;
            slot.len = text.len() as u8;
            slot.text[..text.len()].copy_from_slice(text);
        }
    }
}

/// A decimal integer appended to `out`, without the formatting machinery
/// (entity numbers are most of a large file's integers).
fn push_uint(out: &mut String, mut v: usize) {
    let mut buf = [0u8; 20];
    let mut i = buf.len();
    loop {
        i -= 1;
        buf[i] = b'0' + (v % 10) as u8;
        v /= 10;
        if v == 0 {
            break;
        }
    }
    for &b in &buf[i..] {
        out.push(char::from(b));
    }
}

/// The entities written so far.
///
/// Each is appended to one buffer as its `#n=…;` line as soon as it is
/// added, in number order. Collecting every entity as a string of its own
/// and joining them at the end cost as much as formatting the numbers on
/// a large faceted model (a million allocations and a second copy of the
/// file). An entity reserved before its text is known is spliced in when
/// the file is assembled.
struct W {
    body: String,
    /// Entities numbered so far.
    n: usize,
    reals: Reals,
    /// Reserved entities: number, offset in `body`, and text once set.
    holes: Vec<(usize, usize, String)>,
}

impl W {
    /// A writer for a B-rep of about `vertices` vertices.
    fn new(vertices: usize) -> W {
        W {
            body: String::new(),
            n: 0,
            // Three coordinates a vertex, and as many again for the
            // lines and planes whose points are not vertices.
            reals: Reals::new(6 * vertices),
            holes: Vec::new(),
        }
    }
    /// Starts entity `#n=` and returns its number.
    fn start(&mut self) -> usize {
        self.n += 1;
        self.body.push('#');
        push_uint(&mut self.body, self.n);
        self.body.push('=');
        self.n
    }
    fn finish(&mut self) {
        self.body.push_str(";\n");
    }
    fn add(&mut self, s: String) -> usize {
        let id = self.start();
        self.body.push_str(&s);
        self.finish();
        id
    }
    /// [`W::add`] of formatted text, without a string of its own.
    fn addf(&mut self, args: std::fmt::Arguments<'_>) -> usize {
        let id = self.start();
        let _ = self.body.write_fmt(args);
        self.finish();
        id
    }
    fn reserve(&mut self) -> usize {
        self.n += 1;
        self.holes.push((self.n, self.body.len(), String::new()));
        self.n
    }
    fn set(&mut self, id: usize, s: String) {
        if let Some(h) = self.holes.iter_mut().find(|h| h.0 == id) {
            h.2 = s;
        }
    }
    /// `KIND('',(x,y,...))`.
    fn tuple(&mut self, kind: &str, xs: &[f64]) -> usize {
        let id = self.start();
        self.body.push_str(kind);
        self.body.push_str("('',(");
        for (i, &x) in xs.iter().enumerate() {
            if i > 0 {
                self.body.push(',');
            }
            self.reals.push(&mut self.body, x);
        }
        self.body.push_str("))");
        self.finish();
        id
    }
    /// `#i`.
    fn id(&mut self, i: usize) {
        self.body.push('#');
        push_uint(&mut self.body, i);
    }
    /// `#a,#b,...`, as [`Refs`] formats it.
    fn ids(&mut self, xs: &[usize]) {
        for (k, &i) in xs.iter().enumerate() {
            if k > 0 {
                self.body.push(',');
            }
            self.id(i);
        }
    }
    /// `KIND('',#a,#b,...)` and its number: the entities that refer only
    /// to others, written without the formatting machinery (a faceted
    /// model has millions of them).
    fn refers(&mut self, kind: &str, xs: &[usize]) -> usize {
        let n = self.start();
        self.body.push_str(kind);
        self.body.push_str("(''");
        for &i in xs {
            self.body.push(',');
            self.id(i);
        }
        self.body.push(')');
        self.finish();
        n
    }
    fn pt(&mut self, p: [f64; 3]) -> usize {
        self.tuple("CARTESIAN_POINT", &p)
    }
    fn pt2(&mut self, p: [f64; 2]) -> usize {
        self.tuple("CARTESIAN_POINT", &p)
    }
    fn dir(&mut self, d: [f64; 3]) -> usize {
        self.tuple("DIRECTION", &d)
    }
    fn ax2(&mut self, o: [f64; 3], z: [f64; 3], x: [f64; 3]) -> usize {
        let p = self.pt(o);
        let a = self.dir(z);
        let b = self.dir(x);
        self.refers("AXIS2_PLACEMENT_3D", &[p, a, b])
    }
    /// The file: the buffer with reserved entities in their places (the
    /// last first, so that the earlier offsets still hold) and the
    /// trailer.
    fn into_file(self) -> String {
        let mut body = self.body;
        let mut holes = self.holes;
        holes.sort_by_key(|h| h.1);
        for (id, off, text) in holes.into_iter().rev() {
            let mut line = String::with_capacity(text.len() + 24);
            line.push('#');
            push_uint(&mut line, id);
            line.push('=');
            line.push_str(&text);
            line.push_str(";\n");
            body.insert_str(off, &line);
        }
        body.push_str("ENDSEC;\nEND-ISO-10303-21;\n");
        body
    }
}

/// `#a,#b,...`, formatted where it is used.
struct Refs<'a>(&'a [usize]);

impl std::fmt::Display for Refs<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for (k, i) in self.0.iter().enumerate() {
            if k > 0 {
                f.write_str(",")?;
            }
            write!(f, "#{i}")?;
        }
        Ok(())
    }
}

fn bspline_entity<const D: usize>(w: &mut W, b: &BSpline<D>) -> usize {
    let cps: Vec<usize> = b
        .control
        .iter()
        .map(|p| {
            if D == 3 {
                w.pt([p[0], p[1], p[2 % D]])
            } else {
                w.pt2([p[0], p[1]])
            }
        })
        .collect();
    let mut ks: Vec<f64> = Vec::new();
    let mut ms: Vec<usize> = Vec::new();
    for &k in &b.knots {
        if ks.last() == Some(&k) {
            *ms.last_mut().expect("multiplicity") += 1;
        } else {
            ks.push(k);
            ms.push(1);
        }
    }
    w.addf(format_args!(
        "B_SPLINE_CURVE_WITH_KNOTS('',{},({}),.UNSPECIFIED.,.F.,.F.,({}),({}),.UNSPECIFIED.)",
        b.degree,
        Refs(&cps),
        ms.iter()
            .map(|m| m.to_string())
            .collect::<Vec<_>>()
            .join(","),
        ks.iter().map(|&k| real(k)).collect::<Vec<_>>().join(",")
    ))
}

fn curve_entity(w: &mut W, c: &Curve) -> usize {
    match c {
        Curve::Line { origin, direction } => {
            let p = w.pt(*origin);
            let d = w.dir(*direction);
            let vct = w.start();
            w.body.push_str("VECTOR('',");
            w.id(d);
            w.body.push_str(",1.)");
            w.finish();
            w.refers("LINE", &[p, vct])
        }
        Curve::Circle {
            center,
            normal,
            x_axis,
            radius,
        } => {
            let a = w.ax2(*center, *normal, *x_axis);
            w.addf(format_args!("CIRCLE('',#{a},{})", real(*radius)))
        }
        Curve::Ellipse {
            center,
            normal,
            x_axis,
            major,
            minor,
        } => {
            let a = w.ax2(*center, *normal, *x_axis);
            w.addf(format_args!(
                "ELLIPSE('',#{a},{},{})",
                real(*major),
                real(*minor)
            ))
        }
        Curve::BSpline(b) => bspline_entity(w, b),
    }
}

/// A knot vector as STEP's distinct knots and their multiplicities.
fn knot_runs(knots: &[f64]) -> (Vec<f64>, Vec<usize>) {
    let mut ks: Vec<f64> = Vec::new();
    let mut ms: Vec<usize> = Vec::new();
    for &k in knots {
        if ks.last() == Some(&k) {
            *ms.last_mut().expect("multiplicity") += 1;
        } else {
            ks.push(k);
            ms.push(1);
        }
    }
    (ks, ms)
}

/// `(a,b,...)` of integers or of reals.
fn int_list(xs: &[usize]) -> String {
    let parts: Vec<String> = xs.iter().map(|m| m.to_string()).collect();
    format!("({})", parts.join(","))
}

fn real_list(xs: &[f64]) -> String {
    let parts: Vec<String> = xs.iter().map(|&k| real(k)).collect();
    format!("({})", parts.join(","))
}

/// A B-spline surface: `B_SPLINE_SURFACE_WITH_KNOTS`, or for a rational
/// one the complex instance ISO 10303-42 requires (its supertypes and
/// `RATIONAL_B_SPLINE_SURFACE` with the weights), its partial entities in
/// alphabetical order as Part 21 has them.
fn bspline_surface_entity(w: &mut W, b: &BSplineSurface) -> usize {
    let rows: Vec<String> = b
        .control
        .iter()
        .map(|row| {
            let ids: Vec<usize> = row.iter().map(|&p| w.pt(p)).collect();
            format!("({})", Refs(&ids))
        })
        .collect();
    let net = format!("({})", rows.join(","));
    let (ku, mu) = knot_runs(&b.knots_u);
    let (kv, mv) = knot_runs(&b.knots_v);
    let knots = format!(
        "{},{},{},{},.UNSPECIFIED.",
        int_list(&mu),
        int_list(&mv),
        real_list(&ku),
        real_list(&kv)
    );
    match &b.weights {
        None => w.addf(format_args!(
            "B_SPLINE_SURFACE_WITH_KNOTS('',{},{},{net},.UNSPECIFIED.,.F.,.F.,.F.,{knots})",
            b.degree_u, b.degree_v
        )),
        Some(ws) => {
            let rows: Vec<String> = ws.iter().map(|r| real_list(r)).collect();
            w.addf(format_args!(
                "(BOUNDED_SURFACE()B_SPLINE_SURFACE({},{},{net},.UNSPECIFIED.,.F.,.F.,.F.)B_SPLINE_SURFACE_WITH_KNOTS({knots})GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_SURFACE(({}))REPRESENTATION_ITEM('')SURFACE())",
                b.degree_u,
                b.degree_v,
                rows.join(",")
            ))
        }
    }
}

fn surface_entity(w: &mut W, f: &Face) -> usize {
    // A B-spline carries its own placement: the face's frame is not
    // written.
    if let Surface::BSpline(b) = &f.surface {
        return bspline_surface_entity(w, b);
    }
    let fr = f.frame;
    let a = w.ax2(fr.origin, fr.z, fr.x);
    match &f.surface {
        Surface::Cylinder { radius, .. } => w.addf(format_args!(
            "CYLINDRICAL_SURFACE('',#{a},{})",
            real(*radius)
        )),
        Surface::Cone { slope, .. } => w.addf(format_args!(
            "CONICAL_SURFACE('',#{a},{},{})",
            real(f.ref_radius),
            real(atan(*slope))
        )),
        Surface::Sphere { radius, .. } => {
            w.addf(format_args!("SPHERICAL_SURFACE('',#{a},{})", real(*radius)))
        }
        // A spindle torus's outer part (the apple): ISO 10303-42's
        // subtype for a major radius under the minor one, whose
        // `select_outer` picks it. OCCT reads it as a toroidal surface of
        // those radii, whose parameters on the apple are a ring torus's.
        Surface::Torus {
            major_radius,
            minor_radius,
            ..
        } if major_radius < minor_radius => w.addf(format_args!(
            "DEGENERATE_TOROIDAL_SURFACE('',#{a},{},{},.T.)",
            real(*major_radius),
            real(*minor_radius)
        )),
        Surface::Torus {
            major_radius,
            minor_radius,
            ..
        } => w.addf(format_args!(
            "TOROIDAL_SURFACE('',#{a},{},{})",
            real(*major_radius),
            real(*minor_radius)
        )),
        _ => w.refers("PLANE", &[a]),
    }
}

/// Which non-void shell each void shell lies in: the smallest by volume
/// whose bounding box holds the void's.
fn void_parents(b: &Brep) -> Vec<Option<usize>> {
    let bbox = |s: &crate::model::Shell| {
        let mut lo = [f64::INFINITY; 3];
        let mut hi = [f64::NEG_INFINITY; 3];
        for &f in &s.faces {
            for lp in &b.faces[f as usize].loops {
                for c in &lp.coedges {
                    let e = &b.edges[c.edge as usize];
                    for vtx in [e.start, e.end] {
                        let p = b.vertices[vtx as usize];
                        for k in 0..3 {
                            lo[k] = lo[k].min(p[k]);
                            hi[k] = hi[k].max(p[k]);
                        }
                    }
                }
            }
        }
        (lo, hi)
    };
    let boxes: Vec<_> = b.shells.iter().map(bbox).collect();
    let size = |(lo, hi): ([f64; 3], [f64; 3])| (0..3).map(|k| hi[k] - lo[k]).product::<f64>();
    b.shells
        .iter()
        .enumerate()
        .map(|(i, s)| {
            if !s.void {
                return None;
            }
            let (vl, vh) = boxes[i];
            b.shells
                .iter()
                .enumerate()
                .filter(|(j, o)| {
                    !o.void && (0..3).all(|k| boxes[*j].0[k] <= vl[k] && vh[k] <= boxes[*j].1[k])
                })
                .min_by(|a, c| size(boxes[a.0]).total_cmp(&size(boxes[c.0])))
                .map(|(j, _)| j)
        })
        .collect()
}

/// Writes `brep` as a STEP AP214 file (`AUTOMOTIVE_DESIGN` schema), in
/// millimetres, with parameter-space curves on curved faces and seam
/// curves on periodic ones.
pub fn write_step(brep: &Brep, opts: &StepOptions) -> String {
    // The header goes first in the buffer the entities are appended to,
    // so the file is that buffer: assembling it in a second one copied the
    // whole file (a tenth of writing a large one).
    let mut header = String::new();
    header.push_str("ISO-10303-21;\nHEADER;\n");
    let _ = writeln!(
        header,
        "FILE_DESCRIPTION(({}),'2;1');",
        string(&opts.description)
    );
    let _ = writeln!(
        header,
        "FILE_NAME({},{},({}),({}),{},{},'');",
        string(&opts.file_name),
        string(&opts.timestamp),
        string(&opts.author),
        string(&opts.organization),
        string("meshbrep"),
        string(&opts.originating_system)
    );
    header.push_str(
        "FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }'));\nENDSEC;\nDATA;\n",
    );
    let mut w = W::new(brep.vertices.len());
    w.body.push_str(&header);
    // About what a model of straight edges and planar faces takes (a
    // little over), so the buffer is not copied as it doubles.
    w.body
        .reserve(560 * brep.edges.len() + 320 * brep.faces.len() + 96 * brep.vertices.len());
    let name = string(&opts.product_name);
    let app = w.add("APPLICATION_CONTEXT('automotive design')".into());
    w.addf(format_args!(
        "APPLICATION_PROTOCOL_DEFINITION('international standard','automotive_design',2000,#{app})"
    ));
    let pc = w.addf(format_args!("PRODUCT_CONTEXT('',#{app},'mechanical')"));
    let prod = w.addf(format_args!("PRODUCT({name},{name},'',(#{pc}))"));
    let pdf = w.addf(format_args!("PRODUCT_DEFINITION_FORMATION('','',#{prod})"));
    let pdc = w.addf(format_args!(
        "PRODUCT_DEFINITION_CONTEXT('part definition',#{app},'design')"
    ));
    let pd = w.addf(format_args!(
        "PRODUCT_DEFINITION('design','',#{pdf},#{pdc})"
    ));
    let pds = w.addf(format_args!("PRODUCT_DEFINITION_SHAPE('','',#{pd})"));
    let sdr = w.reserve();
    let lu = w.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))".into());
    let au = w.add("(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.))".into());
    let su = w.add("(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT())".into());
    let unc = w.addf(format_args!(
        "UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.E-07),#{lu},'distance_accuracy_value','confusion accuracy')"
    ));
    let ctx = w.addf(format_args!(
        "(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#{unc}))GLOBAL_UNIT_ASSIGNED_CONTEXT((#{lu},#{au},#{su}))REPRESENTATION_CONTEXT('Context3D','3D'))"
    ));
    let ctx2 = w.add(
        "(GEOMETRIC_REPRESENTATION_CONTEXT(2)PARAMETRIC_REPRESENTATION_CONTEXT()REPRESENTATION_CONTEXT('2D SPACE',''))"
            .into(),
    );
    let origin = w.ax2([0.0; 3], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]);
    // Surfaces first: parameter-space curves refer to them.
    let sids: Vec<usize> = brep
        .faces
        .iter()
        .map(|f| surface_entity(&mut w, f))
        .collect();
    let vids: Vec<usize> = brep
        .vertices
        .iter()
        .map(|&p| {
            let q = w.pt(p);
            w.refers("VERTEX_POINT", &[q])
        })
        .collect();
    // Each edge's parameter-space curves, in face order.
    let mut pcs: Vec<Vec<(usize, &BSpline<2>)>> = vec![Vec::new(); brep.edges.len()];
    for (fi, f) in brep.faces.iter().enumerate() {
        for lp in &f.loops {
            for c in &lp.coedges {
                if let Some(pc) = &c.pcurve {
                    pcs[c.edge as usize].push((fi, pc));
                }
            }
        }
    }
    let eids: Vec<usize> = brep
        .edges
        .iter()
        .enumerate()
        .map(|(i, e)| {
            let c3 = curve_entity(&mut w, &e.curve);
            let geom = if pcs[i].is_empty() {
                c3
            } else {
                let ps: Vec<usize> = pcs[i]
                    .iter()
                    .map(|&(fi, pc)| {
                        let b = bspline_entity(&mut w, pc);
                        let dr = w.addf(format_args!(
                            "DEFINITIONAL_REPRESENTATION('',(#{b}),#{ctx2})"
                        ));
                        w.addf(format_args!("PCURVE('',#{},#{dr})", sids[fi]))
                    })
                    .collect();
                let kind = if e.seam {
                    "SEAM_CURVE"
                } else {
                    "SURFACE_CURVE"
                };
                w.addf(format_args!("{kind}('',#{c3},({}),.PCURVE_S1.)", Refs(&ps)))
            };
            let n = w.start();
            w.body.push_str("EDGE_CURVE('',");
            w.ids(&[vids[e.start as usize], vids[e.end as usize], geom]);
            w.body.push_str(",.T.)");
            w.finish();
            n
        })
        .collect();
    let parents = void_parents(brep);
    let face_entity = |w: &mut W, fi: usize, flip: bool| -> usize {
        let f = &brep.faces[fi];
        let bounds: Vec<usize> = f
            .loops
            .iter()
            .map(|lp| {
                let oes: Vec<usize> = lp
                    .coedges
                    .iter()
                    .map(|c| {
                        let n = w.start();
                        w.body.push_str("ORIENTED_EDGE('',*,*,");
                        w.id(eids[c.edge as usize]);
                        w.body.push_str(if c.forward { ",.T.)" } else { ",.F.)" });
                        w.finish();
                        n
                    })
                    .collect();
                let l = w.start();
                w.body.push_str("EDGE_LOOP('',(");
                w.ids(&oes);
                w.body.push_str("))");
                w.finish();
                let kind = if lp.outer {
                    "FACE_OUTER_BOUND"
                } else {
                    "FACE_BOUND"
                };
                let n = w.start();
                w.body.push_str(kind);
                w.body.push_str("('',");
                w.id(l);
                w.body.push_str(if flip { ",.F.)" } else { ",.T.)" });
                w.finish();
                n
            })
            .collect();
        let n = w.start();
        w.body.push_str("ADVANCED_FACE('',(");
        w.ids(&bounds);
        w.body.push_str("),");
        w.id(sids[fi]);
        w.body.push_str(if f.same_sense != flip {
            ",.T.)"
        } else {
            ",.F.)"
        });
        w.finish();
        n
    };
    let mut shell_ids = Vec::with_capacity(brep.shells.len());
    for sh in &brep.shells {
        let fs: Vec<usize> = sh
            .faces
            .iter()
            .map(|&f| face_entity(&mut w, f as usize, sh.void))
            .collect();
        shell_ids.push(w.addf(format_args!("CLOSED_SHELL('',({}))", Refs(&fs))));
    }
    let mut solids = Vec::new();
    for (i, sh) in brep.shells.iter().enumerate() {
        if sh.void && parents[i].is_some() {
            continue;
        }
        let voids: Vec<usize> = (0..brep.shells.len())
            .filter(|&j| parents[j] == Some(i))
            .map(|j| {
                w.addf(format_args!(
                    "ORIENTED_CLOSED_SHELL('',*,#{},.F.)",
                    shell_ids[j]
                ))
            })
            .collect();
        solids.push(if voids.is_empty() {
            w.addf(format_args!("MANIFOLD_SOLID_BREP('',#{})", shell_ids[i]))
        } else {
            w.addf(format_args!(
                "BREP_WITH_VOIDS('',#{},({}))",
                shell_ids[i],
                Refs(&voids)
            ))
        });
    }
    let mut items = solids;
    items.push(origin);
    let rep = w.addf(format_args!(
        "ADVANCED_BREP_SHAPE_REPRESENTATION('',({}),#{ctx})",
        Refs(&items)
    ));
    w.set(
        sdr,
        format!("SHAPE_DEFINITION_REPRESENTATION(#{pds},#{rep})"),
    );

    w.into_file()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn reals_always_have_a_point() {
        assert_eq!(real(0.0), "0.");
        assert_eq!(real(-0.0), "0.");
        assert_eq!(real(1.0), "1.");
        assert_eq!(real(1.5), "1.5");
        assert_eq!(real(15.0), "1.5E1");
        assert_eq!(real(1e-7), "1.E-7");
        assert_eq!(real(-2.5e-12), "-2.5E-12");
        for x in [0.1, 1.0 / 3.0, 123456.789, -1e300, 5e-324] {
            assert_eq!(real(x).parse::<f64>().unwrap(), x);
        }
    }

    /// The shortcuts in front of `{:E}` (whole numbers, and reals seen
    /// before) give its text exactly: on whole numbers of every length up
    /// to 2^53 and just past it, on random bit patterns, and on values
    /// repeated many times over so that the cache's slots are reused and
    /// overwritten.
    #[test]
    fn real_shortcuts_give_the_formatted_text() {
        let slow = |x: f64| {
            let mut out = String::new();
            if x == 0.0 {
                out.push_str("0.");
                return out;
            }
            let s = format!("{x:E}");
            let (mant, exp) = s.split_once('E').unwrap();
            out.push_str(mant);
            if !mant.contains('.') {
                out.push('.');
            }
            if exp != "0" {
                out.push('E');
                out.push_str(exp);
            }
            out
        };
        let mut seed: u64 = 0x2545_f491_4f6c_dd1d;
        let mut rnd = move || {
            seed ^= seed << 13;
            seed ^= seed >> 7;
            seed ^= seed << 17;
            seed
        };
        let mut values: Vec<f64> = Vec::new();
        for k in 0..=54 {
            let p = 2f64.powi(k);
            values.extend([p - 1.0, p, p + 1.0, -p, 10f64.powi(k.min(22))]);
        }
        values.extend([1.0, -1.0, 15.0, 100.0, 1e15, 1.5, 0.1, 1e-7, 5e-324]);
        for _ in 0..20_000 {
            let r = rnd();
            values.push(f64::from_bits(r));
            values.push((r % 2_000_001) as f64 - 1_000_000.0);
            values.push((r % 1_000_000) as f64 / 64.0);
            values.push(((r >> 11) as f64) * 1e-3);
        }
        values.retain(|x| x.is_finite());
        let (mut small, mut large) = (Reals::new(0), Reals::new(1 << 20));
        for round in 0..3 {
            for &x in &values {
                for cache in [&mut small, &mut large] {
                    let mut fast = String::new();
                    cache.push(&mut fast, x);
                    assert_eq!(fast, slow(x), "{x:?} (round {round})");
                }
                let mut plain = String::new();
                push_real(&mut plain, x, &mut String::new());
                assert_eq!(plain, slow(x), "{x:?}");
            }
        }
    }

    #[test]
    fn strings_are_escaped() {
        assert_eq!(string("it's"), "'it''s'");
        assert_eq!(string("a\\b"), "'a\\\\b'");
        assert_eq!(string("é"), "'\\X2\\00E9\\X0\\'");
    }
}