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
//! A glTF document's rig as plain data: its node hierarchy, its skins'
//! joints in one list, the morph weights of its morphed mesh nodes, and its
//! animation clips.
use std::collections::HashMap;

use glam::{Mat4, Quat, Vec3};
use gltf::accessor::{DataType, Dimensions};
use gltf::animation::{Interpolation as GltfInterpolation, Property, util::ReadOutputs};

use super::super::asset::{Result, Vertex};
use super::super::deformation::{
    Channel, ChannelValues, Clip, Influence, Interpolation, Joint, MAX_INDEX, MorphDelta,
    MorphTarget, MorphWeight, Node, Rig,
};
use super::check_accessor;

/// The rig being imported, where each skin's joints and each morphed
/// node's weights start in it, and each mesh's morph-target count.
pub(super) struct Rigging {
    pub rig: Rig,
    /// Each skin's first joint, by skin index.
    skins: Vec<u32>,
    /// Each morphed node's first weight.
    morphs: HashMap<usize, u32>,
    /// Each mesh's morph-target count (`morph_target_count`), by mesh
    /// index, counted once rather than for each node or channel that
    /// names a mesh.
    targets: Vec<usize>,
}

impl Rigging {
    /// The document's nodes, each with its parent (`parents`), skins and
    /// clips; empty when it has no skin, morph target or animation.
    /// `buffer_bytes` is the total length of `buffers`.
    pub fn new(
        document: &gltf::Document,
        parents: &[Option<usize>],
        (buffers, buffer_bytes): (&[gltf::buffer::Data], usize),
    ) -> Result<Self> {
        let mut rigging = Self {
            rig: Rig::default(),
            skins: Vec::new(),
            morphs: HashMap::new(),
            targets: document
                .meshes()
                .map(|mesh| morph_target_count(&mesh))
                .collect(),
        };
        let morphed = rigging.targets.iter().any(|&targets| targets > 0);
        if document.skins().next().is_none() && document.animations().next().is_none() && !morphed {
            return Ok(rigging);
        }
        // The nodes whose rest pose feeds a joint matrix: each skin's joints
        // and their ancestors.
        let mut posed = vec![false; parents.len()];
        for joint in document.skins().flat_map(|skin| skin.joints()) {
            let mut node = Some(joint.index());
            while let Some(index) = node.filter(|&index| !posed[index]) {
                posed[index] = true;
                node = parents[index];
            }
        }
        rigging.rig.nodes = document
            .nodes()
            .map(|node| {
                // A matrix with a zero-scale axis decomposes to a NaN
                // rotation, which posing spreads to every joint beneath it.
                let (translation, rotation, scale) = node.transform().decomposed();
                if posed[node.index()]
                    && !translation
                        .iter()
                        .chain(&rotation)
                        .chain(&scale)
                        .all(|value| value.is_finite())
                {
                    return Err(format!(
                        "node {} ({}), a joint or a joint's ancestor, has a transform that does not decompose to a finite translation, rotation and scale; re-export it without a zero-scale axis",
                        node.index(),
                        node.name().unwrap_or("unnamed")
                    )
                    .into());
                }
                Ok(Node {
                    name: node.name().map(str::to_owned),
                    parent: parents[node.index()],
                    translation: Vec3::from_array(translation),
                    rotation: Quat::from_array(rotation),
                    scale: Vec3::from_array(scale),
                })
            })
            .collect::<Result<_>>()?;
        for skin in document.skins() {
            rigging.skins.push(rigging.rig.joints.len() as u32);
            if let Some(accessor) = skin.inverse_bind_matrices() {
                check_accessor(
                    &accessor,
                    &format!("skin {}: inverse bind matrices", skin.index()),
                    &[DataType::F32],
                    &[Dimensions::Mat4],
                    Some(skin.joints().count()),
                    (buffers, buffer_bytes),
                )?;
            }
            let reader = skin.reader(|buffer| Some(&buffers[buffer.index()].0));
            let inverse_binds: Vec<Mat4> = match reader.read_inverse_bind_matrices() {
                Some(matrices) => matrices.map(|m| Mat4::from_cols_array_2d(&m)).collect(),
                None => vec![Mat4::IDENTITY; skin.joints().count()],
            };
            if inverse_binds.len() != skin.joints().count()
                || inverse_binds.iter().any(|m| !m.is_finite())
            {
                return Err(format!(
                    "skin {} has {} finite inverse bind matrices for {} joints",
                    skin.index(),
                    inverse_binds.len(),
                    skin.joints().count()
                )
                .into());
            }
            rigging
                .rig
                .joints
                .extend(
                    skin.joints()
                        .zip(inverse_binds)
                        .map(|(node, inverse_bind)| Joint {
                            node: node.index(),
                            inverse_bind,
                        }),
                );
        }
        rigging.rig.clips = document
            .animations()
            .map(|animation| read_clip(&animation, (buffers, buffer_bytes), &rigging.targets))
            .collect::<Result<_>>()?;
        Ok(rigging)
    }

