BREP_reconstruction 0.2.0

Kernel integration for neutral BREP_RANSAC recognition results
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
//! Binary and ASCII STL import with deterministic vertex welding.

use crate::{Mesh, Vec3};
use std::collections::{BTreeMap, HashMap};
use std::fmt::{Display, Formatter};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};

/// The relative vertex-weld tolerance used when none is supplied.
pub const DEFAULT_RELATIVE_WELD_TOLERANCE: f64 = 1.0e-9;

/// Options controlling STL import.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct StlReadOptions {
    /// Absolute distance used to merge vertices. `None` selects
    /// `bounding_box_diagonal * 1e-9`; `Some(0.0)` only merges bitwise-equal
    /// coordinates (with positive and negative zero treated as equal).
    pub weld_tolerance: Option<f64>,
}

/// Encoding detected while importing an STL file.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum StlFormat {
    /// The 80-byte-header binary STL encoding.
    Binary,
    /// The line-oriented ASCII STL encoding.
    Ascii,
}

impl Display for StlFormat {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Binary => "binary",
            Self::Ascii => "ASCII",
        })
    }
}

/// An imported mesh and useful ingestion statistics.
#[derive(Clone, Debug, PartialEq)]
pub struct StlImport {
    /// Indexed triangle mesh with source winding preserved.
    pub mesh: Mesh,
    /// Encoding detected from the file contents.
    pub format: StlFormat,
    /// Number of facets in the source STL.
    pub source_triangle_count: usize,
    /// Number of source facet-corner vertices (three per facet).
    pub source_vertex_count: usize,
    /// Number of vertices remaining after deterministic welding.
    pub welded_vertex_count: usize,
    /// Absolute tolerance used for vertex welding.
    pub weld_tolerance: f64,
}

/// Failure to read, parse, or validate STL input.
#[derive(Debug)]
pub enum StlError {
    /// The source file could not be read.
    Io {
        /// Path passed to the importer.
        path: PathBuf,
        /// Underlying filesystem error.
        source: io::Error,
    },
    /// The byte stream is neither a valid binary nor a valid ASCII STL.
    InvalidFormat(String),
    /// The STL ends before all declared data is present.
    Truncated {
        /// Total byte count required by the binary facet count.
        expected: usize,
        /// Actual byte count supplied.
        actual: usize,
    },
    /// A numeric value or geometric facet is invalid.
    InvalidGeometry(String),
    /// An import option is outside its supported range.
    InvalidOptions(String),
}

impl Display for StlError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io { path, source } => {
                write!(f, "could not read STL '{}': {source}", path.display())
            }
            Self::InvalidFormat(message) => write!(f, "invalid STL format: {message}"),
            Self::Truncated { expected, actual } => write!(
                f,
                "truncated binary STL: expected {expected} bytes, found {actual}"
            ),
            Self::InvalidGeometry(message) => write!(f, "invalid STL geometry: {message}"),
            Self::InvalidOptions(message) => write!(f, "invalid STL options: {message}"),
        }
    }
}

impl std::error::Error for StlError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io { source, .. } => Some(source),
            _ => None,
        }
    }
}

/// Reads an STL file using [`StlReadOptions::default`].
pub fn read_stl(path: impl AsRef<Path>) -> Result<StlImport, StlError> {
    read_stl_with_options(path, &StlReadOptions::default())
}

/// Reads an STL file with explicit import options.
pub fn read_stl_with_options(
    path: impl AsRef<Path>,
    options: &StlReadOptions,
) -> Result<StlImport, StlError> {
    let path = path.as_ref();
    let bytes = fs::read(path).map_err(|source| StlError::Io {
        path: path.to_owned(),
        source,
    })?;
    parse_stl_bytes(&bytes, options)
}

/// Parses binary or ASCII STL bytes and creates an indexed mesh.
///
/// Binary structure is checked before the leading `solid` token because
/// binary STL headers are arbitrary and commonly begin with that word.
pub fn parse_stl_bytes(bytes: &[u8], options: &StlReadOptions) -> Result<StlImport, StlError> {
    validate_options(options)?;
    if bytes.is_empty() {
        return Err(StlError::InvalidFormat("the input is empty".into()));
    }

    let binary_length = declared_binary_length(bytes);
    let (format, triangles) = if binary_length == Some(bytes.len()) {
        (StlFormat::Binary, parse_binary(bytes)?)
    } else {
        match parse_ascii(bytes) {
            Ok(triangles) => (StlFormat::Ascii, triangles),
            Err(ascii_error) => {
                if let Some(expected) = binary_length {
                    if expected > bytes.len() && looks_like_binary(bytes) {
                        return Err(StlError::Truncated {
                            expected,
                            actual: bytes.len(),
                        });
                    }
                }
                return Err(ascii_error);
            }
        }
    };
    build_import(triangles, format, options)
}

