ssplayer_bevy/feedback.rs
1//! The render-world -> main-world hand-off: timeline events and lifecycle edges,
2//! carried back so gameplay can react to them.
3//!
4//! Playback advances in the render world, so what a tick
5//! produces — the events it crossed, whether it started, looped or finished, the
6//! frame it landed on — has to cross back. It does so through a buffer the draw
7//! system fills and a main-world system drains, which is why it lands **one frame late**:
8//! the main world reads on frame N+1 what the render world produced on frame N.
9//! For a sound cue or a state change that is imperceptible; a host that cannot
10//! tolerate it would have to move playback into the main world, which this crate
11//! deliberately does not do.
12
13use std::sync::{Arc, Mutex};
14
15use bevy::prelude::*;
16use ssplayer_wgpu::SsEvent;
17
18use crate::components::{SsPlaybackState, SsSourceInfo, SsTrackInfo, SsTrackState};
19
20/// One player's playback state as of the render frame that produced it.
21pub(crate) struct PlaybackFeedback {
22 /// The main-world entity, already mapped back from its render-world twin.
23 pub entity: Entity,
24 pub frame_no: f32,
25 pub is_finished: bool,
26 pub playing_forward: bool,
27 /// The start *edge* — set only on the first tick after a `play()`.
28 pub started_edge: bool,
29 /// The completion *edge* — set only on the tick the animation finished.
30 pub finished_edge: bool,
31 /// The loop pulse — set only on the tick the timeline wrapped.
32 pub looped: bool,
33 pub events: Vec<SsEvent>,
34 /// The track stack after the advance, for [`SsTrackState`].
35 pub tracks: Vec<SsTrackInfo>,
36 pub sources: Vec<SsSourceInfo>,
37}
38
39/// An element for the render side to fill: what a batch for a cast that grew is
40/// padded with.
41impl Default for PlaybackFeedback {
42 fn default() -> Self {
43 Self { entity: Entity::PLACEHOLDER, frame_no: 0.0, is_finished: false, playing_forward: true, started_edge: false, finished_edge: false, looped: false, events: Vec::new(), tracks: Vec::new(), sources: Vec::new() }
44 }
45}
46
47/// The two batches in flight.
48#[derive(Default)]
49struct Batches {
50 /// What the last render frame produced, until the main world reads it.
51 ready: Vec<PlaybackFeedback>,
52 /// A batch already read, kept so the next render frame fills its elements,
53 /// and their vectors, instead of allocating new ones.
54 spare: Vec<PlaybackFeedback>,
55}
56
57impl Batches {
58 /// Keep `batch` for reuse, unless the one already kept has more room.
59 fn keep(&mut self, batch: Vec<PlaybackFeedback>) {
60 if batch.capacity() > self.spare.capacity() {
61 self.spare = batch;
62 }
63 }
64}
65
66/// The shared buffer, held by a clone in each world.
67///
68/// The render world publishes a batch each frame; the main world reads it once
69/// and hands it back. An `Arc<Mutex<..>>` rather than a channel because it has
70/// to be a `Resource` in both worlds, and a channel endpoint is not `Sync`.
71#[derive(Resource, Clone, Default)]
72pub(crate) struct FeedbackChannel(Arc<Mutex<Batches>>);
73
74impl FeedbackChannel {
75 /// Render side: a batch to fill, holding whatever it last held. It is
76 /// empty only until two frames have gone through.
77 pub(crate) fn spare(&self) -> Vec<PlaybackFeedback> {
78 self.0.lock().map(|mut batches| std::mem::take(&mut batches.spare)).unwrap_or_default()
79 }
80
81 /// Render side: replace this frame's feedback wholesale. Replacing rather
82 /// than appending keeps a main world that skipped a frame from replaying a
83 /// stale batch.
84 pub(crate) fn publish(&self, batch: Vec<PlaybackFeedback>) {
85 if let Ok(mut batches) = self.0.lock() {
86 let unread = std::mem::replace(&mut batches.ready, batch);
87 batches.keep(unread);
88 }
89 }
90
91 /// Main side: read what the last render frame left, if it has not been
92 /// read already, and hand the batch back for the render side to refill.
93 /// What `read` moves out of the elements is what it may keep.
94 pub(crate) fn read(&self, read: impl FnOnce(&mut [PlaybackFeedback])) {
95 let Ok(mut batch) = self.0.lock().map(|mut batches| std::mem::take(&mut batches.ready)) else { return };
96 read(&mut batch);
97 if let Ok(mut batches) = self.0.lock() {
98 batches.keep(batch);
99 }
100 }
101}
102
103/// A timeline event raised on one character this frame.
104///
105/// Carries [`SsEvent`] verbatim — match on it for the user-data marker, the
106/// signal, or the audio trigger. The player never plays sound itself, so an
107/// [`SsEvent::Audio`] is the cue for the host's own audio stack, not a sound.
108#[derive(Message, Clone, Debug)]
109pub struct SsEventMessage {
110 /// The character whose timeline fired it.
111 pub entity: Entity,
112 /// The event, as the player decoded it.
113 pub event: SsEvent,
114}
115
116/// Raised once, on the first frame a character's animation ran after a start:
117/// a new pack or animation on [`crate::SsPlayer`] while
118/// [`crate::SsPlayback`]`::playing` is on, `playing` turning on for a tree that
119/// has not started yet, an [`crate::SsPlay`], or a bumped `restart`. Turning
120/// `playing` back on after a pause resumes, and is not a start; nor is a new
121/// animation with [`crate::SsPlayer::transition_ms`] above zero, which
122/// crossfades on the tree that is already playing.
123#[derive(Message, Clone, Copy, Debug)]
124pub struct SsStarted {
125 /// The character that started.
126 pub entity: Entity,
127}
128
129/// Raised once, on the frame a character's animation reached its end.
130#[derive(Message, Clone, Copy, Debug)]
131pub struct SsFinished {
132 /// The character that finished.
133 pub entity: Entity,
134}
135
136/// Raised once, on the frame a character's timeline wrapped back to the start.
137#[derive(Message, Clone, Copy, Debug)]
138pub struct SsLooped {
139 /// The character that looped.
140 pub entity: Entity,
141}
142
143/// Drain the render world's feedback into the main world: update the pollable
144/// [`SsPlaybackState`] and [`SsTrackState`], and raise the reactive messages.
145///
146/// Runs in `PreUpdate` so a gameplay system reading the messages in `Update`
147/// sees this frame's batch. A message for an entity that has since despawned is
148/// harmless: nothing reads it against a live component.
149pub(crate) fn dispatch_feedback(
150 channel: Res<FeedbackChannel>,
151 mut states: Query<(&mut SsPlaybackState, &mut SsTrackState)>,
152 mut events: MessageWriter<SsEventMessage>,
153 mut started: MessageWriter<SsStarted>,
154 mut finished: MessageWriter<SsFinished>,
155 mut looped: MessageWriter<SsLooped>,
156) {
157 channel.read(|batch| {
158 for feedback in batch {
159 if let Ok((mut state, mut stack)) = states.get_mut(feedback.entity) {
160 state.frame_no = feedback.frame_no;
161 state.finished = feedback.is_finished;
162 state.playing_forward = feedback.playing_forward;
163 // Swapped rather than copied: the batch goes back with the
164 // component's previous vectors, which the render side refills.
165 std::mem::swap(&mut stack.tracks, &mut feedback.tracks);
166 std::mem::swap(&mut stack.sources, &mut feedback.sources);
167 }
168 if feedback.started_edge {
169 started.write(SsStarted { entity: feedback.entity });
170 }
171 for event in feedback.events.drain(..) {
172 events.write(SsEventMessage { entity: feedback.entity, event });
173 }
174 if feedback.finished_edge {
175 finished.write(SsFinished { entity: feedback.entity });
176 }
177 if feedback.looped {
178 looped.write(SsLooped { entity: feedback.entity });
179 }
180 }
181 });
182}