Skip to main content

ssruntime/
instance_slot.rs

1//! [`InstanceSlot`]: an instance part's child context, driven by the parent's instance keys.
2
3use crate::Context;
4
5/// High-level instance-child slot: tracks the per-slot transition state.
6/// `step()` resolves
7/// labels against the *child* runtime context, configures the child's
8/// playback (animation section, loop, direction), and advances the child's
9/// frame — leaving only the C++/host-side `play()` event sink and the
10/// redraw call to the caller.
11pub struct InstanceSlot {
12    last_event_frame: i32,
13    last_is_synthetic: bool,
14    last_independent: bool,
15    // Speed of the last real EventInstance — reused while the implicit frame-0
16    // key is being ignored (independent playback across a parent loop).
17    last_speed: f32,
18    // Speed the most recent `step` drove the child at: the key's, or
19    // `last_speed` while the implicit key is ignored.
20    speed: f32,
21}
22
23impl Default for InstanceSlot {
24    fn default() -> Self {
25        Self::new()
26    }
27}
28
29impl InstanceSlot {
30    pub const fn new() -> Self {
31        Self { last_event_frame: -1, last_is_synthetic: false, last_independent: false, last_speed: 1.0, speed: 1.0 }
32    }
33
34    /// Whether the slot is currently driving its child independently of the
35    /// parent's frame. Reflects the most recently seen `EventInstance.independent`.
36    pub fn is_independent(&self) -> bool {
37        self.last_independent
38    }
39
40    /// The speed the most recent [`Self::step`] drove the child at, `1.0`
41    /// before the first. Usually the key's `speed`, but while the slot ignores
42    /// the implicit frame-0 key it keeps the last real key's, so the event the
43    /// host resolved says `1.0` when the child is not running at it.
44    ///
45    /// Scale the elapsed time handed to the child's own instance and effect
46    /// slots by its absolute value: the child's sub-tree runs on the child's
47    /// clock. Scaling by the resolved event's `speed` instead runs the
48    /// grandchildren at the wrong rate every time the parent goes back before
49    /// the first real key of an independent child.
50    pub fn get_speed(&self) -> f32 {
51        self.speed
52    }
53
54    /// Reset the slot's "last started key" memory to its just-created state so
55    /// the host can re-fire the instance child on an explicit head-out (`play`
56    /// / replay) instead of debouncing the first key as the same one it last
57    /// started. The child context is owned by the host and reset
58    /// separately; the next `step` re-configures it on transition, and the host
59    /// plays it.
60    pub fn reset(&mut self) {
61        *self = Self::new();
62    }
63
64    /// Drive the slot for one tick. Configures `child_ctx` on transition
65    /// edges and advances its frame either by parent-relative seek or by
66    /// delta-time update depending on `independent`.
67    pub fn step(&mut self, ev: crate::types::ss_event_instance_info, child_ctx: &mut Context<'_>, parent_frame: f32, delta_seconds: f32, parent_looped: bool) -> crate::types::ss_instance_step_result {
68        // While the slot drives its child independently, the SpriteStudio implicit
69        // frame-0 playback key (synthetic default) is ignored — the independent
70        // child keeps running across the parent's loop instead of being
71        // re-seeked to it. Only a real authored EventInstance re-transitions it.
72        let ignore_implicit = self.last_independent && ev.is_synthetic_default;
73
74        // Synced children re-arm on the parent loop edge so the authored
75        // EventInstance re-fires each playthrough. Independent children follow the
76        // "last started key" rule instead: a re-crossing of the same key must not
77        // restart the child (sustained / fire-once), only a different key re-fires.
78        // Keep the memory intact when the last started key was independent.
79        // Mirrors EffectSlot.
80        if parent_looped && !ignore_implicit && !self.last_independent {
81            self.last_event_frame = -1;
82            self.last_is_synthetic = false;
83        }
84
85        let transitioned = !ignore_implicit && (self.last_event_frame == -1 || self.last_event_frame != ev.event_frame || self.last_is_synthetic != ev.is_synthetic_default);
86
87        if transitioned {
88            // `_start` / `_end` are implicit — they are not in the label table,
89            // so these fallbacks are what every default key resolves to. They
90            // read the animation's own range, never the section: the
91            // `set_animation_section` below narrows that, and reading it back
92            // shrinks the section again on every re-transition.
93            let start_label_time = child_ctx.resolve_label_time(ev.start_label_hash, child_ctx.get_anime_data_start_frame());
94            let end_label_time = child_ctx.resolve_label_time(ev.end_label_hash, child_ctx.get_anime_data_end_frame());
95            let start_frame = start_label_time + ev.start_offset;
96            let mut end_frame = end_label_time + ev.end_offset;
97            if end_frame < start_frame {
98                end_frame = start_frame;
99            }
100
101            let dir = if ev.reverse { crate::eval::playback_controller::PlaybackDirection::Backward } else { crate::eval::playback_controller::PlaybackDirection::Forward };
102            let style = if ev.pingpong { crate::eval::playback_controller::PlaybackStyle::PingPong } else { crate::eval::playback_controller::PlaybackStyle::Normal };
103            child_ctx.set_playback_direction(dir, style);
104            // Never refused: the end was pulled up to the start above.
105            let _ = child_ctx.set_animation_section(start_frame, end_frame);
106            child_ctx.set_loop_count(ev.loop_num);
107
108            self.last_event_frame = ev.event_frame;
109            self.last_is_synthetic = ev.is_synthetic_default;
110            self.last_speed = ev.speed;
111        }
112
113        // When ignoring the implicit key, keep the child's playback config and
114        // step it with the last real event's independent mode + speed.
115        let independent = if ignore_implicit { true } else { ev.independent };
116        let speed = if ignore_implicit { self.last_speed } else { ev.speed };
117
118        // Branch on `independent`. Synced children are seeked deterministically
119        // from the parent's frame each tick — same `parent_frame` always yields
120        // the same `child_frame`. Independent children own their own controller
121        // time: forward `delta_seconds` to `update`, except on the transition
122        // tick itself — the section change above has already put the child on
123        // its first frame for the direction, where the host's `play()` leaves it,
124        // and a further step here would visibly skip that frame.
125        let child_frame_no = if independent {
126            if delta_seconds > 0.0 && !transitioned {
127                let d_ms = delta_seconds * 1000.0 * speed;
128                child_ctx.update(d_ms)
129            } else {
130                child_ctx.get_frame_no()
131            }
132        } else {
133            let diff = (parent_frame - ev.event_frame as f32) * speed;
134            child_ctx.set_frame_relative(diff);
135            child_ctx.get_frame_no()
136        };
137
138        // Hosts feed this back as `parent_looped` when stepping the child's own
139        // instance/effect slots, so it re-arms the grandchildren's playback keys:
140        // an independent child runs on its own clock, making its loop — not the
141        // parent animation's — the edge they must re-fire on.
142        let child_looped = independent && delta_seconds > 0.0 && !transitioned && child_ctx.just_looped();
143
144        self.last_independent = independent;
145        self.speed = speed;
146
147        crate::types::ss_instance_step_result { visible: true, transitioned, independent, child_frame_no, child_looped }
148    }
149}