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
//! Images a document names without having read them: what a load with
//! [`Keep::image_bytes`](crate::document::Keep::image_bytes) off leaves, as handles from
//! [`Document::images`].
//!
//! Each such image is a glTF image with a `uri`. Its handle says where the image is (a file
//! found through the [`Assets`], an entry in the model's archive, bytes inside the model) and
//! reads it on request; [`Document::embed_images`] reads them all into the document's buffers.

use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};

use serde_json::Value;

use crate::assets::Assets;
use crate::document::Document;
use crate::gltf::{data_uri, mime_from_name, sniff_mime};
use crate::mesh::Image;
use crate::{Context as _, ErrorKind, Result};

/// The most pixels a texture is decoded to, whichever decoder reads it: 16384 by 16384, the largest 2D texture
/// Direct3D 11 and 12 require of a GPU and the largest a WebP can be, so nothing a renderer can draw whole is
/// refused. At four bytes a pixel that is 1 GiB, which a decoder only makes room for when the file holds the data
/// (see [`FREE`]).
#[cfg(any(
    feature = "flt",
    feature = "skp",
    feature = "tga",
    feature = "bmp",
    feature = "gif",
    feature = "tiff",
    feature = "psd",
    feature = "dds",
    all(feature = "obj", any(feature = "webp", feature = "amf"))
))]
pub(crate) const MAX_PIXELS: usize = 1 << 28;

/// Bytes a decoded image may take whatever data its file holds: a small image needs no proof, but a bigger one is
/// decoded only when at least half its data is there, so a header claiming a huge image over a few bytes makes
/// nothing.
#[cfg(any(
    feature = "flt",
    feature = "tga",
    feature = "bmp",
    feature = "gif",
    feature = "tiff",
    feature = "psd",
    feature = "dds"
))]
pub(crate) const FREE: usize = 1 << 22;

/// Where an image is.
///
/// Non-exhaustive: other places an image can be may be added, so a `match` on one needs a
/// wildcard arm.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Location {
    /// A file, found through the [`Assets`].
    File(PathBuf),
    /// An entry in the model's own archive (a `.usdz` or `.3mf`), by its path there.
    Archive(String),
    /// Inside the model: in a buffer (a GLB's binary chunk), a `data:` URI, or embedded by the
    /// format (an FBX `Video`'s content).
    Embedded,
    /// Named by the model but not found.
    Missing,
}

static EMBEDDED: Location = Location::Embedded;
static MISSING: Location = Location::Missing;

/// An image a document names but hasn't read.
#[cfg_attr(
    not(any(
        feature = "obj",
        feature = "ply",
        feature = "3ds",
        feature = "lwo",
        feature = "ac3d",
        feature = "fbx",
        feature = "usd",
        feature = "3mf",
        feature = "gltf"
    )),
    allow(dead_code, reason = "only readers with textures make references")
)]
#[derive(Debug, Clone)]
pub(crate) struct Reference {
    /// The name as the model wrote it.
    pub name: String,
    pub location: Location,
    /// The undecoded bytes of an image from the model itself (archive entry, embedded).
    pub bytes: Option<Vec<u8>>,
    /// Embedded as it is (a glTF image, whose extensions say its type), rather than turned into
    /// PNG or JPEG by the assets.
    pub raw: bool,
    /// For a file noted without looking for it: whether it's there, looked up the first time
    /// [`location`](Self::location) is asked. `None` when `location` is already settled.
    pub found: Option<std::sync::OnceLock<bool>>,
}

impl Reference {
    /// Where the image is. A file noted without looking is looked for the first time this is
    /// asked, and is [`Location::Missing`] when it isn't there.
    pub fn location(&self) -> &Location {
        match (&self.location, &self.found) {
            (Location::File(p), Some(found)) if !*found.get_or_init(|| p.is_file()) => &MISSING,
            (l, _) => l,
        }
    }
}

