bevy_vello 0.13.1

Render assets and scenes in Bevy with Vello
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
use std::time::Duration;

use super::{LottiePlayer, PlayerTransition, asset::VelloLottie};
use crate::{
    PlaybackDirection, PlaybackLoopBehavior, PlaybackOptions, Playhead,
    integrations::lottie::{
        LottieAssetVariant, PlaybackPlayMode, UiVelloLottie, VelloLottie2d,
        player::events::{LottieOnAfterEvent, LottieOnCompletedEvent, LottieOnShowEvent},
    },
    prelude::VelloLottieAnchor,
};
use bevy::{
    camera::primitives::Aabb,
    platform::time::Instant,
    prelude::*,
    ui::{ContentSize, NodeMeasure},
};
use tracing::debug;

/// Helper function to get the next smallest representable f64.
/// For example, prev_f64(3.0) == 2.9999999999999996
#[inline(always)]
fn prev_f64(x: f64) -> f64 {
    let u = x.to_bits();
    let new_u = if u == 0x0000_0000_0000_0000 {
        0x8000_0000_0000_0000 // +0.0 -> -0.0
    } else if u == 0xFFF0_0000_0000_0000 {
        u // -inf -> -inf
    } else if x <= -0.0 {
        u + 1
    } else {
        u - 1
    };
    f64::from_bits(new_u)
}

/// Advance all playheads in the scene
pub fn advance_playheads<A: LottieAssetVariant>(
    mut lotties: Query<(&A, &mut Playhead, &mut LottiePlayer<A>, &PlaybackOptions)>,
    mut assets: ResMut<Assets<VelloLottie>>,
    time: Res<Time>,
) {
    let all_lotties = lotties.iter_mut();

    for (asset, mut playhead, mut player, options) in all_lotties {
        // Get asset
        let Some(asset) = assets.get_mut(asset.asset_id()) else {
            continue;
        };

        // Keep playhead bounded
        let start_frame = options.segments.start.max(asset.composition.frames.start);
        let end_frame = prev_f64(options.segments.end.min(asset.composition.frames.end));
        playhead.frame = playhead.frame.clamp(start_frame, end_frame);

        // Check if we are stopped
        if player.stopped {
            continue;
        }

        // Set first render
        playhead.first_render.get_or_insert(Instant::now());

        // Auto play
        if !player.started && options.autoplay {
            player.started = true;
            player.playing = true;
        }
        // Return if paused
        if !player.playing {
            continue;
        }

        // Handle intermissions
        if let Some(intermission) = playhead.intermission.as_mut() {
            intermission.tick(time.delta());
            if intermission.is_finished() {
                playhead.intermission.take();
                match options.direction {
                    PlaybackDirection::Normal => {
                        playhead.frame = start_frame;
                    }
                    PlaybackDirection::Reverse => {
                        playhead.frame = end_frame;
                    }
                }
            }
            continue;
        }

        // Advance playhead
        let length = end_frame - start_frame;
        playhead.frame += (time.delta_secs_f64()
            * options.speed
            * asset.composition.frame_rate
            * (options.direction as i32 as f64)
            * playhead.playmode_dir)
            % length;

        // Keep the playhead bounded between segments
        let looping = match options.looping {
            PlaybackLoopBehavior::Loop => true,
            PlaybackLoopBehavior::Amount(amt) => playhead.loops_completed < amt,
            PlaybackLoopBehavior::DoNotLoop => false,
        };
        if playhead.frame > end_frame {
            if looping {
                playhead.loops_completed += 1;
                if let PlaybackPlayMode::Bounce = options.play_mode {
                    playhead.playmode_dir *= -1.0;
                }
                // Trigger intermission, if applicable
                if options.intermission > Duration::ZERO {
                    playhead
                        .intermission
                        .replace(Timer::new(options.intermission, TimerMode::Once));
                    playhead.frame = end_frame;
                } else {
                    // Wrap around to the beginning of the segment
                    playhead.frame = start_frame + (playhead.frame - end_frame);
                }
            } else {
                playhead.frame = end_frame;
            }
            // Obey play mode
            if let PlaybackPlayMode::Bounce = options.play_mode {
                playhead.frame = end_frame;
            }
        } else if playhead.frame < start_frame {
            if looping {
                playhead.loops_completed += 1;
                if let PlaybackPlayMode::Bounce = options.play_mode {
                    playhead.playmode_dir *= -1.0;
                }
                // Trigger intermission, if applicable
                if options.intermission > Duration::ZERO {
                    playhead
                        .intermission
                        .replace(Timer::new(options.intermission, TimerMode::Once));
                    playhead.frame = start_frame;
                } else {
                    // Wrap around to the beginning of the segment
                    playhead.frame = end_frame - (start_frame - playhead.frame);
                }
            } else {
                playhead.frame = start_frame;
            }
            // Obey play mode
            if let PlaybackPlayMode::Bounce = options.play_mode {
                playhead.frame = start_frame;
            }
        }
    }
}