fn validate_options(options: &StlReadOptions) -> Result<(), StlError> {
    if let Some(tolerance) = options.weld_tolerance {
        if !tolerance.is_finite() || tolerance < 0.0 {
            return Err(StlError::InvalidOptions(
                "weld_tolerance must be finite and non-negative".into(),
            ));
        }
    }
    Ok(())
}

fn declared_binary_length(bytes: &[u8]) -> Option<usize> {
    let count_bytes: [u8; 4] = bytes.get(80..84)?.try_into().ok()?;
    let count = u32::from_le_bytes(count_bytes) as usize;
    84_usize.checked_add(count.checked_mul(50)?)
}

fn looks_like_binary(bytes: &[u8]) -> bool {
    bytes
        .iter()
        .take(84)
        .any(|&byte| !matches!(byte, b'\t' | b'\n' | b'\r' | 0x20..=0x7e))
}

fn parse_binary(bytes: &[u8]) -> Result<Vec<[Vec3; 3]>, StlError> {
    let expected = declared_binary_length(bytes)
        .ok_or_else(|| StlError::InvalidFormat("binary header is incomplete".into()))?;
    if expected != bytes.len() {
        return Err(if expected > bytes.len() {
            StlError::Truncated {
                expected,
                actual: bytes.len(),
            }
        } else {
            StlError::InvalidFormat(format!(
                "binary STL has {} unexpected trailing bytes",
                bytes.len() - expected
            ))
        });
    }
    let count = (expected - 84) / 50;
    if count == 0 {
        return Err(StlError::InvalidGeometry(
            "the STL contains no triangles".into(),
        ));
    }
    let mut triangles = Vec::with_capacity(count);
    for facet in 0..count {
        let offset = 84 + facet * 50;
        let normal = read_binary_vec3(bytes, offset)?;
        if !normal.is_finite() {
            return Err(StlError::InvalidGeometry(format!(
                "facet {facet} has a non-finite normal"
            )));
        }
        triangles.push([
            read_binary_vec3(bytes, offset + 12)?,
            read_binary_vec3(bytes, offset + 24)?,
            read_binary_vec3(bytes, offset + 36)?,
        ]);
    }
    Ok(triangles)
}

fn read_binary_vec3(bytes: &[u8], offset: usize) -> Result<Vec3, StlError> {
    let component = |start: usize| -> Result<f64, StlError> {
        let raw: [u8; 4] = bytes
            .get(start..start + 4)
            .and_then(|slice| slice.try_into().ok())
            .ok_or_else(|| StlError::InvalidFormat("binary vector is incomplete".into()))?;
        Ok(f32::from_le_bytes(raw) as f64)
    };
    Ok(Vec3::new(
        component(offset)?,
        component(offset + 4)?,
        component(offset + 8)?,
    ))
}

fn parse_ascii(bytes: &[u8]) -> Result<Vec<[Vec3; 3]>, StlError> {
    let text = std::str::from_utf8(bytes)
        .map_err(|_| StlError::InvalidFormat("ASCII STL is not valid UTF-8".into()))?;
    let lines: Vec<(usize, &str)> = text
        .lines()
        .enumerate()
        .filter_map(|(index, line)| {
            let trimmed = line.trim();
            (!trimmed.is_empty()).then_some((index + 1, trimmed))
        })
        .collect();
    let Some(&(first_line, first_raw)) = lines.first() else {
        return Err(StlError::InvalidFormat("the input is empty".into()));
    };
    let first = first_raw.strip_prefix('\u{feff}').unwrap_or(first_raw);
    if !first
        .split_whitespace()
        .next()
        .is_some_and(|token| token.eq_ignore_ascii_case("solid"))
    {
        return Err(StlError::InvalidFormat(format!(
            "line {first_line}: ASCII STL must begin with 'solid'"
        )));
    }

    let mut cursor = 1;
    let mut triangles = Vec::new();
    while cursor < lines.len() {
        let (line_number, line) = lines[cursor];
        if line
            .split_whitespace()
            .next()
            .is_some_and(|token| token.eq_ignore_ascii_case("endsolid"))
        {
            cursor += 1;
            if cursor != lines.len() {
                return Err(StlError::InvalidFormat(format!(
                    "line {}: content follows 'endsolid'",
                    lines[cursor].0
                )));
            }
            break;
        }
        let normal = parse_prefixed_vec3(line_number, line, &["facet", "normal"])?;
        if !normal.is_finite() {
            return Err(StlError::InvalidGeometry(format!(
                "line {line_number}: facet normal is non-finite"
            )));
        }
        cursor += 1;
        expect_ascii_line(&lines, cursor, &["outer", "loop"])?;
        cursor += 1;
        let mut vertices = [Vec3::ZERO; 3];
        for vertex in &mut vertices {
            let &(number, source) = lines
                .get(cursor)
                .ok_or_else(|| StlError::InvalidFormat("ASCII STL ends inside a facet".into()))?;
            *vertex = parse_prefixed_vec3(number, source, &["vertex"])?;
            cursor += 1;
        }
        expect_ascii_line(&lines, cursor, &["endloop"])?;
        cursor += 1;
        expect_ascii_line(&lines, cursor, &["endfacet"])?;
        cursor += 1;
        triangles.push(vertices);
    }
    if triangles.is_empty() {
        return Err(StlError::InvalidGeometry(
            "the STL contains no triangles".into(),
        ));
    }
    Ok(triangles)
}

