Skip to main content

ssruntime/web/
mod.rs

1//! Wasm bindings for ssruntime.
2//!
3//! This module mirrors the C FFI surface in `src/ffi/mod.rs` 1:1 for JS/TS
4//! Players. POD return types (`ss_event_instance_info`, `ss_effect_event_info`)
5//! are exposed as
6//! wasm-bindgen wrapper classes (`WebEventInstanceInfo`,
7//! `WebEffectEventInfo`) because wasm-bindgen cannot expose `#[repr(C)]`
8//! structs by value.
9//!
10//! Not exposed:
11//!
12//! - `ss_runtime_set_log_callback`, which requires bridging a JS `Function`
13//!   and a `js-sys` dependency.
14//! - `ss_runtime_ssab_schema_version`.
15
16// The FFI side is authoritative: update `src/ffi/mod.rs` first and reflect the
17// change here. A fallible call reports through `js_error`.
18
19use crate::owning::{OwningContext, OwningEffectSlot};
20use crate::{SsabData, SsabResource};
21use alloc::boxed::Box;
22use alloc::string::ToString;
23use alloc::sync::Arc;
24use wasm_bindgen::prelude::*;
25
26#[wasm_bindgen]
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub enum WebCoordinateSystem {
29    YUp = 0,
30    YDown = 1,
31}
32
33impl From<crate::eval::SsCoordinateSystem> for WebCoordinateSystem {
34    fn from(cs: crate::eval::SsCoordinateSystem) -> Self {
35        match cs {
36            crate::eval::SsCoordinateSystem::YUp => WebCoordinateSystem::YUp,
37            crate::eval::SsCoordinateSystem::YDown => WebCoordinateSystem::YDown,
38        }
39    }
40}
41
42impl From<WebCoordinateSystem> for crate::eval::SsCoordinateSystem {
43    fn from(cs: WebCoordinateSystem) -> Self {
44        match cs {
45            WebCoordinateSystem::YUp => crate::eval::SsCoordinateSystem::YUp,
46            WebCoordinateSystem::YDown => crate::eval::SsCoordinateSystem::YDown,
47        }
48    }
49}
50
51#[wasm_bindgen]
52#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53pub enum WebOrigin {
54    Center = 0,
55    TopLeft = 1,
56}
57
58impl From<crate::eval::SsOrigin> for WebOrigin {
59    fn from(origin: crate::eval::SsOrigin) -> Self {
60        match origin {
61            crate::eval::SsOrigin::Center => WebOrigin::Center,
62            crate::eval::SsOrigin::TopLeft => WebOrigin::TopLeft,
63        }
64    }
65}
66
67impl From<WebOrigin> for crate::eval::SsOrigin {
68    fn from(origin: WebOrigin) -> Self {
69        match origin {
70            WebOrigin::Center => crate::eval::SsOrigin::Center,
71            WebOrigin::TopLeft => crate::eval::SsOrigin::TopLeft,
72        }
73    }
74}
75
76#[wasm_bindgen]
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub enum WebUnit {
79    Pixel = 0,
80    Normalized = 1,
81}
82
83impl From<crate::eval::SsUnit> for WebUnit {
84    fn from(unit: crate::eval::SsUnit) -> Self {
85        match unit {
86            crate::eval::SsUnit::Pixel => WebUnit::Pixel,
87            crate::eval::SsUnit::Normalized => WebUnit::Normalized,
88        }
89    }
90}
91
92impl From<WebUnit> for crate::eval::SsUnit {
93    fn from(unit: WebUnit) -> Self {
94        match unit {
95            WebUnit::Pixel => crate::eval::SsUnit::Pixel,
96            WebUnit::Normalized => crate::eval::SsUnit::Normalized,
97        }
98    }
99}
100
101#[wasm_bindgen]
102#[derive(Clone, Copy, Debug, PartialEq, Eq)]
103pub enum WebPlaybackDirection {
104    Forward = 0,
105    Backward = 1,
106}
107
108impl From<crate::eval::playback_controller::PlaybackDirection> for WebPlaybackDirection {
109    fn from(dir: crate::eval::playback_controller::PlaybackDirection) -> Self {
110        match dir {
111            crate::eval::playback_controller::PlaybackDirection::Forward => WebPlaybackDirection::Forward,
112            crate::eval::playback_controller::PlaybackDirection::Backward => WebPlaybackDirection::Backward,
113        }
114    }
115}
116
117impl From<WebPlaybackDirection> for crate::eval::playback_controller::PlaybackDirection {
118    fn from(dir: WebPlaybackDirection) -> Self {
119        match dir {
120            WebPlaybackDirection::Forward => crate::eval::playback_controller::PlaybackDirection::Forward,
121            WebPlaybackDirection::Backward => crate::eval::playback_controller::PlaybackDirection::Backward,
122        }
123    }
124}
125
126#[wasm_bindgen]
127#[derive(Clone, Copy, Debug, PartialEq, Eq)]
128pub enum WebPlaybackStyle {
129    Normal = 0,
130    PingPong = 1,
131}
132
133impl From<crate::eval::playback_controller::PlaybackStyle> for WebPlaybackStyle {
134    fn from(style: crate::eval::playback_controller::PlaybackStyle) -> Self {
135        match style {
136            crate::eval::playback_controller::PlaybackStyle::Normal => WebPlaybackStyle::Normal,
137            crate::eval::playback_controller::PlaybackStyle::PingPong => WebPlaybackStyle::PingPong,
138        }
139    }
140}
141
142impl From<WebPlaybackStyle> for crate::eval::playback_controller::PlaybackStyle {
143    fn from(style: WebPlaybackStyle) -> Self {
144        match style {
145            WebPlaybackStyle::Normal => crate::eval::playback_controller::PlaybackStyle::Normal,
146            WebPlaybackStyle::PingPong => crate::eval::playback_controller::PlaybackStyle::PingPong,
147        }
148    }
149}
150
151/// JS-friendly mirror of `ss_event_instance_info` (`src/types.rs`).
152///
153/// Returned by `SSRuntimeContext::get_active_event_instance` and consumed by
154/// `SSRuntimeInstanceSlot::step`. Construct directly via the
155/// `WebEventInstanceInfo` constructor when bridging from raw values, or call
156/// `synthetic_default` to obtain SS6 defaults.
157#[wasm_bindgen]
158#[derive(Clone, Copy, Debug)]
159pub struct WebEventInstanceInfo {
160    pub event_frame: i32,
161    pub start_label_hash: u32,
162    pub start_offset: i32,
163    pub end_label_hash: u32,
164    pub end_offset: i32,
165    pub loop_num: i32,
166    pub speed: f32,
167    pub independent: bool,
168    pub reverse: bool,
169    pub pingpong: bool,
170    pub is_synthetic_default: bool,
171}
172
173#[wasm_bindgen]
174impl WebEventInstanceInfo {
175    #[wasm_bindgen(constructor)]
176    #[allow(clippy::too_many_arguments)]
177    pub fn new(event_frame: i32, start_label_hash: u32, start_offset: i32, end_label_hash: u32, end_offset: i32, loop_num: i32, speed: f32, independent: bool, reverse: bool, pingpong: bool, is_synthetic_default: bool) -> WebEventInstanceInfo {
178        WebEventInstanceInfo { event_frame, start_label_hash, start_offset, end_label_hash, end_offset, loop_num, speed, independent, reverse, pingpong, is_synthetic_default }
179    }
180
181    pub fn synthetic_default() -> WebEventInstanceInfo {
182        crate::types::ss_event_instance_info::synthetic_default().into()
183    }
184}
185
186impl From<crate::types::ss_event_instance_info> for WebEventInstanceInfo {
187    fn from(v: crate::types::ss_event_instance_info) -> Self {
188        WebEventInstanceInfo {
189            event_frame: v.event_frame,
190            start_label_hash: v.start_label_hash,
191            start_offset: v.start_offset,
192            end_label_hash: v.end_label_hash,
193            end_offset: v.end_offset,
194            loop_num: v.loop_num,
195            speed: v.speed,
196            independent: v.independent,
197            reverse: v.reverse,
198            pingpong: v.pingpong,
199            is_synthetic_default: v.is_synthetic_default,
200        }
201    }
202}
203
204impl From<WebEventInstanceInfo> for crate::types::ss_event_instance_info {
205    fn from(v: WebEventInstanceInfo) -> Self {
206        crate::types::ss_event_instance_info {
207            event_frame: v.event_frame,
208            start_label_hash: v.start_label_hash,
209            start_offset: v.start_offset,
210            end_label_hash: v.end_label_hash,
211            end_offset: v.end_offset,
212            loop_num: v.loop_num,
213            speed: v.speed,
214            independent: v.independent,
215            reverse: v.reverse,
216            pingpong: v.pingpong,
217            is_synthetic_default: v.is_synthetic_default,
218        }
219    }
220}
221
222/// JS-friendly mirror of `ss_effect_event_info` (`src/types.rs`).
223#[wasm_bindgen]
224#[derive(Clone, Copy, Debug)]
225pub struct WebEffectEventInfo {
226    pub event_frame: i32,
227    pub start_time: i32,
228    pub speed: f32,
229    pub independent: bool,
230    pub is_synthetic_default: bool,
231}
232
233#[wasm_bindgen]
234impl WebEffectEventInfo {
235    #[wasm_bindgen(constructor)]
236    pub fn new(event_frame: i32, start_time: i32, speed: f32, independent: bool, is_synthetic_default: bool) -> WebEffectEventInfo {
237        WebEffectEventInfo { event_frame, start_time, speed, independent, is_synthetic_default }
238    }
239
240    pub fn synthetic_default() -> WebEffectEventInfo {
241        crate::types::ss_effect_event_info::synthetic_default().into()
242    }
243}
244
245impl From<crate::types::ss_effect_event_info> for WebEffectEventInfo {
246    fn from(v: crate::types::ss_effect_event_info) -> Self {
247        WebEffectEventInfo { event_frame: v.event_frame, start_time: v.start_time, speed: v.speed, independent: v.independent, is_synthetic_default: v.is_synthetic_default }
248    }
249}
250
251impl From<WebEffectEventInfo> for crate::types::ss_effect_event_info {
252    fn from(v: WebEffectEventInfo) -> Self {
253        crate::types::ss_effect_event_info { event_frame: v.event_frame, start_time: v.start_time, speed: v.speed, independent: v.independent, is_synthetic_default: v.is_synthetic_default }
254    }
255}
256
257/// How every fallible call here reports: a JS `Error` with the Brain's own wording
258/// as its message.
259///
260/// `Display`, not `Debug`: `Debug` prints the Rust variant name, an identifier from
261/// a language a JS caller is not writing, and it reaches their user through
262/// whatever the Player puts in front of them. `Display` also carries what a variant
263/// knows: `InvalidVersion` names the version expected and the one that arrived.
264fn js_error(e: crate::error::SSRuntimeError) -> JsValue {
265    js_message(&alloc::format!("{}", e))
266}
267
268/// An `Error` rather than a bare string, so that whoever catches it finds `message`
269/// and a stack.
270fn js_message(message: &str) -> JsValue {
271    JsError::new(message).into()
272}
273
274#[wasm_bindgen]
275pub struct SSRuntimeResource {
276    inner: Arc<SsabResource>,
277}
278
279#[wasm_bindgen]
280impl SSRuntimeResource {
281    /// Copies and parses a `.ssab`. The runtime does not verify the bytes — a malformed or
282    /// crafted pack causes out-of-bounds reads within this module's memory — so pass only
283    /// packs you trust. A schema-version mismatch is reported as an error.
284    #[wasm_bindgen(constructor)]
285    pub fn new(data: &[u8]) -> Result<SSRuntimeResource, JsValue> {
286        let ssab_data = SsabData::load_copy(data).map_err(|e| js_message(&e.to_string()))?;
287        // SAFETY: the JS caller guarantees a valid `.ssab`, as the C ABI's caller does; nothing
288        // here can check it (crate docs, "Limitations to design around").
289        let inner = unsafe { SsabResource::new(ssab_data) };
290        if inner.resource().is_none() {
291            // The reason, not just the fact: a version mismatch names both
292            // versions, which is the whole of what the user needs to act.
293            let reason = inner.parse_error().map_or_else(|| alloc::string::String::from("Failed to parse SSAB data"), |e| alloc::format!("{}", e));
294            return Err(js_message(&reason));
295        }
296        Ok(SSRuntimeResource { inner })
297    }
298}
299
300#[wasm_bindgen]
301pub struct SSRuntimeContext {
302    inner: OwningContext,
303}
304
305#[wasm_bindgen]
306impl SSRuntimeContext {
307    #[wasm_bindgen(constructor)]
308    pub fn new(data: Option<Box<[u8]>>) -> Result<SSRuntimeContext, JsValue> {
309        let mut ctx = SSRuntimeContext { inner: OwningContext::new() };
310        if let Some(d) = data {
311            let res = SSRuntimeResource::new(&d)?;
312            ctx.bind_resource(&res);
313        }
314        Ok(ctx)
315    }
316
317    pub fn reset(&mut self) {
318        self.inner.reset();
319    }
320
321    pub fn bind_resource(&mut self, resource: &SSRuntimeResource) -> bool {
322        self.inner.bind(resource.inner.clone()).is_ok()
323    }
324
325    pub fn load_ssab_copy(&mut self, data: &[u8]) -> bool {
326        if let Ok(ssab_data) = SsabData::load_copy(data) {
327            // SAFETY: the JS caller guarantees a valid `.ssab`, as for `SSRuntimeResource::new`.
328            let res = SSRuntimeResource { inner: unsafe { SsabResource::new(ssab_data) } };
329            if res.inner.resource().is_some() {
330                return self.bind_resource(&res);
331            }
332        }
333        false
334    }
335
336    pub fn get_render_mode(&self) -> u8 {
337        self.inner.render_mode() as u8
338    }
339
340    pub fn set_render_mode(&mut self, mode: u8) {
341        self.inner.set_render_mode(crate::eval::RenderMode::from_u8(mode));
342    }
343
344    pub fn setup_animation(&mut self, name: &str) -> Result<(), JsValue> {
345        self.inner.setup_animation(name).map_err(js_error)
346    }
347
348    pub fn setup_animation_by_hash(&mut self, name_hash: u32) -> Result<(), JsValue> {
349        self.inner.setup_animation_by_hash(name_hash).map_err(js_error)
350    }
351
352    /// Build the frame data for `frame_no` and return its byte length. Read the
353    /// bytes with `get_frame_data_buf`, which does not evaluate again.
354    ///
355    /// Evaluating the frame is the expensive half of a tick, so it happens here
356    /// once. The buf/len pair is pure, like every other one on this type.
357    pub fn prepare_frame_data(&mut self, frame_no: f32) -> Result<usize, JsValue> {
358        self.inner.get_frame_data(frame_no).map(|s| s.len()).map_err(js_error)
359    }
360
361    // Zero-copy getters
362
363    /// Pointer to what the last `prepare_frame_data` built. Null before the
364    /// first call; valid until the next one.
365    pub fn get_frame_data_buf(&self) -> *const u8 {
366        self.inner.get_frame_data_ptr()
367    }
368
369    pub fn get_frame_data_len(&self) -> usize {
370        self.inner.get_frame_data_len()
371    }
372
373    pub fn get_world_matrices_buf(&self) -> *const f32 {
374        self.inner.get_world_matrices_ptr()
375    }
376
377    pub fn get_world_matrices_len(&self) -> usize {
378        self.inner.get_world_matrices_len()
379    }
380
381    pub fn get_mesh_vertices_x_buf(&self) -> *const f32 {
382        self.inner.get_mesh_vertices_x_ptr()
383    }
384
385    pub fn get_mesh_vertices_x_len(&self) -> usize {
386        self.inner.get_mesh_vertices_x_len()
387    }
388
389    pub fn get_mesh_vertices_y_buf(&self) -> *const f32 {
390        self.inner.get_mesh_vertices_y_ptr()
391    }
392
393    pub fn get_mesh_vertices_y_len(&self) -> usize {
394        self.inner.get_mesh_vertices_y_len()
395    }
396
397    pub fn get_mesh_uvs_buf(&self) -> *const f32 {
398        self.inner.get_mesh_uvs_ptr()
399    }
400
401    pub fn get_mesh_uvs_len(&self) -> usize {
402        self.inner.get_mesh_uvs_len()
403    }
404
405    pub fn get_mesh_indices_buf(&self) -> *const i32 {
406        self.inner.get_mesh_indices_ptr()
407    }
408
409    pub fn get_mesh_indices_len(&self) -> usize {
410        self.inner.get_mesh_indices_len()
411    }
412
413    pub fn get_mesh_vertex_offsets_buf(&self) -> *const u32 {
414        self.inner.get_mesh_vertex_offsets_ptr()
415    }
416
417    pub fn get_mesh_vertex_offsets_len(&self) -> usize {
418        self.inner.get_mesh_vertex_offsets_len()
419    }
420
421    pub fn get_mesh_index_offsets_buf(&self) -> *const u32 {
422        self.inner.get_mesh_index_offsets_ptr()
423    }
424
425    pub fn get_mesh_index_offsets_len(&self) -> usize {
426        self.inner.get_mesh_index_offsets_len()
427    }
428
429    pub fn get_nines_vertices_buf(&self) -> *const f32 {
430        self.inner.get_nines_vertices_ptr()
431    }
432
433    pub fn get_nines_vertices_len(&self) -> usize {
434        self.inner.get_nines_vertices_len()
435    }
436
437    pub fn get_nines_uvs_buf(&self) -> *const f32 {
438        self.inner.get_nines_uvs_ptr()
439    }
440
441    pub fn get_nines_uvs_len(&self) -> usize {
442        self.inner.get_nines_uvs_len()
443    }
444
445    pub fn get_nines_box_coords_buf(&self) -> *const f32 {
446        self.inner.get_nines_box_coords_ptr()
447    }
448
449    pub fn get_nines_box_coords_len(&self) -> usize {
450        self.inner.get_nines_box_coords_len()
451    }
452
453    pub fn get_nines_indices_buf(&self) -> *const i32 {
454        self.inner.get_nines_indices_ptr()
455    }
456
457    pub fn get_nines_indices_len(&self) -> usize {
458        self.inner.get_nines_indices_len()
459    }
460
461    pub fn get_nines_vertex_offsets_buf(&self) -> *const u32 {
462        self.inner.get_nines_vertex_offsets_ptr()
463    }
464
465    pub fn get_nines_vertex_offsets_len(&self) -> usize {
466        self.inner.get_nines_vertex_offsets_len()
467    }
468
469    pub fn get_nines_index_offsets_buf(&self) -> *const u32 {
470        self.inner.get_nines_index_offsets_ptr()
471    }
472
473    pub fn get_nines_index_offsets_len(&self) -> usize {
474        self.inner.get_nines_index_offsets_len()
475    }
476
477    pub fn get_local_uvs_buf(&self) -> *const f32 {
478        self.inner.get_local_uvs_ptr()
479    }
480
481    pub fn get_local_uvs_len(&self) -> usize {
482        self.inner.get_local_uvs_len()
483    }
484
485    pub fn get_cell_meta_buf(&self) -> *const f32 {
486        self.inner.get_cell_meta_ptr()
487    }
488
489    pub fn get_cell_meta_len(&self) -> usize {
490        self.inner.get_cell_meta_len()
491    }
492
493    pub fn get_local_vertices_buf(&self) -> *const f32 {
494        self.inner.get_local_vertices_ptr()
495    }
496
497    pub fn get_local_vertices_len(&self) -> usize {
498        self.inner.get_local_vertices_len()
499    }
500
501    pub fn get_shape_vertices_buf(&self) -> *const f32 {
502        self.inner.get_shape_vertices_ptr()
503    }
504
505    pub fn get_shape_vertices_len(&self) -> usize {
506        self.inner.get_shape_vertices_len()
507    }
508
509    pub fn get_shape_vertex_box_coords_buf(&self) -> *const f32 {
510        self.inner.get_shape_vertex_box_coords_ptr()
511    }
512
513    pub fn get_shape_vertex_box_coords_len(&self) -> usize {
514        self.inner.get_shape_vertex_box_coords_len()
515    }
516
517    pub fn get_shape_vertex_counts_buf(&self) -> *const i32 {
518        self.inner.get_shape_vertex_counts_ptr()
519    }
520
521    pub fn get_shape_vertex_counts_len(&self) -> usize {
522        self.inner.get_shape_vertex_counts_len()
523    }
524
525    pub fn get_ssab_buf(&self) -> Result<*const u8, JsValue> {
526        self.inner.get_ssab_data().map(|s| s.as_ptr()).ok_or_else(|| js_message("SSAB data not found"))
527    }
528
529    pub fn get_ssab_len(&self) -> Result<usize, JsValue> {
530        self.inner.get_ssab_data().map(|s| s.len()).ok_or_else(|| js_message("SSAB data not found"))
531    }
532
533    // Frame Number getter functions
534    pub fn get_frame_no(&self) -> f32 {
535        self.inner.get_frame_no()
536    }
537
538    /// `true` once the configured loops have completed, and sticky until the
539    /// next `play` / `setup_animation`. Never `true` under an infinite loop
540    /// count, and never raised by `stop`.
541    ///
542    /// This is a *state*, not a pulse: to notify once, take its rising edge.
543    pub fn is_finished(&self) -> bool {
544        self.inner.is_finished()
545    }
546
547    pub fn just_looped(&self) -> bool {
548        self.inner.just_looped()
549    }
550
551    // Playback state and setting getters
552    pub fn is_playing(&self) -> bool {
553        self.inner.is_playing()
554    }
555
556    pub fn is_playing_forward(&self) -> bool {
557        self.inner.is_playing_forward()
558    }
559
560    pub fn is_pausing(&self) -> bool {
561        self.inner.is_pausing()
562    }
563
564    /// The character's clock: `true` from `play` until `stop` or the next
565    /// setup, after track 0 has finished as well.
566    pub fn is_clock_playing(&self) -> bool {
567        self.inner.is_clock_playing()
568    }
569
570    /// `true` while `pause` holds a playing clock, after track 0 has finished
571    /// as well. Implies `is_clock_playing`.
572    pub fn is_clock_pausing(&self) -> bool {
573        self.inner.is_clock_pausing()
574    }
575
576    /// `true` while the track stack would move the pose on a running clock for
577    /// a reason other than track 0's own animation stepping: a fade on any
578    /// track, or another source still playing on a track that is heard.
579    /// Independent of the clock; read it with `is_clock_playing` and
580    /// `is_clock_pausing`.
581    pub fn is_stack_in_motion(&self) -> bool {
582        self.inner.is_stack_in_motion()
583    }
584
585    pub fn get_skip_frames(&self) -> bool {
586        self.inner.get_skip_frames()
587    }
588
589    pub fn get_playback_direction(&self) -> WebPlaybackDirection {
590        self.inner.get_playback_direction().into()
591    }
592
593    pub fn get_playback_style(&self) -> WebPlaybackStyle {
594        self.inner.get_playback_style().into()
595    }
596
597    pub fn get_loop_count(&self) -> i32 {
598        self.inner.get_loop_count()
599    }
600
601    pub fn get_remaining_loops(&self) -> i32 {
602        self.inner.get_remaining_loops()
603    }
604
605    pub fn get_start_frame(&self) -> i32 {
606        self.inner.get_start_frame()
607    }
608
609    pub fn get_end_frame(&self) -> i32 {
610        self.inner.get_end_frame()
611    }
612
613    pub fn get_frame_rate(&self) -> i32 {
614        self.inner.get_frame_rate()
615    }
616
617    pub fn get_speed_scale(&self) -> f32 {
618        self.inner.get_speed_scale()
619    }
620
621    // Playback setup
622    pub fn set_skip_frames(&mut self, skip: bool) {
623        self.inner.set_skip_frames(skip);
624    }
625
626    pub fn set_loop_count(&mut self, loop_count: i32) {
627        self.inner.set_loop_count(loop_count);
628    }
629
630    pub fn set_frame_rate(&mut self, frame_rate: i32) {
631        self.inner.set_frame_rate(frame_rate);
632    }
633
634    pub fn set_playback_direction(&mut self, direction: WebPlaybackDirection, style: WebPlaybackStyle) {
635        self.inner.set_playback_direction(direction.into(), style.into());
636    }
637
638    pub fn set_speed_scale(&mut self, speed_scale: f32) {
639        self.inner.set_speed_scale(speed_scale);
640    }
641
642    /// Throws `Invalid parameter` when both ends are in range and the end is
643    /// before the start; the section and the playhead stay as they were.
644    pub fn set_animation_section(&mut self, start_frame: i32, end_frame: i32) -> Result<(), JsValue> {
645        self.inner.set_animation_section(start_frame, end_frame).map_err(js_error)
646    }
647
648    pub fn set_coordinate_system(&mut self, coordinate_system: WebCoordinateSystem) {
649        self.inner.set_coordinate_system(coordinate_system.into());
650    }
651
652    pub fn get_coordinate_system(&self) -> WebCoordinateSystem {
653        self.inner.get_coordinate_system().into()
654    }
655
656    pub fn set_origin(&mut self, origin: WebOrigin) {
657        self.inner.set_origin(origin.into());
658    }
659
660    pub fn get_origin(&self) -> WebOrigin {
661        self.inner.get_origin().into()
662    }
663
664    pub fn set_unit(&mut self, unit: WebUnit) {
665        self.inner.set_unit(unit.into());
666    }
667
668    pub fn get_unit(&self) -> WebUnit {
669        self.inner.get_unit().into()
670    }
671
672    pub fn update(&mut self, delta: f32) -> f32 {
673        self.inner.update(delta)
674    }
675
676    pub fn play(&mut self) {
677        self.inner.play();
678    }
679
680    pub fn play_with_start_frame(&mut self, frame_no: f32) {
681        self.inner.play_with_start_frame(frame_no);
682    }
683
684    /// Holds playback in place (idempotent). `is_playing` stays true; read
685    /// `is_pausing` to tell a held animation from a running one.
686    pub fn pause(&mut self) {
687        self.inner.pause();
688    }
689
690    /// Lifts a `pause` (idempotent). `play` rewinds, so it is not a resume.
691    pub fn resume(&mut self) {
692        self.inner.resume();
693    }
694
695    pub fn stop(&mut self) {
696        self.inner.stop();
697    }
698
699    pub fn set_frame_no(&mut self, frame: f32) {
700        self.inner.set_frame_no(frame);
701    }
702
703    pub fn next_frame(&mut self) {
704        self.inner.next_frame();
705    }
706
707    pub fn prev_frame(&mut self) {
708        self.inner.prev_frame();
709    }
710
711    // Animation mixing — the track stack, mirroring the C FFI surface. Tracks
712    // fold onto the setup pose in ascending order: a track's `alpha` is its
713    // strength, while a source's `weight` only sets proportions among several
714    // sources sharing one track. Track 0 carries the structure and events.
715
716    pub fn set_track_animation(&mut self, track: u32, name: &str) -> Result<(), JsValue> {
717        self.inner.set_track_animation(track, name).map_err(js_error)
718    }
719
720    pub fn set_track_animation_by_hash(&mut self, track: u32, hash: u32) -> Result<(), JsValue> {
721        self.inner.set_track_animation_by_hash(track, hash).map_err(js_error)
722    }
723
724    pub fn set_track_alpha(&mut self, track: u32, alpha: f32) -> Result<(), JsValue> {
725        self.inner.set_track_alpha(track, alpha).map_err(js_error)
726    }
727
728    pub fn get_track_alpha(&self, track: u32) -> Option<f32> {
729        self.inner.get_track_alpha(track)
730    }
731
732    /// `blend`: 0 = mix (lerp onto what is below), 1 = additive (offset from the setup pose).
733    pub fn set_track_blend(&mut self, track: u32, blend: u32) -> Result<(), JsValue> {
734        let blend = match blend {
735            0 => crate::TrackBlend::Mix,
736            1 => crate::TrackBlend::Additive,
737            _ => return Err(js_message("blend must be 0 (mix) or 1 (additive)")),
738        };
739        self.inner.set_track_blend(track, blend).map_err(js_error)
740    }
741
742    pub fn get_track_blend(&self, track: u32) -> Option<u32> {
743        self.inner.get_track_blend(track).map(|b| match b {
744            crate::TrackBlend::Mix => 0,
745            crate::TrackBlend::Additive => 1,
746        })
747    }
748
749    /// `sync`: 0 = free (start from the head), 1 = start (start at track 0's phase).
750    /// Set it before laying an animation on the track.
751    pub fn set_track_sync(&mut self, track: u32, sync: u32) -> Result<(), JsValue> {
752        let sync = match sync {
753            0 => crate::TrackSync::Free,
754            1 => crate::TrackSync::Start,
755            _ => return Err(js_message("sync must be 0 (free) or 1 (start)")),
756        };
757        self.inner.set_track_sync(track, sync).map_err(js_error)
758    }
759
760    pub fn get_track_sync(&self, track: u32) -> Option<u32> {
761        self.inner.get_track_sync(track).map(|s| match s {
762            crate::TrackSync::Free => 0,
763            crate::TrackSync::Start => 1,
764        })
765    }
766
767    pub fn get_track_count(&self) -> u32 {
768        self.inner.get_track_count()
769    }
770
771    pub fn clear_track(&mut self, track: u32) -> Result<(), JsValue> {
772        self.inner.clear_track(track).map_err(js_error)
773    }
774
775    pub fn crossfade(&mut self, track: u32, name: &str, duration_ms: f32) -> Result<(), JsValue> {
776        self.inner.crossfade(track, name, duration_ms).map_err(js_error)
777    }
778
779    pub fn crossfade_by_hash(&mut self, track: u32, hash: u32, duration_ms: f32) -> Result<(), JsValue> {
780        self.inner.crossfade_by_hash(track, hash, duration_ms).map_err(js_error)
781    }
782
783    pub fn fade_track(&mut self, track: u32, target_alpha: f32, duration_ms: f32) -> Result<(), JsValue> {
784        self.inner.fade_track(track, target_alpha, duration_ms).map_err(js_error)
785    }
786
787    pub fn get_track_fade_progress(&self, track: u32) -> Option<f32> {
788        self.inner.get_track_fade_progress(track)
789    }
790
791    pub fn cancel_track_fade(&mut self, track: u32) -> Result<(), JsValue> {
792        self.inner.cancel_track_fade(track).map_err(js_error)
793    }
794
795    pub fn set_track_frame(&mut self, track: u32, frame: f32) -> Result<(), JsValue> {
796        self.inner.set_track_frame(track, frame).map_err(js_error)
797    }
798
799    pub fn get_track_frame(&self, track: u32) -> Option<f32> {
800        self.inner.get_track_frame(track)
801    }
802
803    pub fn set_track_speed(&mut self, track: u32, speed: f32) -> Result<(), JsValue> {
804        self.inner.set_track_speed(track, speed).map_err(js_error)
805    }
806
807    pub fn get_track_speed(&self, track: u32) -> Option<f32> {
808        self.inner.get_track_speed(track)
809    }
810
811    pub fn set_track_frame_rate(&mut self, track: u32, frame_rate: i32) -> Result<(), JsValue> {
812        self.inner.set_track_frame_rate(track, frame_rate).map_err(js_error)
813    }
814
815    pub fn get_track_frame_rate(&self, track: u32) -> Option<i32> {
816        self.inner.get_track_frame_rate(track)
817    }
818
819    pub fn set_track_skip_frames(&mut self, track: u32, skip: bool) -> Result<(), JsValue> {
820        self.inner.set_track_skip_frames(track, skip).map_err(js_error)
821    }
822
823    pub fn get_track_skip_frames(&self, track: u32) -> Option<bool> {
824        self.inner.get_track_skip_frames(track)
825    }
826
827    pub fn set_track_playback_direction(&mut self, track: u32, direction: WebPlaybackDirection, style: WebPlaybackStyle) -> Result<(), JsValue> {
828        self.inner.set_track_playback_direction(track, direction.into(), style.into()).map_err(js_error)
829    }
830
831    pub fn get_track_playback_direction(&self, track: u32) -> Option<WebPlaybackDirection> {
832        self.inner.get_track_playback_direction(track).map(Into::into)
833    }
834
835    pub fn get_track_playback_style(&self, track: u32) -> Option<WebPlaybackStyle> {
836        self.inner.get_track_playback_style(track).map(Into::into)
837    }
838
839    /// Belongs to the animation on the track: laying another one there starts
840    /// it looping forever again, so state the count after laying it.
841    pub fn set_track_loop_count(&mut self, track: u32, loop_count: i32) -> Result<(), JsValue> {
842        self.inner.set_track_loop_count(track, loop_count).map_err(js_error)
843    }
844
845    pub fn get_track_loop_count(&self, track: u32) -> Option<i32> {
846        self.inner.get_track_loop_count(track)
847    }
848
849    /// `is_finished` for one track; `false` for a track with no animation.
850    pub fn is_track_finished(&self, track: u32) -> bool {
851        self.inner.is_track_finished(track)
852    }
853
854    /// `just_looped` for one track.
855    pub fn track_just_looped(&self, track: u32) -> bool {
856        self.inner.track_just_looped(track)
857    }
858
859    /// The outgoing side of a crossfade on the track fires events while its
860    /// share, `1 - t`, is at least this. Silent from the start by default.
861    pub fn set_track_outgoing_event_threshold(&mut self, track: u32, threshold: f32) -> Result<(), JsValue> {
862        self.inner.set_track_outgoing_event_threshold(track, threshold).map_err(js_error)
863    }
864
865    pub fn get_track_outgoing_event_threshold(&self, track: u32) -> Option<f32> {
866        self.inner.get_track_outgoing_event_threshold(track)
867    }
868
869    pub fn get_track_main_source(&self, track: u32) -> Option<u32> {
870        self.inner.get_track_main_source(track)
871    }
872
873    pub fn add_track_source(&mut self, track: u32, name: &str, weight: f32) -> Result<u32, JsValue> {
874        self.inner.add_track_source(track, name, weight).map_err(js_error)
875    }
876
877    pub fn add_track_source_by_hash(&mut self, track: u32, hash: u32, weight: f32) -> Result<u32, JsValue> {
878        self.inner.add_track_source_by_hash(track, hash, weight).map_err(js_error)
879    }
880
881    pub fn set_source_weight(&mut self, handle: u32, weight: f32) -> Result<(), JsValue> {
882        self.inner.set_source_weight(handle, weight).map_err(js_error)
883    }
884
885    pub fn get_source_weight(&self, handle: u32) -> Option<f32> {
886        self.inner.get_source_weight(handle)
887    }
888
889    pub fn set_source_frame(&mut self, handle: u32, frame: f32) -> Result<(), JsValue> {
890        self.inner.set_source_frame(handle, frame).map_err(js_error)
891    }
892
893    pub fn get_source_frame(&self, handle: u32) -> Option<f32> {
894        self.inner.get_source_frame(handle)
895    }
896
897    /// Which animation the source plays, as an index into the ssab's animations;
898    /// the table a passed event index addresses.
899    pub fn get_source_animation_index(&self, handle: u32) -> Option<u32> {
900        self.inner.get_source_animation_index(handle)
901    }
902
903    /// Which animation track 0's main source plays, as an index into the
904    /// ssab's animations; a crossfade or a track animation on track 0 changes
905    /// it from the call on.
906    pub fn get_current_animation_index(&self) -> Option<u32> {
907        self.inner.get_current_animation_index()
908    }
909
910    pub fn set_source_event_threshold(&mut self, handle: u32, threshold: f32) -> Result<(), JsValue> {
911        self.inner.set_source_event_threshold(handle, threshold).map_err(js_error)
912    }
913
914    pub fn get_source_event_threshold(&self, handle: u32) -> Option<f32> {
915        self.inner.get_source_event_threshold(handle)
916    }
917
918    pub fn get_passed_event_source_handle(&self, index: i32) -> u32 {
919        if index < 0 {
920            return u32::MAX;
921        }
922        self.inner.get_passed_event_source_handles().get(index as usize).copied().unwrap_or(u32::MAX)
923    }
924
925    pub fn get_passed_event_count(&self) -> i32 {
926        self.inner.get_passed_event_indices().len() as i32
927    }
928
929    pub fn get_passed_event_index(&self, index: i32) -> i32 {
930        self.inner.get_passed_event_indices().get(index as usize).copied().unwrap_or(-1)
931    }
932
933    /// Mirror of `ss_runtime_get_active_event_instance`. Returns SS6 defaults
934    /// (`is_synthetic_default = true`, `loop_num = 1`, `speed = 1.0`) when no
935    /// event is active. Most Players should pass the returned value directly
936    /// to `SSRuntimeInstanceSlot::step`, which resolves the labels internally.
937    pub fn get_active_event_instance(&mut self, slot_index: u32) -> WebEventInstanceInfo {
938        self.inner.get_active_event_instance(slot_index).into()
939    }
940
941    /// Mirror of `ss_runtime_get_active_effect_event`.
942    pub fn get_active_effect_event(&mut self, slot_index: u32) -> WebEffectEventInfo {
943        self.inner.get_active_effect_event(slot_index).into()
944    }
945
946    // ---- Override Layer: per-part runtime overrides ----------------------
947    // Mirrors the `ss_runtime_*_override` C FFI in `src/ffi/mod.rs`.
948
949    /// Mirror of `ss_runtime_find_part_index`. `-1` if not loaded / not found.
950    pub fn find_part_index(&self, part_name: &str) -> i32 {
951        self.inner.find_part_index(part_name)
952    }
953
954    /// Mirror of `ss_runtime_set_part_visibility_override`.
955    /// `force`: 0=clear/revert, 1=force-hide. Anything else, 2 (reserved for
956    /// force-visible) included, is rejected.
957    pub fn set_part_visibility_override(&mut self, part: u32, force: u8, cascade: bool) -> Result<(), JsValue> {
958        self.inner.set_part_visibility_override(part, force, cascade).map_err(js_error)
959    }
960
961    /// Mirror of `ss_runtime_clear_part_visibility_override`.
962    pub fn clear_part_visibility_override(&mut self, part: u32) -> Result<(), JsValue> {
963        self.inner.clear_part_visibility_override(part).map_err(js_error)
964    }
965
966    /// Mirror of `ss_runtime_set_part_color_override`. `rgba` packed `0xRRGGBBAA`
967    /// (fills all four corners); `blend_op`: 0=Mix 1=Mul 2=Add 3=Sub;
968    /// `priority_mode`: 0=OverwriteOnNextKeyframe 1=HoldUntilNextAnimation 2=Permanent.
969    pub fn set_part_color_override(&mut self, part: u32, blend_op: u8, rgba: u32, priority_mode: u8) -> Result<(), JsValue> {
970        self.inner.set_part_color_override(part, blend_op, rgba, priority_mode).map_err(js_error)
971    }
972
973    /// Mirror of `ss_runtime_set_part_color_override_corners`. `rgba_ltrtlbrb` =
974    /// 4 packed RGBA in ssruntime corner order `lt, rt, lb, rb`.
975    pub fn set_part_color_override_corners(&mut self, part: u32, blend_op: u8, rgba_ltrtlbrb: &[u32], priority_mode: u8) -> Result<(), JsValue> {
976        if rgba_ltrtlbrb.len() < 4 {
977            return Err(js_message("rgba_ltrtlbrb must have 4 elements"));
978        }
979        let corners = [rgba_ltrtlbrb[0].to_be_bytes(), rgba_ltrtlbrb[1].to_be_bytes(), rgba_ltrtlbrb[2].to_be_bytes(), rgba_ltrtlbrb[3].to_be_bytes()];
980        self.inner.set_part_color_override_corners(part, blend_op, corners, priority_mode).map_err(js_error)
981    }
982
983    /// Mirror of `ss_runtime_clear_part_color_override`.
984    pub fn clear_part_color_override(&mut self, part: u32) -> Result<(), JsValue> {
985        self.inner.clear_part_color_override(part).map_err(js_error)
986    }
987
988    /// Mirror of `ss_runtime_set_part_cell_override`. `(0, 0)` reverts to the
989    /// animation; Normal + Mask parts only; errors if the cell is unresolvable.
990    pub fn set_part_cell_override(&mut self, part: u32, cellmap_name_hash: u32, cell_name_hash: u32, priority_mode: u8) -> Result<(), JsValue> {
991        self.inner.set_part_cell_override(part, cellmap_name_hash, cell_name_hash, priority_mode).map_err(js_error)
992    }
993
994    /// Mirror of `ss_runtime_clear_part_cell_override`.
995    pub fn clear_part_cell_override(&mut self, part: u32) -> Result<(), JsValue> {
996        self.inner.clear_part_cell_override(part).map_err(js_error)
997    }
998
999    /// Mirror of `ss_runtime_clear_all_part_overrides`.
1000    pub fn clear_all_part_overrides(&mut self) {
1001        self.inner.clear_all_part_overrides();
1002    }
1003}
1004
1005/// JS-friendly wrapper of `EffectSlot`. Same conceptual flow as the C FFI:
1006/// 1) construct via `create`, 2) call `step` per frame with the resolved
1007/// active event and timing, 3) read `get_draw_plan_buf`/`get_draw_plan_len`
1008/// only when `step` returned `true` and only before the next call.
1009#[wasm_bindgen]
1010pub struct SSRuntimeEffectSlot {
1011    inner: OwningEffectSlot,
1012    last_draw_plan_ptr: *const u8,
1013    last_draw_plan_len: usize,
1014}
1015
1016#[wasm_bindgen]
1017impl SSRuntimeEffectSlot {
1018    pub fn create(resource: &SSRuntimeResource, effect_name_hash: u32, seed: u32) -> Result<SSRuntimeEffectSlot, JsValue> {
1019        match OwningEffectSlot::new(resource.inner.clone(), effect_name_hash, seed) {
1020            Ok(inner) => Ok(SSRuntimeEffectSlot { inner, last_draw_plan_ptr: core::ptr::null(), last_draw_plan_len: 0 }),
1021            Err(e) => Err(js_error(e)),
1022        }
1023    }
1024
1025    /// Advance one frame. `ev` is the event info returned by
1026    /// `SSRuntimeContext::get_active_effect_event` (or built manually via
1027    /// `WebEffectEventInfo`).
1028    ///
1029    /// `y_flip = true` for Y-down rendering (pixi.js), mirroring each particle's Y
1030    /// position, rotation sign and quad; `vert_stride = 2` packs
1031    /// (x,y) verts, `3` packs (x,y,0) for engines requiring 3-component verts.
1032    /// `draw` is whether the part is in this frame's `draw_order`: a hidden
1033    /// part steps with `false`, which moves its clock and builds no plan. Pass
1034    /// `true` when stepping before this frame's `draw_order` is known.
1035    /// Returns `true` if visible; on `true` callers read the plan via
1036    /// `get_draw_plan_buf` / `get_draw_plan_len` before the next step.
1037    #[allow(clippy::too_many_arguments)]
1038    pub fn step(&mut self, ev: &WebEffectEventInfo, parent_frame: f32, delta_seconds: f32, fps: f32, parent_looped: bool, y_flip: bool, vert_stride: u8, draw: bool) -> bool {
1039        let r = self.inner.step((*ev).into(), parent_frame, delta_seconds, fps, parent_looped, y_flip, vert_stride, draw);
1040        self.last_draw_plan_ptr = r.draw_plan_buf;
1041        self.last_draw_plan_len = r.draw_plan_len;
1042        r.visible
1043    }
1044
1045    pub fn get_draw_plan_buf(&self) -> *const u8 {
1046        self.last_draw_plan_ptr
1047    }
1048
1049    pub fn get_draw_plan_len(&self) -> usize {
1050        self.last_draw_plan_len
1051    }
1052
1053    pub fn get_seed(&self) -> u32 {
1054        self.inner.get_seed()
1055    }
1056
1057    pub fn is_independent(&self) -> bool {
1058        self.inner.is_independent()
1059    }
1060
1061    /// Reset the slot's playback / "last started key" memory to its just-created
1062    /// state without destroying it. Call on an explicit head-out (replay) so a
1063    /// re-played animation re-fires its effect from scratch instead of debouncing
1064    /// the first key as the same one the slot last started. Mirrors the C-API
1065    /// `ss_effect_slot_reset`.
1066    pub fn reset(&mut self) {
1067        self.inner.reset();
1068        self.last_draw_plan_ptr = core::ptr::null();
1069        self.last_draw_plan_len = 0;
1070    }
1071}
1072
1073/// JS-friendly wrapper of `InstanceSlot`. Same conceptual flow as the C FFI:
1074/// 1) construct via `create`, 2) call `step` per frame with the resolved
1075/// active event, child context, and timing, 3) on `transitioned == true`
1076/// call `play` on the child context: the slot configures the child for the
1077/// new key without starting it, and an independent child never advances
1078/// otherwise.
1079#[wasm_bindgen]
1080pub struct SSRuntimeInstanceSlot {
1081    inner: crate::InstanceSlot,
1082    last_visible: bool,
1083    last_transitioned: bool,
1084    last_independent: bool,
1085    last_child_frame_no: f32,
1086    last_child_looped: bool,
1087}
1088
1089#[wasm_bindgen]
1090impl SSRuntimeInstanceSlot {
1091    pub fn create() -> SSRuntimeInstanceSlot {
1092        SSRuntimeInstanceSlot { inner: crate::InstanceSlot::new(), last_visible: false, last_transitioned: false, last_independent: false, last_child_frame_no: 0.0, last_child_looped: false }
1093    }
1094
1095    /// Advance one tick. `ev` is the event info returned by
1096    /// `SSRuntimeContext::get_active_event_instance` (or built manually via
1097    /// `WebEventInstanceInfo`). `child_ctx` must be the *child* runtime —
1098    /// label resolution and frame stepping run against it.
1099    /// Returns `true` if visible. Inspect `transitioned`, `independent`,
1100    /// `child_frame_no`, `child_looped` via the corresponding getters.
1101    pub fn step(&mut self, ev: &WebEventInstanceInfo, child_ctx: &mut SSRuntimeContext, parent_frame: f32, delta_seconds: f32, parent_looped: bool) -> bool {
1102        let r = self.inner.step((*ev).into(), &mut child_ctx.inner, parent_frame, delta_seconds, parent_looped);
1103        self.last_visible = r.visible;
1104        self.last_transitioned = r.transitioned;
1105        self.last_independent = r.independent;
1106        self.last_child_frame_no = r.child_frame_no;
1107        self.last_child_looped = r.child_looped;
1108        r.visible
1109    }
1110
1111    pub fn transitioned(&self) -> bool {
1112        self.last_transitioned
1113    }
1114
1115    pub fn independent(&self) -> bool {
1116        self.last_independent
1117    }
1118
1119    pub fn child_frame_no(&self) -> f32 {
1120        self.last_child_frame_no
1121    }
1122
1123    pub fn child_looped(&self) -> bool {
1124        self.last_child_looped
1125    }
1126
1127    pub fn is_independent(&self) -> bool {
1128        self.inner.is_independent()
1129    }
1130
1131    /// The speed the last `step` drove the child at. Scale the elapsed time
1132    /// handed to the child's own slots by its absolute value, not by the event's
1133    /// `speed`, which reads `1.0` while the slot ignores the implicit key. Mirrors
1134    /// the C-API `ss_instance_slot_get_speed`.
1135    pub fn get_speed(&self) -> f32 {
1136        self.inner.get_speed()
1137    }
1138
1139    /// Reset the slot's "last started key" memory to its just-created state
1140    /// without destroying it. Call on an explicit head-out (replay) so a
1141    /// re-played animation re-fires the instance child from scratch instead of
1142    /// debouncing the first key as the same one the slot last started. Mirrors
1143    /// the C-API `ss_instance_slot_reset`.
1144    pub fn reset(&mut self) {
1145        self.inner.reset();
1146        self.last_visible = false;
1147        self.last_transitioned = false;
1148        self.last_independent = false;
1149        self.last_child_frame_no = 0.0;
1150        self.last_child_looped = false;
1151    }
1152}
1153
1154#[wasm_bindgen]
1155pub fn ss_runtime_hash_string(s: &str) -> u32 {
1156    crate::fnv1a_hash_str(s)
1157}