    /// `mesh`'s morph-target count.
    pub fn mesh_targets(&self, mesh: &gltf::Mesh<'_>) -> usize {
        self.targets[mesh.index()]
    }

    /// The first joint of `skin` and its joint count.
    pub fn skin(&self, skin: &gltf::Skin) -> (u32, u32) {
        (self.skins[skin.index()], skin.joints().count() as u32)
    }

    /// The first of the `count` morph weights of `node`, added on first use
    /// with its rest weights (the node's, else its mesh's, else zero).
    pub fn morph_weights(&mut self, node: &gltf::Node<'_>, count: usize) -> Result<u32> {
        if let Some(&first) = self.morphs.get(&node.index()) {
            return Ok(first);
        }
        let rest = node
            .weights()
            .or_else(|| node.mesh().and_then(|mesh| mesh.weights()))
            .map(<[f32]>::to_vec)
            .unwrap_or_else(|| vec![0.; count]);
        if rest.len() != count || rest.iter().any(|w| !w.is_finite()) {
            return Err(format!(
                "node {} has {} finite rest morph weights for {count} targets",
                node.index(),
                rest.len()
            )
            .into());
        }
        let first = self.rig.morph_weights.len() as u32;
        if (first as usize + count) > MAX_INDEX as usize + 1 {
            return Err(format!(
                "node {} has morph weights beyond the 65536 an asset may have",
                node.index()
            )
            .into());
        }
        self.rig
            .morph_weights
            .extend(rest.into_iter().map(|rest| MorphWeight {
                node: node.index(),
                rest,
            }));
        self.morphs.insert(node.index(), first);
        Ok(first)
    }
}

/// Each node's parent, the hierarchy glTF 2.0 requires (3.5.3: disjoint
/// strict trees, each node with at most one parent and none its own
/// ancestor), which gltf's validation leaves unchecked: a node with two
/// parents, or under a cycle, is refused, whether or not the document
/// deforms, since the loader's and `Rig`'s walks of it assume trees.
pub(super) fn parents(document: &gltf::Document) -> Result<Vec<Option<usize>>> {
    let nodes: Vec<gltf::Node<'_>> = document.nodes().collect();
    let mut parents = vec![None; nodes.len()];
    for node in &nodes {
        for child in node.children() {
            if parents[child.index()].replace(node.index()).is_some() {
                return Err(format!(
                    "node {} has more than one parent; the node hierarchy must be a set of trees",
                    child.index()
                )
                .into());
            }
        }
    }
    // With one parent at most, each node is reached once from the roots,
    // and only one under a cycle is not.
    let mut reached = vec![false; nodes.len()];
    let mut stack: Vec<usize> = (0..nodes.len())
        .filter(|&node| parents[node].is_none())
        .collect();
    while let Some(node) = stack.pop() {
        reached[node] = true;
        stack.extend(nodes[node].children().map(|child| child.index()));
    }
    if let Some(node) = reached.iter().position(|reached| !reached) {
        return Err(format!(
            "node {node}'s ancestors form a cycle; the node hierarchy must be a set of trees"
        )
        .into());
    }
    Ok(parents)
}

/// `mesh`'s morph-target count: its first primitive with targets' (glTF
/// 2.0 3.7.2.2, as KhronosGroup/glTF#2650 words it), which every primitive
/// with targets must share; a primitive without any takes none.
fn morph_target_count(mesh: &gltf::Mesh<'_>) -> usize {
    mesh.primitives()
        .map(|primitive| primitive.morph_targets().count())
        .find(|&count| count > 0)
        .unwrap_or(0)
}

