sgl-3d 0.4.2

Caller-driven 3D rendering for SGL games, native and in the browser (WebGPU)
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
//! glTF 2.0 import into an [`Asset`]: the document, its images, its scene's
//! mesh nodes, with rigid nodes' transforms baked into the vertices and
//! skinned ones' kept in bind space, and its rig (`rig`): nodes, skins,
//! morph weights and animation clips.
use std::path::Path;

use glam::{Mat4, Quat, Vec3};
use gltf::accessor::{DataType, Dimensions};
use gltf::animation::Property;

use super::asset::{Asset, Material, Result, Vertex};
use super::deformation;
use super::images::Image;
use super::load_budget::{Budget, MAX_LOAD_BYTES};
use material::read_material;
use meshes::{batch, ignored_attribute, read_node};
use rig::Rigging;

mod material;
mod meshes;
mod rig;
#[cfg(test)]
mod rig_tests;
mod sources;
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests;

/// Optional application adaptations applied while loading an asset.
#[derive(Clone, Copy, Default)]
pub struct LoadOptions<'a> {
    /// Maximum authored emissive strength, applied before the emissive color.
    /// `None` preserves authored intensity. A cap must be finite and nonnegative.
    pub emissive_strength_cap: Option<f32>,
    /// Where each of the glTF's images a material map samples comes from,
    /// asked once per such image in image order. `None` decodes each one.
    #[allow(clippy::type_complexity)]
    pub images: Option<&'a (dyn Fn(GltfImage<'_>) -> Result<ImageSource> + Sync)>,
    /// Which of the scene's mesh nodes load, asked once per mesh node with
    /// its authored name; `None` loads every one. Every ancestor's
    /// transform applies, selected or not, and each descendant is asked
    /// itself. Selecting none is an error.
    #[allow(clippy::type_complexity)]
    pub nodes: Option<&'a (dyn Fn(Option<&str>) -> bool + Sync)>,
}

impl std::fmt::Debug for LoadOptions<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LoadOptions")
            .field("emissive_strength_cap", &self.emissive_strength_cap)
            .field("images", &self.images.map(|_| "Fn"))
            .field("nodes", &self.nodes.map(|_| "Fn"))
            .finish()
    }
}

/// A glTF image the loader is about to read, as `LoadOptions::images` sees
/// it.
#[derive(Clone, Copy, Debug)]
pub struct GltfImage<'a> {
    /// Its index in the glTF, which materials' texture indices and
    /// `Asset::images` use.
    pub index: usize,
    /// Its authored name.
    pub name: Option<&'a str>,
    /// The file it refers to, relative to the glTF and percent-encoded, as
    /// authored; `None` when it is embedded (a buffer view or a data URI).
    pub uri: Option<&'a str>,
}

/// Where a loaded asset's image comes from, as Bevy's glTF loader resolves
/// each image's source (`load_image`): the glTF's own, decoded, or the
/// game's.
#[derive(Clone, Debug)]
pub enum ImageSource {
    /// Read and decode the glTF's image: an 8-bit PNG or JPEG, embedded or
    /// beside a glTF file.
    Decode,
    /// This image instead, such as a compressed chain from the game's export
    /// step. The glTF's image is neither read nor decoded.
    Supplied(Image),
}

/// Load a `.gltf` or `.glb` file, preserving authored emissive strength.
pub fn load(path: &Path) -> Result<Asset> {
    load_with_options(path, LoadOptions::default())
}

/// Load a file with explicit application adaptations. External buffers and
/// images resolve beneath its directory, without parent segments, schemes
/// or symlinks; buffers must match `byteLength`. Source reads are bounded,
/// and decoded RGBA images share the scene-data budget (4 GiB native,
/// 1 GiB browser); image sides are at most 16384, checked before decoding.
/// A browser has no file system: it fetches the
/// bytes and calls [`load_slice_with_options`].
pub fn load_with_options(path: &Path, options: LoadOptions<'_>) -> Result<Asset> {
    load_inner(path, options).map_err(|error| format!("{}: {error}", path.display()).into())
}