/// An image a reader collected for a material: read, or a reference to read later.
#[derive(Debug)]
pub(crate) enum Source {
    Image(Image),
    #[cfg_attr(
        not(any(
            feature = "obj",
            feature = "ply",
            feature = "3ds",
            feature = "lwo",
            feature = "ac3d",
            feature = "fbx",
            feature = "usd",
            feature = "3mf"
        )),
        allow(dead_code, reason = "only readers with textures make references")
    )]
    Ref(Reference, String),
}

impl From<Image> for Source {
    fn from(i: Image) -> Self {
        Source::Image(i)
    }
}

/// The textures a model names that its document doesn't have, as every reader reports them: the one path from
/// a reader's lookups to `droppedTextures` and `missingFiles` in `asset.extras.source` (see [`crate::source`]).
/// [`Images`] counts them as it looks textures up, they travel with its [`List`], and the document's builder
/// writes them.
#[derive(Debug, Default, Clone, PartialEq)]
pub(crate) struct Missed {
    /// How many textures the model names and the document doesn't have: not found, or found and not an image
    /// that can be embedded. Each texture once, however many materials name it.
    pub dropped: usize,
    /// The names, as the model wrote them, of those that weren't found.
    pub files: Vec<String>,
    /// The names of the dropped textures the reader knows by name, found or not, each once: so that a texture
    /// the documents a reader loads as parts of one (the mesh files a scene places, a tileset's tiles) all miss is
    /// counted once across them.
    pub names: Vec<String>,
}

impl Missed {
    /// Whether nothing was missed.
    pub fn is_empty(&self) -> bool {
        self.dropped == 0 && self.files.is_empty()
    }

    /// Counts a texture the document doesn't have, known by `name` (none when empty): named twice, it is counted
    /// once.
    pub fn drop(&mut self, name: &str) {
        let name = name.trim();
        if name.is_empty() {
            self.dropped += 1;
        } else if !self.names.iter().any(|n| n == name) {
            self.names.push(name.to_owned());
            self.dropped += 1;
        }
    }

    /// Takes in what another list of images, or another document, missed: a texture both know by the same name
    /// is counted once.
    pub fn add(&mut self, other: Missed) {
        let shared = other.names.iter().filter(|n| self.names.contains(n)).count();
        self.dropped += other.dropped.saturating_sub(shared);
        for n in other.names {
            if !self.names.contains(&n) {
                self.names.push(n);
            }
        }
        for f in other.files {
            if !self.files.contains(&f) {
                self.files.push(f);
            }
        }
    }

    /// Writes what was missed into a document's `asset.extras.source`: `droppedTextures`, unless the reader
    /// counted its own there, and the names added to `missingFiles`.
    pub fn write(&self, source: &mut serde_json::Map<String, serde_json::Value>) {
        use serde_json::{Value, json};
        if self.dropped > 0 && !source.contains_key("droppedTextures") {
            source.insert("droppedTextures".into(), json!(self.dropped));
        }
        if !self.files.is_empty() {
            let list = source.entry("missingFiles").or_insert_with(|| json!([]));
            if let Some(list) = list.as_array_mut() {
                for f in &self.files {
                    if !list.iter().any(|v| v.as_str() == Some(f)) {
                        list.push(Value::from(f.as_str()));
                    }
                }
            }
        }
    }
}

/// A reader's images in order, with what it looked for and didn't get.
#[derive(Debug, Default)]
pub(crate) struct List {
    items: Vec<Source>,
    pub missed: Missed,
}

impl std::ops::Deref for List {
    type Target = Vec<Source>;

    fn deref(&self) -> &Vec<Source> {
        &self.items
    }
}

impl std::ops::DerefMut for List {
    fn deref_mut(&mut self) -> &mut Vec<Source> {
        &mut self.items
    }
}

impl From<Vec<Source>> for List {
    fn from(items: Vec<Source>) -> Self {
        List {
            items,
            missed: Missed::default(),
        }
    }
}

impl List {
    /// The images, and what was missed.
    pub fn parts(self) -> (Vec<Source>, Missed) {
        (self.items, self.missed)
    }
}