/// `animation`'s clip; `targets` holds each mesh's morph-target count.
fn read_clip(
    animation: &gltf::Animation<'_>,
    (buffers, buffer_bytes): (&[gltf::buffer::Data], usize),
    targets: &[usize],
) -> Result<Clip> {
    let label = format!("animation {}", animation.index());
    let channels = animation
        .channels()
        .map(|channel| {
            // glTF 2.0 3.11's accessor types for keyframe times and each
            // property's values.
            use DataType::{F32, I8, I16, U8, U16};
            let sampler = channel.sampler();
            check_accessor(
                &sampler.input(),
                &format!("{label}: keyframe times"),
                &[F32],
                &[Dimensions::Scalar],
                None,
                (buffers, buffer_bytes),
            )?;
            let interpolation = match sampler.interpolation() {
                GltfInterpolation::Step => Interpolation::Step,
                GltfInterpolation::Linear => Interpolation::Linear,
                GltfInterpolation::CubicSpline => Interpolation::CubicSpline,
            };
            // A keyframe's values: a cubic spline's in-tangent, value and
            // out-tangent, each one element a morph target for weights.
            let per_key = if interpolation == Interpolation::CubicSpline {
                3
            } else {
                1
            };
            let (types, shape, per_value): (&[DataType], _, _) = match channel.target().property() {
                Property::Translation | Property::Scale => (&[F32], Dimensions::Vec3, 1),
                Property::Rotation => (&[F32, I8, U8, I16, U16], Dimensions::Vec4, 1),
                Property::MorphTargetWeights => {
                    let targets = channel
                        .target()
                        .node()
                        .mesh()
                        .map_or(0, |mesh| targets[mesh.index()]);
                    if targets == 0 {
                        return Err(format!(
                            "{label}: morph weights animate a node without morph targets"
                        )
                        .into());
                    }
                    (&[F32, I8, U8, I16, U16], Dimensions::Scalar, targets)
                }
            };
            let values = sampler
                .input()
                .count()
                .checked_mul(per_key)
                .and_then(|values| values.checked_mul(per_value))
                .ok_or_else(|| format!("{label}: a channel has too many keyframe values"))?;
            check_accessor(
                &sampler.output(),
                &format!("{label}: keyframe values"),
                types,
                &[shape],
                Some(values),
                (buffers, buffer_bytes),
            )?;
            let reader = channel.reader(|buffer| Some(&buffers[buffer.index()].0));
            let times: Vec<f32> = reader
                .read_inputs()
                .ok_or_else(|| format!("{label}: a channel has no keyframe times"))?
                .collect();
            if times.is_empty()
                || times.iter().any(|t| !t.is_finite())
                || times.windows(2).any(|pair| pair[1] <= pair[0])
            {
                return Err(format!(
                    "{label}: keyframe times must be finite and strictly increasing; re-export valid glTF"
                )
                .into());
            }
            let values = match reader
                .read_outputs()
                .ok_or_else(|| format!("{label}: a channel has no keyframe values"))?
            {
                ReadOutputs::Translations(values) => {
                    ChannelValues::Translation(values.map(Vec3::from_array).collect())
                }
                ReadOutputs::Rotations(values) => {
                    ChannelValues::Rotation(values.into_f32().map(Quat::from_array).collect())
                }
                ReadOutputs::Scales(values) => {
                    ChannelValues::Scale(values.map(Vec3::from_array).collect())
                }
                ReadOutputs::MorphTargetWeights(values) => {
                    ChannelValues::MorphWeights(values.into_f32().collect())
                }
            };
            Ok(Channel {
                node: channel.target().node().index(),
                interpolation,
                times,
                values,
            })
        })
        .collect::<Result<_>>()?;
    Ok(Clip {
        name: animation.name().map(str::to_owned),
        channels,
    })
}

