polysmelt 0.23.0

Pure-Rust 3D asset interchange: glTF/GLB reading and writing, meshopt compression, and readers for common mesh formats, SketchUp included
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
//! Meshes: sources read through their accessors, the primitives' index lists turned into triangles (or line
//! segments) over vertices that share every attribute, and polygons with holes bridged and ear-clipped.

use std::collections::HashMap;
use std::rc::Rc;

use super::xml::{self, Dom};
use crate::mesh::{Prim, srgb_to_linear, triangulate};
use crate::num::u32_of;
use crate::polygon::triangulate_holes;
use crate::vec3::{self, cross};

/// The values of a `<source>`, read through its accessor: `width` numbers to an element.
#[derive(Debug, Default)]
pub(super) struct Acc<T> {
    pub width: usize,
    pub data: Vec<T>,
}

impl<T> Acc<T> {
    pub(super) fn count(&self) -> usize {
        self.data.len().checked_div(self.width).unwrap_or(0)
    }

    /// Element `i`, when there is one.
    pub(super) fn get(&self, i: u32) -> Option<&[T]> {
        let start = (i as usize).checked_mul(self.width)?;
        self.data.get(start..start.checked_add(self.width)?)
    }
}

/// How many numbers a `<param>` of `type` takes.
fn param_size(kind: Option<&str>) -> usize {
    match kind.unwrap_or("float") {
        "float2" | "double2" | "int2" => 2,
        "float3" | "double3" | "int3" => 3,
        "float4" | "double4" | "int4" | "float2x2" | "double2x2" => 4,
        "float3x3" | "double3x3" => 9,
        "float4x4" | "double4x4" => 16,
        _ => 1,
    }
}

/// The array a source's accessor reads (or the source's own array) and the accessor.
fn array_of(dom: &Dom<'_>, source: usize) -> (Option<usize>, Option<usize>) {
    let accessor = dom.path(source, &["technique_common", "accessor"]);
    let array = accessor
        .and_then(|a| dom.link(a, "source"))
        .filter(|&a| dom.parent(a) == Some(source) || dom.name(a).ends_with(b"_array"))
        .or_else(|| dom.children(source).find(|&c| dom.name(c).ends_with(b"_array")));
    (array, accessor)
}

/// Reads a numeric source through its accessor: unnamed params skipped, stride and offset honored. A source with no
/// accessor is its array, `fallback` numbers to an element.
pub(super) fn read<T: Copy>(dom: &Dom<'_>, source: usize, fallback: usize, parse: impl Fn(&[u8]) -> Vec<T>) -> Acc<T> {
    let (array, accessor) = array_of(dom, source);
    let values = array.map(|a| parse(dom.text(a))).unwrap_or_default();
    let Some(a) = accessor else {
        let width = fallback.max(1);
        let n = values.len() / width * width;
        let mut data = values;
        data.truncate(n);
        return Acc { width, data };
    };
    let stride = dom.attr_num::<usize>(a, "stride").unwrap_or(1).max(1);
    let offset = dom.attr_num::<usize>(a, "offset").unwrap_or(0);
    let mut picks = Vec::new();
    let mut at = 0;
    for p in dom.kids(a, "param") {
        let size = param_size(dom.attr(p, "type"));
        if dom.attr(p, "name").is_some_and(|n| !n.is_empty()) {
            picks.extend(at..at + size);
        }
        at += size;
    }
    // Unnamed params are skipped, unless none is named: then the accessor is read whole.
    if picks.is_empty() {
        picks.extend(0..if at == 0 { stride } else { at });
    }
    picks.retain(|&p| p < stride);
    let Some(&last) = picks.last() else {
        return Acc {
            width: 0,
            data: Vec::new(),
        };
    };
    let available = if values.len() > offset + last {
        (values.len() - offset - last - 1) / stride + 1
    } else {
        0
    };
    let count = dom
        .attr_num::<usize>(a, "count")
        .map_or(available, |c| c.min(available));
    let width = picks.len();
    let contiguous = offset == 0 && width == stride;
    let data = if contiguous {
        let mut data = values;
        data.truncate(count * stride);
        data
    } else {
        let mut data = Vec::with_capacity(count * width);
        for i in 0..count {
            let base = offset + i * stride;
            data.extend(picks.iter().map(|&p| values[base + p]));
        }
        data
    };
    Acc { width, data }
}

