Skip to main content

ssruntime/
lib.rs

1//! The playback **Brain** of the SpriteStudio SDK.
2//!
3//! `ssruntime` loads `.ssab` animation binaries produced by `ssconverter` and computes,
4//! for every frame, everything a renderer needs: part transforms, mesh deformations,
5//! colors, and a cross-engine **DrawBatch** plan. It performs no rendering of its own —
6//! each *Player* (engine integration) consumes the emitted state and draws with its
7//! native API. That split is what keeps playback identical across engines.
8//!
9//! ```text
10//!   .sspj (XML)          .ssab (FlatBuffers)        FrameData + DrawBatch         pixels
11//!        │                       │                          │                       │
12//!        └──── ssconverter ──────┴──────  ssruntime  ────────┴────── Player ─────────┘
13//!                                          (Brain)                    (Body)
14//! ```
15//!
16//! # API faces
17//!
18//! The same core is exposed three ways; pick the one that matches your host:
19//!
20//! | Face | Entry point | Consumer |
21//! |---|---|---|
22//! | Rust (`rlib`) | [`Context`], [`AnimationResource`] | Rust-native Players, this crate's own tests |
23//! | C ABI (`staticlib` / `cdylib`, emitted by `ssruntime-ffi`) | [`ffi`] — `ss_runtime_*`, header generated by `cbindgen` | Unity, Godot, Ren'Py, Flutter, C/C++ engines |
24//! | JS / WASM (emitted by `ssruntime-ffi`) | the `web` module (feature `web`, `wasm-bindgen`) | the browser Player collection |
25//!
26//! # Quick start (Rust)
27//!
28//! ```no_run
29//! use ssruntime::{AnimationResource, Context};
30//!
31//! # fn main() -> Result<(), ssruntime::error::SSRuntimeError> {
32//! # let ssab_bytes: &[u8] = &[];
33//! // 1. Parse the .ssab once. A resource is read-only and can back many contexts.
34//! // SAFETY: a pack the converter wrote, so a valid .ssab (see Limitations below).
35//! let resource = unsafe { AnimationResource::new(ssab_bytes) }?;
36//!
37//! // 2. A context holds the playback state of one animated object.
38//! let mut ctx = Context::new();
39//! ctx.bind_resource(&resource);
40//! ctx.setup_animation("Wait")?;
41//! ctx.set_loop_count(-1); // -1 = loop forever
42//! ctx.play();
43//!
44//! // 3. Each tick: advance time, then ask for that frame's data.
45//! //    `update` takes **milliseconds**, matching the animation's fps.
46//! while ctx.is_playing() {
47//!     let frame_no = ctx.update(1000.0 / 60.0);
48//!     let framedata: &[u8] = ctx.get_frame_data(frame_no)?;
49//!     // `framedata` is a FlatBuffer: the FrameData schema says how to read it.
50//! }
51//! # Ok(())
52//! # }
53//! ```
54//!
55//! Transport, loop count, ping-pong, playback range and FPS all live on the context and
56//! are backed by [`eval::playback_controller::PlaybackController`].
57//!
58//! Frame numbers are `f32`: the runtime interpolates between source keyframes, so
59//! playback stays smooth above and below the authored framerate.
60//!
61//! # Module map
62//!
63//! - [`eval`] — the evaluation core: interpolation, matrices, geometry,
64//!   [`eval::playback_controller`] (transport, loop, ping-pong, seek),
65//!   [`eval::framedata`] (the per-frame FlatBuffer), [`eval::override_layer`]
66//!   (per-part color / cell / visibility overrides), [`eval::effect`] (particles).
67//! - [`types`] — `#[repr(C)]` POD structs returned by value across API boundaries.
68//! - [`error`] — [`error::SSRuntimeError`] and its stable integer codes.
69//! - [`ffi`] — the C ABI surface (feature `ffi`).
70//! - `web` — the `wasm-bindgen` surface (feature `web`).
71//!
72//! # Feature flags
73//!
74//! | Feature | Purpose |
75//! |---|---|
76//! | `ffi` | C-API exports. For `ssruntime-ffi`, not for Rust dependents — see below. |
77//! | `libc_alloc` | `libc::malloc`/`free`-backed `#[global_allocator]` for `no_std` FFI builds (mobile / desktop). |
78//! | `wasm_alloc` | `dlmalloc`-backed `#[global_allocator]` for `no_std` WASM builds. |
79//! | `emscripten_alloc` | Emscripten libc-backed `#[global_allocator]` for Emscripten `no_std` builds. |
80//! | `custom_alloc` | Routes allocation and abort to host-provided `ss_custom_alloc` / `ss_custom_free` / `ss_custom_abort` symbols, for console and engine allocators. Build as `staticlib`. |
81//! | `panic-handler` | Provides `#[panic_handler]` for `no_std` FFI builds. |
82//! | `web` | `wasm-bindgen` bindings for JS/TS interop. Same caveat as `ffi`. |
83//! | `std` | Opt-in developer ergonomics only; never used by release scripts. |
84//!
85//! Nothing is on by default: a Rust dependent wants the `rlib` and nothing else.
86//!
87//! `ffi` and `web` exist for `ssruntime-ffi`, the sibling crate that emits this one as
88//! a `staticlib` / `cdylib`. Enabling either from a Rust dependency compiles
89//! `#[no_mangle] extern "C"` symbols into your binary, and those collide if the same
90//! binary also links a prebuilt `libssruntime`. The allocator and `panic-handler`
91//! features are for the same builds, and are inert in an `rlib` that `std` backs.
92//!
93//! The allocator features are mutually exclusive — pairing `custom_alloc` with another
94//! trips a `compile_error!` rather than the compiler's opaque "multiple global allocators".
95//!
96//! # `no_std`
97//!
98//! This crate is `no_std`-first and every release deliverable is built that way;
99//! `std` exists for local developer convenience. An allocator is still required
100//! (`alloc` is used for animation state and metadata), which is what the
101//! `*_alloc` features above provide.
102//!
103//! A Rust dependent takes the crate as it comes:
104//!
105//! ```toml
106//! ssruntime = "7.0.0-beta.1"
107//! ```
108//!
109//! The binary deliverables are built from `ssruntime-ffi`, which passes these through:
110//!
111//! ```text
112//! # Mobile / desktop, C-API
113//! cargo build -p ssruntime-ffi --no-default-features --features ffi,libc_alloc,panic-handler
114//! # Browser, wasm-bindgen
115//! cargo build -p ssruntime-ffi --target wasm32-unknown-unknown --no-default-features --features web
116//! # Pure WASM (WASI or a custom engine)
117//! cargo build -p ssruntime-ffi --target wasm32-unknown-unknown --no-default-features --features ffi,wasm_alloc,panic-handler
118//! ```
119//!
120//! # Limitations to design around
121//!
122//! - **Input is not validated.** To keep the binary small and playback allocation-free,
123//!   `.ssab` is read zero-copy with no structural checks. Malformed or hostile input can
124//!   cause out-of-bounds reads. Verifying asset integrity is the *Player's* job — do it
125//!   before loading anything that came from a network or an end user. The FlatBuffers
126//!   accessors do not bounds-check in release builds, so reading anything but a valid
127//!   `.ssab` is undefined behaviour; that precondition is why [`AnimationResource::new`]
128//!   and [`SsabResource::new`] are `unsafe fn`.
129//! - **Borrowed buffers are not owned.** One [`AnimationResource`] may back several
130//!   [`Context`]s, and across the C ABI resources are reference-counted — destroying a
131//!   resource handle that contexts are still bound to is safe. What is *not* managed for
132//!   you is the `.ssab` byte buffer behind `ss_resource_create_borrow`: it is never
133//!   copied, so the caller must keep it alive and unmodified for as long as the resource
134//!   exists. `ss_resource_create_copy` trades memory for not having to.
135//!
136//! # Further reading
137//!
138//! - [Player Porting Guide](https://github.com/cri-middleware/SpriteStudio-SDK/tree/HEAD/libs/ssruntime/docs)
139//!   — how to build a Player on this crate, start to finish.
140//! - [FrameData schema](https://github.com/cri-middleware/SpriteStudio-SDK/blob/HEAD/libs/ssruntime/SCHEMA.md)
141//!   — the layout of what [`Context::get_frame_data`] returns.
142//! - [Limitations](https://github.com/cri-middleware/SpriteStudio-SDK/blob/HEAD/libs/ssruntime/docs/10_introduction/20_limitations.md)
143//!   — supported scope and spec constraints. Read before making Player design decisions.
144//!
145// Without `ffi` there is no module to link to, so the links above go to its source.
146#![cfg_attr(not(feature = "ffi"), doc = "[`ffi`]: https://github.com/cri-middleware/SpriteStudio-SDK/blob/HEAD/libs/ssruntime/src/ffi/mod.rs")]
147#![cfg_attr(all(not(feature = "std"), not(test)), no_std)]
148
149mod platform;
150
151extern crate alloc;
152extern crate libm;
153
154#[rustfmt::skip]
155/// The generated bindings of `fbs/framedata.fbs` and `fbs/effect_draw_plan.fbs`.
156/// cbindgen:ignore
157pub mod runtime;
158pub mod error;
159pub mod eval;
160
161pub use crate::eval::SsCoordinateSystem;
162
163pub mod interpolate;
164
165pub mod types;
166
167#[cfg(feature = "ffi")]
168pub mod ffi;
169
170#[cfg(feature = "web")]
171pub mod web;
172
173mod context;
174mod effect_slot;
175mod instance_slot;
176mod mix;
177#[cfg(any(feature = "ffi", feature = "web"))]
178mod owning;
179mod resource;
180
181pub use context::Context;
182pub use effect_slot::{EffectContext, EffectSlot};
183pub use instance_slot::InstanceSlot;
184pub use mix::{TrackBlend, TrackSync};
185pub use resource::{AnimationMetadata, AnimationResource, SsabData, SsabResource, fnv1a_hash_str};
186
187#[cfg(all(test, feature = "std"))]
188mod tests;