scena 1.7.2

A Rust-native scene-graph renderer with typed scene state, glTF assets, and explicit prepare/render lifecycles.
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
//! glTF animation playback, mixer state, skinning, and morph-target support.

use std::sync::{
    Arc,
    atomic::{AtomicBool, AtomicU64, Ordering},
};

use slotmap::new_key_type;

use crate::diagnostics::AnimationError;
use crate::scene::{NodeKey, Quat, Vec3};

mod sampling;
use self::sampling::{sample_quat, sample_vec3, sample_weights};

new_key_type! {
    pub struct AnimationMixerKey;
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AnimationClipKey(u64);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnimationPlaybackState {
    Playing,
    Paused,
    Stopped,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnimationLoopMode {
    Once,
    Repeat,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnimationTarget {
    Translation,
    Rotation,
    Scale,
    Weights,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnimationInterpolation {
    Linear,
    Step,
    CubicSpline,
}

#[derive(Debug, Clone, PartialEq)]
pub struct AnimationClip {
    key: AnimationClipKey,
    name: Option<String>,
    channels: Vec<AnimationChannel>,
    duration_seconds: f32,
}

#[derive(Debug, Clone, PartialEq)]
pub struct AnimationSourceClip {
    name: Option<String>,
    channels: Vec<AnimationSourceChannel>,
    duration_seconds: f32,
}

#[derive(Debug, Clone, PartialEq)]
pub struct AnimationChannel {
    target_node: NodeKey,
    target: AnimationTarget,
    input_seconds: Vec<f32>,
    output: AnimationOutput,
    interpolation: AnimationInterpolation,
}

#[derive(Debug, Clone, PartialEq)]
pub struct AnimationSourceChannel {
    source_node: usize,
    target: AnimationTarget,
    input_seconds: Vec<f32>,
    output: AnimationOutput,
    interpolation: AnimationInterpolation,
}

#[derive(Debug, Clone, PartialEq)]
pub enum AnimationOutput {
    Vec3(Vec<Vec3>),
    Quat(Vec<Quat>),
    Weights(Vec<Vec<f32>>),
}

#[derive(Debug, Clone)]
pub struct AnimationMixer {
    clip: AnimationClip,
    state: AnimationPlaybackState,
    time_seconds: f32,
    speed: f32,
    loop_mode: AnimationLoopMode,
    import_live: Arc<AtomicBool>,
}

impl AnimationClipKey {
    pub(crate) fn fresh() -> Self {
        static NEXT: AtomicU64 = AtomicU64::new(1);
        Self(NEXT.fetch_add(1, Ordering::Relaxed))
    }

    pub const fn as_u64(self) -> u64 {
        self.0
    }
}

impl AnimationClip {
    pub fn authored(
        name: Option<String>,
        channels: Vec<AnimationChannel>,
        duration_seconds: f32,
    ) -> Result<Self, AnimationError> {
        Self::new(AnimationClipKey::fresh(), name, channels, duration_seconds)
    }

    pub fn new(
        key: AnimationClipKey,
        name: Option<String>,
        channels: Vec<AnimationChannel>,
        duration_seconds: f32,
    ) -> Result<Self, AnimationError> {
        validate_clip(&channels, duration_seconds)?;
        Ok(Self {
            key,
            name,
            channels,
            duration_seconds,
        })
    }

    pub(crate) fn new_unchecked(
        key: AnimationClipKey,
        name: Option<String>,
        channels: Vec<AnimationChannel>,
        duration_seconds: f32,
    ) -> Self {
        Self {
            key,
            name,
            channels,
            duration_seconds,
        }
    }

    pub const fn key(&self) -> AnimationClipKey {
        self.key
    }

    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    pub fn channels(&self) -> &[AnimationChannel] {
        &self.channels
    }

    pub const fn duration_seconds(&self) -> f32 {
        self.duration_seconds
    }
}

impl AnimationSourceClip {
    pub fn new(
        name: Option<String>,
        channels: Vec<AnimationSourceChannel>,
        duration_seconds: f32,
    ) -> Self {
        Self {
            name,
            channels,
            duration_seconds,
        }
    }

    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    pub fn channels(&self) -> &[AnimationSourceChannel] {
        &self.channels
    }

    pub const fn duration_seconds(&self) -> f32 {
        self.duration_seconds
    }

    pub fn rebind<F, G>(
        &self,
        key: AnimationClipKey,
        mut map_node: F,
        mut map_vec3: G,
    ) -> AnimationClip
    where
        F: FnMut(usize) -> Option<NodeKey>,
        G: FnMut(AnimationTarget, Vec3) -> Vec3,
    {
        let channels = self
            .channels
            .iter()
            .filter_map(|channel| channel.rebind(&mut map_node, &mut map_vec3))
            .collect();
        AnimationClip::new_unchecked(key, self.name.clone(), channels, self.duration_seconds)
    }
}

fn validate_clip(
    channels: &[AnimationChannel],
    duration_seconds: f32,
) -> Result<(), AnimationError> {
    if !duration_seconds.is_finite() || duration_seconds <= 0.0 {
        return Err(AnimationError::InvalidClip {
            reason: "duration_seconds must be finite and positive".to_owned(),
        });
    }
    if channels.is_empty() {
        return Err(AnimationError::InvalidClip {
            reason: "clip must contain at least one channel".to_owned(),
        });
    }
    for (channel_index, channel) in channels.iter().enumerate() {
        validate_channel(channel_index, channel, duration_seconds)?;
    }
    Ok(())
}

fn validate_channel(
    channel_index: usize,
    channel: &AnimationChannel,
    duration_seconds: f32,
) -> Result<(), AnimationError> {
    if channel.input_seconds.is_empty() {
        return Err(invalid_channel(channel_index, "times must not be empty"));
    }
    let mut previous = None;
    for (time_index, time) in channel.input_seconds.iter().copied().enumerate() {
        if !time.is_finite() || time < 0.0 {
            return Err(invalid_channel(
                channel_index,
                format!("time[{time_index}] must be finite and non-negative"),
            ));
        }
        if time > duration_seconds {
            return Err(invalid_channel(
                channel_index,
                format!("time[{time_index}] exceeds clip duration"),
            ));
        }
        if previous.is_some_and(|previous| time <= previous) {
            return Err(invalid_channel(
                channel_index,
                format!("time[{time_index}] must be strictly increasing"),
            ));
        }
        previous = Some(time);
    }
    let expected_values = if channel.interpolation == AnimationInterpolation::CubicSpline {
        channel.input_seconds.len().saturating_mul(3)
    } else {
        channel.input_seconds.len()
    };
    match &channel.output {
        AnimationOutput::Vec3(values) => {
            if values.len() != expected_values {
                return Err(invalid_channel(
                    channel_index,
                    format!("Vec3 output length must be {expected_values}"),
                ));
            }
            if let Some(index) = values.iter().position(|value| !vec3_is_finite(*value)) {
                return Err(invalid_channel(
                    channel_index,
                    format!("Vec3 output[{index}] must be finite"),
                ));
            }
        }
        AnimationOutput::Quat(values) => {
            if values.len() != expected_values {
                return Err(invalid_channel(
                    channel_index,
                    format!("Quat output length must be {expected_values}"),
                ));
            }
            if let Some(index) = values.iter().position(|value| !quat_is_finite(*value)) {
                return Err(invalid_channel(
                    channel_index,
                    format!("Quat output[{index}] must be finite"),
                ));
            }
        }
        AnimationOutput::Weights(values) => {
            if values.len() != expected_values {
                return Err(invalid_channel(
                    channel_index,
                    format!("Weights output length must be {expected_values}"),
                ));
            }
            let Some(width) = values.first().map(Vec::len).filter(|width| *width > 0) else {
                return Err(invalid_channel(
                    channel_index,
                    "weights output must contain at least one morph target",
                ));
            };
            for (index, value) in values.iter().enumerate() {
                if value.len() != width {
                    return Err(invalid_channel(
                        channel_index,
                        format!("weights output[{index}] has inconsistent width"),
                    ));
                }
                if value.iter().any(|component| !component.is_finite()) {
                    return Err(invalid_channel(
                        channel_index,
                        format!("weights output[{index}] must be finite"),
                    ));
                }
            }
        }
    }
    Ok(())
}

fn invalid_channel(channel_index: usize, reason: impl Into<String>) -> AnimationError {
    AnimationError::InvalidClip {
        reason: format!("channel {channel_index}: {}", reason.into()),
    }
}

fn quat_is_finite(value: Quat) -> bool {
    value.x.is_finite() && value.y.is_finite() && value.z.is_finite() && value.w.is_finite()
}

fn vec3_is_finite(value: Vec3) -> bool {
    value.x.is_finite() && value.y.is_finite() && value.z.is_finite()
}

impl AnimationChannel {
    pub fn new(
        target_node: NodeKey,
        target: AnimationTarget,
        input_seconds: Vec<f32>,
        output: AnimationOutput,
        interpolation: AnimationInterpolation,
    ) -> Self {
        Self {
            target_node,
            target,
            input_seconds,
            output,
            interpolation,
        }
    }

    pub const fn target_node(&self) -> NodeKey {
        self.target_node
    }

    pub const fn target(&self) -> AnimationTarget {
        self.target
    }

    pub fn sample_vec3(&self, time_seconds: f32) -> Option<Vec3> {
        let AnimationOutput::Vec3(values) = &self.output else {
            return None;
        };
        sample_vec3(
            &self.input_seconds,
            values,
            self.interpolation,
            time_seconds,
        )
    }

    pub fn sample_quat(&self, time_seconds: f32) -> Option<Quat> {
        let AnimationOutput::Quat(values) = &self.output else {
            return None;
        };
        sample_quat(
            &self.input_seconds,
            values,
            self.interpolation,
            time_seconds,
        )
    }

    pub fn sample_weights(&self, time_seconds: f32) -> Option<Vec<f32>> {
        let AnimationOutput::Weights(values) = &self.output else {
            return None;
        };
        sample_weights(
            &self.input_seconds,
            values,
            self.interpolation,
            time_seconds,
        )
    }
}

impl AnimationSourceChannel {
    pub fn new(
        source_node: usize,
        target: AnimationTarget,
        input_seconds: Vec<f32>,
        output: AnimationOutput,
        interpolation: AnimationInterpolation,
    ) -> Self {
        Self {
            source_node,
            target,
            input_seconds,
            output,
            interpolation,
        }
    }

    pub const fn source_node(&self) -> usize {
        self.source_node
    }

    pub fn input_seconds(&self) -> &[f32] {
        &self.input_seconds
    }

    fn rebind<F, G>(&self, map_node: &mut F, map_vec3: &mut G) -> Option<AnimationChannel>
    where
        F: FnMut(usize) -> Option<NodeKey>,
        G: FnMut(AnimationTarget, Vec3) -> Vec3,
    {
        let output = match &self.output {
            AnimationOutput::Vec3(values) => AnimationOutput::Vec3(
                values
                    .iter()
                    .copied()
                    .map(|value| map_vec3(self.target, value))
                    .collect(),
            ),
            AnimationOutput::Quat(values) => AnimationOutput::Quat(values.clone()),
            AnimationOutput::Weights(values) => AnimationOutput::Weights(values.clone()),
        };
        Some(AnimationChannel::new(
            map_node(self.source_node)?,
            self.target,
            self.input_seconds.clone(),
            output,
            self.interpolation,
        ))
    }
}

impl AnimationMixer {
    pub fn new(clip: AnimationClip, import_live: Arc<AtomicBool>) -> Self {
        Self {
            clip,
            state: AnimationPlaybackState::Stopped,
            time_seconds: 0.0,
            speed: 1.0,
            loop_mode: AnimationLoopMode::Once,
            import_live,
        }
    }

    pub const fn state(&self) -> AnimationPlaybackState {
        self.state
    }

    pub const fn time_seconds(&self) -> f32 {
        self.time_seconds
    }

    pub const fn speed(&self) -> f32 {
        self.speed
    }

    pub const fn loop_mode(&self) -> AnimationLoopMode {
        self.loop_mode
    }

    pub fn clip(&self) -> &AnimationClip {
        &self.clip
    }

    pub(crate) fn is_stale(&self) -> bool {
        !self.import_live.load(Ordering::Acquire)
    }

    pub(crate) fn play(&mut self) {
        self.state = AnimationPlaybackState::Playing;
    }

    pub(crate) fn pause(&mut self) {
        self.state = AnimationPlaybackState::Paused;
    }

    pub(crate) fn stop(&mut self) {
        self.state = AnimationPlaybackState::Stopped;
        self.time_seconds = 0.0;
    }

    pub(crate) fn seek(&mut self, time_seconds: f32) {
        self.time_seconds = self.clamp_or_wrap_time(time_seconds.max(0.0));
    }

    pub(crate) fn set_speed(&mut self, speed: f32) {
        self.speed = if speed.is_finite() { speed } else { 1.0 };
    }

    pub(crate) fn set_loop_mode(&mut self, loop_mode: AnimationLoopMode) {
        self.loop_mode = loop_mode;
        self.time_seconds = self.clamp_or_wrap_time(self.time_seconds);
    }

    pub(crate) fn advance(&mut self, delta_seconds: f32) {
        if self.state != AnimationPlaybackState::Playing {
            return;
        }
        let delta = if delta_seconds.is_finite() {
            delta_seconds.max(0.0)
        } else {
            0.0
        };
        self.time_seconds = self.clamp_or_wrap_time(self.time_seconds + delta * self.speed);
    }

    fn clamp_or_wrap_time(&self, time_seconds: f32) -> f32 {
        let duration = self.clip.duration_seconds.max(0.0);
        if duration <= f32::EPSILON {
            return 0.0;
        }
        match self.loop_mode {
            AnimationLoopMode::Once => time_seconds.clamp(0.0, duration),
            AnimationLoopMode::Repeat => time_seconds.rem_euclid(duration),
        }
    }
}