fn load_inner(path: &Path, options: LoadOptions<'_>) -> Result<Asset> {
    check(options)?;
    let mut budget = Budget::new();
    let bytes = budget.read_file(path, None)?;
    let (document, buffers) = import(&bytes, path.parent(), &mut budget).map_err(|error| {
        format!("glTF import failed: {error}; check referenced files and re-export valid glTF from the Blender source")
    })?;
    decode(document, &buffers, path.parent(), options, &mut budget)
}

/// Load an embedded glTF/GLB with the same material and geometry rules as [`load`].
/// External file URIs cannot be resolved from bytes; embed buffers and images,
/// or supply the images ([`load_slice_with_options`]).
pub fn load_slice(bytes: &[u8]) -> Result<Asset> {
    load_slice_with_options(bytes, LoadOptions::default())
}

/// Load an embedded glTF/GLB with explicit application adaptations, under
/// the same rules as [`load_with_options`]. An image the options supply
/// may be an external file the bytes cannot resolve.
pub fn load_slice_with_options(bytes: &[u8], options: LoadOptions<'_>) -> Result<Asset> {
    check(options)?;
    let mut budget = Budget::new();
    budget.charge(bytes.len() as u64)?;
    let (document, buffers) = import(bytes, None, &mut budget)
        .map_err(|error| format!("embedded glTF import failed: {error}"))?;
    decode(document, &buffers, None, options, &mut budget)
}

fn check(options: LoadOptions<'_>) -> Result<()> {
    if options
        .emissive_strength_cap
        .is_some_and(|cap| !cap.is_finite() || cap < 0.0)
    {
        return Err("emissive strength cap must be finite and nonnegative".into());
    }
    Ok(())
}

/// The glTF extensions SGL3D honours: a file may require any of them. The
/// loader reads each itself, from the extension's values.
const SUPPORTED_EXTENSIONS: [&str; 13] = [
    "KHR_materials_anisotropy",
    "KHR_materials_clearcoat",
    "KHR_materials_diffuse_transmission",
    "KHR_materials_dispersion",
    "KHR_materials_emissive_strength",
    "KHR_materials_ior",
    "KHR_materials_iridescence",
    "KHR_materials_sheen",
    "KHR_materials_specular",
    "KHR_materials_transmission",
    "KHR_materials_unlit",
    "KHR_materials_volume",
    "EXT_materials_bump",
];

/// Something in a glTF that SGL3D does not render and the file does not
/// require, which glTF lets a loader leave out (glTF 2.0 5.17.1): the load
/// lists it in [`Asset::ignored`] and renders the rest. What the file
/// requires is never left out: a load fails on it instead.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Ignored {
    /// An extension the file lists in `extensionsUsed` but not in
    /// `extensionsRequired`, which SGL3D does not support. What it adds is
    /// left out: a texture takes its core source, a material its core
    /// values.
    Extension(String),
    /// Material `material`'s occlusion map (an index into
    /// [`Asset::materials`]): SGL3D samples occlusion only from the red
    /// channel of the material's metallic-roughness image on `TEXCOORD_0`
    /// (ORM packing), not yet from an image of its own.
    OcclusionMap { material: usize },
    /// Material `material`'s `KHR_materials_specular` specular or specular
    /// colour texture: SGL3D takes the extension's factors alone so far.
    SpecularMap { material: usize },
    /// Image `image` (an index into [`Asset::images`]), which no material
    /// map SGL3D samples uses, such as an extension's texture source or an
    /// ignored map's image: it is neither asked of
    /// [`LoadOptions::images`], read nor decoded, and its entry is a
    /// one-texel placeholder.
    Image { image: usize },
    /// Vertex attribute `name` of mesh `mesh`'s primitive `primitive`,
    /// which SGL3D does not read: a third or later UV set (`TEXCOORD_2`
    /// on), a second or later colour set (`COLOR_1` on) or an
    /// application-specific one (`_NAME`).
    Attribute {
        mesh: usize,
        primitive: usize,
        name: String,
    },
}