/// The words of a `Name_array` or `IDREF_array` source.
pub(super) fn names(dom: &Dom<'_>, source: usize) -> Vec<String> {
    let (array, _) = array_of(dom, source);
    array
        .map(|a| xml::words(dom.text(a)).map(str::to_owned).collect())
        .unwrap_or_default()
}

/// What an input feeds.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Sem {
    Position,
    Normal,
    Texcoord,
    Color,
    Tangent,
    Binormal,
}

impl Sem {
    fn of(name: &str) -> Option<Self> {
        Some(match name {
            "POSITION" => Sem::Position,
            "NORMAL" => Sem::Normal,
            "TEXCOORD" | "UV" => Sem::Texcoord,
            "COLOR" => Sem::Color,
            "TANGENT" | "TEXTANGENT" => Sem::Tangent,
            "BINORMAL" | "TEXBINORMAL" => Sem::Binormal,
            _ => return None,
        })
    }

    /// Numbers to an element when a source has no accessor.
    fn width(self) -> usize {
        match self {
            Sem::Texcoord => 2,
            Sem::Color => 4,
            _ => 3,
        }
    }
}

/// An input of a primitive, with its values.
struct Stream {
    sem: Sem,
    set: u32,
    offset: usize,
    acc: Rc<Acc<f32>>,
}

/// One primitive of a mesh, ready for the builder.
pub(super) struct Piece {
    pub prim: Prim,
    /// The material symbol it's drawn with.
    pub symbol: Option<String>,
    /// The `set` of each `TEXCOORD` input, in the order of the primitive's `TEXCOORD_n`.
    pub sets: Vec<u32>,
    /// Each vertex's index into the mesh's `<vertices>`, which skins and morph targets index.
    pub points: Vec<u32>,
    pub triangles: usize,
    /// The triangles, polygons and segments left out for a corner that names no position.
    pub dropped: usize,
}

/// Source values by element, read once.
pub(super) type Sources = HashMap<usize, Rc<Acc<f32>>>;

pub(super) fn source(dom: &Dom<'_>, sources: &mut Sources, el: usize, fallback: usize) -> Rc<Acc<f32>> {
    sources
        .entry(el)
        .or_insert_with(|| Rc::new(read(dom, el, fallback, xml::floats32_raw)))
        .clone()
}

/// The position source a mesh's `<vertices>` names.
pub(super) fn positions(dom: &Dom<'_>, sources: &mut Sources, mesh: usize) -> Option<Rc<Acc<f32>>> {
    let vertices = dom.child(mesh, "vertices")?;
    let input = dom
        .kids(vertices, "input")
        .find(|&i| dom.attr(i, "semantic") == Some("POSITION"))?;
    let el = dom.link(input, "source")?;
    Some(source(dom, sources, el, 3))
}