/// The images a reader collects: read and decoded, or with `lazy`, references.
#[cfg_attr(
    not(any(
        feature = "obj",
        feature = "ply",
        feature = "3ds",
        feature = "lwo",
        feature = "ac3d",
        feature = "fbx",
        feature = "usd",
        feature = "3mf"
    )),
    allow(dead_code, reason = "only readers with textures collect images")
)]
#[derive(Debug, Default)]
pub(crate) struct Images {
    pub list: List,
    lazy: bool,
    /// The model's folder, which URIs of files are made relative to.
    #[cfg_attr(
        not(any(
            feature = "obj",
            feature = "ply",
            feature = "3ds",
            feature = "lwo",
            feature = "ac3d",
            feature = "fbx",
            feature = "usd"
        )),
        allow(dead_code, reason = "only readers of texture files use it")
    )]
    dir: PathBuf,
    /// The texture files read so far, so a file named twice is one image.
    files: std::collections::HashMap<PathBuf, Option<usize>>,
    /// What [`find`](Self::find) made of each set of names and folders, so a texture many
    /// materials name is looked for once.
    found: std::collections::HashMap<(Vec<String>, Vec<PathBuf>), Option<usize>>,
}

#[cfg_attr(
    not(any(
        feature = "obj",
        feature = "ply",
        feature = "3ds",
        feature = "lwo",
        feature = "ac3d",
        feature = "fbx",
        feature = "usd",
        feature = "3mf"
    )),
    allow(dead_code, reason = "only readers with textures collect images")
)]
impl Images {
    /// Collects references when `lazy`; `dir` is the model's folder.
    pub fn new(lazy: bool, dir: &Path) -> Self {
        Self {
            list: List::default(),
            lazy,
            dir: dir.to_path_buf(),
            files: std::collections::HashMap::new(),
            found: std::collections::HashMap::new(),
        }
    }

    fn push(&mut self, s: Source) -> usize {
        self.list.push(s);
        self.list.len() - 1
    }