fn expect_ascii_line(
    lines: &[(usize, &str)],
    cursor: usize,
    expected: &[&str],
) -> Result<(), StlError> {
    let &(number, source) = lines
        .get(cursor)
        .ok_or_else(|| StlError::InvalidFormat("ASCII STL ends inside a facet".into()))?;
    let tokens: Vec<_> = source.split_whitespace().collect();
    if tokens.len() == expected.len()
        && tokens
            .iter()
            .zip(expected)
            .all(|(actual, expected)| actual.eq_ignore_ascii_case(expected))
    {
        Ok(())
    } else {
        Err(StlError::InvalidFormat(format!(
            "line {number}: expected '{}'",
            expected.join(" ")
        )))
    }
}

fn parse_prefixed_vec3(
    line_number: usize,
    source: &str,
    prefix: &[&str],
) -> Result<Vec3, StlError> {
    let tokens: Vec<_> = source.split_whitespace().collect();
    if tokens.len() != prefix.len() + 3
        || !tokens[..prefix.len()]
            .iter()
            .zip(prefix)
            .all(|(actual, expected)| actual.eq_ignore_ascii_case(expected))
    {
        return Err(StlError::InvalidFormat(format!(
            "line {line_number}: expected '{} x y z'",
            prefix.join(" ")
        )));
    }
    let mut values = [0.0; 3];
    for (index, token) in tokens[prefix.len()..].iter().enumerate() {
        values[index] = token.parse::<f64>().map_err(|_| {
            StlError::InvalidFormat(format!("line {line_number}: '{token}' is not a number"))
        })?;
    }
    let vector = Vec3::new(values[0], values[1], values[2]);
    if !vector.is_finite() {
        return Err(StlError::InvalidGeometry(format!(
            "line {line_number}: vector contains a non-finite value"
        )));
    }
    Ok(vector)
}

fn build_import(
    source: Vec<[Vec3; 3]>,
    format: StlFormat,
    options: &StlReadOptions,
) -> Result<StlImport, StlError> {
    let source_triangle_count = source.len();
    let source_vertex_count = source_triangle_count.checked_mul(3).ok_or_else(|| {
        StlError::InvalidGeometry("source vertex count exceeds platform limits".into())
    })?;
    let mut bbox_min = source[0][0];
    let mut bbox_max = source[0][0];
    for (facet, triangle) in source.iter().enumerate() {
        for &point in triangle {
            if !point.is_finite() {
                return Err(StlError::InvalidGeometry(format!(
                    "facet {facet} has a non-finite vertex"
                )));
            }
            bbox_min.x = bbox_min.x.min(point.x);
            bbox_min.y = bbox_min.y.min(point.y);
            bbox_min.z = bbox_min.z.min(point.z);
            bbox_max.x = bbox_max.x.max(point.x);
            bbox_max.y = bbox_max.y.max(point.y);
            bbox_max.z = bbox_max.z.max(point.z);
        }
        validate_triangle(*triangle, facet)?;
    }
    let extent = bbox_max - bbox_min;
    let diagonal = extent.length();
    if !extent.is_finite() || !diagonal.is_finite() || diagonal <= 0.0 {
        return Err(StlError::InvalidGeometry(
            "the bounding box is zero-sized or outside the supported numeric range".into(),
        ));
    }
    let weld_tolerance = options
        .weld_tolerance
        .unwrap_or(diagonal * DEFAULT_RELATIVE_WELD_TOLERANCE);
    if !weld_tolerance.is_finite() {
        return Err(StlError::InvalidGeometry(
            "the derived weld tolerance is outside the supported numeric range".into(),
        ));
    }
    let (vertices, triangles) = weld_vertices(&source, bbox_min, diagonal, weld_tolerance)?;
    let welded_vertex_count = vertices.len();
    Ok(StlImport {
        mesh: Mesh::new(vertices, triangles),
        format,
        source_triangle_count,
        source_vertex_count,
        welded_vertex_count,
        weld_tolerance,
    })
}