/// The document in `bytes`, validated, and its buffers. glTF 2.0 5.17.2: a
/// file that requires an extension SGL3D does not support fails to load.
/// The gltf crate's validation knows none of the material extensions SGL3D
/// reads itself, so once every required one is known to be supported the
/// list is cleared for it; all its structural validation remains.
fn import(
    bytes: &[u8],
    base: Option<&Path>,
    budget: &mut Budget,
) -> Result<(gltf::Document, Vec<gltf::buffer::Data>)> {
    // The gltf crate subtracts the 12-byte header from the length the GLB
    // header declares unchecked, so a header declaring less is refused here.
    if bytes.starts_with(b"glTF") {
        let length = bytes
            .get(8..12)
            .and_then(|length| <[u8; 4]>::try_from(length).ok())
            .map(u32::from_le_bytes);
        if length.is_none_or(|length| length < 12) {
            return Err("the GLB header is truncated or declares a length below its own 12 bytes; re-export valid glTF".into());
        }
    }
    // Keep the BIN chunk borrowed until its size has passed the source budget.
    let glb = bytes
        .starts_with(b"glTF")
        .then(|| gltf::binary::Glb::from_slice(bytes))
        .transpose()?;
    let json = glb.as_ref().map_or(bytes, |glb| glb.json.as_ref());
    let mut root: gltf::json::Root = serde_json::from_slice(json)?;
    if let Some(extension) = root
        .extensions_required
        .iter()
        .find(|extension| !SUPPORTED_EXTENSIONS.contains(&extension.as_str()))
    {
        return Err(format!("the file requires glTF extension {extension}, which SGL3D does not support; bake it into the export or add renderer support").into());
    }
    check_root(&root)?;
    root.extensions_required.clear();
    let document = gltf::Document::from_json(root)?;
    let blob = glb.as_ref().and_then(|glb| glb.bin.as_deref());
    let buffers = sources::buffers(&document, base, blob, budget)?;
    Ok((document, buffers))
}

/// Check the references and source variants gltf-json 1.4.1 leaves unchecked
/// before its own validation indexes POSITION or its readers unwrap them.
fn check_root(root: &gltf::json::Root) -> Result<()> {
    use gltf::json::validation::Checked;
    for (mesh, data) in root.meshes.iter().enumerate() {
        for (primitive, data) in data.primitives.iter().enumerate() {
            for (attribute, accessor) in &data.attributes {
                if accessor.value() >= root.accessors.len() {
                    return Err(format!("mesh {mesh} primitive {primitive} attribute {attribute:?}: accessor {} is out of range", accessor.value()).into());
                }
            }
            for (target, data) in data.targets.iter().flatten().enumerate() {
                for (attribute, accessor) in [
                    ("POSITION", data.positions),
                    ("NORMAL", data.normals),
                    ("TANGENT", data.tangents),
                ] {
                    if let Some(accessor) = accessor
                        && accessor.value() >= root.accessors.len()
                    {
                        return Err(format!("mesh {mesh} primitive {primitive} morph target {target} {attribute}: accessor {} is out of range", accessor.value()).into());
                    }
                }
            }
        }
    }
    for (animation, data) in root.animations.iter().enumerate() {
        for (channel, data) in data.channels.iter().enumerate() {
            if data.target.node.value() >= root.nodes.len() {
                return Err(format!(
                    "animation {animation} channel {channel}: target node {} is out of range",
                    data.target.node.value()
                )
                .into());
            }
            if !matches!(data.target.path, Checked::Valid(_)) {
                return Err(format!(
                    "animation {animation} channel {channel}: invalid target path"
                )
                .into());
            }
        }
    }
    for (image, data) in root.images.iter().enumerate() {
        if data.uri.is_some() == data.buffer_view.is_some() {
            return Err(
                format!("image {image}: exactly one of uri and bufferView is required").into(),
            );
        }
        if data.buffer_view.is_some() && data.mime_type.is_none() {
            return Err(format!("image {image}: bufferView requires mimeType").into());
        }
    }
    Ok(())
}