    #[cfg_attr(
        not(any(
            feature = "obj",
            feature = "ply",
            feature = "3ds",
            feature = "lwo",
            feature = "ac3d",
            feature = "fbx",
            feature = "usd"
        )),
        allow(dead_code, reason = "only readers of texture files use it")
    )]
    /// The texture file at `path`, found by the assets for `reference`: its index, or `None`
    /// when it's read and isn't an image the assets can embed.
    pub fn file(&mut self, assets: &dyn Assets, path: PathBuf, reference: &str) -> Option<usize> {
        if let Some(&i) = self.files.get(&path) {
            return i;
        }
        let i = self.read_file(assets, path.clone(), reference);
        if i.is_none() {
            // Found, and not an image that can be embedded.
            self.list.missed.drop(reference);
        }
        self.files.insert(path, i);
        i
    }

    #[cfg_attr(
        not(any(feature = "ply", feature = "3ds", feature = "lwo", feature = "fbx", feature = "usd")),
        allow(dead_code, reason = "only readers of texture files use it")
    )]
    /// The texture file a model names: the first of `names` the assets find, each looked for
    /// from `dirs` in turn. Its index, or `None` when none is found or the one found isn't an
    /// image the assets can embed; a later name isn't tried then, as the model named the first.
    pub fn find(&mut self, assets: &dyn Assets, names: &[impl AsRef<str>], dirs: &[&Path]) -> Option<usize> {
        let key = (
            names.iter().map(|n| n.as_ref().to_owned()).collect(),
            dirs.iter().map(|d| d.to_path_buf()).collect(),
        );
        if let Some(&i) = self.found.get(&key) {
            return i;
        }
        let path = names.iter().find_map(|n| {
            let n = n.as_ref();
            Some((dirs.iter().find_map(|d| assets.find(n, d))?, n))
        });
        if path.is_none()
            && let Some(first) = names.first()
        {
            self.miss(first.as_ref());
        }
        let i = path.and_then(|(p, n)| self.file(assets, p, n));
        self.found.insert(key, i);
        i
    }

    /// Notes a texture the model names as `reference` that wasn't found: for a reader that looks its textures up
    /// itself. Named twice, it is missed once.
    pub fn miss(&mut self, reference: &str) {
        let name = reference.trim();
        if !name.is_empty() && !self.list.missed.files.iter().any(|f| f == name) {
            self.list.missed.files.push(name.to_owned());
            self.list.missed.drop(name);
        }
    }

    #[cfg_attr(
        not(any(feature = "fbx", feature = "usd", feature = "3mf", feature = "dae", feature = "flt")),
        allow(dead_code, reason = "only readers that read their textures themselves use it")
    )]
    /// Counts a texture the model names as `reference` (or holds itself, under that name) that isn't an image
    /// that can be embedded: for a reader that reads its textures itself. Named twice, it is counted once.
    pub fn drop(&mut self, reference: &str) {
        self.list.missed.drop(reference);
    }

    #[cfg_attr(
        not(any(feature = "md3", feature = "md5", feature = "iqm")),
        allow(
            dead_code,
            reason = "only readers of formats that name textures without extensions use it"
        )
    )]
    /// The texture a material or shader names when the name may be a file's without its extension, as game
    /// formats write them (`models/imp/imp`): as written (the assets find a file of that name in any image
    /// format), then with each of `endings` added (`.tga`, `_d.tga`: the format's own conventions). A name with
    /// an extension is only looked for as written.
    pub fn find_bare(&mut self, assets: &dyn Assets, name: &str, endings: &[&str], dir: &Path) -> Option<usize> {
        if name.is_empty() {
            return None;
        }
        let mut tries = vec![name.to_owned()];
        // An extension is short: a dot further back is part of the name.
        if Path::new(name).extension().is_none_or(|e| e.len() > 4) {
            tries.extend(endings.iter().map(|e| format!("{name}{e}")));
        }
        self.find(assets, &tries, &[dir])
    }

    #[cfg_attr(
        not(feature = "obj"),
        allow(dead_code, reason = "only the OBJ reader reads texture files itself")
    )]
    /// What became of the texture file at `path`, when it has been asked for: its index, or
    /// `None` for one that isn't an image the assets can embed.
    #[allow(clippy::option_option, reason = "not asked for and not an image differ")]
    pub fn known(&self, path: &Path) -> Option<Option<usize>> {
        self.files.get(path).copied()
    }

    #[cfg_attr(
        not(feature = "obj"),
        allow(dead_code, reason = "only the OBJ reader reads texture files itself")
    )]
    /// The texture file at `path`, read by the caller as `img`: kept as that file's image, so
    /// asking for the file again finds it rather than reading it twice.
    pub fn read(&mut self, path: PathBuf, img: Image) -> usize {
        if let Some(&Some(i)) = self.files.get(&path) {
            return i;
        }
        let i = self.push(Source::Image(img));
        self.files.insert(path, Some(i));
        i
    }

    #[cfg_attr(
        not(any(
            feature = "obj",
            feature = "ply",
            feature = "3ds",
            feature = "lwo",
            feature = "ac3d",
            feature = "fbx",
            feature = "usd"
        )),
        allow(dead_code, reason = "only readers of texture files use it")
    )]
    fn read_file(&mut self, assets: &dyn Assets, path: PathBuf, reference: &str) -> Option<usize> {
        if !self.lazy {
            let img = assets.load_image(&path)?;
            return Some(self.push(Source::Image(img)));
        }
        let uri = file_uri(&path, &self.dir);
        let r = Reference {
            name: reference.to_owned(),
            location: Location::File(path),
            bytes: None,
            raw: false,
            found: None,
        };
        Some(self.push(Source::Ref(r, uri)))
    }

    #[cfg_attr(
        not(any(feature = "3mf", feature = "dae")),
        allow(dead_code, reason = "only readers of archives and embedded textures use it")
    )]
    /// A texture the model holds itself, at `location`: `convert` makes the image when it's
    /// read now. Its index, or `None` when `convert` makes none, which counts it as a texture the
    /// document doesn't have: call this once for each texture.
    pub fn bytes(
        &mut self,
        bytes: Cow<'_, [u8]>,
        reference: &str,
        location: Location,
        convert: impl FnOnce(&[u8]) -> Option<Image>,
    ) -> Option<usize> {
        // The name of an archive's entry or a file is the texture's; one embedded may be made up.
        let named = !matches!(location, Location::Embedded);
        let i = self.take(bytes, reference, location, convert, false);
        if i.is_none() {
            let missed = &mut self.list.missed;
            missed.dropped += 1;
            let name = reference.trim();
            if named && !name.is_empty() && !missed.names.iter().any(|n| n == name) {
                missed.names.push(name.to_owned());
            }
        }
        i
    }

    #[cfg_attr(
        not(any(feature = "fbx", feature = "usd", feature = "flt")),
        allow(
            dead_code,
            reason = "only readers with a file to look for in an embedded texture's place use it"
        )
    )]
    /// [`bytes`](Self::bytes) without counting a texture `convert` makes no image of: for a reader
    /// that has somewhere else to look for it (a file of the name an embedded texture gives), and
    /// counts it with [`drop`](Self::drop) when that gives none either. Collecting references,
    /// bytes without a PNG or JPEG header are tried now, so that what the reader looks for in their
    /// place is what a full read finds.
    pub fn try_bytes(
        &mut self,
        bytes: Cow<'_, [u8]>,
        reference: &str,
        location: Location,
        convert: impl FnOnce(&[u8]) -> Option<Image>,
    ) -> Option<usize> {
        self.take(bytes, reference, location, convert, true)
    }

    /// The image `convert` makes of `bytes`, or with `lazy` a reference to them, unread unless
    /// `check` and they don't say they're a PNG or JPEG.
    fn take(
        &mut self,
        bytes: Cow<'_, [u8]>,
        reference: &str,
        location: Location,
        convert: impl FnOnce(&[u8]) -> Option<Image>,
        check: bool,
    ) -> Option<usize> {
        if self.lazy && check && Image::mime_of(&bytes).is_none() {
            convert(&bytes)?;
        } else if !self.lazy {
            let img = convert(&bytes)?;
            return Some(self.push(Source::Image(img)));
        }
        let uri = match &location {
            Location::Archive(entry) => encode(entry),
            _ => encode(&reference.replace('\\', "/")),
        };
        let r = Reference {
            name: reference.to_owned(),
            location,
            bytes: Some(bytes.into_owned()),
            raw: false,
            found: None,
        };
        Some(self.push(Source::Ref(r, uri)))
    }
}