fn validate_triangle(points: [Vec3; 3], facet: usize) -> Result<(), StlError> {
    let ab = points[1] - points[0];
    let ac = points[2] - points[0];
    if !ab.is_finite() || !ac.is_finite() {
        return Err(StlError::InvalidGeometry(format!(
            "facet {facet} exceeds the supported numeric range"
        )));
    }
    let scale = [ab.x, ab.y, ab.z, ac.x, ac.y, ac.z]
        .into_iter()
        .fold(0.0_f64, |largest, value| largest.max(value.abs()));
    let cross = if scale > 0.0 {
        (ab / scale).cross(ac / scale)
    } else {
        Vec3::ZERO
    };
    if !cross.is_finite() || cross.length_squared() == 0.0 {
        return Err(StlError::InvalidGeometry(format!(
            "facet {facet} is degenerate"
        )));
    }
    Ok(())
}

fn weld_vertices(
    source: &[[Vec3; 3]],
    bbox_min: Vec3,
    diagonal: f64,
    tolerance: f64,
) -> Result<(Vec<Vec3>, Vec<[u32; 3]>), StlError> {
    if tolerance == 0.0 {
        return weld_exact(source);
    }
    // Leave headroom for the neighbor-cell offsets below.
    if diagonal / tolerance > (i64::MAX - 2) as f64 {
        return Err(StlError::InvalidOptions(
            "weld_tolerance is too small relative to the model size; use zero for exact welding"
                .into(),
        ));
    }

    let mut vertices = Vec::<Vec3>::new();
    let mut cells = BTreeMap::<[i64; 3], Vec<u32>>::new();
    let mut triangles = Vec::with_capacity(source.len());
    for (facet, points) in source.iter().enumerate() {
        let mut triangle = [0_u32; 3];
        for (corner, &point) in points.iter().enumerate() {
            let key = cell_key(point, bbox_min, tolerance)?;
            let mut matched = None;
            for dx in -1..=1 {
                for dy in -1..=1 {
                    for dz in -1..=1 {
                        let neighbor = [key[0] + dx, key[1] + dy, key[2] + dz];
                        if let Some(candidates) = cells.get(&neighbor) {
                            for &candidate in candidates {
                                let delta = (point - vertices[candidate as usize]) / tolerance;
                                if delta.length_squared() <= 1.0
                                    && matched.is_none_or(|current| candidate < current)
                                {
                                    matched = Some(candidate);
                                }
                            }
                        }
                    }
                }
            }
            let index = match matched {
                Some(index) => index,
                None => {
                    let index = u32::try_from(vertices.len()).map_err(|_| {
                        StlError::InvalidGeometry(
                            "the welded mesh exceeds the u32 vertex-index limit".into(),
                        )
                    })?;
                    vertices.push(point);
                    cells.entry(key).or_default().push(index);
                    index
                }
            };
            triangle[corner] = index;
        }
        if triangle[0] == triangle[1] || triangle[1] == triangle[2] || triangle[2] == triangle[0] {
            return Err(StlError::InvalidGeometry(format!(
                "facet {facet} becomes degenerate at weld tolerance {tolerance:e}"
            )));
        }
        validate_triangle(triangle.map(|index| vertices[index as usize]), facet)?;
        triangles.push(triangle);
    }
    Ok((vertices, triangles))
}

fn cell_key(point: Vec3, origin: Vec3, tolerance: f64) -> Result<[i64; 3], StlError> {
    let relative = point - origin;
    let cell = [relative.x, relative.y, relative.z].map(|value| (value / tolerance).floor());
    if cell
        .iter()
        .any(|&value| !value.is_finite() || value < 0.0 || value > (i64::MAX - 2) as f64)
    {
        return Err(StlError::InvalidOptions(
            "weld_tolerance cannot be represented by the spatial index".into(),
        ));
    }
    Ok(cell.map(|value| value as i64))
}