/// `document`'s images, each one `materials` sample from where
/// `options.images` says, decoded where it says nothing. Bevy's glTF loader
/// resolves each image's source as it loads (9d12036
/// `crates/bevy_gltf/src/loader/mod.rs` `load_image`): it decodes an
/// embedded image and leaves an external one to its asset server, so the
/// loader never decodes it. Here the game, which has no asset server,
/// chooses for each image. A file's images resolve beside it (`base`). An
/// image no material samples is a placeholder, listed in `ignored`: glTF
/// lets a loader leave out what an unsupported extension adds (glTF 2.0
/// 5.17.1), such as a texture's `KHR_texture_basisu` or `EXT_texture_webp`
/// source, which a loader without it replaces with the core `source`, and
/// SGL3D never binds an ignored map's image.
fn read_images(
    document: &gltf::Document,
    buffers: &[gltf::buffer::Data],
    base: Option<&Path>,
    options: LoadOptions<'_>,
    materials: &[Material],
    ignored: &mut Vec<Ignored>,
    budgets: (&mut Budget, &mut Budget),
) -> Result<Vec<Image>> {
    let (budget, decoded_budget) = budgets;
    let mut sampled = vec![false; document.images().len()];
    for image in materials.iter().flat_map(sampled_images) {
        sampled[image] = true;
    }
    document
        .images()
        .map(|image| {
            let index = image.index();
            if !sampled[index] {
                ignored.push(Ignored::Image { image: index });
                return Ok(Image::Rgba8(image::RgbaImage::new(1, 1)));
            }
            let file = match image.source() {
                gltf::image::Source::Uri { uri, .. } if !uri.starts_with("data:") => Some(uri),
                _ => None,
            };
            let source = match options.images {
                None => ImageSource::Decode,
                Some(sources) => sources(GltfImage {
                    index,
                    name: image.name(),
                    uri: file,
                })
                .map_err(|error| format!("image {index}: {error}"))?,
            };
            match source {
                ImageSource::Supplied(supplied) => Ok(supplied),
                ImageSource::Decode => {
                    if let gltf::image::Source::View { view, .. } = image.source()
                        && !in_buffer(&view)
                    {
                        return Err(format!("image {index}'s buffer view does not fit its buffer; re-export valid glTF").into());
                    }
                    let data = sources::image(image.source(), base, buffers, budget, decoded_budget)
                        .map_err(|error| format!("image {index} import failed: {error}; check referenced files and re-export valid glTF from the Blender source"))?;
                    Ok(Image::Rgba8(data.into_rgba8()))
                }
            }
        })
        .collect()
}

/// The images `material`'s maps sample: every one it names but an occlusion
/// map's outside its metallic-roughness image, which SGL3D does not sample.
fn sampled_images(material: &Material) -> Vec<usize> {
    let mut images: Vec<usize> = material.texture_indices().into_iter().flatten().collect();
    if let Some(occlusion) = material
        .occlusion_texture
        .filter(|_| !material.packed_occlusion())
        && let Some(slot) = images.iter().position(|&image| image == occlusion)
    {
        images.swap_remove(slot);
    }
    images
}