/// Whether encoded image bytes are a gray PNG or JPEG, by the header: a PNG's color type, a JPEG's component count.
#[cfg(any(feature = "obj", feature = "usd"))]
pub(crate) fn gray(b: &[u8]) -> bool {
    if b.starts_with(b"\x89PNG\r\n\x1a\n") {
        // IHDR comes first; color type 0 is gray, 4 gray with alpha.
        return b.get(12..16) == Some(b"IHDR".as_slice()) && matches!(b.get(25), Some(0 | 4));
    }
    if !b.starts_with(&[0xFF, 0xD8]) {
        return false;
    }
    let mut i = 2usize;
    while i + 4 <= b.len() {
        if b[i] != 0xFF {
            return false;
        }
        let marker = b[i + 1];
        if marker == 0xFF {
            i += 1;
            continue;
        }
        // A start of frame (not a table): its component count follows the precision, height and width.
        if (0xC0..=0xCF).contains(&marker) && !matches!(marker, 0xC4 | 0xC8 | 0xCC) {
            return b.get(i + 9) == Some(&1);
        }
        if matches!(marker, 0xD9 | 0xDA) {
            return false;
        }
        i = i.saturating_add(2 + usize::from(u16::from_be_bytes([b[i + 2], b[i + 3]])));
    }
    false
}