/// The primitives of a `<mesh>` (or `<convex_mesh>`), drawing at most `budget` triangles; `Err` with the
/// number drawn when they'd draw more.
pub(super) fn mesh(
    dom: &Dom<'_>,
    sources: &mut Sources,
    mesh: usize,
    budget: usize,
    crease: f32,
) -> Result<Vec<Piece>, usize> {
    let mut out = Vec::new();
    let mut drawn = 0usize;
    for el in dom.children(mesh) {
        let kind = match dom.name(el) {
            b"triangles" => Kind::Triangles,
            b"polylist" => Kind::Polylist,
            b"polygons" => Kind::Polygons,
            b"trifans" => Kind::Fans,
            b"tristrips" => Kind::Strips,
            b"lines" => Kind::Lines,
            b"linestrips" => Kind::Linestrips,
            _ => continue,
        };
        let piece = primitive(dom, sources, el, kind, budget - drawn, crease).map_err(|n| drawn + n)?;
        if let Some(p) = piece {
            drawn += p.triangles;
            out.push(p);
        }
    }
    Ok(out)
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Kind {
    Triangles,
    Polylist,
    Polygons,
    Fans,
    Strips,
    Lines,
    Linestrips,
}

/// The inputs of a primitive: its streams, the offset of `VERTEX` (the points skins index) and the `<p>` stride.
fn inputs(dom: &Dom<'_>, sources: &mut Sources, el: usize) -> (Vec<Stream>, Option<usize>, usize) {
    let mut streams = Vec::new();
    let mut vertex_offset = None;
    let mut stride = 1;
    let mut add = |sem: Sem, set: u32, offset: usize, src: usize, streams: &mut Vec<Stream>| {
        let acc = source(dom, sources, src, sem.width());
        streams.push(Stream { sem, set, offset, acc });
    };
    for input in dom.kids(el, "input") {
        let Some(offset) = dom.attr_num::<usize>(input, "offset").or(Some(0)) else {
            continue;
        };
        // A wild offset would make every corner huge.
        if offset > 64 {
            continue;
        }
        stride = stride.max(offset + 1);
        let set = dom.attr_num::<u32>(input, "set").unwrap_or(0);
        let semantic = dom.attr(input, "semantic").unwrap_or("");
        // A mesh has one `<vertices>`, which is what `VERTEX` reads however its URL is written.
        let src = dom.link(input, "source").or_else(|| {
            (semantic == "VERTEX")
                .then(|| dom.parent(el).and_then(|m| dom.child(m, "vertices")))
                .flatten()
        });
        let Some(src) = src else {
            continue;
        };
        if semantic == "VERTEX" && dom.is(src, "source") {
            // The positions themselves.
            vertex_offset.get_or_insert(offset);
            add(Sem::Position, set, offset, src, &mut streams);
        } else if semantic == "VERTEX" {
            vertex_offset.get_or_insert(offset);
            for vi in dom.kids(src, "input") {
                let Some(sem) = dom.attr(vi, "semantic").and_then(Sem::of) else {
                    continue;
                };
                let Some(vs) = dom.link(vi, "source") else {
                    continue;
                };
                let set = dom.attr_num::<u32>(vi, "set").unwrap_or(set);
                add(sem, set, offset, vs, &mut streams);
            }
        } else if let Some(sem) = Sem::of(semantic) {
            if sem == Sem::Position {
                vertex_offset.get_or_insert(offset);
            }
            add(sem, set, offset, src, &mut streams);
        }
    }
    // One position stream, the first.
    let mut seen = false;
    streams.retain(|s| {
        if s.sem != Sem::Position {
            return true;
        }
        let keep = !seen;
        seen = true;
        keep
    });
    (streams, vertex_offset, stride)
}

fn primitive(
    dom: &Dom<'_>,
    sources: &mut Sources,
    el: usize,
    kind: Kind,
    budget: usize,
    crease: f32,
) -> Result<Option<Piece>, usize> {
    let (streams, vertex_offset, stride) = inputs(dom, sources, el);
    let Some(pos) = streams.iter().position(|s| s.sem == Sem::Position) else {
        return Ok(None);
    };
    let symbol = dom.attr(el, "material").map(str::to_owned);
    let mut c = Corners::new(streams, pos, vertex_offset, stride, budget);
    match kind {
        Kind::Triangles => {
            for p in dom.kids(el, "p") {
                let idx = xml::indices(dom.text(p));
                for tri in idx.chunks_exact(stride * 3) {
                    c.triangle(&tri[..stride], &tri[stride..2 * stride], &tri[2 * stride..], false);
                    if c.over {
                        break;
                    }
                }
            }
        }
        Kind::Polylist => {
            let counts = dom
                .child(el, "vcount")
                .map(|v| xml::indices(dom.text(v)))
                .unwrap_or_default();
            if let Some(p) = dom.child(el, "p") {
                let idx = xml::indices(dom.text(p));
                let mut at = 0usize;
                for &n in &counts {
                    let n = n as usize;
                    let Some(end) = n.checked_mul(stride).and_then(|len| at.checked_add(len)) else {
                        break;
                    };
                    if end > idx.len() {
                        break;
                    }
                    c.polygon(&idx[at..end]);
                    at = end;
                    if c.over {
                        break;
                    }
                }
            }
        }
        Kind::Polygons => {
            for child in dom.children(el) {
                if c.over {
                    break;
                }
                if dom.is(child, "p") {
                    let idx = xml::indices(dom.text(child));
                    c.polygon(&idx[..idx.len() / stride * stride]);
                } else if dom.is(child, "ph") {
                    let Some(outer) = dom.child(child, "p") else {
                        continue;
                    };
                    let outer = xml::indices(dom.text(outer));
                    let holes: Vec<Vec<u32>> = dom.kids(child, "h").map(|h| xml::indices(dom.text(h))).collect();
                    c.polygon_with_holes(&outer, &holes);
                }
            }
        }
        Kind::Fans | Kind::Strips => {
            for p in dom.kids(el, "p") {
                let idx = xml::indices(dom.text(p));
                let corners: Vec<&[u32]> = idx.chunks_exact(stride).collect();
                for k in 2..corners.len() {
                    let (a, b, d) = if kind == Kind::Fans {
                        (corners[0], corners[k - 1], corners[k])
                    } else if k % 2 == 0 {
                        (corners[k - 2], corners[k - 1], corners[k])
                    } else {
                        (corners[k - 1], corners[k - 2], corners[k])
                    };
                    c.triangle(a, b, d, true);
                    if c.over {
                        break;
                    }
                }
            }
        }
        // Segments come from the file's own indices, so they cost no more than the file; the triangle budget
        // doesn't count them.
        Kind::Lines => {
            for p in dom.kids(el, "p") {
                let idx = xml::indices(dom.text(p));
                for seg in idx.chunks_exact(stride * 2) {
                    c.segment(&seg[..stride], &seg[stride..]);
                }
            }
        }
        Kind::Linestrips => {
            for p in dom.kids(el, "p") {
                let idx = xml::indices(dom.text(p));
                let corners: Vec<&[u32]> = idx.chunks_exact(stride).collect();
                for pair in corners.windows(2) {
                    c.segment(pair[0], pair[1]);
                }
            }
        }
    }
    if c.over {
        return Err(c.triangles);
    }
    Ok(c.finish(symbol, crease))
}

/// The empty slot of the corner table.
const EMPTY: u32 = u32::MAX;

/// Builds a primitive's vertices from corners (a `<p>` tuple each), one vertex for each distinct combination of the
/// indices its inputs read.
struct Corners {
    streams: Vec<Stream>,
    pos: usize,
    stride: usize,
    vertex_offset: usize,
    /// The offsets some input reads: what tells corners apart.
    keyed: Vec<usize>,
    /// With one keyed offset, the vertex of each index.
    direct: Vec<u32>,
    /// Otherwise, an open-addressed table of vertex numbers, and each vertex's key.
    table: Vec<u32>,
    keys: Vec<u32>,
    key: Vec<u32>,
    budget: usize,
    triangles: usize,
    over: bool,
    positions: Vec<[f32; 3]>,
    normals: Vec<[f32; 3]>,
    tangents: Vec<[f32; 3]>,
    binormals: Vec<[f32; 3]>,
    uvs: Vec<Vec<[f32; 2]>>,
    colors: Vec<Vec<[f32; 4]>>,
    points: Vec<u32>,
    indices: Vec<u32>,
    /// Line segments, a pair of vertices each.
    lines: Vec<u32>,
    /// What was left out for a corner that names no position.
    dropped: usize,
    /// Which output each stream fills: its set's number among the inputs of its kind.
    slot: Vec<usize>,
    sets: Vec<u32>,
    // Scratch.
    poly: Vec<u32>,
    outline: Vec<[f32; 3]>,
    tris: Vec<[u32; 3]>,
}

impl Corners {
    fn new(mut streams: Vec<Stream>, pos: usize, vertex_offset: Option<usize>, stride: usize, budget: usize) -> Self {
        // Texture coordinate and color sets in order of their set numbers.
        let mut order: Vec<usize> = (0..streams.len()).collect();
        order.sort_by_key(|&i| (streams[i].sem as u8, streams[i].set));
        let mut slot = vec![0; streams.len()];
        let mut sets = Vec::new();
        let (mut nuv, mut ncolor) = (0, 0);
        let (mut normal, mut tangent, mut binormal) = (false, false, false);
        let mut drop = vec![false; streams.len()];
        for &i in &order {
            match streams[i].sem {
                Sem::Texcoord => {
                    slot[i] = nuv;
                    nuv += 1;
                    sets.push(streams[i].set);
                }
                Sem::Color => {
                    slot[i] = ncolor;
                    ncolor += 1;
                }
                // One of each of the others.
                Sem::Normal => drop[i] = std::mem::replace(&mut normal, true),
                Sem::Tangent => drop[i] = std::mem::replace(&mut tangent, true),
                Sem::Binormal => drop[i] = std::mem::replace(&mut binormal, true),
                Sem::Position => {}
            }
        }
        let pos_offset = streams[pos].offset;
        let mut keyed: Vec<usize> = streams
            .iter()
            .zip(&drop)
            .filter(|(_, d)| !**d)
            .map(|(s, _)| s.offset)
            .collect();
        keyed.sort_unstable();
        keyed.dedup();
        let positions = streams[pos].acc.count();
        let direct = if keyed.len() == 1 {
            vec![EMPTY; positions]
        } else {
            Vec::new()
        };
        // Dropped streams read nothing.
        let mut k = 0;
        streams.retain(|_| {
            k += 1;
            !drop[k - 1]
        });
        let mut k = 0;
        slot.retain(|_| {
            k += 1;
            !drop[k - 1]
        });
        let pos = streams.iter().position(|s| s.sem == Sem::Position).unwrap_or(0);
        Self {
            streams,
            pos,
            stride,
            vertex_offset: vertex_offset.unwrap_or(pos_offset),
            keyed,
            direct,
            table: Vec::new(),
            keys: Vec::new(),
            key: Vec::new(),
            budget,
            triangles: 0,
            over: false,
            positions: Vec::new(),
            normals: Vec::new(),
            tangents: Vec::new(),
            binormals: Vec::new(),
            uvs: vec![Vec::new(); nuv],
            colors: vec![Vec::new(); ncolor],
            points: Vec::new(),
            indices: Vec::new(),
            lines: Vec::new(),
            slot,
            sets,
            poly: Vec::new(),
            outline: Vec::new(),
            tris: Vec::new(),
            dropped: 0,
        }
    }

    /// The vertex of a corner, made when it's new; `None` when the corner names no position.
    #[inline]
    fn vertex(&mut self, corner: &[u32]) -> Option<u32> {
        let pi = *corner.get(self.streams[self.pos].offset)?;
        if pi as usize >= self.streams[self.pos].acc.count() {
            return None;
        }
        if self.keyed.len() == 1 {
            let at = &mut self.direct[pi as usize];
            if *at == EMPTY {
                *at = u32_of(self.positions.len());
                self.emit(corner);
            }
            return Some(self.direct[pi as usize]);
        }
        self.key.clear();
        for &o in &self.keyed {
            self.key.push(*corner.get(o).unwrap_or(&EMPTY));
        }
        if self.positions.len() * 2 >= self.table.len() {
            self.grow();
        }
        let mask = self.table.len() - 1;
        let w = self.keyed.len();
        let mut h = hash(&self.key) & mask;
        loop {
            let v = self.table[h];
            if v == EMPTY {
                let n = u32_of(self.positions.len());
                self.table[h] = n;
                self.keys.extend_from_slice(&self.key);
                self.emit(corner);
                return Some(n);
            }
            let start = v as usize * w;
            // Compared number by number: keys are short, and a call to compare memory costs more than they do.
            if self.keys[start..start + w].iter().zip(&self.key).all(|(a, b)| a == b) {
                return Some(v);
            }
            h = (h + 1) & mask;
        }
    }

    fn grow(&mut self) {
        let size = (self.table.len() * 2).max(1024);
        self.table = vec![EMPTY; size];
        let mask = size - 1;
        let w = self.keyed.len();
        for v in 0..self.positions.len() {
            let mut h = hash(&self.keys[v * w..v * w + w]) & mask;
            while self.table[h] != EMPTY {
                h = (h + 1) & mask;
            }
            self.table[h] = u32_of(v);
        }
    }

    /// Appends a new vertex's attributes.
    fn emit(&mut self, corner: &[u32]) {
        self.points.push(corner.get(self.vertex_offset).copied().unwrap_or(0));
        for (s, &slot) in self.streams.iter().zip(&self.slot) {
            let v = corner.get(s.offset).and_then(|&i| s.acc.get(i)).unwrap_or(&[]);
            let at = |k: usize| v.get(k).copied().filter(|x| x.is_finite()).unwrap_or(0.0);
            match s.sem {
                // A position that isn't finite stays as it is: what's drawn on it is dropped as the primitive
                // is written.
                Sem::Position => {
                    let raw = |k: usize| v.get(k).copied().unwrap_or(0.0);
                    self.positions.push([raw(0), raw(1), raw(2)]);
                }
                // A normal with no length stays zero, and takes its faces' as the primitive is written.
                Sem::Normal => self.normals.push(vec3::unit([at(0), at(1), at(2)]).unwrap_or([0.0; 3])),
                Sem::Tangent => self.tangents.push([at(0), at(1), at(2)]),
                Sem::Binormal => self.binormals.push([at(0), at(1), at(2)]),
                Sem::Texcoord => self.uvs[slot].push([at(0), 1.0 - at(1)]),
                Sem::Color => {
                    let a = if v.len() >= 4 { at(3) } else { 1.0 };
                    self.colors[slot].push([srgb_to_linear(at(0)), srgb_to_linear(at(1)), srgb_to_linear(at(2)), a]);
                }
            }
        }
    }

    /// A triangle, as the file has it: one with no area, or with a corner twice, is kept.
    #[inline]
    fn push(&mut self, a: u32, b: u32, c: u32) {
        self.triangles += 1;
        if self.triangles > self.budget {
            self.over = true;
            return;
        }
        self.indices.extend_from_slice(&[a, b, c]);
    }

    /// A triangle of three corners. One unrolled from a strip or a fan (`strip`) that names a vertex twice
    /// restarts the strip, and draws nothing.
    fn triangle(&mut self, a: &[u32], b: &[u32], c: &[u32], strip: bool) {
        let (Some(a), Some(b), Some(c)) = (self.vertex(a), self.vertex(b), self.vertex(c)) else {
            self.dropped += 1;
            return;
        };
        if strip && !crate::geometry::distinct([a, b, c]) {
            return;
        }
        self.push(a, b, c);
    }

    /// A line segment; one that starts and ends at the same vertex draws nothing.
    fn segment(&mut self, a: &[u32], b: &[u32]) {
        let (Some(a), Some(b)) = (self.vertex(a), self.vertex(b)) else {
            self.dropped += 1;
            return;
        };
        if a != b {
            self.lines.extend_from_slice(&[a, b]);
        }
    }

    /// The vertices of a polygon's corners; `false` when one names no position. `tidy` leaves out a corner
    /// repeated in place and one that closes the outline, which an outline cut around holes can't have.
    fn outline(&mut self, idx: &[u32], out: &mut Vec<u32>, tidy: bool) -> bool {
        out.clear();
        for corner in idx.chunks_exact(self.stride) {
            let Some(v) = self.vertex(corner) else {
                return false;
            };
            if !tidy || out.last() != Some(&v) {
                out.push(v);
            }
        }
        while tidy && out.len() > 1 && out.first() == out.last() {
            out.pop();
        }
        true
    }

    fn polygon(&mut self, idx: &[u32]) {
        let n = idx.len() / self.stride;
        if n == 3 {
            let s = self.stride;
            self.triangle(&idx[..s], &idx[s..2 * s], &idx[2 * s..3 * s], false);
            return;
        }
        if n < 3 {
            return;
        }
        let mut poly = std::mem::take(&mut self.poly);
        if !self.outline(idx, &mut poly, false) {
            self.dropped += 1;
        } else if poly.len() >= 3 {
            if poly.len() == 3 {
                self.push(poly[0], poly[1], poly[2]);
            } else {
                self.outline.clear();
                self.outline.extend(poly.iter().map(|&v| self.positions[v as usize]));
                self.tris.clear();
                triangulate(&self.outline, &mut self.tris);
                let tris = std::mem::take(&mut self.tris);
                for t in &tris {
                    self.push(poly[t[0] as usize], poly[t[1] as usize], poly[t[2] as usize]);
                }
                self.tris = tris;
            }
        }
        self.poly = poly;
    }

    fn polygon_with_holes(&mut self, outer: &[u32], holes: &[Vec<u32>]) {
        let stride = self.stride;
        let mut ring = Vec::new();
        if !self.outline(&outer[..outer.len() / stride * stride], &mut ring, true) {
            self.dropped += 1;
            return;
        }
        if ring.len() < 3 {
            return;
        }
        let mut hole_rings = Vec::new();
        for h in holes {
            let mut r = Vec::new();
            if self.outline(&h[..h.len() / stride * stride], &mut r, true) && r.len() >= 3 {
                hole_rings.push(r);
            }
        }
        if hole_rings.is_empty() {
            let flat: Vec<u32> = outer[..outer.len() / stride * stride].to_vec();
            self.polygon(&flat);
            return;
        }
        // Triangulated in the outline's plane, wound as it is; the triangles count through the outline then the holes.
        let ids: Vec<u32> = ring.iter().chain(hole_rings.iter().flatten()).copied().collect();
        let loops: Vec<Vec<[f64; 3]>> = std::iter::once(&ring)
            .chain(&hole_rings)
            .map(|r| r.iter().map(|&v| self.positions[v as usize].map(f64::from)).collect())
            .collect();
        for t in triangulate_holes(&loops, None) {
            self.push(ids[t[0]], ids[t[1]], ids[t[2]]);
        }
    }

    fn finish(self, symbol: Option<String>, crease: f32) -> Option<Piece> {
        if self.indices.is_empty() && self.lines.is_empty() {
            return None;
        }
        let n = self.positions.len();
        let tangents = if self.tangents.len() == n && self.normals.len() == n {
            self.tangents
                .iter()
                .enumerate()
                .map(|(i, t)| {
                    let w = match (self.binormals.get(i), self.normals.get(i)) {
                        (Some(b), Some(nm)) if self.binormals.len() == n => {
                            let c = cross(*nm, *t);
                            if c[0] * b[0] + c[1] * b[1] + c[2] * b[2] < 0.0 {
                                -1.0
                            } else {
                                1.0
                            }
                        }
                        _ => 1.0,
                    };
                    [t[0], t[1], t[2], w]
                })
                .collect()
        } else {
            Vec::new()
        };
        let mut uvs = self.uvs.into_iter();
        let first_uv = uvs.next().unwrap_or_default();
        let rest: Vec<Vec<[f32; 2]>> = uvs.collect();
        let uv_sets = if rest.is_empty() {
            Vec::new()
        } else {
            std::iter::once(Vec::new()).chain(rest).collect()
        };
        let mut colors = self.colors.into_iter();
        let first_color = colors.next().unwrap_or_default();
        let rest: Vec<Vec<[f32; 4]>> = colors.collect();
        let color_sets = if rest.is_empty() {
            Vec::new()
        } else {
            std::iter::once(Vec::new()).chain(rest).collect()
        };
        let triangles = self.indices.len() / 3;
        let mut prim = Prim {
            positions: self.positions,
            normals: self.normals,
            tangents,
            uvs: first_uv,
            uv_sets,
            colors: first_color,
            color_sets,
            indices: self.indices,
            lines: self.lines,
            ..Prim::default()
        };
        // Without normals in the file, the default ones; the vertices they add keep their points, which skins
        // and morph targets go by.
        let mut points = self.points;
        if prim.normals.len() != n && !prim.indices.is_empty() {
            let added = crate::geometry::default_normals(&mut prim, crease);
            crate::geometry::follow(&mut points, n, &added);
        }
        Some(Piece {
            prim,
            symbol,
            sets: self.sets,
            points,
            triangles,
            dropped: self.dropped,
        })
    }
}

#[inline]
fn hash(key: &[u32]) -> usize {
    let mut h: u64 = 0;
    for &k in key {
        h = (h.rotate_left(5) ^ u64::from(k)).wrapping_mul(0x517c_c1b7_2722_0a95);
    }
    // The high bits mix best.
    usize::try_from(h >> 32).unwrap_or(0) ^ usize::try_from(h & 0xFFFF_FFFF).unwrap_or(0).rotate_left(16)
}