fn decode(
    document: gltf::Document,
    buffers: &[gltf::buffer::Data],
    base: Option<&Path>,
    options: LoadOptions<'_>,
    budget: &mut Budget,
) -> Result<Asset> {
    let scene = document
        .default_scene()
        .or_else(|| document.scenes().next())
        .ok_or("GLB contains no scene")?;
    let parents = rig::parents(&document)?;
    let mut decoded_budget = Budget::new();
    decoded_budget.charge(check_scene(&document, &scene, &parents)?)?;
    // What the file uses but does not require (import refused the rest).
    let mut ignored: Vec<Ignored> = document
        .extensions_used()
        .filter(|extension| !SUPPORTED_EXTENSIONS.contains(extension))
        .map(|extension| Ignored::Extension(extension.to_owned()))
        .collect();
    let mut materials = document
        .materials()
        .enumerate()
        .map(|(index, material)| {
            let strength = material.emissive_strength().unwrap_or(1.0);
            let mut result = read_material(material, &document, index, &mut ignored)?;
            if let Some(cap) = options.emissive_strength_cap
                && strength > cap
            {
                result.emissive = result.emissive.map(|value| value * cap / strength);
            }
            Ok(result)
        })
        .collect::<Result<Vec<_>>>()?;
    let images = read_images(
        &document,
        buffers,
        base,
        options,
        &materials,
        &mut ignored,
        (budget, &mut decoded_budget),
    )?;
    for mesh in document.meshes() {
        for primitive in mesh.primitives() {
            ignored.extend(
                primitive
                    .attributes()
                    .filter(|(semantic, _)| ignored_attribute(semantic))
                    .map(|(semantic, _)| Ignored::Attribute {
                        mesh: mesh.index(),
                        primitive: primitive.index(),
                        name: semantic.to_string(),
                    }),
            );
        }
    }
    // glTF primitives may omit a material; retain the specification default.
    let default_material = materials.len();
    materials.push(Material::default());
    let buffer_bytes = buffers.iter().map(|buffer| buffer.0.len()).sum();
    let mut rigging = Rigging::new(&document, &parents, (buffers, buffer_bytes))?;
    let include_node = options.nodes.unwrap_or(&|_| true);
    let mut meshes = Vec::new();
    for node in scene.nodes() {
        read_node(
            node,
            Mat4::IDENTITY,
            (buffers, buffer_bytes),
            (default_material, &materials),
            &mut rigging,
            &mut meshes,
            include_node,
        )?;
    }
    if meshes.is_empty() {
        return Err("scene has no triangle meshes".into());
    }
    Ok(Asset {
        meshes: batch(meshes, materials.len()),
        materials,
        images,
        rig: rigging.rig,
        ignored,
    })
}

/// Refuses a scene the load would read too much of, before reading any of
/// it: one that lists a node among its roots more than once or a node with
/// a parent, which glTF 2.0 forbids (3.5.1, and the scene schema's
/// `uniqueItems`: a scene's `nodes` are distinct root nodes) and which
/// would read a subtree's meshes again each time it is listed, and one
/// whose load, as `load_bytes` counts it, would hold more than
/// `MAX_LOAD_BYTES`. `parents` holds each node's parent, its hierarchy a
/// set of trees.
fn check_scene(
    document: &gltf::Document,
    scene: &gltf::Scene<'_>,
    parents: &[Option<usize>],
) -> Result<u64> {
    let mut listed = vec![false; parents.len()];
    for node in scene.nodes().map(|node| node.index()) {
        if std::mem::replace(&mut listed[node], true) {
            return Err(format!(
                "scene {} lists root node {node} more than once; re-export valid glTF",
                scene.index()
            )
            .into());
        }
        if let Some(parent) = parents[node] {
            return Err(format!("scene {} lists node {node} as a root, but node {parent} is its parent; re-export valid glTF", scene.index()).into());
        }
    }
    load_bytes(document, scene).ok_or_else(|| format!("scene {}'s meshes (once for each node that uses them), skins and animation clips would take more than the {MAX_LOAD_BYTES} bytes one load may; split the asset", scene.index()).into())
}