#[cfg_attr(
    not(any(
        feature = "obj",
        feature = "ply",
        feature = "3ds",
        feature = "lwo",
        feature = "ac3d",
        feature = "fbx",
        feature = "usd"
    )),
    allow(dead_code, reason = "only readers of texture files use it")
)]
/// A URI for a file at `path`: relative to the model's folder when it's under it.
fn file_uri(path: &Path, dir: &Path) -> String {
    let rel = path.strip_prefix(dir).unwrap_or(path);
    let s = rel.to_string_lossy().replace('\\', "/");
    if rel.is_absolute() || s.starts_with('/') || s.as_bytes().get(1) == Some(&b':') {
        format!("file:///{}", encode(s.trim_start_matches('/')).replace("%3A", ":"))
    } else {
        encode(&s)
    }
}

#[cfg_attr(
    not(any(
        feature = "obj",
        feature = "ply",
        feature = "3ds",
        feature = "lwo",
        feature = "ac3d",
        feature = "fbx",
        feature = "usd",
        feature = "3mf"
    )),
    allow(dead_code, reason = "only readers with textures make references")
)]
/// `s` percent-encoded for a URI path: everything but unreserved characters and `/`.
fn encode(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        if b.is_ascii_alphanumeric() || b"-._~/".contains(&b) {
            out.push(char::from(b));
        } else {
            let _ = write!(out, "%{b:02X}");
        }
    }
    out
}

/// An image of one of the MIME types glTF images carry.
fn image_of(bytes: crate::Bytes, mime: Option<&str>) -> Option<Image> {
    let mime = sniff_mime(&bytes).or_else(|| mime_from_name(&format!("x.{}", mime?.strip_prefix("image/")?)))?;
    Some(Image { bytes, mime })
}

/// One of a document's images: read, or named and not yet read. See [`Document::images`].
#[derive(Debug, Clone, Copy)]
pub struct ImageHandle<'d> {
    index: usize,
    json: &'d Value,
    reference: Option<&'d Reference>,
    doc: &'d Document,
}

impl<'d> ImageHandle<'d> {
    /// Its index in the glTF `images`.
    #[must_use]
    pub fn index(&self) -> usize {
        self.index
    }

    /// Its glTF `name`.
    #[must_use]
    pub fn name(&self) -> Option<&'d str> {
        self.json.get("name").and_then(Value::as_str)
    }

    /// Whether it's only named, not yet read: [`load`](Self::load) reads it, and
    /// [`Document::embed_images`] puts it in the document.
    #[must_use]
    pub fn is_pending(&self) -> bool {
        self.reference.is_some()
    }

    /// The name the model gave it (a path as written, an archive entry, an embedded texture's
    /// file name), for an image not yet read.
    #[must_use]
    pub fn reference(&self) -> Option<&'d str> {
        self.reference.map(|r| r.name.as_str())
    }

    /// Where it is. A file a glTF names is looked for the first time this (or anything that
    /// needs it: [`path`](Self::path), [`mime`](Self::mime), [`load`](Self::load)) is asked,
    /// not when the document is loaded.
    #[must_use]
    pub fn location(&self) -> &'d Location {
        self.reference.map_or(&EMBEDDED, Reference::location)
    }

    /// Its file, when it's in one.
    #[must_use]
    pub fn path(&self) -> Option<&'d Path> {
        match self.location() {
            Location::File(p) => Some(p),
            _ => None,
        }
    }

    /// Its MIME type: as the document says, or from its bytes or its name.
    #[must_use]
    pub fn mime(&self) -> Option<&'d str> {
        if let Some(m) = self.json.get("mimeType").and_then(Value::as_str) {
            return Some(m);
        }
        let r = self.reference?;
        r.bytes
            .as_deref()
            .and_then(sniff_mime)
            .or_else(|| mime_from_name(&r.name))
            .or_else(|| self.path().and_then(|p| mime_from_name(&p.to_string_lossy())))
    }

    /// The image, read now: a file through `assets` (which also turn formats glTF doesn't carry
    /// into PNG or JPEG, as a load that reads images would have), or the bytes the document
    /// holds.
    ///
    /// # Errors
    ///
    /// When its file is missing or can't be read, or it isn't an image `assets` can embed.
    pub fn load(&self, assets: &dyn Assets) -> Result<Image> {
        let i = self.index;
        let Some(r) = self.reference else {
            let bytes = if let Some(v) = self.json.get("bufferView").and_then(Value::as_u64) {
                self.doc.view_shared(crate::num::usize_of(v))?
            } else {
                let uri = self.json.get("uri").and_then(Value::as_str);
                data_uri(uri.with_context(ErrorKind::Corrupt, || format!("image {i} has no bytes"))?)?
                    .1
                    .into()
            };
            return image_of(bytes, self.mime())
                .with_context(ErrorKind::Unsupported, || format!("image {i}: unknown image format"));
        };
        let bytes: Cow<'_, [u8]> = match (r.location(), &r.bytes) {
            (_, Some(b)) => Cow::Borrowed(b),
            (Location::File(p), None) => assets
                .read(p)
                .ok_or_else(|| crate::Error::missing(format!("image {i} can't be read")).at(p))?,
            _ => bail!(MissingAsset, "image {i} ({:?}) wasn't found", r.name),
        };
        let img = if r.raw {
            image_of(crate::Bytes::from(bytes.into_owned()), self.mime())
        } else {
            let name = self.path().map_or_else(|| PathBuf::from(&r.name), Path::to_path_buf);
            assets.image(&bytes, &name)
        };
        img.with_context(ErrorKind::Unsupported, || {
            format!("image {i} ({:?}) isn't an image that can be embedded", r.name)
        })
    }
}