fn weld_exact(source: &[[Vec3; 3]]) -> Result<(Vec<Vec3>, Vec<[u32; 3]>), StlError> {
    let mut vertices = Vec::new();
    let mut indices = HashMap::<[u64; 3], u32>::new();
    let mut triangles = Vec::with_capacity(source.len());
    for (facet, points) in source.iter().enumerate() {
        let mut triangle = [0_u32; 3];
        for (corner, &point) in points.iter().enumerate() {
            let canonical_bits = |value: f64| if value == 0.0 { 0 } else { value.to_bits() };
            let key = [
                canonical_bits(point.x),
                canonical_bits(point.y),
                canonical_bits(point.z),
            ];
            let index = match indices.get(&key) {
                Some(&index) => index,
                None => {
                    let index = u32::try_from(vertices.len()).map_err(|_| {
                        StlError::InvalidGeometry(
                            "the welded mesh exceeds the u32 vertex-index limit".into(),
                        )
                    })?;
                    vertices.push(point);
                    indices.insert(key, index);
                    index
                }
            };
            triangle[corner] = index;
        }
        if triangle[0] == triangle[1] || triangle[1] == triangle[2] || triangle[2] == triangle[0] {
            return Err(StlError::InvalidGeometry(format!(
                "facet {facet} becomes degenerate after exact vertex welding"
            )));
        }
        validate_triangle(triangle.map(|index| vertices[index as usize]), facet)?;
        triangles.push(triangle);
    }
    Ok((vertices, triangles))
}

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

    fn binary_stl(header: &[u8], facets: &[[[f32; 3]; 3]]) -> Vec<u8> {
        let mut bytes = vec![b' '; 80];
        bytes[..header.len()].copy_from_slice(header);
        bytes.extend_from_slice(&(facets.len() as u32).to_le_bytes());
        for points in facets {
            for value in [0.0_f32, 0.0, 1.0] {
                bytes.extend_from_slice(&value.to_le_bytes());
            }
            for point in points {
                for value in point {
                    bytes.extend_from_slice(&value.to_le_bytes());
                }
            }
            bytes.extend_from_slice(&0_u16.to_le_bytes());
        }
        bytes
    }

    const SQUARE_ASCII: &str = "solid square\n\
        facet normal 0 0 1\n\
          outer loop\n\
            vertex 0 0 0\n\
            vertex 1 0 0\n\
            vertex 1 1 0\n\
          endloop\n\
        endfacet\n\
        facet normal 0 0 1\n\
          outer loop\n\
            vertex 0 0 0\n\
            vertex 1 1 0\n\
            vertex 0 1 0\n\
          endloop\n\
        endfacet\n\
        endsolid square\n";

    #[test]
    fn imports_ascii_and_welds_shared_vertices_for_adjacency() {
        let imported =
            parse_stl_bytes(SQUARE_ASCII.as_bytes(), &StlReadOptions::default()).unwrap();
        assert_eq!(imported.format, StlFormat::Ascii);
        assert_eq!(imported.source_triangle_count, 2);
        assert_eq!(imported.source_vertex_count, 6);
        assert_eq!(imported.welded_vertex_count, 4);
        assert_eq!(imported.mesh.triangles, vec![[0, 1, 2], [0, 2, 3]]);
        assert!(imported.mesh.vertex_normals.is_none());
        let analyzed = imported
            .mesh
            .analyze(&MeshAnalysisOptions::default())
            .unwrap();
        assert_eq!(analyzed.triangles[0].neighbors[2], Some(1));
        assert_eq!(analyzed.triangles[1].neighbors[0], Some(0));
    }

    #[test]
    fn imports_binary_and_preserves_winding() {
        let bytes = binary_stl(
            b"ordinary binary",
            &[[[0., 0., 0.], [0., 1., 0.], [1., 0., 0.]]],
        );
        let imported = parse_stl_bytes(&bytes, &StlReadOptions::default()).unwrap();
        assert_eq!(imported.format, StlFormat::Binary);
        assert_eq!(imported.mesh.triangles, vec![[0, 1, 2]]);
        let analyzed = imported
            .mesh
            .analyze(&MeshAnalysisOptions::default())
            .unwrap();
        assert!(analyzed.triangles[0].normal.z < 0.0);
    }

    #[test]
    fn binary_header_beginning_with_solid_is_not_misclassified() {
        let bytes = binary_stl(
            b"solid definitely still binary",
            &[[[0., 0., 0.], [1., 0., 0.], [0., 1., 0.]]],
        );
        let imported = parse_stl_bytes(&bytes, &StlReadOptions::default()).unwrap();
        assert_eq!(imported.format, StlFormat::Binary);
    }

    #[test]
    fn explicit_tolerance_welds_nearby_vertices_deterministically() {
        let ascii = "solid square\n\
            facet normal 0 0 1\nouter loop\n\
            vertex 0 0 0\nvertex 1 0 0\nvertex 1 1 0\n\
            endloop\nendfacet\n\
            facet normal 0 0 1\nouter loop\n\
            vertex 0.00001 0 0\nvertex 1.00001 1 0\nvertex 0 1 0\n\
            endloop\nendfacet\nendsolid square\n";
        let exact = parse_stl_bytes(
            ascii.as_bytes(),
            &StlReadOptions {
                weld_tolerance: Some(0.0),
            },
        )
        .unwrap();
        assert_eq!(exact.welded_vertex_count, 6);
        let welded = parse_stl_bytes(
            ascii.as_bytes(),
            &StlReadOptions {
                weld_tolerance: Some(0.001),
            },
        )
        .unwrap();
        assert_eq!(welded.welded_vertex_count, 4);
        assert_eq!(welded.mesh.triangles, vec![[0, 1, 2], [0, 2, 3]]);
    }

    #[test]
    fn rejects_truncated_binary() {
        let mut bytes = binary_stl(b"binary", &[[[0., 0., 0.], [1., 0., 0.], [0., 1., 0.]]]);
        bytes.truncate(bytes.len() - 7);
        assert!(matches!(
            parse_stl_bytes(&bytes, &StlReadOptions::default()),
            Err(StlError::Truncated { .. })
        ));
    }

    #[test]
    fn rejects_non_finite_and_degenerate_facets() {
        let nan = binary_stl(
            b"binary",
            &[[[0., 0., 0.], [f32::NAN, 0., 0.], [0., 1., 0.]]],
        );
        assert!(matches!(
            parse_stl_bytes(&nan, &StlReadOptions::default()),
            Err(StlError::InvalidGeometry(_))
        ));
        let degenerate = b"solid bad\nfacet normal 0 0 1\nouter loop\nvertex 0 0 0\nvertex 1 0 0\nvertex 2 0 0\nendloop\nendfacet\nendsolid bad\n";
        assert!(matches!(
            parse_stl_bytes(degenerate, &StlReadOptions::default()),
            Err(StlError::InvalidGeometry(message)) if message.contains("degenerate")
        ));
    }

    #[test]
    fn rejects_malformed_ascii_and_invalid_options() {
        let malformed =
            b"solid bad\nfacet normal 0 0 1\nouter loop\nvertex 0 0 0\nendloop\nendfacet\n";
        assert!(matches!(
            parse_stl_bytes(malformed, &StlReadOptions::default()),
            Err(StlError::InvalidFormat(_))
        ));
        assert!(matches!(
            parse_stl_bytes(
                SQUARE_ASCII.as_bytes(),
                &StlReadOptions {
                    weld_tolerance: Some(f64::NAN)
                }
            ),
            Err(StlError::InvalidOptions(_))
        ));
    }

    #[test]
    fn accepts_utf8_bom_and_case_insensitive_ascii_keywords() {
        let source = "\u{feff}SOLID one\n\
            FACET NORMAL 0 0 1\nOUTER LOOP\n\
            VERTEX 0 0 0\nVERTEX 1 0 0\nVERTEX 0 1 0\n\
            ENDLOOP\nENDFACET\nENDSOLID one\n";
        let imported = parse_stl_bytes(source.as_bytes(), &StlReadOptions::default()).unwrap();
        assert_eq!(imported.format, StlFormat::Ascii);
        assert_eq!(imported.welded_vertex_count, 3);
    }

    #[test]
    fn rejects_empty_binary_and_trailing_binary_data() {
        let empty = binary_stl(b"empty", &[]);
        assert!(matches!(
            parse_stl_bytes(&empty, &StlReadOptions::default()),
            Err(StlError::InvalidGeometry(message)) if message.contains("no triangles")
        ));

        let mut trailing = binary_stl(b"binary", &[[[0., 0., 0.], [1., 0., 0.], [0., 1., 0.]]]);
        trailing.push(0);
        assert!(parse_stl_bytes(&trailing, &StlReadOptions::default()).is_err());
    }
}