pub fn run_time_transitions<A: LottieAssetVariant>(
    mut commands: Commands,
    query_player: Query<(Entity, &LottiePlayer<A>, &Playhead, &PlaybackOptions, &A)>,
    mut assets: ResMut<Assets<VelloLottie>>,
) {
    for (entity, player, playhead, options, lottie) in query_player.iter() {
        let Some(current_asset) = assets.get_mut(lottie.asset_id()) else {
            // Asset has not loaded yet and is therefore not visible. It would be odd to run transitions on assets that aren't visible.
            continue;
        };

        for transition in player.state().transitions.iter() {
            match transition {
                PlayerTransition::OnMouseEnter { .. }
                | PlayerTransition::OnMouseClick { .. }
                | PlayerTransition::OnMouseLeave { .. } => {
                    // Handled via observer
                }
                PlayerTransition::OnAfter { state, secs } => {
                    let started = playhead.first_render;
                    if started.is_some_and(|s| s.elapsed().as_secs_f32() >= *secs) {
                        commands
                            .entity(entity)
                            .trigger(|entity| LottieOnAfterEvent {
                                entity,
                                next_state: state,
                            });
                    }
                }
                PlayerTransition::OnComplete { state } => {
                    let loops_needed = match options.looping {
                        PlaybackLoopBehavior::DoNotLoop => Some(0),
                        PlaybackLoopBehavior::Amount(amt) => Some(amt),
                        PlaybackLoopBehavior::Loop => Some(0),
                    };
                    match options.direction {
                        PlaybackDirection::Normal => {
                            let end_frame = prev_f64(
                                options
                                    .segments
                                    .end
                                    .min(current_asset.composition.frames.end),
                            );
                            if playhead.frame == end_frame
                                && loops_needed
                                    .is_some_and(|needed| playhead.loops_completed >= needed)
                            {
                                commands
                                    .entity(entity)
                                    .trigger(|entity| LottieOnCompletedEvent {
                                        entity,
                                        next_state: state,
                                    });
                            }
                        }
                        PlaybackDirection::Reverse => {
                            let start_frame = options
                                .segments
                                .start
                                .max(current_asset.composition.frames.start);
                            if playhead.frame == start_frame
                                && loops_needed
                                    .is_some_and(|needed| playhead.loops_completed >= needed)
                            {
                                commands
                                    .entity(entity)
                                    .trigger(|entity| LottieOnCompletedEvent {
                                        entity,
                                        next_state: state,
                                    });
                            }
                        }
                    }
                }
                PlayerTransition::OnShow { state } => {
                    if playhead.first_render.is_some() {
                        commands.entity(entity).trigger(|entity| LottieOnShowEvent {
                            entity,
                            next_state: state,
                        });
                    }
                }
            }
        }
    }
}

pub fn transition_state<A: LottieAssetVariant>(
    mut commands: Commands,
    mut query_sm: Query<(Entity, &mut LottiePlayer<A>, &mut Playhead)>,
    assets: Res<Assets<VelloLottie>>,
) {
    for (entity, mut player, mut playhead) in query_sm.iter_mut() {
        // Is there a state to transition to?
        let Some(next_state) = player.next_state else {
            continue;
        };
        // Is it the same state?
        if Some(next_state) == player.current_state {
            player.next_state.take();
            continue;
        }

        debug!("animation controller transitioning to={next_state}");
        let target_state = player
            .states
            .get(&next_state)
            .unwrap_or_else(|| panic!("state not found: '{next_state}'"));
        let target_options = target_state
            .options
            .as_ref()
            .or(player.state().options.as_ref())
            .cloned()
            .unwrap_or_default();

        // Swap asset
        if let Some(target_handle) = target_state.asset.as_ref() {
            commands.entity(entity).insert(target_handle.clone());
        }
        // Reset playheads if requested
        let reset_playhead =
            player.state().reset_playhead_on_exit || target_state.reset_playhead_on_start;
        if reset_playhead {
            let target_asset = target_state.asset.as_ref();
            if let Some(target_asset) = target_asset {
                let Some(asset) = assets.get(target_asset.asset_id()) else {
                    tracing::warn!("not ready for state transition, re-queueing {next_state}...");
                    player.next_state = Some(next_state);
                    continue;
                };
                let frame = match target_options.direction {
                    PlaybackDirection::Normal => target_options
                        .segments
                        .start
                        .max(asset.composition.frames.start),
                    PlaybackDirection::Reverse => prev_f64(
                        target_options
                            .segments
                            .end
                            .min(asset.composition.frames.end),
                    ),
                };
                playhead.seek(frame);
            }
        }

        // Swap theme
        if let Some(theme) = target_state.theme.as_ref() {
            commands.entity(entity).insert(theme.clone());
        }

        // Swap playback options
        if target_state.options.is_some() {
            commands.entity(entity).insert(target_options);
        }

        // Reset playhead state
        playhead.intermission.take();
        playhead.loops_completed = 0;
        playhead.first_render.take();
        playhead.playmode_dir = 1.0;

        // Reset player state
        player.started = false;
        player.playing = false;
        player.current_state.replace(next_state);
    }
}