impl Document {
    /// The document's images, read or not. A load with
    /// [`Keep::image_bytes`](crate::document::Keep::image_bytes) off leaves the images it found
    /// unread: each is a glTF image with a `uri` (relative to the model's folder, for a file
    /// under it), and its handle says where it is and reads it.
    pub fn images(&self) -> impl Iterator<Item = ImageHandle<'_>> {
        let list = self.base.get("images").and_then(Value::as_array);
        list.into_iter()
            .flatten()
            .enumerate()
            .map(move |(index, json)| ImageHandle {
                index,
                json,
                reference: self.refs.get(&index),
                doc: self,
            })
    }

    /// Reads every image not yet read into a buffer of its own, so the document stands alone
    /// (as a GLB from [`to_glb`](Self::to_glb) then does). Returns how many couldn't be read;
    /// they stay references by `uri`.
    pub fn embed_images(&mut self, assets: &dyn Assets) -> usize {
        let mut loaded = Vec::new();
        let mut failed = 0;
        for h in self.images().filter(ImageHandle::is_pending) {
            match h.load(assets) {
                Ok(img) => loaded.push((h.index, img)),
                Err(_) => failed += 1,
            }
        }
        for (i, Image { bytes, mime }) in loaded {
            let len = bytes.len();
            let buffer = self.push_buffer(bytes);
            let view = self.push_view(serde_json::json!({ "buffer": buffer, "byteLength": len }));
            if let Some(img) = self.base_mut()["images"][i].as_object_mut() {
                img.remove("uri");
                img.insert("bufferView".into(), view.into());
                img.insert("mimeType".into(), mime.into());
            }
            self.refs.remove(&i);
        }
        failed
    }
}

/// The references a document's images make, by image index.
pub(crate) type Refs = BTreeMap<usize, Reference>;

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

    #[test]
    fn uris() {
        assert_eq!(file_uri(Path::new("m/tex/a b.png"), Path::new("m")), "tex/a%20b.png");
        assert_eq!(file_uri(Path::new("other/a.png"), Path::new("m")), "other/a.png");
        assert_eq!(file_uri(Path::new("/abs/a.png"), Path::new("m")), "file:///abs/a.png");
        assert_eq!(
            file_uri(Path::new("C:\\x\\a.png"), Path::new("m")),
            "file:///C:/x/a.png"
        );
    }
}