/// The bytes a load of `scene` produces, from the counts its accessors
/// declare, or None once they pass `MAX_LOAD_BYTES`: for each of the
/// scene's mesh nodes, selected or not, each of its mesh's primitives'
/// vertices (with their skin influences on a skinned node), indices and
/// morph target deltas; each skin's joints; and each animation channel's
/// keyframe times and values. A mesh counts once for each node that uses
/// it, and a sampler once for each channel, as the load reads them. No
/// read takes more elements than its accessor declares, so what the load
/// allocates stays in proportion to this. Each primitive counts at least
/// one vertex, each skin a joint and each channel a keyframe, so the
/// count's own work stops within the cap too.
fn load_bytes(document: &gltf::Document, scene: &gltf::Scene<'_>) -> Option<u64> {
    use std::mem::size_of;
    let bytes = |count: usize, size: usize| (count.max(1) as u64).checked_mul(size as u64);
    let mut mesh_nodes = Vec::new();
    let mut nodes: Vec<gltf::Node<'_>> = scene.nodes().collect();
    while let Some(node) = nodes.pop() {
        nodes.extend(node.children());
        if node.mesh().is_some() {
            mesh_nodes.push(node);
        }
    }
    let primitives = mesh_nodes.iter().flat_map(|node| {
        let vertex = size_of::<Vertex>()
            + node
                .skin()
                .map_or(0, |_| size_of::<deformation::Influence>());
        let primitives = node.mesh().into_iter().flat_map(|mesh| mesh.primitives());
        primitives.map(move |primitive| {
            let vertices = primitive
                .get(&gltf::Semantic::Positions)
                .map_or(0, |positions| positions.count());
            let indices = primitive
                .indices()
                .map_or(vertices, |indices| indices.count());
            let deltas = bytes(vertices, size_of::<deformation::MorphDelta>())?
                .checked_mul(primitive.morph_targets().count() as u64)?;
            bytes(vertices, vertex)?
                .checked_add(bytes(indices, size_of::<u32>())?)?
                .checked_add(deltas)
        })
    });
    let skins = document
        .skins()
        .map(|skin| bytes(skin.joints().count(), size_of::<deformation::Joint>()));
    let channels = document
        .animations()
        .flat_map(|animation| animation.channels())
        .map(|channel| {
            let value = match channel.target().property() {
                Property::Translation | Property::Scale => size_of::<Vec3>(),
                Property::Rotation => size_of::<Quat>(),
                Property::MorphTargetWeights => size_of::<f32>(),
            };
            let sampler = channel.sampler();
            bytes(sampler.input().count(), size_of::<f32>())?
                .checked_add(bytes(sampler.output().count(), value)?)
        });
    primitives
        .chain(skins)
        .chain(channels)
        .try_fold(0u64, |total, bytes| {
            total
                .checked_add(bytes?)
                .filter(|&total| total <= MAX_LOAD_BYTES)
        })
}