fn helper_calculate_aabb(lottie: &VelloLottie, anchor: &VelloLottieAnchor) -> Aabb {
    let (width, height) = (
        lottie.composition.width as f32,
        lottie.composition.height as f32,
    );
    let half_size = Vec3::new(width / 2.0, height / 2.0, 0.0);
    let (dx, dy) = {
        match anchor {
            VelloLottieAnchor::TopLeft => (half_size.x, -half_size.y),
            VelloLottieAnchor::Left => (half_size.x, 0.0),
            VelloLottieAnchor::BottomLeft => (half_size.x, half_size.y),
            VelloLottieAnchor::Top => (0.0, -half_size.y),
            VelloLottieAnchor::Center => (0.0, 0.0),
            VelloLottieAnchor::Bottom => (0.0, half_size.y),
            VelloLottieAnchor::TopRight => (-half_size.x, -half_size.y),
            VelloLottieAnchor::Right => (-half_size.x, 0.0),
            VelloLottieAnchor::BottomRight => (-half_size.x, half_size.y),
        }
    };
    let adjustment = Vec3::new(dx, dy, 0.0);
    let min = -half_size + adjustment;
    let max = half_size + adjustment;
    Aabb::from_min_max(min, max)
}

pub fn update_lottie_2d_aabb_on_asset_load(
    mut asset_events: MessageReader<AssetEvent<VelloLottie>>,
    mut world_lotties: Query<(&mut Aabb, &mut VelloLottie2d, &VelloLottieAnchor)>,
    lotties: Res<Assets<VelloLottie>>,
) {
    for event in asset_events.read() {
        let id = if let AssetEvent::LoadedWithDependencies { id } = event {
            *id
        } else {
            continue;
        };
        let Some(lottie) = lotties.get(id) else {
            // Not yet loaded
            continue;
        };
        for (mut aabb, _, anchor) in world_lotties
            .iter_mut()
            .filter(|(_, lottie, _)| lottie.id() == id)
        {
            let new_aabb = helper_calculate_aabb(lottie, anchor);
            *aabb = new_aabb;
        }
    }
}

pub fn update_lottie_2d_aabb_on_change(
    mut world_lotties: Query<
        (&mut Aabb, &mut VelloLottie2d, &VelloLottieAnchor),
        Changed<VelloLottie2d>,
    >,
    lotties: Res<Assets<VelloLottie>>,
) {
    for (mut aabb, lottie, anchor) in world_lotties.iter_mut() {
        let Some(lottie) = lotties.get(&lottie.0) else {
            // Not yet loaded
            continue;
        };
        let new_aabb = helper_calculate_aabb(lottie, anchor);
        *aabb = new_aabb;
    }
}

pub fn update_ui_lottie_content_size_on_change(
    mut query: Query<
        (&mut ContentSize, &ComputedNode, &mut UiVelloLottie),
        Or<(Changed<UiVelloLottie>, Changed<ComputedNode>)>,
    >,
    lotties: Res<Assets<VelloLottie>>,
) {
    for (mut content_size, node, lottie) in query.iter_mut() {
        let Some(lottie) = lotties.get(&lottie.0) else {
            // Not yet loaded
            continue;
        };
        let (width, height) = (
            lottie.composition.width as f32,
            lottie.composition.height as f32,
        );
        let size = Vec2::new(width, height) / node.inverse_scale_factor();
        let measure = NodeMeasure::Fixed(bevy::ui::FixedMeasure { size });
        content_size.set(measure);
    }
}