/// A skinned primitive's influences on the joints of its skin, which starts
/// at joint `first` of the asset's rig and has `count` joints: each with
/// finite, nonnegative weights of finite positive sum, naming joints of its skin
/// among the 65536 an asset may have.
pub(super) fn read_influences<'a, 's, F>(
    reader: &gltf::mesh::Reader<'a, 's, F>,
    (first, count): (u32, u32),
    vertices: usize,
    label: &str,
) -> Result<Vec<Influence>>
where
    F: Clone + Fn(gltf::Buffer<'a>) -> Option<&'s [u8]>,
{
    let joints: Vec<[u16; 4]> = reader
        .read_joints(0)
        .ok_or_else(|| format!("{label}: a skinned primitive lacks JOINTS_0"))?
        .into_u16()
        .collect();
    let weights: Vec<[f32; 4]> = reader
        .read_weights(0)
        .ok_or_else(|| format!("{label}: a skinned primitive lacks WEIGHTS_0"))?
        .into_f32()
        .collect();
    if joints.len() != vertices || weights.len() != vertices {
        return Err(format!("{label}: joint and weight counts differ from positions").into());
    }
    joints
        .into_iter()
        .zip(weights)
        .map(|(joints, weights)| {
            if joints.iter().any(|&joint| u32::from(joint) >= count) {
                return Err(format!("{label}: a vertex names a joint its skin lacks").into());
            }
            if joints.iter().any(|&joint| first + u32::from(joint) > MAX_INDEX) {
                return Err(
                    format!("{label}: a vertex names a joint beyond the 65536 an asset may have")
                        .into(),
                );
            }
            let sum = weights.iter().sum::<f32>();
            if weights.iter().any(|w| !w.is_finite() || *w < 0.)
                || !sum.is_finite()
                || sum <= 0.
            {
                return Err(format!(
                    "{label}: a vertex's joint weights must be finite and nonnegative with a finite positive sum"
                )
                .into());
            }
            Ok(Influence {
                joints: joints.map(|joint| first + u32::from(joint)),
                weights,
            })
        })
        .collect()
}

/// A primitive's morph targets, scaled by the rig's weights from `first`,
/// in the space its vertices were baked to: positions by `transform`;
/// normals by `normal_transform`, and tangents by `transform` projected off
/// the baked normal, each at the factor that normalized its baked vector.
/// A target displaces no tangent of a `baked` vertex whose tangent is
/// absent (zero), as when it was not authored or lay along its normal.
pub(super) fn read_morph_targets<'a, 's, F>(
    reader: &gltf::mesh::Reader<'a, 's, F>,
    first: u32,
    (transform, normal_transform): (Mat4, Mat4),
    (normals, authored_tangents): (&[[f32; 3]], Option<&[[f32; 4]]>),
    baked: &[Vertex],
    label: &str,
) -> Result<Vec<MorphTarget>>
where
    F: Clone + Fn(gltf::Buffer<'a>) -> Option<&'s [u8]>,
{
    let count = normals.len();
    let read = |values: Option<Vec<[f32; 3]>>, target: usize| -> Result<Vec<Vec3>> {
        let Some(values) = values else {
            return Ok(vec![Vec3::ZERO; count]);
        };
        if values.len() != count || values.iter().flatten().any(|v| !v.is_finite()) {
            return Err(
                format!("{label}: morph target {target} does not match its positions").into(),
            );
        }
        Ok(values.into_iter().map(Vec3::from_array).collect())
    };
    reader
        .read_morph_targets()
        .enumerate()
        .map(|(target, (positions, target_normals, tangents))| {
            let positions = read(positions.map(Iterator::collect), target)?;
            let target_normals = read(target_normals.map(Iterator::collect), target)?;
            let tangents = read(tangents.map(Iterator::collect), target)?;
            let deltas = (0..count)
                .map(|vertex| {
                    // The baked normal was normalized after `normal_transform`,
                    // and the baked tangent after `transform` and projection
                    // off it; their displacements keep those scales.
                    let normal =
                        normal_transform.transform_vector3(Vec3::from_array(normals[vertex]));
                    let baked_normal = normal.normalize();
                    let tangent = authored_tangents
                        .filter(|_| baked[vertex].tangent != [0.0; 4])
                        .map_or(Vec3::ZERO, |authored| {
                            let [x, y, z, _] = authored[vertex];
                            let transformed = transform.transform_vector3(Vec3::new(x, y, z));
                            let projected =
                                transformed - baked_normal * baked_normal.dot(transformed);
                            transform.transform_vector3(tangents[vertex]) / projected.length()
                        });
                    MorphDelta {
                        position: transform.transform_vector3(positions[vertex]).to_array(),
                        normal: (normal_transform.transform_vector3(target_normals[vertex])
                            / normal.length())
                        .to_array(),
                        tangent: tangent.to_array(),
                    }
                })
                .collect();
            Ok(MorphTarget {
                weight: first + target as u32,
                deltas,
            })
        })
        .collect()
}