/// Refuses an accessor the gltf crate's readers cannot read, which its
/// validation lets through and its readers (gltf 1.4.1 `mesh::Reader`,
/// `skin::Reader`, `animation::util::Reader` and `accessor::util::Iter`)
/// assume away, panicking or misreading otherwise: one holding a component
/// type or shape glTF 2.0 does not allow for its use (`types`, `shapes`),
/// one of no elements, and one whose elements or sparse substitutions do
/// not lie within their buffer views at a stride no narrower than an
/// element, whose views do not lie within their buffers, or whose sparse
/// indices are not strictly increasing and below its count (glTF 2.0
/// 3.6.2.3). `what` names its use.
///
/// It also refuses one whose element count its use does not allow, before
/// gltf's readers allocate that many, so what each use reads stays in
/// proportion to the file's data: `count` is the count glTF requires (the
/// primitive's vertices, the skin's joints, the sampler's keyframes),
/// itself fixed by data or the document, or None where nothing fixes it.
/// An accessor without a buffer view (a sparse one) declares its count
/// without data; where nothing fixes that count, its elements may take no
/// more bytes than the file's buffers hold (`buffer_bytes`, their total),
/// the bound its elements would meet in a buffer view.
fn check_accessor(
    accessor: &gltf::Accessor<'_>,
    what: &str,
    types: &[DataType],
    shapes: &[Dimensions],
    count: Option<usize>,
    (buffers, buffer_bytes): (&[gltf::buffer::Data], usize),
) -> Result<()> {
    let index = accessor.index();
    let (data_type, shape) = (accessor.data_type(), accessor.dimensions());
    if !types.contains(&data_type) || !shapes.contains(&shape) {
        return Err(format!("{what} accessor {index} holds {data_type:?} {shape:?}, where glTF allows {types:?} {shapes:?}; re-export valid glTF").into());
    }
    let sparse = accessor.sparse();
    if accessor.count() == 0 || sparse.as_ref().is_some_and(|sparse| sparse.count() == 0) {
        return Err(
            format!("{what} accessor {index} has no elements; re-export valid glTF").into(),
        );
    }
    let elements = accessor.count();
    if let Some(count) = count
        && elements != count
    {
        return Err(format!("{what} accessor {index} has {elements} elements where its use needs {count}; re-export valid glTF").into());
    }
    if count.is_none()
        && accessor.view().is_none()
        && elements
            .checked_mul(accessor.size())
            .is_none_or(|bytes| bytes > buffer_bytes)
    {
        return Err(format!("{what} accessor {index} has {elements} elements without a buffer view, more than the file's {buffer_bytes} buffer bytes would hold; re-export valid glTF").into());
    }
    let size = accessor.size();
    let within = accessor
        .view()
        .is_none_or(|view| fits(&view, accessor.offset(), accessor.count(), size))
        && sparse.as_ref().is_none_or(|sparse| {
            let (indices, values) = (sparse.indices(), sparse.values());
            fits(
                &indices.view(),
                indices.offset(),
                sparse.count(),
                indices.index_type().size(),
            ) && fits(&values.view(), values.offset(), sparse.count(), size)
        });
    if !within {
        return Err(format!(
            "{what} accessor {index} does not fit its buffer view and buffer; re-export valid glTF"
        )
        .into());
    }
    if let Some(sparse) = sparse {
        use gltf::accessor::sparse::IndexType;
        use gltf::accessor::util::{ItemIter, SparseIndicesIter};

        let indices = sparse.indices();
        let view = indices.view();
        let stride = view.stride().unwrap_or(indices.index_type().size());
        // `fits` proved these offsets and every index are inside the
        // imported buffer. Use the same typed iterator and stride as gltf's
        // sparse reader, which otherwise silently drops invalid indices.
        let bytes = &buffers[view.buffer().index()].0
            [view.offset() + indices.offset()..view.offset() + view.length()];
        let indices = match indices.index_type() {
            IndexType::U8 => SparseIndicesIter::U8(ItemIter::new(bytes, stride)),
            IndexType::U16 => SparseIndicesIter::U16(ItemIter::new(bytes, stride)),
            IndexType::U32 => SparseIndicesIter::U32(ItemIter::new(bytes, stride)),
        };
        let mut previous = None;
        for sparse_index in indices.take(sparse.count()) {
            if sparse_index as usize >= elements
                || previous.is_some_and(|previous| sparse_index <= previous)
            {
                return Err(format!("{what} accessor {index} has sparse indices that are not strictly increasing and below its {elements} elements; re-export valid glTF").into());
            }
            previous = Some(sparse_index);
        }
    }
    Ok(())
}

/// Whether `count` elements of `size` bytes from `offset` lie within `view`
/// at its stride, an element's when it has none, as gltf's
/// `accessor::util::Iter::new` reads them, and `view` within its buffer.
fn fits(view: &gltf::buffer::View<'_>, offset: usize, count: usize, size: usize) -> bool {
    let stride = view.stride().unwrap_or(size);
    in_buffer(view)
        && stride >= size
        && count
            .checked_sub(1)
            .and_then(|last| last.checked_mul(stride))
            .and_then(|start| start.checked_add(offset))
            .and_then(|start| start.checked_add(size))
            .is_some_and(|end| end <= view.length())
}

/// Whether `view` lies within its buffer, which gltf slices it from
/// unchecked (gltf 1.4.1 `accessor::util::buffer_view_slice` and
/// `image::Data::from_source` add its offset and length unchecked, and the
/// latter indexes the buffer's data with them). `import_buffers` holds each
/// buffer's data to at least its declared length.
fn in_buffer(view: &gltf::buffer::View<'_>) -> bool {
    view.offset()
        .checked_add(view.length())
        .is_some_and(|end| end <= view.buffer().length())
}